Debian Codegraph @

lib/ansible/executor/powershell/exec_wrapper.ps1

raw
1 # (c) 2025 Ansible Project
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 using namespace System.Collections
5 using namespace System.Collections.Generic
6 using namespace System.Diagnostics.CodeAnalysis
7 using namespace System.IO
8 using namespace System.IO.Compression
9 using namespace System.Linq
10 using namespace System.Management.Automation
11 using namespace System.Management.Automation.Language
12 using namespace System.Management.Automation.Security
13 using namespace System.Reflection
14 using namespace System.Security.Cryptography
15 using namespace System.Text
16
17 [SuppressMessageAttribute(
18 "PSUseCmdletCorrectly",
19 "",
20 Justification = "ConvertFrom-Json is being used in a steppable pipeline and works this way."
21 )]
22 [CmdletBinding()]
23 param (
24 [Parameter(ValueFromPipeline)]
25 [string]
26 $InputObject,
27
28 [Parameter()]
29 [PSObject]
30 $Manifest,
31
32 [Parameter()]
33 [switch]
34 $EncodeInputOutput,
35
36 [Parameter()]
37 [string]
38 $MinOSVersion,
39
40 [Parameter()]
41 [string]
42 $MinPSVersion,
43
44 [Parameter()]
45 [string]
46 $TempPath,
47
48 [Parameter()]
49 [string]
50 $PwshPath,
51
52 [Parameter()]
53 [switch]
54 $DecompressInput,
55
56 [Parameter()]
57 [PSObject]
58 $ActionParameters
59 )
60
61 begin {
62 $DebugPreference = "SilentlyContinue"
63 $ErrorActionPreference = "Stop"
64 $ProgressPreference = "SilentlyContinue"
65
66 if ($PSCommandPath -and (Test-Path -LiteralPath $PSCommandPath)) {
67 Remove-Item -LiteralPath $PSCommandPath -Force
68 }
69
70 # Try and set the console encoding to UTF-8 allowing Ansible to read the
71 # output of the wrapper as UTF-8 bytes.
72 try {
73 [Console]::InputEncoding = [Console]::OutputEncoding = [UTF8Encoding]::new()
74 }
75 catch {
76 # PSRP will not have a console host so this will fail. Fallback to
77 # setting the private field we know is present on this version. This
78 # is important as PowerShell uses this encoding when decoding output
79 # from a new process that it spawns.
80 if ($PSVersionTable.PSVersion -lt '6.0') {
81 [Console].GetField('_outputEncoding', [BindingFlags]'NonPublic, Static').SetValue($null, [UTF8Encoding]::new())
82 }
83 }
84
85 $respawnPipeline = $null
86 if ($PwshPath) {
87 $null = $PSBoundParameters.Remove('PwshPath')
88
89 $targetPwsh = Get-Command -Name $PwshPath -CommandType Application -ErrorAction Ignore |
90 Select-Object -First 1 |
91 ForEach-Object { [Path]::GetFullPath($_.Path) }
92 if (-not $targetPwsh) {
93 @{
94 failed = $true
95 msg = "Could not find the specified PowerShell interpreter '$PwshPath'."
96 } | ConvertTo-Json -Compress
97 $Host.SetShouldExit(1)
98 return
99 }
100
101 # Resolve the path in case of a symbolic link, ResolveLinkTarget is
102 # present in pwsh 7+.
103 if ([Directory]::ResolveLinkTarget) {
104 $targetPath = [Directory]::ResolveLinkTarget($targetPwsh, $true)
105 if ($targetPath) {
106 $targetPwsh = $targetPath.FullName
107 }
108 }
109 else {
110 while ($true) {
111 $target = Get-Item -LiteralPath $targetPwsh
112 if ($target.LinkType -ne 'SymbolicLink') {
113 break
114 }
115
116 $targetPath = $target.Target
117 if ($targetPath -notmatch '([a-z]:[\\/])|([\\/]{2})') {
118 # If the target isn't rooted in a drive or UNC path then
119 # they are relative to the link location.
120 $targetPath = [Path]::Combine(
121 [Path]::GetDirectoryName($targetPwsh),
122 $targetPath)
123 }
124 $targetPwsh = [Path]::GetFullPath($targetPath)
125 }
126 }
127
128 # We don't compare the exe as the current process may not be the
129 # normal interpreter but the WSManProvHost used by PSRP. Instead see if
130 # the PSHome path is the same as the target interpreter directory.
131 $targetPSHome = Split-Path -Path $targetPwsh -Parent
132 if ($targetPSHome -ne $PSHome) {
133 $bootstrapWrapper = (Get-PSCallStack)[1].InvocationInfo.MyCommand.Definition
134 $encCommand = [Convert]::ToBase64String([Encoding]::Unicode.GetBytes($bootstrapWrapper))
135
136 $targetPwshArgs = @(
137 '-NoProfile'
138 '-NonInteractive'
139 if ($PSVersionTable.PSVersion -lt '6.0' -or $IsWindows) {
140 '-ExecutionPolicy'
141 'Unrestricted'
142 }
143 '-EncodedCommand'
144 $encCommand
145 )
146
147 # Switch parameters need to be converted to a boolean so they
148 # serialized properly in JSON
149 $PSBoundParameters['DecompressInput'] = $PSBoundParameters['DecompressInput'].IsPresent
150
151 $execManifest = @{
152 name = 'exec_wrapper-respawn.ps1'
153 params = $PSBoundParameters
154 script = $MyInvocation.MyCommand.ScriptBlock.ToString()
155 } | ConvertTo-Json -Compress -Depth 99
156
157 $respawnPipeline = { & $targetPwsh @targetPwshArgs }.GetSteppablePipeline()
158
159 # Need to set back to Continue to stderr ErrorRecords don't stop at
160 # the first one (line).
161 $ErrorActionPreference = 'Continue'
162 $null = $respawnPipeline.Begin($true)
163 $null = $respawnPipeline.Process($execManifest)
164 $null = $respawnPipeline.Process("`0`0`0`0")
165 # Remaining input will be sent in the process block
166 return
167 }
168 }
169
170 if ($MinOSVersion) {
171 [version]$actualOSVersion = (Get-Item -LiteralPath $env:SystemRoot\System32\kernel32.dll).VersionInfo.ProductVersion
172
173 if ($actualOSVersion -lt $MinOSVersion) {
174 @{
175 failed = $true
176 msg = "This module cannot run on this OS as it requires a minimum version of $MinOSVersion, actual was $actualOSVersion"
177 } | ConvertTo-Json -Compress
178 $Host.SetShouldExit(1)
179 return
180 }
181 }
182
183 if ($MinPSVersion) {
184 if ([version]$PSVersionTable.PSVersion -lt $MinPSVersion) {
185 @{
186 failed = $true
187 msg = "This module cannot run as it requires a minimum PowerShell version of $MinPSVersion, actual was ""$($PSVersionTable.PSVersion)"""
188 } | ConvertTo-Json -Compress
189 $Host.SetShouldExit(1)
190 return
191 }
192 }
193
194 # $Script:AnsibleManifest = [PSCustomObject]@{} # Defined in process/end.
195 $Script:AnsibleShouldConstrain = if ($PSVersionTable.PSVersion -lt '6.0' -or $IsWindows) {
196 [SystemPolicy]::GetSystemLockdownPolicy() -eq 'Enforce'
197 }
198 else {
199 $false
200 }
201 $Script:AnsibleTrustedHashList = [HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
202 $Script:AnsibleUnsupportedHashList = [HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
203 $Script:AnsibleWrapperWarnings = [List[string]]::new()
204 $Script:AnsibleTempPath = @(
205 # Wrapper defined tmpdir
206 [Environment]::ExpandEnvironmentVariables($TempPath)
207 # Fallback to user's tmpdir
208 [Path]::GetTempPath()
209 # Should not happen but just in case use the current dir.
210 $pwd.Path
211 ) | Where-Object {
212 if (-not $_) {
213 return $false
214 }
215
216 try {
217 Test-Path -LiteralPath $_ -ErrorAction Ignore
218 }
219 catch {
220 # Access denied could cause Test-Path to throw an exception.
221 $false
222 }
223 } | Select-Object -First 1
224 $Script:AnsibleTempScripts = [List[string]]::new()
225 $Script:AnsibleClrFacadeSet = $false
226
227 Function Get-AnsibleScript {
228 [CmdletBinding()]
229 param (
230 [Parameter(Mandatory)]
231 [string]
232 $Name,
233
234 [Parameter()]
235 [switch]
236 $IncludeScriptBlock,
237
238 [Parameter()]
239 [switch]
240 $SkipHashCheck
241 )
242
243 if (-not $Script:AnsibleManifest.scripts.PSObject.Properties.Match($Name)) {
244 $err = [ErrorRecord]::new(
245 [Exception]::new("Could not find the script '$Name'."),
246 "ScriptNotFound",
247 [ErrorCategory]::ObjectNotFound,
248 $Name)
249 $PSCmdlet.ThrowTerminatingError($err)
250 }
251
252 $scriptInfo = $Script:AnsibleManifest.scripts.$Name
253 $scriptBytes = [Convert]::FromBase64String($scriptInfo.script)
254 $scriptContents = [Encoding]::UTF8.GetString($scriptBytes)
255
256 $sbk = $null
257 if ($IncludeScriptBlock) {
258 $sbk = [Parser]::ParseInput(
259 $scriptContents,
260 $Name,
261 [ref]$null,
262 [ref]$null).GetScriptBlock()
263 }
264
265 $outputValue = [PSCustomObject]@{
266 Name = $Name
267 Script = $scriptContents
268 Path = $scriptInfo.path
269 ScriptBlock = $sbk
270 ShouldConstrain = $false
271 }
272
273 if (-not $Script:AnsibleShouldConstrain) {
274 $outputValue
275 return
276 }
277
278 if (-not $SkipHashCheck) {
279 $sha256 = [SHA256]::Create()
280 $scriptHash = [BitConverter]::ToString($sha256.ComputeHash($scriptBytes)).Replace("-", "")
281 $sha256.Dispose()
282
283 if ($Script:AnsibleUnsupportedHashList.Contains($scriptHash)) {
284 $err = [ErrorRecord]::new(
285 [Exception]::new("Provided script for '$Name' is marked as unsupported in CLM mode."),
286 "ScriptUnsupported",
287 [ErrorCategory]::SecurityError,
288 $Name)
289 $PSCmdlet.ThrowTerminatingError($err)
290 }
291 elseif ($Script:AnsibleTrustedHashList.Contains($scriptHash)) {
292 $outputValue
293 return
294 }
295 }
296
297 # If we have reached here we are running in a locked down environment
298 # and the script is not trusted in the signed hashlists. Check if it
299 # contains the authenticode signature and verify that using PowerShell.
300 # [SystemPolicy]::GetFilePolicyEnforcement(...) is a new API but only
301 # present in Server 2025+ so we need to rely on the known behaviour of
302 # Get-Command to fail with CommandNotFoundException if the script is
303 # not allowed to run.
304 $outputValue.ShouldConstrain = $true
305 if ($scriptContents -like "*`r`n# SIG # Begin signature block`r`n*") {
306 Set-WinPSDefaultFileEncoding
307
308 # If the script is manually signed we need to ensure the signature
309 # is valid and trusted by the OS policy.
310 # We must use '.ps1' so the ExternalScript WDAC check will apply.
311 $tmpFile = [Path]::Combine($Script:AnsibleTempPath, "ansible-tmp-$([Guid]::NewGuid()).ps1")
312 try {
313 [File]::WriteAllBytes($tmpFile, $scriptBytes)
314 $cmd = Get-Command -Name $tmpFile -CommandType ExternalScript -ErrorAction Stop
315
316 # Get-Command caches the file contents after loading which we
317 # use to verify it was not modified before the signature check.
318 $expectedScript = $cmd.OriginalEncoding.GetString($scriptBytes)
319 if ($expectedScript -ne $cmd.ScriptContents) {
320 $err = [ErrorRecord]::new(
321 [Exception]::new("Script has been modified during signature check."),
322 "ScriptModifiedTrusted",
323 [ErrorCategory]::SecurityError,
324 $Name)
325 $PSCmdlet.ThrowTerminatingError($err)
326 }
327
328 $outputValue.ShouldConstrain = $false
329 }
330 catch [CommandNotFoundException] {
331 $null = $null # No-op but satisfies the linter.
332 }
333 finally {
334 if (Test-Path -LiteralPath $tmpFile) {
335 Remove-Item -LiteralPath $tmpFile -Force
336 }
337 }
338 }
339
340 if ($outputValue.ShouldConstrain -and $IncludeScriptBlock) {
341 # If the script is untrusted and a scriptblock was requested we
342 # error out as the sbk would have run in FLM.
343 $err = [ErrorRecord]::new(
344 [Exception]::new("Provided script for '$Name' is not trusted to run."),
345 "ScriptNotTrusted",
346 [ErrorCategory]::SecurityError,
347 $Name)
348 $PSCmdlet.ThrowTerminatingError($err)
349 }
350 else {
351 $outputValue
352 }
353 }
354
355 Function Get-NextAnsibleAction {
356 [CmdletBinding()]
357 param ()
358
359 $action, $newActions = $Script:AnsibleManifest.actions
360 $Script:AnsibleManifest.actions = @($newActions | Select-Object)
361
362 $actionName = $action.name
363 $actionParams = @{}
364 $actionScript = Get-AnsibleScript -Name $actionName -IncludeScriptBlock
365
366 foreach ($prop in $action.params.PSObject.Properties) {
367 $actionParams[$prop.Name] = $prop.Value
368 }
369 foreach ($prop in $action.secure_params.PSObject.Properties) {
370 if (-not $prop.Value) {
371 continue
372 }
373
374 $actionParams[$prop.Name] = $prop.Value | ConvertTo-SecureString -AsPlainText -Force
375 }
376
377 [PSCustomObject]@{
378 Name = $actionName
379 ScriptBlock = $actionScript.ScriptBlock
380 Parameters = $actionParams
381 }
382 }
383
384 Function Get-AnsibleExecWrapper {
385 [CmdletBinding()]
386 param (
387 [Parameter()]
388 [switch]
389 $ManifestAsParam,
390
391 [Parameter()]
392 [switch]
393 $EncodeInputOutput,
394
395 [Parameter()]
396 [switch]
397 $IncludeScriptBlock
398 )
399
400 $scriptInfo = Get-AnsibleScript -Name exec_wrapper.ps1 -IncludeScriptBlock:$IncludeScriptBlock
401 $params = @{
402 # TempPath may contain env vars that change based on the runtime
403 # environment. Ensure we use that and not the $script:AnsibleTempPath
404 # when starting the exec wrapper.
405 TempPath = $TempPath
406 EncodeInputOutput = $EncodeInputOutput.IsPresent
407 }
408
409 $inputData = $null
410 if ($ManifestAsParam) {
411 $params.Manifest = $Script:AnsibleManifest
412 }
413 else {
414 $inputData = ConvertTo-Json -InputObject $Script:AnsibleManifest -Depth 99 -Compress
415 if ($EncodeInputOutput) {
416 $inputData = [Convert]::ToBase64String([Encoding]::UTF8.GetBytes($inputData))
417 }
418 }
419
420 [PSCustomObject]@{
421 ScriptInfo = $scriptInfo
422 Parameters = $params
423 InputData = $inputData
424 }
425 }
426
427 Function Import-PowerShellUtil {
428 [CmdletBinding()]
429 param (
430 [Parameter(Mandatory)]
431 [string[]]
432 $Name
433 )
434
435 foreach ($moduleName in $Name) {
436 $moduleInfo = Get-AnsibleScript -Name $moduleName -IncludeScriptBlock
437 $moduleShortName = [Path]::GetFileNameWithoutExtension($moduleName)
438 $null = New-Module -Name $moduleShortName -ScriptBlock $moduleInfo.ScriptBlock |
439 Import-Module -Scope Global
440 }
441 }
442
443 Function Import-CSharpUtil {
444 [CmdletBinding()]
445 param (
446 [Parameter(Mandatory)]
447 [string[]]
448 $Name
449 )
450
451 Import-PowerShellUtil -Name Ansible.ModuleUtils.AddType.psm1
452
453 $isBasicUtil = $false
454 $csharpModules = foreach ($moduleName in $Name) {
455 $scriptInfo = Get-AnsibleScript -Name $moduleName
456
457 if ($scriptInfo.ShouldConstrain) {
458 throw "C# module util '$Name' is not trusted and cannot be loaded."
459 }
460 if ($moduleName -eq 'Ansible.Basic.cs') {
461 $isBasicUtil = $true
462 }
463
464 $scriptInfo.Script
465 }
466
467 $fakeModule = [PSCustomObject]@{
468 Tmpdir = $Script:AnsibleTempPath
469 }
470 $warningFunc = [PSScriptMethod]::new('Warn', {
471 param($message)
472 $Script:AnsibleWrapperWarnings.Add($message)
473 })
474 $fakeModule.PSObject.Members.Add($warningFunc)
475 Add-CSharpType -References $csharpModules -AnsibleModule $fakeModule
476
477 if ($isBasicUtil) {
478 # Ansible.Basic.cs is a special case where we need to provide it
479 # with the wrapper warnings list so it injects it into the result.
480 [Ansible.Basic.AnsibleModule]::_WrapperWarnings = $Script:AnsibleWrapperWarnings
481 }
482 }
483
484 Function Import-SignedHashList {
485 [CmdletBinding()]
486 param (
487 [Parameter(Mandatory, ValueFromPipeline)]
488 [string]
489 $Name
490 )
491
492 process {
493 try {
494 # We skip the hash check to ensure we verify based on the
495 # authenticode signature and not whether it's trusted by an
496 # existing signed hash list.
497 $scriptInfo = Get-AnsibleScript -Name $Name -SkipHashCheck
498 if ($scriptInfo.ShouldConstrain) {
499 throw "script is not signed or not trusted to run."
500 }
501
502 $hashListAst = [Parser]::ParseInput(
503 $scriptInfo.Script,
504 $Name,
505 [ref]$null,
506 [ref]$null)
507 $manifestAst = $hashListAst.Find({ $args[0] -is [HashtableAst] }, $false)
508 if ($null -eq $manifestAst) {
509 throw "expecting a single hashtable in the signed manifest."
510 }
511
512 $out = $manifestAst.SafeGetValue()
513 if (-not $out.Contains('Version')) {
514 throw "expecting hash list to contain 'Version' key."
515 }
516 if ($out.Version -ne 1) {
517 throw "unsupported hash list Version $($out.Version), expecting 1."
518 }
519
520 if (-not $out.Contains('HashList')) {
521 throw "expecting hash list to contain 'HashList' key."
522 }
523
524 $out.HashList | ForEach-Object {
525 if ($_ -isnot [hashtable] -or -not $_.ContainsKey('Hash') -or $_.Hash -isnot [string] -or $_.Hash.Length -ne 64) {
526 throw "expecting hash list to contain hashtable with Hash key with a value of a SHA256 strings."
527 }
528
529 if ($_.Mode -eq 'Trusted') {
530 $null = $Script:AnsibleTrustedHashList.Add($_.Hash)
531 }
532 elseif ($_.Mode -eq 'Unsupported') {
533 # Allows us to provide a better error when trying to run
534 # something in CLM that is marked as unsupported.
535 $null = $Script:AnsibleUnsupportedHashList.Add($_.Hash)
536 }
537 else {
538 throw "expecting hash list entry for $($_.Hash) to contain a mode of 'Trusted' or 'Unsupported' but got '$($_.Mode)'."
539 }
540 }
541 }
542 catch {
543 $_.ErrorDetails = [ErrorDetails]::new("Failed to process signed manifest '$Name': $_")
544 $PSCmdlet.WriteError($_)
545 }
546 }
547 }
548
549 Function New-TempAnsibleFile {
550 [OutputType([string])]
551 [CmdletBinding()]
552 param (
553 [Parameter(Mandatory)]
554 [string]
555 $FileName,
556
557 [Parameter(Mandatory)]
558 [string]
559 $Content
560 )
561
562 $name = [Path]::GetFileNameWithoutExtension($FileName)
563 $ext = [Path]::GetExtension($FileName)
564 $newName = "$($name)-$([Guid]::NewGuid())$ext"
565
566 $path = Join-Path -Path $Script:AnsibleTempPath $newName
567 Set-WinPSDefaultFileEncoding
568 [File]::WriteAllText($path, $Content, [UTF8Encoding]::new($false))
569
570 $path
571 }
572
573 Function Set-WinPSDefaultFileEncoding {
574 [CmdletBinding()]
575 param ()
576
577 # WinPS defaults to the locale encoding when loading a script from the
578 # file path but in Ansible we expect it to always be UTF-8 without a
579 # BOM. This lazily sets an internal field so pwsh reads it as UTF-8.
580 # If we don't do this then scripts saved as UTF-8 on the Ansible
581 # controller will not run as expected.
582 if ($PSVersionTable.PSVersion -lt '6.0' -and -not $Script:AnsibleClrFacadeSet) {
583 $clrFacade = [PSObject].Assembly.GetType('System.Management.Automation.ClrFacade')
584 $defaultEncodingField = $clrFacade.GetField('_defaultEncoding', [BindingFlags]'NonPublic, Static')
585 $defaultEncodingField.SetValue($null, [UTF8Encoding]::new($false))
586 $Script:AnsibleClrFacadeSet = $true
587 }
588 }
589
590 Function Write-AnsibleErrorJson {
591 [CmdletBinding()]
592 param (
593 [Parameter(Mandatory)]
594 [ErrorRecord]
595 $ErrorRecord,
596
597 [Parameter()]
598 [string]
599 $Message = "failure during exec_wrapper"
600 )
601
602 $exception = @(
603 "$ErrorRecord"
604 "$($ErrorRecord.InvocationInfo.PositionMessage)"
605 "+ CategoryInfo : $($ErrorRecord.CategoryInfo)"
606 "+ FullyQualifiedErrorId : $($ErrorRecord.FullyQualifiedErrorId)"
607 ""
608 "ScriptStackTrace:"
609 "$($ErrorRecord.ScriptStackTrace)"
610
611 if ($ErrorRecord.Exception.StackTrace) {
612 "$($ErrorRecord.Exception.StackTrace)"
613 }
614 ) -join ([Environment]::NewLine)
615
616 @{
617 failed = $true
618 msg = "${Message}: $ErrorRecord"
619 exception = $exception
620 } | ConvertTo-Json -Compress
621 $host.SetShouldExit(1)
622 }
623
624 Function Write-PowerShellClixmlStderr {
625 [CmdletBinding()]
626 param (
627 [Parameter(Mandatory)]
628 [AllowEmptyString()]
629 [string]
630 $Output
631 )
632
633 if (-not $Output) {
634 return
635 }
636
637 # -EncodedCommand in WinPS will output CLIXML to stderr. This attempts to parse
638 # it into a human readable format otherwise it'll just output the raw CLIXML.
639 $wroteStderr = $false
640 if ($Output.StartsWith('#< CLIXML')) {
641 $clixml = $Output -split "\r?\n"
642 if ($clixml.Count -eq 2) {
643 try {
644 # PSSerialize.Deserialize doesn't tell us what streams each record
645 # is for so we get the S attribute manually.
646 $streams = @(([xml]$clixml[1]).Objs.GetEnumerator() | ForEach-Object { $_.S })
647 $objects = @([PSSerializer]::Deserialize($clixml[1]))
648
649 for ($i = 0; $i -lt $objects.Count; $i++) {
650 $msg = $objects[$i]
651 if ($msg -isnot [string] -or $streams.Length -le $i) {
652 continue
653 }
654
655 # Doesn't use TrimEnd() so it only removes the last newline
656 if ($msg.EndsWith([Environment]::NewLine)) {
657 $msg = $msg.Substring(0, $msg.Length - [Environment]::NewLine.Length)
658 }
659 $stream = $streams[$i]
660 switch ($stream) {
661 'error' { $host.UI.WriteErrorLine($msg) }
662 'debug' { $host.UI.WriteDebugLine($msg) }
663 'verbose' { $host.UI.WriteVerboseLine($msg) }
664 'warning' { $host.UI.WriteWarningLine($msg) }
665 }
666 }
667 $wroteStderr = $true
668 }
669 catch {
670 $null = $_
671 }
672 }
673 }
674 if (-not $wroteStderr) {
675 $host.UI.WriteErrorLine($Output.TrimEnd())
676 }
677 }
678
679 # To handle optional input for the incoming manifest and optional input to
680 # the subsequent action we optionally run this step in the begin or end
681 # block.
682 $jsonPipeline = $null
683 $actionPipeline = $null
684 $setupManifest = {
685 [CmdletBinding()]
686 param (
687 [Parameter()]
688 [switch]
689 $ExpectingInput
690 )
691
692 if ($jsonPipeline) {
693 $Script:AnsibleManifest = $jsonPipeline.End()[0]
694 $jsonPipeline.Dispose()
695 $jsonPipeline = $null
696 }
697 else {
698 $Script:AnsibleManifest = $Manifest
699 }
700
701 if ($Script:AnsibleShouldConstrain) {
702 $Script:AnsibleManifest.signed_hashlist | Import-SignedHashList
703 }
704
705 $actionInfo = Get-NextAnsibleAction
706 $actionParams = $actionInfo.Parameters
707
708 if ($ActionParameters) {
709 foreach ($prop in $ActionParameters.PSObject.Properties) {
710 $actionParams[$prop.Name] = $prop.Value
711 }
712 }
713
714 $actionPipeline = { & $actionInfo.ScriptBlock @actionParams }.GetSteppablePipeline()
715 $actionPipeline.Begin($ExpectingInput)
716 if (-not $ExpectingInput) {
717 $null = $actionPipeline.Process()
718 }
719 }
720
721 try {
722 if ($Manifest) {
723 # If the manifest was provided through the parameter, we can start the
724 # action pipeline and all subsequent input (if any) will be sent to the
725 # action.
726 # It is important that $setupManifest is called by dot sourcing or
727 # else the pipelines started in it loose access to all parent scopes.
728 # https://github.com/PowerShell/PowerShell/issues/17868
729 . $setupManifest -ExpectingInput:$MyInvocation.ExpectingInput
730 }
731 else {
732 # Otherwise the first part of the input is the manifest json with the
733 # chance for extra data afterwards.
734 $jsonPipeline = { ConvertFrom-Json }.GetSteppablePipeline()
735 $jsonPipeline.Begin($true)
736 }
737 }
738 catch {
739 Write-AnsibleErrorJson -ErrorRecord $_
740 }
741 }
742
743 process {
744 if ($respawnPipeline) {
745 $null = $respawnPipeline.Process($InputObject)
746 return
747 }
748
749 $inputStream = $outputStream = $gzipStream = $null
750 try {
751 if ($actionPipeline) {
752 # We received our manifest and started the action pipeline, redirect
753 # all further input to that pipeline.
754 $null = $actionPipeline.Process($InputObject)
755 }
756 elseif ([string]::Equals($InputObject, "`0`0`0`0")) {
757 # Special marker used to indicate all subsequent input is for the
758 # action. Setup that pipeline and finalise the manifest.
759 . $setupManifest -ExpectingInput
760 }
761 elseif ($jsonPipeline) {
762 # Data is for the JSON manifest, decode if needed.
763 if ($EncodeInputOutput) {
764 $jsonPipeline.Process([Encoding]::UTF8.GetString([Convert]::FromBase64String($InputObject)))
765 }
766 elseif ($DecompressInput) {
767 $inputStream = [MemoryStream]::new([Convert]::FromBase64String($InputObject))
768 $gzipStream = [GZipStream]::new($inputStream, [CompressionMode]::Decompress)
769 $outputStream = [MemoryStream]::new()
770 $gzipStream.CopyTo($outputStream)
771
772 $jsonPipeline.Process([Encoding]::UTF8.GetString($outputStream.ToArray()))
773 }
774 else {
775 $jsonPipeline.Process($InputObject)
776 }
777 }
778 }
779 catch {
780 Write-AnsibleErrorJson -ErrorRecord $_
781 }
782 finally {
783 if ($inputStream) { $inputStream.Dispose() }
784 if ($outputStream) { $outputStream.Dispose() }
785 if ($gzipStream) { $gzipStream.Dispose() }
786 }
787 }
788
789 end {
790 if ($respawnPipeline) {
791 $respawnPipeline.End()
792 return
793 }
794
795 try {
796 if ($jsonPipeline) {
797 # Only manifest input was received, process it now and start the
798 # action pipeline with no input being provided.
799 . $setupManifest
800 }
801
802 $out = $actionPipeline.End()
803 if ($EncodeInputOutput) {
804 [Convert]::ToBase64String([Encoding]::UTF8.GetBytes($out))
805 }
806 else {
807 $out
808 }
809 }
810 catch {
811 Write-AnsibleErrorJson -ErrorRecord $_
812 }
813 finally {
814 $actionPipeline.Dispose()
815 if ($Script:AnsibleTempScripts) {
816 Remove-Item -LiteralPath $Script:AnsibleTempScripts -Force -ErrorAction Ignore
817 }
818 }
819 }