Debian Codegraph @

lib/ansible/executor/powershell/become_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 #AnsibleRequires -CSharpUtil Ansible.Become
5
6 using namespace System.Collections
7 using namespace System.Diagnostics
8 using namespace System.IO
9 using namespace System.Management.Automation
10 using namespace System.Management.Automation.Security
11 using namespace System.Net
12 using namespace System.Text
13
14 [CmdletBinding()]
15 param (
16 [Parameter()]
17 [AllowEmptyString()]
18 [string]
19 $BecomeUser,
20
21 [Parameter()]
22 [SecureString]
23 $BecomePassword,
24
25 [Parameter()]
26 [string]
27 $LogonType = 'Interactive',
28
29 [Parameter()]
30 [string]
31 $LogonFlags = 'WithProfile'
32 )
33
34 Import-CSharpUtil -Name 'Ansible.AccessToken.cs', 'Ansible.Become.cs', 'Ansible.Process.cs'
35
36 # We need to set password to the value of NullString so a null password is
37 # preserved when crossing the .NET boundary. If we pass $null it will
38 # automatically be converted to "" and we need to keep the distinction for
39 # accounts that don't have a password and when someone wants to become without
40 # knowing the password.
41 $password = [NullString]::Value
42 if ($null -ne $BecomePassword) {
43 $password = [NetworkCredential]::new("", $BecomePassword).Password
44 }
45
46 $executable = if ($PSVersionTable.PSVersion -lt '6.0') {
47 'powershell.exe'
48 }
49 else {
50 'pwsh.exe'
51 }
52 $executablePath = Join-Path -Path $PSHome -ChildPath $executable
53
54 $actionInfo = Get-AnsibleExecWrapper -EncodeInputOutput
55 $bootstrapManifest = ConvertTo-Json -InputObject @{
56 n = "exec_wrapper-become-$([Guid]::NewGuid()).ps1"
57 s = $actionInfo.ScriptInfo.Script
58 p = $actionInfo.Parameters
59 } -Depth 99 -Compress
60
61 # NB: CreateProcessWithTokenW commandline maxes out at 1024 chars, must
62 # bootstrap via small wrapper to invoke the exec_wrapper. Strings are used to
63 # avoid sanity tests like aliases and spaces.
64 [string]$command = @'
65 $m=foreach($i in $input){
66 if([string]::Equals($i,"`0`0`0`0")){break}
67 $i
68 }
69 $m=$m|ConvertFrom-Json
70 $p=@{}
71 foreach($o in $m.p.PSObject.Properties){$p[$o.Name]=$o.Value}
72 '@
73
74 if ([SystemPolicy]::GetSystemLockdownPolicy() -eq 'Enforce') {
75 # If we started in CLM we need to execute the script from a file so that
76 # PowerShell validates our exec_wrapper is trusted and will run in FLM.
77 $command += @'
78 $n=Join-Path $env:TEMP $m.n
79 $null=New-Item $n -Value $m.s -Type File -Force
80 try{$input|&$n @p}
81 finally{if(Test-Path -LiteralPath $n){Remove-Item -LiteralPath $n -Force}}
82 '@
83 }
84 else {
85 # If we started in FLM we pass the script through stdin and execute in
86 # memory.
87 $command += @'
88 $c=[System.Management.Automation.Language.Parser]::ParseInput($m.s,$m.n,[ref]$null,[ref]$null).GetScriptBlock()
89 $input|&$c @p
90 '@
91 }
92
93 # Strip out any leading or trailing whitespace and remove empty lines.
94 $command = @(
95 ($command -split "\r?\n") |
96 ForEach-Object { $_.Trim() } |
97 Where-Object { -not [string]::IsNullOrWhiteSpace($_) }
98 ) -join "`n"
99
100 $encCommand = [Convert]::ToBase64String([Encoding]::Unicode.GetBytes($command))
101 # Shortened version of '-NonInteractive -NoProfile -ExecutionPolicy Bypass -EncodedCommand $encCommand'
102 $commandLine = "$executable -noni -nop -ex Bypass -e $encCommand"
103 $result = [Ansible.Become.BecomeUtil]::CreateProcessAsUser(
104 $BecomeUser,
105 $password,
106 $LogonFlags,
107 $LogonType,
108 $executablePath,
109 $commandLine,
110 $env:SystemRoot,
111 $null,
112 "$bootstrapManifest`n`0`0`0`0`n$($actionInfo.InputData)")
113
114 $stdout = $result.StandardOut
115 try {
116 $stdout = [Encoding]::UTF8.GetString([Convert]::FromBase64String($stdout))
117 }
118 catch [FormatException] {
119 # output wasn't Base64, ignore as it may contain an error message we want to pass to Ansible
120 $null = $_
121 }
122
123 $Host.UI.WriteLine($stdout)
124 Write-PowerShellClixmlStderr -Output $result.StandardError
125 $Host.SetShouldExit($result.ExitCode)