diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 8766a41..7867e27 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -2758,6 +2758,26 @@ if ($compiled) { $fwdExpected = (@($fwdArgs | ForEach-Object { '[' + $_ + ']' }) -join '') Test-Assert ($text -ceq $fwdExpected) ("a .cmd that passes %* on gets the list through exactly (" + $text + ")") + # cmd.exe itself given a list gets the same quoting: the program after /c + # still gets the list exactly (spaces, quotes, trailing backslashes), and + # no element can make cmd.exe run another command. Under any spelling of + # cmd.exe's name. + $text = $null + try { $text = Get-ArgvText (Invoke-PkProcessWithTimeout -FilePath $cmdExe -Arguments (@('/d', '/c', $argvExe) + $fwdArgs) -TimeoutMs 10000).Stdout } catch { $text = "threw: $_" } + Test-Assert ($text -ceq $fwdExpected) ("cmd.exe /c given a list passes it on to the program exactly (" + $text + ")") + $cmdHits = 0 + $cmdThrew = 0 + $cmdNames = @($cmdExe, 'cmd', 'CMD.EXE', ($cmdExe.ToUpperInvariant() + '.')) + foreach ($cmdName in $cmdNames) { + foreach ($payload in $injPayloads) { + try { $null = Invoke-PkProcessWithTimeout -FilePath $cmdName -Arguments @('/d', '/c', 'echo', $payload) -WorkingDirectory $injDir -TimeoutMs 10000 } catch { $cmdThrew++; Write-Host " injection probe threw: $_" } + if ([System.IO.File]::Exists($injMarker)) { $cmdHits++; [System.IO.File]::Delete($injMarker) } + } + } + Test-Assert ($cmdHits -eq 0 -and $cmdThrew -eq 0) ("a quote in a list element can't make cmd.exe /c run another command (" + $cmdHits + " of " + ($cmdNames.Count * $injPayloads.Count) + " did, " + $cmdThrew + " failed to run)") + $cmdBatch = Invoke-PkProcessBatch -MaxConcurrent 1 -Commands @(@{ FilePath = 'cmd.exe'; WorkingDirectory = $injDir; Arguments = @('/d', '/c', 'echo', $injPayloads[0]) }) + Test-Assert (-not [System.IO.File]::Exists($injMarker) -and $cmdBatch.Results[0].ExitCode -eq 0) "the same for cmd.exe through the batch" + # A line break would end cmd.exe's command line and drop the rest, so it's # refused for a batch file, and still fine for any other program. $nlError = '' diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 9c3d34f..cbcfa95 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -729,16 +729,16 @@ function ConvertTo-PkArgumentString { # .DESCRIPTION # An argument with a space, tab, newline or quote is wrapped in quotes, its # quotes become \", and backslashes are doubled where they come before a quote. - # These are the C runtime's rules, which most Windows programs use; cmd.exe /c + # These are the C runtime's rules, which most Windows programs use; cmd.exe # parses its own way. An argument with one of & | < > ^ ( ) , ; is quoted # too, so a .bat or .cmd program, which runs through cmd.exe, gets it as one # argument instead of cmd acting on it. The kit's -Arguments and Arguments - # values do this themselves when given a list, and for a .bat or .cmd - # program they also write a quote as "" instead of \", which cmd.exe can't - # be tricked by. This function's own output uses \": for a .bat or .cmd, - # give the kit the list instead. Not covered for those programs either way: - # cmd expands %NAME% inside quotes, and splits batch arguments at = (left - # unquoted, since some programs read NAME=value themselves). + # values do this themselves when given a list, and for cmd.exe or a + # batch-file program they also write a quote as "" instead of \", which + # cmd.exe can't be tricked by. This function's own output uses \": for + # those, give the kit the list instead. Not covered for those programs + # either way: cmd expands %NAME% inside quotes, and splits batch arguments + # at = (left unquoted, since some programs read NAME=value themselves). # .PARAMETER Arguments # The arguments, in order. A $null one is left out; an empty string is passed # as "". A file or folder object (from Get-ChildItem or Get-Item) is its full @@ -765,9 +765,9 @@ function ConvertTo-PkArgumentString { } function ConvertTo-PkArgumentStringCore { - # ConvertTo-PkArgumentString's body. -ForBatchFile: for a .bat or .cmd, - # whose command line cmd.exe reads first, a quote is written "" instead of - # \". cmd.exe counts every quote, \" included, so with \" an argument like + # ConvertTo-PkArgumentString's body. -ForBatchFile: for cmd.exe or a .bat + # or .cmd, whose command line cmd.exe reads first, a quote is written "" + # instead of \". cmd.exe counts every quote, \" included, so with \" an argument like # a" & del ... & " runs a second command. "" keeps the count even, and the # C runtime still reads it as one quote in a program the batch file passes # %* to. A line break would end cmd.exe's command line, so it's refused. @@ -789,7 +789,7 @@ function ConvertTo-PkArgumentStringCore { # On 5.1 a FileInfo from Get-ChildItem casts to its bare name. if ($item -is [System.IO.FileSystemInfo]) { $arg = $item.FullName } else { $arg = [string]$item } if ($ForBatchFile -and $arg.IndexOfAny([char[]]@("`r", "`n")) -ge 0) { - throw ("Arguments element " + $position + " contains a line break, which can't be passed to a .bat or .cmd program: cmd.exe would end the command line there and drop the rest. Pass it another way (a file, an environment variable).") + throw ("Arguments element " + $position + " contains a line break, which can't be passed to cmd.exe or a .bat or .cmd program: cmd.exe would end the command line there and drop the rest. Pass it another way (a file, an environment variable).") } # The C runtime only needs whitespace and quotes quoted. The rest are for # cmd.exe, which runs a .bat/.cmd: it acts on & | < > ^ ( ) outside @@ -832,8 +832,8 @@ function Resolve-PkArguments { # -Arguments as given -> the command line: a string as written, a list # quoted one argument per element (a [string] cast would join it with # spaces, or $OFS), a lone file or folder object as its full path. - # -FilePath picks batch-file quoting for a .bat or .cmd. A bare name only - # finds an .exe, so a batch file always has its extension here. + # -FilePath picks batch-file quoting for cmd.exe or a .bat or .cmd. A bare + # name only finds an .exe, so a batch file always has its extension here. param($Arguments, [string]$FilePath = '') if ($null -eq $Arguments) { return '' } if ($Arguments -is [string]) { return $Arguments } @@ -842,8 +842,11 @@ function Resolve-PkArguments { } if ($Arguments -is [System.Collections.IEnumerable] -or $Arguments -is [System.IO.FileSystemInfo]) { # Windows drops trailing dots and spaces from a file name, so - # 'run.cmd.' still runs through cmd.exe. - $forBatchFile = ($FilePath.Trim().Trim('"').TrimEnd(' ', '.') -match '\.(bat|cmd)$') + # 'run.cmd.' still runs through cmd.exe. cmd.exe itself, given a list + # (cmd /c tool "a b"), reads its command line the same way, so it gets + # the same quoting. + $exeName = $FilePath.Trim().Trim('"').TrimEnd(' ', '.') + $forBatchFile = ($exeName -match '\.(bat|cmd)$' -or $exeName -match '(^|[\\/])cmd(\.exe)?$') return (ConvertTo-PkArgumentStringCore -Arguments @($Arguments) -ForBatchFile:$forBatchFile) } return [string]$Arguments diff --git a/README.md b/README.md index 20b3d19..030a080 100644 --- a/README.md +++ b/README.md @@ -129,7 +129,7 @@ Each command is a hashtable with `FilePath`, `Arguments` and optionally `Working - The program gets exactly that list back, spaces, quotes and trailing backslashes included. Don't pre-quote elements: a quote inside one is passed on as a quote character. - `$null` elements are left out, a file or folder object from `Get-ChildItem` or `Get-Item` is its full path, and an element that's itself a list is an error. -- The quoting follows the rules most Windows programs use. `cmd.exe /c` parses its own way, so give it one string. +- The quoting follows the rules most Windows programs use. `cmd.exe` itself (`FilePath = 'cmd.exe'`, `Arguments = @('/d', '/c', 'tool.exe', $file)`) gets the batch-file quoting described next, and the program after `/c` gets the rest of the list as given. `cmd.exe` strips the quotes from a program path with spaces, though, so for one of those give it one string: `'/d /s /c ""C:\My Tools\tool.exe" "a b""'`. - A `.bat` or `.cmd` program runs through `cmd.exe`, and the list is quoted for it: an element holding `&`, `|`, `<`, `>`, `^`, `(`, `)`, `,`, `;` or `"` reaches it as one argument and can't make `cmd.exe` run anything else. A `"` is written `""` for it, so the batch file itself sees the quote doubled in `%1` or `%~1`, while a program it passes `%*` on to gets the list back as given. An element with a line break is an error. What quoting can't stop: `cmd.exe` expands `%NAME%` when a variable by that name exists, and splits batch arguments at `=` (left unquoted, since some programs read `NAME=value` themselves). The batch file can also undo the quoting: `%~1` strips the quotes, so a line like `echo %~1` runs the `& echo INJECTED` in an element `a & echo INJECTED`. Keep it quoted in the batch file (`"%~1"`), or use `%1`. Only the list form gets this quoting. A string, including one built with `ConvertTo-PkArgumentString`, is passed as written.