Debian Codegraph @

ansible_collections/community/windows/plugins/modules/win_pssession_configuration.ps1

raw
1 #!powershell
2
3 # Copyright: (c) 2020, Brian Scholer <@briantist>
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 #AnsibleRequires -CSharpUtil Ansible.Basic
7 #AnsibleRequires -CSharpUtil Ansible.AccessToken
8
9 $type = @{
10 guid = [Func[[Object], [System.Guid]]] {
11 [System.Guid]::ParseExact($args[0].Trim([char[]]'}{').Replace('-', ''), 'N')
12 }
13 version = [Func[[Object], [System.Version]]] {
14 [System.Version]::Parse($args[0])
15 }
16 int64 = [Func[[Object], [System.Int64]]] {
17 [System.Int64]::Parse($args[0])
18 }
19 double = [Func[[Object], [System.Double]]] {
20 [System.Double]::Parse($args[0])
21 }
22 }
23
24 $pssc_options = @{
25 guid = @{ type = $type.guid }
26 schema_version = @{ type = $type.version }
27 author = @{ type = 'str' }
28 description = @{ type = 'str' }
29 company_name = @{ type = 'str' }
30 copyright = @{ type = 'str' }
31 session_type = @{ type = 'str' ; choices = @('default', 'empty', 'restricted_remote_server') }
32 transcript_directory = @{ type = 'path' }
33 run_as_virtual_account = @{ type = 'bool' }
34 run_as_virtual_account_groups = @{ type = 'list' ; elements = 'str' }
35 mount_user_drive = @{ type = 'bool' }
36 user_drive_maximum_size = @{ type = $type.int64 }
37 group_managed_service_account = @{ type = 'str' }
38 scripts_to_process = @{ type = 'list' ; elements = 'str' }
39 role_definitions = @{ type = 'dict' }
40 required_groups = @{ type = 'dict' }
41 language_mode = @{ type = 'str' ; choices = @('no_language', 'restricted_language', 'constrained_language', 'full_language') }
42 execution_policy = @{ type = 'str' ; choices = @('default', 'remote_signed', 'restricted', 'undefined', 'unrestricted') }
43 powershell_version = @{ type = $type.version }
44 modules_to_import = @{ type = 'list' ; elements = 'raw' }
45 visible_aliases = @{ type = 'list' ; elements = 'str' }
46 visible_cmdlets = @{ type = 'list' ; elements = 'raw' }
47 visible_functions = @{ type = 'list' ; elements = 'raw' }
48 visible_external_commands = @{ type = 'list' ; elements = 'str' }
49 alias_definitions = @{ type = 'dict' }
50 function_definitions = @{ type = 'dict' }
51 variable_definitions = @{ type = 'list' ; elements = 'dict' }
52 environment_variables = @{ type = 'dict' }
53 types_to_process = @{ type = 'list' ; elements = 'path' }
54 formats_to_process = @{ type = 'list' ; elements = 'path' }
55 assemblies_to_load = @{ type = 'list' ; elements = 'str' }
56 }
57
58 $session_configuration_options = @{
59 name = @{ type = 'str' ; required = $true }
60 processor_architecure = @{ type = 'str' ; choices = @('amd64', 'x86') }
61 access_mode = @{ type = 'str' ; choices = @('disabled', 'local', 'remote') }
62 use_shared_process = @{ type = 'bool' }
63 thread_apartment_state = @{ type = 'str' ; choices = @('mta', 'sta') }
64 thread_options = @{ type = 'str' ; choices = @('default', 'reuse_thread', 'use_current_thread', 'use_new_thread') }
65 startup_script = @{ type = 'path' }
66 maximum_received_data_size_per_command_mb = @{ type = $type.double }
67 maximum_received_object_size_mb = @{ type = $type.double }
68 security_descriptor_sddl = @{ type = 'str' }
69 run_as_credential_username = @{ type = 'str' }
70 run_as_credential_password = @{ type = 'str' ; no_log = $true }
71 }
72
73 $behavior_options = @{
74 state = @{ type = 'str' ; choices = @('present', 'absent') ; default = 'present' }
75 lenient_config_fields = @{ type = 'list' ; elements = 'str' ; default = @('guid', 'author', 'company_name', 'copyright', 'description') }
76 async_timeout = @{ type = 'int' ; default = 300 }
77 async_poll = @{ type = 'int' ; default = 1 }
78 <#
79 # TODO: possible future enhancement to wait for existing connections to finish
80 # Existing connections can be found with:
81 # Get-WSManInstance -ComputerName localhost -ResourceURI shell -Enumerate
82
83 existing_connection_timeout_seconds = @{ type = 'int' ; default = 0 }
84 existing_connection_timeout_interval_ms = @{ type = 'int' ; default = 500 }
85 existing_connection_timeout_action = @{ type = 'str' ; choices = @('terminate', 'fail') ; default = 'terminate' }
86 existing_connection_wait_states = @{ type = 'list' ; elements = 'str' ; default = @('connected') }
87 #>
88 }
89
90 $spec = @{
91 options = $pssc_options + $session_configuration_options + $behavior_options
92 required_together = @(
93 , @('run_as_credential_username', 'run_as_credential_password')
94 )
95 supports_check_mode = $true
96 }
97
98 $module = [Ansible.Basic.AnsibleModule]::Create($args, $spec)
99
100
101 function Import-PowerShellDataFileLegacy {
102 <#
103 .SYNOPSIS
104 A pre-PowerShell 5.0 version of Import-PowerShellDataFile
105
106 .DESCRIPTION
107 Safely imports a PowerShell Data file in PowerShell versions before 5.0
108 when the built-in command was introduced. Non-literal Path support is not included.
109 #>
110 [CmdletBinding()]
111 [OutputType([hashtable])]
112 [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingInvokeExpression', '', Justification = 'Required to process PS data file')]
113 param(
114 [Parameter(Mandatory = $true)]
115 [Alias('Path')]
116 [String]
117 $LiteralPath
118 )
119
120 End {
121 $astloader = [System.Management.Automation.Language.Parser]::ParseFile($LiteralPath, [ref] $null , [ref] $null)
122 $ht = $astloader.Find({ param($ast)
123 $ast -is [System.Management.Automation.Language.HashtableAst]
124 }, $false)
125
126 if (-not $ht) {
127 throw "Invalid PowerShell Data File."
128 }
129
130 # SafeGetValue() is not available before PowerShell 5 anyway, so we'll do the unsafe load and just execute it.
131 # The only files we're loading are ones we generated from options, or ones that were already attached to existing
132 # session configurations.
133 # $ht.SafeGetValue()
134 Invoke-Expression -Command $ht.Extent.Text
135 }
136 }
137
138 if (-not (Get-Command -Name 'Microsoft.PowerShell.Utility\Import-PowerShellDataFile' -ErrorAction SilentlyContinue)) {
139 New-Alias -Name 'Import-PowerShellDataFile' -Value 'Import-PowerShellDataFileLegacy'
140 }
141
142 function ConvertFrom-SnakeCase {
143 [CmdletBinding()]
144 [OutputType([String])]
145 param(
146 [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
147 [String]
148 $SnakedString
149 )
150
151 Process {
152 [regex]::Replace($SnakedString, '^_?.|_.', { param($m) $m.Value.TrimStart('_').ToUpperInvariant() })
153 }
154 }
155
156 function ConvertFrom-AnsibleOption {
157 [CmdletBinding()]
158 [OutputType([System.Collections.IDictionary])]
159 param(
160 [Parameter(Mandatory = $true)]
161 [System.Collections.IDictionary]
162 $Params ,
163
164 [Parameter(Mandatory = $true)]
165 [hashtable]
166 $OptionSet
167 )
168
169 End {
170 $ret = @{}
171 foreach ($option in $OptionSet.GetEnumerator()) {
172 $raw_name = $option.Name
173 switch -Wildcard ($raw_name) {
174 'run_as_credential_*' {
175 $raw_name = $raw_name -replace '_[^_]+$'
176 $name = ConvertFrom-SnakeCase -SnakedString $raw_name
177 if (-not $ret.Contains($name)) {
178 $un = $Params["${raw_name}_username"]
179 if ($un) {
180 $secpw = ConvertTo-SecureString -String $Params["${raw_name}_password"] -AsPlainText -Force
181 $value = New-Object -TypeName PSCredential -ArgumentList $un, $secpw
182 $ret[$name] = $value
183 }
184 }
185 break
186 }
187
188 default {
189 $value = $Params[$raw_name]
190 if ($null -ne $value) {
191 if ($option.Value.choices) {
192 # the options that have choices have them listed in snake_case versions of their real values
193 $value = ConvertFrom-SnakeCase -SnakedString $value
194 }
195 $name = ConvertFrom-SnakeCase -SnakedString $raw_name
196 $ret[$name] = $value
197 }
198 }
199 }
200 }
201
202 $ret
203 }
204 }
205
206 function Write-GeneratedSessionConfiguration {
207 [CmdletBinding()]
208 [OutputType([System.IO.FileInfo])]
209 param(
210 [Parameter(Mandatory = $true)]
211 [System.Collections.IDictionary]
212 $ParameterSet ,
213
214 [Parameter()]
215 [String]
216 $OutFile
217 )
218
219 End {
220 $file = if ($OutFile) {
221 $OutFile
222 }
223 else {
224 [System.IO.Path]::GetTempFileName()
225 }
226
227 $file = $file -replace '(?<!\.pssc)$', '.pssc'
228 New-PSSessionConfigurationFile -Path $file @ParameterSet
229 [System.IO.FileInfo]$file
230 }
231 }
232
233 function Compare-ConfigFile {
234 <#
235 .SYNOPSIS
236 This function compares the existing config file to the desired
237
238 .DESCRIPTION
239 We'll load the contents of both the desired and existing config, remove fields that shouldn't be
240 compared, then generate a new config based on the existing and compare those files.
241
242 This could be done as a direct file compare, without loading the contents as objects.
243 The primary reasons to do it this slightly more complicated way are:
244
245 - To ignore GUID as a value that matters: if you don't supply it a new one is generated for you,
246 but PSSessionConfigurations don't use this for anything; it's just metadata. If you supply one,
247 we want to compare it. If you don't, we shouldn't count the "mismatch" against you though.
248
249 - To normalize the existing file based on the following stuff so we avoid unnecessary changes:
250
251 - A file compare either has to be case insensitive (won't catch changes in values) or case sensitive
252 (will may force changes on differences that don't matter, like case differences in key values)
253
254 - A file compare will see changes on whitespace and line ending differences; although those could be
255 accounted for in other ways, this method handles them.
256
257 - A file compare will see changes on other non-impacting syntax style differences like indentation.
258 #>
259 [CmdletBinding()]
260 [OutputType([bool])]
261 param(
262 [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
263 [System.IO.FileInfo]
264 $ConfigFilePath ,
265
266 [Parameter(Mandatory = $true)]
267 [System.IO.FileInfo]
268 $NewConfigFile ,
269
270 [Parameter(Mandatory = $true)]
271 [System.Collections.IDictionary]
272 $Params ,
273
274 [Parameter()]
275 [String[]]
276 $UseExistingIfMissing
277 )
278
279 Process {
280 $desired_config = $NewConfigFile.FullName
281
282 $existing_content = Import-PowerShellDataFile -LiteralPath $ConfigFilePath.FullName
283 $desired_content = Import-PowerShellDataFile -LiteralPath $desired_config
284
285 $module.Diff.before.pscc = $existing_content
286 $module.Diff.after.pscc = $desired_content
287
288 $regen = $false
289 foreach ($ignorable_param in $UseExistingIfMissing) {
290 # here we're checking for the parameters that shouldn't be compared if they are in the existing
291 # config, but missing in the desired config. To account for this, we copy the value from the
292 # existing into the desired so that when we regenerate it, it'll match the existing if there
293 # aren't other changes.
294 if (-not $Params.Contains($ignorable_param) -and $existing_content.Contains($ignorable_param)) {
295 $desired_content[$ignorable_param] = $existing_content[$ignorable_param]
296 $regen = $true
297 }
298 }
299
300 # re-write and read the desired config file
301 if ($regen) {
302 $NewConfigFile.Delete()
303 $desired_config = Write-GeneratedSessionConfiguration -ParameterSet $desired_content -OutFile $desired_config
304 }
305
306 $desired_content = Get-Content -Raw -LiteralPath $desired_config
307
308 # re-write/import the existing one too to get a pristine version
309 # this will account for unimporant case differences, comments, whitespace, etc.
310 $pristine_config = Write-GeneratedSessionConfiguration -ParameterSet $existing_content
311 $existing_content = Get-Content -Raw -LiteralPath $pristine_config
312
313 # with all this de/serializing out of the way we can just do a simple case-sensitive string compare
314 $desired_content -ceq $existing_content
315
316 Remove-Item -LiteralPath $pristine_config -Force -ErrorAction SilentlyContinue
317 }
318 }
319
320 function Compare-SessionOption {
321 <#
322 .DESCRIPTION
323 This function is used for comparing the session options that don't get set in the config file.
324 This _should_ have been straightforward for anything other than RunAsCredential, except that for
325 some godforesaken reason a smattering of settings have names that differ from their parameter name.
326
327 This list is defined internally in PowerShell here:
328 https://git.io/JfUk7
329
330 #>
331 [CmdletBinding()]
332 [OutputType([bool])]
333 param(
334 [Parameter(Mandatory = $true)]
335 [System.Collections.IDictionary]
336 $DesiredOptions ,
337
338 [Parameter(Mandatory = $true)]
339 [Object]
340 $ExistingOptions
341 )
342
343 End {
344 $optnamer = @{
345 ThreadApartmentState = 'pssessionthreadapartmentstate'
346 ThreadOptions = 'pssessionthreadoptions'
347 MaximumReceivedDataSizePerCommandMb = 'PSMaximumReceivedDataSizePerCommandMB'
348 MaximumReceivedObjectSizeMb = 'PSMaximumReceivedObjectSizeMB'
349 } | Add-Member -MemberType ScriptMethod -Name GetValueOrKey -Value {
350 param($key)
351
352 $val = $this[$key]
353 if ($null -eq $val) {
354 return $key
355 }
356 else {
357 return $val
358 }
359 } -Force -PassThru
360
361 # Determine diffs in diff mode
362 # AccessMode is not a property itself, it's a switch for the Register/Set command which changes some other config properties.
363 # Remove it from Diff because it cannot be determined...
364 $ignore_options_in_diff = @('AccessMode', 'RunAsCredential')
365
366 $smatch = $true
367 $after = @{}
368 $before = @{}
369
370 foreach ($opt in $session_configuration_options.GetEnumerator()) {
371 if ($opt.Name -in $ignore_options_in_diff) { continue }
372 $key = ConvertFrom-SnakeCase -SnakedString $optnamer.GetValueOrKey($opt.Name)
373 $before.Add($key, $ExistingOptions.($key))
374 }
375 $after = $before.Clone()
376
377 foreach ($opt in $DesiredOptions.GetEnumerator()) {
378 if ($opt.Name -in $ignore_options_in_diff) { continue }
379 $key = ConvertFrom-SnakeCase -SnakedString $optnamer.GetValueOrKey($opt.Name)
380 $after[$key] = $opt.Value
381
382 $smatch = $smatch -and (
383 $ExistingOptions.($optnamer.GetValueOrKey($opt.Name)) -ceq $opt.Value
384 )
385 if (-not $smatch -and -not $module.DiffMode) {
386 break
387 }
388 }
389
390 $module.Diff.before.session = $before
391 $module.Diff.after.session = $after
392
393 if ($DesiredOptions.Contains('RunAsCredential')) {
394 # since we can't retrieve/compare password, a change must always be made if a cred is specified
395 return $false
396 }
397
398 return $smatch
399 }
400 }
401
402 <#
403 For use with possible future enhancement.
404 Right now the biggest challenges to this are:
405 - Ansible's connection itself: the number doesn't go to 0 while we're here running
406 and waiting for it. I thought being async it would disappear but either that's not
407 the case or it's taking too long to do so.
408
409 - I have not found a reliable way to determine which WinRM connection is the one used for
410 the Ansible connection. Over psrp we can use Get-PSSession -ComputerName but that won't
411 work for the winrm connection plugin.
412
413 - Connections seem to take time to disappear. In tests when trying to start time-limited
414 sessions, like:
415 icm -computername . -scriptblock { Start-Sleep -Seconds 30 } -AsJob
416 After the time elapses the connection lingers for a little while after. Should be ok but
417 does add some challenges to writing tests.
418
419 - Checking for instances of the shell resource looks reliable, but I'm not yet certain
420 if it captures all WinRM connections, like CIM connections. Still would be better than
421 nothing.
422 #>
423 # function Wait-WinRMConnection {
424 # <#
425 # .SYNOPSIS
426 # Waits for existing WinRM connections to finish
427
428 # .DESCRIPTION
429 # Finds existing WinRM connections that are in a set of states (configurable), and waits for them
430 # to disappear, or times out.
431 # #>
432 # [CmdletBinding()]
433 # param(
434 # [Parameter(Mandatory=$true)]
435 # [Ansible.Basic.AnsibleModule]
436 # $Module
437 # )
438
439 # End {
440 # $action = $Module.Params.existing_connection_timeout_action
441 # $states = $Module.Params.existing_connection_wait_states
442 # $timeout_ms = [System.Math]::Min(0, $Module.Params.existing_connection_timeout_seconds) * 1000
443 # $interval = [System.Math]::Max([System.Math]::Min(100, $Module.Params.existing_connection_timeout_interval_ms), $timeout_ms)
444
445 # # Would only with psrp
446 # $thiscon = Get-PSSession -ComputerName . | Select-Object -ExpandProperty InstanceId
447
448 # $sw = New-Object -TypeName System.Diagnostics.Stopwatch
449
450 # do {
451 # $connections = Get-WSManInstance -ComputerName localhost -ResourceURI shell -Enumerate |
452 # Where-Object -FilterScript {
453 # $states -contains $_.State -and (
454 # -not $thiscon -or
455 # $thiscon -ne $_.ShellId
456 # )
457 # }
458
459 # $sw.Start()
460 # Start-Sleep -Milliseconds $interval
461 # } while ($connections -and $sw.ElapsedMilliseconds -lt $timeout_ms)
462 # $sw.Stop()
463
464 # if ($connections -and $action -eq 'fail') {
465 # # somehow $connections.Count sometimes is blank (not 0) but I can't figure out how that's possible
466 # $Module.FailJson("$($connections.Count) remained after timeout.")
467 # }
468 # }
469 # }
470
471 $PSDefaultParameterValues = @{
472 '*-PSSessionConfiguration:Force' = $true
473 'ConvertFrom-AnsibleOption:Params' = $module.Params
474 'Wait-WinRMConnection:Module' = $module
475 }
476
477 $opt_pssc = ConvertFrom-AnsibleOption -OptionSet $pssc_options
478 $opt_session = ConvertFrom-AnsibleOption -OptionSet $session_configuration_options
479
480 $existing = Get-PSSessionConfiguration -Name $opt_session.Name -ErrorAction SilentlyContinue
481
482 try {
483 $module.Diff.before = @{ session = $null; pscc = $null; }
484 $module.Diff.after = @{ session = $null; pscc = $null; }
485
486 if ($opt_pssc.Count) {
487 # config file options were passed to the module, so generate a config file from those
488 $desired_config = Write-GeneratedSessionConfiguration -ParameterSet $opt_pssc
489 }
490 if ($existing) {
491 # the endpoint is registered
492 if ($existing.ConfigFilePath -and (Test-Path -LiteralPath $existing.ConfigFilePath)) {
493 # the registered endpoint uses a config file
494 if ($desired_config) {
495 # a desired config file exists, so compare it to the existing one
496 $content_match = $existing |
497 Compare-ConfigFile -NewConfigFile $desired_config -Params $opt_pssc -UseExistingIfMissing (
498 $module.Params.lenient_config_fields | ConvertFrom-SnakeCase
499 )
500 }
501 else {
502 # existing endpoint has a config file but no config file options were passed, so there is no match
503 $content_match = $false
504 }
505 }
506 else {
507 # existing endpoint doesn't use a config file, so it's a match if there are also no config options passed
508 $content_match = $opt_pssc.Count -eq 0
509 }
510
511 $session_match = Compare-SessionOption -DesiredOptions $opt_session -ExistingOptions $existing
512 }
513
514 $state = $module.Params.state
515
516 $create = $state -eq 'present' -and (-not $existing -or -not $content_match)
517 $remove = $existing -and ($state -eq 'absent' -or -not $content_match)
518 $session_change = -not $session_match -and $state -ne 'absent'
519
520 $module.Result.changed = $create -or $remove -or $session_change
521
522 # In this module, we pre-emptively remove the session configuratin if there's any change
523 # in the config file options, and then re-register later if needed.
524 # But if the RunAs credential is wrong, the register will fail, and since we already removed
525 # the existing one, it will be gone.
526 #
527 # So let's ensure we can actually use the credential by logging on with TokenUtil,
528 # that way we can fail before touching the existing config.
529 if ($opt_session.Contains('RunAsCredential')) {
530 $cred = $opt_session.RunAsCredential
531 $username = $cred.Username
532 $domain = $null
533 if ($username.Contains('\')) {
534 $domain, $username = $username.Split('\')
535 }
536 try {
537 $handle = [Ansible.AccessToken.TokenUtil]::LogonUser($username, $domain, $cred.GetNetworkCredential().Password, 'Network', 'Default')
538 $handle.Dispose()
539 }
540 catch {
541 $module.FailJson("Could not validate RunAs Credential: $($_.Exception.Message)", $_)
542 }
543 }
544
545 if (-not $module.CheckMode) {
546 if ($remove) {
547 # Wait-WinRMConnection
548 $null = Unregister-PSSessionConfiguration -Name $opt_session.Name
549 }
550
551 if ($create) {
552 if ($desired_config) {
553 $opt_session.Path = $desired_config
554 }
555 # Wait-WinRMConnection
556 $null = Register-PSSessionConfiguration @opt_session
557 }
558 elseif ($session_change) {
559 $psso = $opt_session
560 # Wait-WinRMConnection
561 $null = Set-PSSessionConfiguration @psso
562 }
563 }
564 }
565 catch [System.Management.Automation.ParameterBindingException] {
566 $e = $_
567 if ($e.Exception.ErrorId -eq 'NamedParameterNotFound') {
568 $psv = $PSVersionTable.PSVersion.ToString(2)
569 $param = $e.Exception.ParameterName
570 $cmd = $e.InvocationInfo.MyCommand.Name
571 $message = "Parameter '$param' is not available for '$cmd' in PowerShell $psv."
572 }
573 else {
574 $message = "Unknown parameter binding error: $($e.Exception.Message)"
575 }
576
577 $module.FailJson($message, $e)
578 }
579 finally {
580 if ($desired_config) {
581 Remove-Item -LiteralPath $desired_config -Force -ErrorAction SilentlyContinue
582 }
583 }
584
585 $module.ExitJson()