Debian Codegraph @

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

raw
1 #!powershell
2
3 # Copyright: (c) 2018, Kevin Subileau (@ksubileau)
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 #Requires -Module Ansible.ModuleUtils.Legacy
7 #Requires -Module Ansible.ModuleUtils.SID
8
9 $ErrorActionPreference = "Stop"
10
11 # List of authentication methods as string. Used for parameter validation and conversion to integer flag, so order is important!
12 $auth_methods_set = @("none", "password", "smartcard", "both")
13 # List of session timeout actions as string. Used for parameter validation and conversion to integer flag, so order is important!
14 $session_timeout_actions_set = @("disconnect", "reauth")
15
16 $params = Parse-Args -arguments $args -supports_check_mode $true
17 $check_mode = Get-AnsibleParam -obj $params -name "_ansible_check_mode" -type "bool" -default $false
18 $diff_mode = Get-AnsibleParam -obj $params -name "_ansible_diff" -type "bool" -default $false
19
20 $name = Get-AnsibleParam -obj $params -name "name" -type "str" -failifempty $true
21 $state = Get-AnsibleParam -obj $params -name "state" -type "str" -default "present" -validateset "absent", "present", "enabled", "disabled"
22 $auth_method = Get-AnsibleParam -obj $params -name "auth_method" -type "str" -validateset $auth_methods_set
23 $order = Get-AnsibleParam -obj $params -name "order" -type "int"
24 $session_timeout = Get-AnsibleParam -obj $params -name "session_timeout" -type "int"
25 $session_timeout_action_params = @{
26 obj = $params
27 name = "session_timeout_action"
28 type = "str"
29 default = "disconnect"
30 validateset = $session_timeout_actions_set
31 }
32 $session_timeout_action = Get-AnsibleParam @session_timeout_action_params
33 $idle_timeout = Get-AnsibleParam -obj $params -name "idle_timeout" -type "int"
34 $allow_only_sdrts_servers = Get-AnsibleParam -obj $params -name "allow_only_sdrts_servers" -type "bool"
35 $user_groups = Get-AnsibleParam -obj $params -name "user_groups" -type "list"
36 $computer_groups = Get-AnsibleParam -obj $params -name "computer_groups" -type "list"
37
38 # Device redirections
39 $redirect_clipboard = Get-AnsibleParam -obj $params -name "redirect_clipboard" -type "bool"
40 $redirect_drives = Get-AnsibleParam -obj $params -name "redirect_drives" -type "bool"
41 $redirect_printers = Get-AnsibleParam -obj $params -name "redirect_printers" -type "bool"
42 $redirect_serial = Get-AnsibleParam -obj $params -name "redirect_serial" -type "bool"
43 $redirect_pnp = Get-AnsibleParam -obj $params -name "redirect_pnp" -type "bool"
44
45
46 Function ConvertTo-Sid {
47 [OutputType([string])]
48 [CmdletBinding()]
49 param (
50 [Parameter(Mandatory, ValueFromPipeline)]
51 [string[]]
52 $InputObject
53 )
54
55 process {
56 foreach ($user in $InputObject) {
57 # RDS uses the UPN format with the builtin domain but Convert-ToSID tries to look this up as a domain.
58 # Ensure the input value is in the Netlogon format to ensure BUILTIN is resolved properly
59 if ($user.EndsWith("@builtin", [System.StringComparison]::OrdinalIgnoreCase)) {
60 $user = "BUILTIN\$($user.Substring(0, $user.Length - 8))"
61 }
62
63 Convert-ToSID -account_name $user
64 }
65 }
66 }
67
68
69 function Get-CAP([string] $name) {
70 $cap_path = "RDS:\GatewayServer\CAP\$name"
71 $cap = @{
72 Name = $name
73 }
74
75 # Fetch CAP properties
76 Get-ChildItem -LiteralPath $cap_path | ForEach-Object { $cap.Add($_.Name, $_.CurrentValue) }
77 # Convert boolean values
78 $cap.Enabled = $cap.Status -eq 1
79 $cap.Remove("Status")
80 $cap.AllowOnlySDRTSServers = $cap.AllowOnlySDRTSServers -eq 1
81
82 # Convert multiple choices values
83 $cap.AuthMethod = $auth_methods_set[$cap.AuthMethod]
84 $cap.SessionTimeoutAction = $session_timeout_actions_set[$cap.SessionTimeoutAction]
85
86 # Fetch CAP device redirection settings
87 $cap.DeviceRedirection = @{}
88 Get-ChildItem -LiteralPath "$cap_path\DeviceRedirection" | ForEach-Object { $cap.DeviceRedirection.Add($_.Name, ($_.CurrentValue -eq 1)) }
89
90 # Fetch CAP user and computer groups in Down-Level Logon format
91 $cap.UserGroups = @(
92 Get-ChildItem -LiteralPath "$cap_path\UserGroups" |
93 Select-Object -ExpandProperty Name |
94 ForEach-Object { Convert-FromSID -sid (ConvertTo-Sid -InputObject $_) }
95 )
96 $cap.ComputerGroups = @(
97 Get-ChildItem -LiteralPath "$cap_path\ComputerGroups" |
98 Select-Object -ExpandProperty Name |
99 ForEach-Object { Convert-FromSID -sid (ConvertTo-Sid -InputObject $_) }
100 )
101
102 return $cap
103 }
104
105 function Set-CAPPropertyValue {
106 [CmdletBinding(SupportsShouldProcess = $true)]
107 param (
108 [Parameter(Mandatory = $true)]
109 [string] $name,
110 [Parameter(Mandatory = $true)]
111 [string] $property,
112 [Parameter(Mandatory = $true)]
113 $value,
114 [Parameter()]
115 $resultobj = @{}
116 )
117
118 $cap_path = "RDS:\GatewayServer\CAP\$name"
119
120 try {
121 Set-Item -LiteralPath "$cap_path\$property" -Value $value -ErrorAction Stop
122 }
123 catch {
124 Fail-Json -obj $resultobj -message "Failed to set property $property of CAP ${name}: $($_.Exception.Message)"
125 }
126 }
127
128 $result = @{
129 changed = $false
130 }
131 $diff_text = $null
132
133 # Validate CAP name
134 if ($name -match "[*/\\;:?`"<>|\t]+") {
135 Fail-Json -obj $result -message "Invalid character in CAP name."
136 }
137
138 # Validate user groups
139 if ($null -ne $user_groups) {
140 if ($user_groups.Count -lt 1) {
141 Fail-Json -obj $result -message "Parameter 'user_groups' cannot be an empty list."
142 }
143
144 $user_groups = $user_groups | ForEach-Object {
145 $group = $_
146 # Test that the group is resolvable on the local machine
147 $sid = ConvertTo-Sid -InputObject $group
148 if (!$sid) {
149 Fail-Json -obj $result -message "$group is not a valid user group on the host machine or domain"
150 }
151
152 # Return the normalized group name in Down-Level Logon format
153 Convert-FromSID -sid $sid
154 }
155 $user_groups = @($user_groups)
156 }
157
158 # Validate computer groups
159 if ($null -ne $computer_groups) {
160 $computer_groups = $computer_groups | ForEach-Object {
161 $group = $_
162 # Test that the group is resolvable on the local machine
163 $sid = ConvertTo-Sid -InputObject $group
164 if (!$sid) {
165 Fail-Json -obj $result -message "$group is not a valid computer group on the host machine or domain"
166 }
167
168 # Return the normalized group name in Down-Level Logon format
169 Convert-FromSID -sid $sid
170 }
171 $computer_groups = @($computer_groups)
172 }
173
174 # Validate order parameter
175 if ($null -ne $order -and $order -lt 1) {
176 Fail-Json -obj $result -message "Parameter 'order' must be a strictly positive integer."
177 }
178
179 # Ensure RemoteDesktopServices module is loaded
180 if ($null -eq (Get-Module -Name RemoteDesktopServices -ErrorAction SilentlyContinue)) {
181 Import-Module -Name RemoteDesktopServices
182 }
183
184 # Check if a CAP with the given name already exists
185 $cap_exist = Test-Path -LiteralPath "RDS:\GatewayServer\CAP\$name"
186
187 if ($state -eq 'absent') {
188 if ($cap_exist) {
189 Remove-Item -LiteralPath "RDS:\GatewayServer\CAP\$name" -Recurse -WhatIf:$check_mode
190 $diff_text += "-[$name]"
191 $result.changed = $true
192 }
193 }
194 else {
195 $diff_text_added_prefix = ''
196 if (-not $cap_exist) {
197 if ($null -eq $user_groups) {
198 Fail-Json -obj $result -message "User groups must be defined to create a new CAP."
199 }
200
201 # Auth method is required when creating a new CAP. Set it to password by default.
202 if ($null -eq $auth_method) {
203 $auth_method = "password"
204 }
205
206 # Create a new CAP
207 if (-not $check_mode) {
208 $CapArgs = @{
209 Name = $name
210 UserGroupNames = $user_groups -join ';'
211 }
212 $cimParams = @{
213 Namespace = "Root\CIMV2\TerminalServices"
214 ClassName = "Win32_TSGatewayConnectionAuthorizationPolicy"
215 MethodName = "Create"
216 Arguments = $CapArgs
217 }
218 $return = Invoke-CimMethod @cimParams
219 if ($return.ReturnValue -ne 0) {
220 Fail-Json -obj $result -message "Failed to create CAP $name (code: $($return.ReturnValue))"
221 }
222 }
223
224 $cap_exist = -not $check_mode
225
226 $diff_text_added_prefix = '+'
227 $result.changed = $true
228 }
229
230 $diff_text += "$diff_text_added_prefix[$name]`n"
231
232 # We cannot configure a CAP that was created above in check mode as it won't actually exist
233 if ($cap_exist) {
234 $cap = Get-CAP -Name $name
235 $wmi_cap = Get-CimInstance -ClassName Win32_TSGatewayConnectionAuthorizationPolicy -Namespace Root\CIMv2\TerminalServices -Filter "name='$($name)'"
236
237 if ($state -in @('disabled', 'enabled')) {
238 $cap_enabled = $state -ne 'disabled'
239 if ($cap.Enabled -ne $cap_enabled) {
240 $diff_text += "-State = $(@('disabled', 'enabled')[[int]$cap.Enabled])`n+State = $state`n"
241 Set-CAPPropertyValue -Name $name -Property Status -Value ([int]$cap_enabled) -ResultObj $result -WhatIf:$check_mode
242 $result.changed = $true
243 }
244 }
245
246 if ($null -ne $auth_method -and $auth_method -ne $cap.AuthMethod) {
247 $diff_text += "-AuthMethod = $($cap.AuthMethod)`n+AuthMethod = $auth_method`n"
248 $set_params = @{
249 Name = $name
250 Property = "AuthMethod"
251 Value = ([array]::IndexOf($auth_methods_set, $auth_method))
252 ResultObj = $result
253 WhatIf = $check_mode
254 }
255 Set-CAPPropertyValue @set_params
256 $result.changed = $true
257 }
258
259 if ($null -ne $order -and $order -ne $cap.EvaluationOrder) {
260 # Order cannot be greater than the total number of existing CAPs (InvalidArgument exception)
261 $cap_count = (Get-ChildItem -LiteralPath "RDS:\GatewayServer\CAP").Count
262 if ($order -gt $cap_count) {
263 $msg = -join @(
264 "Given value '$order' for parameter 'order' is greater than the number of existing CAPs. "
265 "The actual order will be capped to '$cap_count'."
266 )
267 Add-Warning -obj $result -message $msg
268 $order = $cap_count
269 }
270
271 $diff_text += "-Order = $($cap.EvaluationOrder)`n+Order = $order`n"
272 Set-CAPPropertyValue -Name $name -Property EvaluationOrder -Value $order -ResultObj $result -WhatIf:$check_mode
273 $result.changed = $true
274 }
275
276 if ($null -ne $session_timeout -and ($session_timeout -ne $cap.SessionTimeout -or $session_timeout_action -ne $cap.SessionTimeoutAction)) {
277 try {
278 Set-Item -Path "RDS:\GatewayServer\CAP\$name\SessionTimeout" `
279 -Value $session_timeout `
280 -SessionTimeoutAction ([array]::IndexOf($session_timeout_actions_set, $session_timeout_action)) `
281 -ErrorAction Stop `
282 -WhatIf:$check_mode
283 }
284 catch {
285 Fail-Json -obj $result -message "Failed to set property ComputerGroupType of RAP ${name}: $($_.Exception.Message)"
286 }
287
288 $diff_text += "-SessionTimeoutAction = $($cap.SessionTimeoutAction)`n+SessionTimeoutAction = $session_timeout_action`n"
289 $diff_text += "-SessionTimeout = $($cap.SessionTimeout)`n+SessionTimeout = $session_timeout`n"
290 $result.changed = $true
291 }
292
293 if ($null -ne $idle_timeout -and $idle_timeout -ne $cap.IdleTimeout) {
294 $diff_text += "-IdleTimeout = $($cap.IdleTimeout)`n+IdleTimeout = $idle_timeout`n"
295 Set-CAPPropertyValue -Name $name -Property IdleTimeout -Value $idle_timeout -ResultObj $result -WhatIf:$check_mode
296 $result.changed = $true
297 }
298
299 if ($null -ne $allow_only_sdrts_servers -and $allow_only_sdrts_servers -ne $cap.AllowOnlySDRTSServers) {
300 $diff_text += "-AllowOnlySDRTSServers = $($cap.AllowOnlySDRTSServers)`n+AllowOnlySDRTSServers = $allow_only_sdrts_servers`n"
301 Set-CAPPropertyValue -Name $name -Property AllowOnlySDRTSServers -Value ([int]$allow_only_sdrts_servers) -ResultObj $result -WhatIf:$check_mode
302 $result.changed = $true
303 }
304
305 if ($null -ne $redirect_clipboard -and $redirect_clipboard -ne $cap.DeviceRedirection.Clipboard) {
306 $diff_text += "-RedirectClipboard = $($cap.DeviceRedirection.Clipboard)`n+RedirectClipboard = $redirect_clipboard`n"
307 Set-CAPPropertyValue -Name $name -Property "DeviceRedirection\Clipboard" -Value ([int]$redirect_clipboard) -ResultObj $result -WhatIf:$check_mode
308 $result.changed = $true
309 }
310
311 if ($null -ne $redirect_drives -and $redirect_drives -ne $cap.DeviceRedirection.DiskDrives) {
312 $diff_text += "-RedirectDrives = $($cap.DeviceRedirection.DiskDrives)`n+RedirectDrives = $redirect_drives`n"
313 Set-CAPPropertyValue -Name $name -Property "DeviceRedirection\DiskDrives" -Value ([int]$redirect_drives) -ResultObj $result -WhatIf:$check_mode
314 $result.changed = $true
315 }
316
317 if ($null -ne $redirect_printers -and $redirect_printers -ne $cap.DeviceRedirection.Printers) {
318 $diff_text += "-RedirectPrinters = $($cap.DeviceRedirection.Printers)`n+RedirectPrinters = $redirect_printers`n"
319 Set-CAPPropertyValue -Name $name -Property "DeviceRedirection\Printers" -Value ([int]$redirect_printers) -ResultObj $result -WhatIf:$check_mode
320 $result.changed = $true
321 }
322
323 if ($null -ne $redirect_serial -and $redirect_serial -ne $cap.DeviceRedirection.SerialPorts) {
324 $diff_text += "-RedirectSerial = $($cap.DeviceRedirection.SerialPorts)`n+RedirectSerial = $redirect_serial`n"
325 Set-CAPPropertyValue -Name $name -Property "DeviceRedirection\SerialPorts" -Value ([int]$redirect_serial) -ResultObj $result -WhatIf:$check_mode
326 $result.changed = $true
327 }
328
329 if ($null -ne $redirect_pnp -and $redirect_pnp -ne $cap.DeviceRedirection.PlugAndPlayDevices) {
330 $diff_text += "-RedirectPnP = $($cap.DeviceRedirection.PlugAndPlayDevices)`n+RedirectPnP = $redirect_pnp`n"
331 Set-CAPPropertyValue -Name $name -Property "DeviceRedirection\PlugAndPlayDevices" -Value ([int]$redirect_pnp) -ResultObj $result -WhatIf:$check_mode
332 $result.changed = $true
333 }
334
335 if ($null -ne $user_groups) {
336 $groups_to_remove = @($cap.UserGroups | Where-Object { $user_groups -notcontains $_ })
337 $groups_to_add = @($user_groups | Where-Object { $cap.UserGroups -notcontains $_ })
338
339 $user_groups_diff = $null
340 foreach ($group in $groups_to_add) {
341 if (-not $check_mode) {
342 $return = $wmi_cap | Invoke-CimMethod -MethodName AddUserGroupNames -Arguments @{ UserGroupNames = $group }
343 if ($return.ReturnValue -ne 0) {
344 Fail-Json -obj $result -message "Failed to add user group $($group) (code: $($return.ReturnValue))"
345 }
346 }
347 $user_groups_diff += " +$group`n"
348 $result.changed = $true
349 }
350
351 foreach ($group in $groups_to_remove) {
352 if (-not $check_mode) {
353 $return = $wmi_cap | Invoke-CimMethod -MethodName RemoveUserGroupNames -Arguments @{ UserGroupNames = $group }
354 if ($return.ReturnValue -ne 0) {
355 Fail-Json -obj $result -message "Failed to remove user group $($group) (code: $($return.ReturnValue))"
356 }
357 }
358 $user_groups_diff += " -$group`n"
359 $result.changed = $true
360 }
361
362 if ($user_groups_diff) {
363 $diff_text += "~UserGroups`n$user_groups_diff"
364 }
365 }
366
367 if ($null -ne $computer_groups) {
368 $groups_to_remove = @($cap.ComputerGroups | Where-Object { $computer_groups -notcontains $_ })
369 $groups_to_add = @($computer_groups | Where-Object { $cap.ComputerGroups -notcontains $_ })
370
371 $computer_groups_diff = $null
372 foreach ($group in $groups_to_add) {
373 if (-not $check_mode) {
374 $return = $wmi_cap | Invoke-CimMethod -MethodName AddComputerGroupNames -Arguments @{ ComputerGroupNames = $group }
375 if ($return.ReturnValue -ne 0) {
376 Fail-Json -obj $result -message "Failed to add computer group $($group) (code: $($return.ReturnValue))"
377 }
378 }
379 $computer_groups_diff += " +$group`n"
380 $result.changed = $true
381 }
382
383 foreach ($group in $groups_to_remove) {
384 if (-not $check_mode) {
385 $return = $wmi_cap | Invoke-CimMethod -MethodName RemoveComputerGroupNames -Arguments @{ ComputerGroupNames = $group }
386 if ($return.ReturnValue -ne 0) {
387 Fail-Json -obj $result -message "Failed to remove computer group $($group) (code: $($return.ReturnValue))"
388 }
389 }
390 $computer_groups_diff += " -$group`n"
391 $result.changed = $true
392 }
393
394 if ($computer_groups_diff) {
395 $diff_text += "~ComputerGroups`n$computer_groups_diff"
396 }
397 }
398 }
399 }
400
401 if ($diff_mode -and $result.changed -eq $true) {
402 $result.diff = @{
403 prepared = $diff_text
404 }
405 }
406
407 Exit-Json $result