diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 19d5525..949478f 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -2707,6 +2707,53 @@ if ($compiled) { } try { [System.IO.File]::Delete($batFile) } catch { } # temp file only; best effort + # A quote inside a list element for a .bat/.cmd program. cmd.exe reads the + # command line first and counts every quote, \" included, so with \" an + # element like a" & & " ran that command. The kit writes "" for + # those programs instead. The batch file itself does nothing, so only + # cmd.exe's own reading of the command line could create the marker. The + # marker is a bare name in the working folder, so a space in %TEMP% can't + # make the injected command write somewhere else and the check pass anyway. + $injDir = Join-Path $env:TEMP ("pk-inj-" + [guid]::NewGuid().ToString("N")) + $null = New-Item -ItemType Directory -Path $injDir + $injMarker = Join-Path $injDir 'pk-marker.txt' + $injBat = Join-Path $injDir 'noop.cmd' + [System.IO.File]::WriteAllText($injBat, "@rem does nothing`r`n") + $injPayloads = @('a" & echo x>pk-marker.txt & "', 'a"&echo x>pk-marker.txt&"', '"&echo x>pk-marker.txt', 'a\" & echo x>pk-marker.txt & \"', 'a\\" & echo x>pk-marker.txt & "', 'a"^&echo x>pk-marker.txt', 'a"""&echo x>pk-marker.txt&"""') + $injHits = 0 + foreach ($payload in $injPayloads) { + try { $null = Invoke-PkProcessWithTimeout -FilePath $injBat -Arguments @($payload) -WorkingDirectory $injDir -TimeoutMs 10000 } catch { Write-Host " injection probe threw: $_" } + if ([System.IO.File]::Exists($injMarker)) { $injHits++; [System.IO.File]::Delete($injMarker) } + } + Test-Assert ($injHits -eq 0) ("a quote in a list element can't make a .cmd program run another command (" + $injHits + " of " + $injPayloads.Count + " did)") + $injUpper = Join-Path $injDir 'NOOP.BAT' + [System.IO.File]::WriteAllText($injUpper, "@rem does nothing`r`n") + $null = Invoke-PkProcessBatch -MaxConcurrent 1 -Commands @(@{ FilePath = $injUpper; WorkingDirectory = $injDir; Arguments = @($injPayloads[0]) }) + Test-Assert (-not [System.IO.File]::Exists($injMarker)) "the same through the batch, for a .BAT in capitals" + # Windows drops trailing dots and spaces from a file name, so 'noop.cmd.' + # still goes through cmd.exe. + try { $null = Invoke-PkProcessWithTimeout -FilePath ($injBat + '.') -Arguments @($injPayloads[0]) -WorkingDirectory $injDir -TimeoutMs 10000 } catch { Write-Host " injection probe threw: $_" } + Test-Assert (-not [System.IO.File]::Exists($injMarker)) "and for a .cmd path written with a trailing dot" + + # And a batch file that passes %* on to a program still gets every + # argument to it exactly: the C runtime reads "" inside quotes as one quote. + $fwdBat = Join-Path $injDir 'fwd.cmd' + [System.IO.File]::WriteAllText($fwdBat, ('@"' + $argvExe + '" %*' + "`r`n")) + $fwdArgs = @('say "hi"', 'a\"b', 'C:\dir with space\', 'a" & echo x & "', '""', '"', 'a\\"b', 'a&b', 'plain') + $text = $null + try { $text = Get-ArgvText (Invoke-PkProcessWithTimeout -FilePath $fwdBat -Arguments $fwdArgs -TimeoutMs 10000).Stdout } catch { $text = "threw: $_" } + $fwdExpected = (@($fwdArgs | ForEach-Object { '[' + $_ + ']' }) -join '') + Test-Assert ($text -ceq $fwdExpected) ("a .cmd that passes %* on gets the list through exactly (" + $text + ")") + + # 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 = '' + try { $null = Invoke-PkProcessWithTimeout -FilePath $fwdBat -Arguments @('a', ("b" + "`n" + "c")) -TimeoutMs 10000 } catch { $nlError = [string]$_ } + $nlBatch = (Invoke-PkProcessBatch -MaxConcurrent 1 -Commands @(@{ FilePath = $fwdBat; Arguments = @(("b" + "`r" + "c")) })).Results[0] + Test-Assert ($nlError -like '*element 2*line break*' -and [string]$nlBatch.StartError -like '*line break*') ("a line break in a list element for a .cmd is refused with a clear error (" + $nlError + ")") + Test-Assert ((Get-BatchArgvText @(("b" + "`n" + "c"))) -eq ("[b" + "`n" + "c]")) "and still reaches an ordinary program" + try { [System.IO.Directory]::Delete($injDir, $true) } catch { } # temp folder only; best effort + # A string is still exactly as written. Test-Assert ((Get-BatchArgvText '"C:\My Files\a.png" out.jxl') -eq $spacedText) "a string is still passed exactly as written" # The documented change: list elements are values, not pieces of a command line. diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 142f565..bf17f45 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -735,12 +735,13 @@ function ConvertTo-PkArgumentString { # These are the C runtime's rules, which most Windows programs use; cmd.exe /c # 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. Not covered for those programs: cmd - # expands %NAME% inside quotes, splits batch arguments at = (left unquoted, - # since some programs read NAME=value themselves), and counts a \" as a - # quote, so an argument containing a quote can end up partly unquoted. The - # kit's -Arguments and Arguments values do this themselves when given a - # list. + # 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). # .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 @@ -763,6 +764,24 @@ function ConvertTo-PkArgumentString { # $null element into '' before it can be left out. [object[]]$Arguments ) + return (ConvertTo-PkArgumentStringCore -Arguments $Arguments) +} + +function ConvertTo-PkArgumentStringCore { + # ConvertTo-PkArgumentString's body. -ForBatchFile is for a .bat or .cmd + # program, whose command line cmd.exe reads first: a quote inside an + # argument is written "" instead of \". cmd.exe counts every quote, and to + # it \" is an ordinary quote that ends the quoted part, so an argument like + # a" & del ... & " ran its second command. "" keeps cmd's count even, and a + # program the batch file passes %* on to still reads "" as one quote (the C + # runtime does). A line break would end cmd.exe's command line there and + # silently drop the rest, so it's refused. + param( + [AllowNull()] + [AllowEmptyCollection()] + [object[]]$Arguments, + [switch]$ForBatchFile + ) $parts = [System.Collections.Generic.List[string]]::new() $position = 0 foreach ($item in $Arguments) { @@ -774,6 +793,9 @@ function ConvertTo-PkArgumentString { } # 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).") + } # The C runtime only needs quotes around whitespace and quotes. The rest # are cmd.exe's: it runs a .bat/.cmd program's command line, acting on # & | < > ^ ( ) outside quotes and splitting batch arguments at , ; @@ -788,9 +810,15 @@ function ConvertTo-PkArgumentString { foreach ($ch in $arg.ToCharArray()) { if ($ch -eq '\') { $backslashes++; continue } if ($ch -eq '"') { - # Each backslash before a quote is doubled, then the quote escaped. - $null = $sb.Append('\', 2 * $backslashes + 1) - $null = $sb.Append('"') + # Each backslash before a quote is doubled, then the quote + # escaped: \" normally, "" for a batch file (see above). + if ($ForBatchFile) { + $null = $sb.Append('\', 2 * $backslashes) + $null = $sb.Append('""') + } else { + $null = $sb.Append('\', 2 * $backslashes + 1) + $null = $sb.Append('"') + } } else { if ($backslashes -gt 0) { $null = $sb.Append('\', $backslashes) } $null = $sb.Append($ch) @@ -809,14 +837,22 @@ function Resolve-PkArguments { # -Arguments / Arguments as given -> the command line. A string is used as # written; a list is quoted one argument per element, so a path with a space # stays whole (a plain [string] cast would join it with spaces, or $OFS). A - # lone file or folder object is one argument, its full path. - param($Arguments) + # lone file or folder object is one argument, its full path. -FilePath is + # the program: a list for a .bat or .cmd is quoted for cmd.exe (see + # ConvertTo-PkArgumentStringCore). A bare name only ever 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 } if ($Arguments -is [System.Collections.IDictionary]) { throw ("Arguments must be one string or a list of arguments (got a " + $Arguments.GetType().Name + ").") } - if ($Arguments -is [System.Collections.IEnumerable] -or $Arguments -is [System.IO.FileSystemInfo]) { return (ConvertTo-PkArgumentString -Arguments @($Arguments)) } + 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)$') + return (ConvertTo-PkArgumentStringCore -Arguments @($Arguments) -ForBatchFile:$forBatchFile) + } return [string]$Arguments } @@ -931,7 +967,7 @@ function Start-PkProcessCore { [System.Management.Automation.SessionState]$CallerState ) $encoding = Resolve-PkEncoding -Encoding $OutputEncoding - $commandLine = Resolve-PkArguments -Arguments $Arguments + $commandLine = Resolve-PkArguments -Arguments $Arguments -FilePath $FilePath # Self-starting: a caller who never ran Initialize-ParallelKit still # gets children that die with the script, and output reads that # aren't starved of threads. Both are cheap no-ops once done. @@ -2116,7 +2152,7 @@ function Get-PkWorkerSafeFunctionNames { return @('Write-PkMessage', 'Test-PkAbortSignal', 'Test-PkCancelRequested', 'Initialize-PkThreadPool', 'Stop-PkProcessTree', 'Stop-PkJobProcesses', 'Resolve-PkEncoding', 'Start-PkProcess', 'Wait-PkProcess', 'Wait-PkRunningJobs', 'Complete-PkProcess', 'Invoke-PkProcessWithTimeout', 'Invoke-PkProcessDispatch', 'Invoke-PkProcessDispatchCore', 'Invoke-PkProcessBatch', - 'Register-PkCancellationSource', 'Unregister-PkCancellationSource', 'New-PkBatchResult', 'ConvertTo-PkArgumentString', 'Get-PkForceStopReason', 'Resolve-PkFileSystemPath', 'Add-PkDispatchGroupJobs', 'Start-PkProcessCore', 'Get-PkJobTimeLimit', 'Stop-PkTimedOutJob', 'Get-PkStartFailureCause', 'Resolve-PkArguments', 'Invoke-PkCallback') + 'Register-PkCancellationSource', 'Unregister-PkCancellationSource', 'New-PkBatchResult', 'ConvertTo-PkArgumentString', 'Get-PkForceStopReason', 'Resolve-PkFileSystemPath', 'Add-PkDispatchGroupJobs', 'Start-PkProcessCore', 'Get-PkJobTimeLimit', 'Stop-PkTimedOutJob', 'Get-PkStartFailureCause', 'Resolve-PkArguments', 'Invoke-PkCallback', 'ConvertTo-PkArgumentStringCore') } function Get-PkHandlerParamCount { diff --git a/README.md b/README.md index 33b2fa1..311504b 100644 --- a/README.md +++ b/README.md @@ -123,7 +123,7 @@ $batch = Invoke-PkRun { Invoke-PkProcessBatch @batchParams } Long parameter lists in these examples use splatting (`@batchParams`) instead of trailing backticks: it's easier to read, and a stray space after a backtick can't break it. -Each command is a hashtable with `FilePath`, `Arguments` and optionally `WorkingDirectory`, plus any keys of your own. `Arguments` is either one string, passed to the program exactly as written, or a list, where each element is one argument: `Arguments = @($in, $out)` works with spaces in the paths. A list is quoted the way `ConvertTo-PkArgumentString @(...)` quotes it, so the program gets exactly that list back, spaces, quotes and trailing backslashes included, and `$null` elements are left out. A file or folder object from `Get-ChildItem` or `Get-Item` is passed as its full path. An element that's itself a list is an error, not one argument. Quotes inside an element are passed on as quote characters, so don't pre-quote list elements. It follows the rules most Windows programs use; `cmd.exe /c` parses its own way, so give it one string. A `.bat` or `.cmd` program runs through `cmd.exe` too. A list element holding `&`, `|`, `<`, `>`, `^`, `(`, `)`, `,` or `;` is quoted, so such a program gets it as one argument. What quoting can't cover there: `cmd.exe` expands `%NAME%` in an argument, quoted or not, when a variable by that name exists; it splits batch arguments at `=`, which isn't quoted because some programs read `NAME=value` from the command line themselves; and an element containing a `"` can leave the characters after it unquoted as far as `cmd.exe` is concerned. Programs run hidden, with their output captured. +Each command is a hashtable with `FilePath`, `Arguments` and optionally `WorkingDirectory`, plus any keys of your own. `Arguments` is either one string, passed to the program exactly as written, or a list, where each element is one argument: `Arguments = @($in, $out)` works with spaces in the paths. A list is quoted the way `ConvertTo-PkArgumentString @(...)` quotes it, so the program gets exactly that list back, spaces, quotes and trailing backslashes included, and `$null` elements are left out. A file or folder object from `Get-ChildItem` or `Get-Item` is passed as its full path. An element that's itself a list is an error, not one argument. Quotes inside an element are passed on as quote characters, so don't pre-quote list elements. It follows the rules most Windows programs use; `cmd.exe /c` parses its own way, so give it one string. A `.bat` or `.cmd` program runs through `cmd.exe` too. A list element holding `&`, `|`, `<`, `>`, `^`, `(`, `)`, `,` or `;` is quoted, so such a program gets it as one argument. What quoting can't cover there: `cmd.exe` expands `%NAME%` in an argument, quoted or not, when a variable by that name exists; and it splits batch arguments at `=`, which isn't quoted because some programs read `NAME=value` from the command line themselves. A `"` inside an element is written `""` for these programs, so `cmd.exe` can't be made to run anything else, and a batch file that passes `%*` on to another program still delivers it as one `"`. An element holding a line break can't be passed to them at all, so it's an error. All this needs the list form: a string, including one from `ConvertTo-PkArgumentString`, is passed as written. Programs run hidden, with their output captured. Programs run in your current location (`Get-Location`) unless a command says otherwise, and a relative `WorkingDirectory`, or a `FilePath` with a folder in it like `.\tools\cjxl.exe`, is relative to that location too. Drives PowerShell knows, like `~` or one made with `New-PSDrive`, work in both. A bare name like `cjxl.exe` is found the way Windows finds programs, mostly on `PATH`. A `.bat` or `.cmd` program can't run in a network-share (`\\server\share`) folder: `cmd.exe` falls back to `C:\Windows` there, so give such commands a local `WorkingDirectory`.