Fail if the PowerShell command is too long

This commit is contained in:
Andrea Mazzoleni 2026-07-06 22:41:08 +02:00
parent ad6ddafd05
commit 19297d6c3d

View file

@ -163,14 +163,17 @@ size_t windows_direct_size(void)
#define WINDOWS_NTFS_MAGIC 0x5346544E /* 'N','T','F','S' */
#define PS_CMD_MAX 16384
#define PS_CMD_MAX 16384 /* needs a x4 factor to handle -EncodedCommand */
#define SNAPSHOT_GUID ".guid"
static const char b64chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static void base64_encode(const unsigned char* in, size_t in_len, char* out, size_t out_max)
static int base64_encode(const unsigned char* in, size_t in_len, char* out, size_t out_max)
{
if (out_max == 0)
return -1;
size_t i, j = 0;
for (i = 0; i < in_len; i += 3) {
uint32_t val = 0;
@ -186,7 +189,7 @@ static void base64_encode(const unsigned char* in, size_t in_len, char* out, siz
}
if (j + 4 >= out_max)
break;
return -1;
out[j++] = b64chars[(val >> 18) & 0x3F];
out[j++] = b64chars[(val >> 12) & 0x3F];
@ -194,6 +197,7 @@ static void base64_encode(const unsigned char* in, size_t in_len, char* out, siz
out[j++] = (count > 2) ? b64chars[val & 0x3F] : '=';
}
out[j] = 0;
return 0;
}
/*
@ -211,21 +215,26 @@ static void base64_encode(const unsigned char* in, size_t in_len, char* out, siz
static int windows_ps(const char* ps_command, char* out, size_t out_size)
{
char cmd[PS_CMD_MAX];
WCHAR wcmd[PS_CMD_MAX];
WCHAR wcmd[PS_CMD_MAX / 4];
char b64cmd[PS_CMD_MAX];
FILE* fp;
int ret;
int wlen;
/* convert UTF-8 command to UTF-16LE WCHARs */
wlen = MultiByteToWideChar(CP_UTF8, 0, ps_command, -1, wcmd, PS_CMD_MAX);
wlen = MultiByteToWideChar(CP_UTF8, 0, ps_command, -1, wcmd, PS_CMD_MAX / 4);
if (wlen <= 0) {
errno = EINVAL;
errno = E2BIG;
log_error(errno, "Failed to run PowerShell command '%s' (too big to convert).\n", ps_command);
return -1;
}
/* base64 encode the UTF-16LE command bytes (excluding the null terminator) */
base64_encode((const unsigned char*)wcmd, (wlen - 1) * sizeof(WCHAR), b64cmd, sizeof(b64cmd));
if (base64_encode((const unsigned char*)wcmd, (wlen - 1) * sizeof(WCHAR), b64cmd, sizeof(b64cmd)) != 0) {
errno = E2BIG;
log_error(errno, "Failed to run PowerShell command '%s' (too big to encode).\n", ps_command);
return -1;
}
ret = snprintf(cmd, sizeof(cmd), "powershell.exe -NoProfile -NonInteractive -EncodedCommand \"%s\" 2>nul", b64cmd);
if (ret < 0 || ret >= (int)sizeof(cmd)) {