Debian Codegraph @

test/support/windows-integration/plugins/modules/win_regedit.ps1

raw
1 #!powershell
2
3 # Copyright: (c) 2015, Adam Keech <[email protected]>
4 # Copyright: (c) 2015, Josh Ludwig <[email protected]>
5 # Copyright: (c) 2017, Jordan Borean <[email protected]>
6 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
7
8 #Requires -Module Ansible.ModuleUtils.Legacy
9 #Requires -Module Ansible.ModuleUtils.PrivilegeUtil
10
11 $params = Parse-Args -arguments $args -supports_check_mode $true
12 $check_mode = Get-AnsibleParam -obj $params -name "_ansible_check_mode" -type "bool" -default $false
13 $diff_mode = Get-AnsibleParam -obj $params -name "_ansible_diff" -type "bool" -default $false
14 $_remote_tmp = Get-AnsibleParam $params "_ansible_remote_tmp" -type "path" -default $env:TMP
15
16 $path = Get-AnsibleParam -obj $params -name "path" -type "str" -failifempty $true -aliases "key"
17 $name = Get-AnsibleParam -obj $params -name "name" -type "str" -aliases "entry","value"
18 $data = Get-AnsibleParam -obj $params -name "data"
19 $type = Get-AnsibleParam -obj $params -name "type" -type "str" -default "string" -validateset "none","binary","dword","expandstring","multistring","string","qword" -aliases "datatype"
20 $state = Get-AnsibleParam -obj $params -name "state" -type "str" -default "present" -validateset "present","absent"
21 $delete_key = Get-AnsibleParam -obj $params -name "delete_key" -type "bool" -default $true
22 $hive = Get-AnsibleParam -obj $params -name "hive" -type "path"
23
24 $result = @{
25 changed = $false
26 data_changed = $false
27 data_type_changed = $false
28 }
29
30 if ($diff_mode) {
31 $result.diff = @{
32 before = ""
33 after = ""
34 }
35 }
36
37 $registry_util = @'
38 using System;
39 using System.Collections.Generic;
40 using System.Runtime.InteropServices;
41
42 namespace Ansible.WinRegedit
43 {
44 internal class NativeMethods
45 {
46 [DllImport("advapi32.dll", CharSet = CharSet.Unicode)]
47 public static extern int RegLoadKeyW(
48 UInt32 hKey,
49 string lpSubKey,
50 string lpFile);
51
52 [DllImport("advapi32.dll", CharSet = CharSet.Unicode)]
53 public static extern int RegUnLoadKeyW(
54 UInt32 hKey,
55 string lpSubKey);
56 }
57
58 public class Win32Exception : System.ComponentModel.Win32Exception
59 {
60 private string _msg;
61 public Win32Exception(string message) : this(Marshal.GetLastWin32Error(), message) { }
62 public Win32Exception(int errorCode, string message) : base(errorCode)
63 {
64 _msg = String.Format("{0} ({1}, Win32ErrorCode {2})", message, base.Message, errorCode);
65 }
66 public override string Message { get { return _msg; } }
67 public static explicit operator Win32Exception(string message) { return new Win32Exception(message); }
68 }
69
70 public class Hive : IDisposable
71 {
72 private const UInt32 SCOPE = 0x80000002; // HKLM
73 private string hiveKey;
74 private bool loaded = false;
75
76 public Hive(string hiveKey, string hivePath)
77 {
78 this.hiveKey = hiveKey;
79 int ret = NativeMethods.RegLoadKeyW(SCOPE, hiveKey, hivePath);
80 if (ret != 0)
81 throw new Win32Exception(ret, String.Format("Failed to load registry hive at {0}", hivePath));
82 loaded = true;
83 }
84
85 public static void UnloadHive(string hiveKey)
86 {
87 int ret = NativeMethods.RegUnLoadKeyW(SCOPE, hiveKey);
88 if (ret != 0)
89 throw new Win32Exception(ret, String.Format("Failed to unload registry hive at {0}", hiveKey));
90 }
91
92 public void Dispose()
93 {
94 if (loaded)
95 {
96 // Make sure the garbage collector disposes all unused handles and waits until it is complete
97 GC.Collect();
98 GC.WaitForPendingFinalizers();
99
100 UnloadHive(hiveKey);
101 loaded = false;
102 }
103 GC.SuppressFinalize(this);
104 }
105 ~Hive() { this.Dispose(); }
106 }
107 }
108 '@
109
110 # fire a warning if the property name isn't specified, the (Default) key ($null) can only be a string
111 if ($null -eq $name -and $type -ne "string") {
112 Add-Warning -obj $result -message "the data type when name is not specified can only be 'string', the type has automatically been converted"
113 $type = "string"
114 }
115
116 # Check that the registry path is in PSDrive format: HKCC, HKCR, HKCU, HKLM, HKU
117 if ($path -notmatch "^HK(CC|CR|CU|LM|U):\\") {
118 Fail-Json $result "path: $path is not a valid powershell path, see module documentation for examples."
119 }
120
121 # Add a warning if the path does not contains a \ and is not the leaf path
122 $registry_path = (Split-Path -Path $path -NoQualifier).Substring(1) # removes the hive: and leading \
123 $registry_leaf = Split-Path -Path $path -Leaf
124 if ($registry_path -ne $registry_leaf -and -not $registry_path.Contains('\')) {
125 $msg = "path is not using '\' as a separator, support for '/' as a separator will be removed in a future Ansible version"
126 Add-DeprecationWarning -obj $result -message $msg -version 2.12
127 $registry_path = $registry_path.Replace('/', '\')
128 }
129
130 # Simplified version of Convert-HexStringToByteArray from
131 # https://cyber-defense.sans.org/blog/2010/02/11/powershell-byte-array-hex-convert
132 # Expects a hex in the format you get when you run reg.exe export,
133 # and converts to a byte array so powershell can modify binary registry entries
134 # import format is like 'hex:be,ef,be,ef,be,ef,be,ef,be,ef'
135 Function Convert-RegExportHexStringToByteArray($string) {
136 # Remove 'hex:' from the front of the string if present
137 $string = $string.ToLower() -replace '^hex\:',''
138
139 # Remove whitespace and any other non-hex crud.
140 $string = $string -replace '[^a-f0-9\\,x\-\:]',''
141
142 # Turn commas into colons
143 $string = $string -replace ',',':'
144
145 # Maybe there's nothing left over to convert...
146 if ($string.Length -eq 0) {
147 return ,@()
148 }
149
150 # Split string with or without colon delimiters.
151 if ($string.Length -eq 1) {
152 return ,@([System.Convert]::ToByte($string,16))
153 } elseif (($string.Length % 2 -eq 0) -and ($string.IndexOf(":") -eq -1)) {
154 return ,@($string -split '([a-f0-9]{2})' | foreach-object { if ($_) {[System.Convert]::ToByte($_,16)}})
155 } elseif ($string.IndexOf(":") -ne -1) {
156 return ,@($string -split ':+' | foreach-object {[System.Convert]::ToByte($_,16)})
157 } else {
158 return ,@()
159 }
160 }
161
162 Function Compare-RegistryProperties($existing, $new) {
163 # Outputs $true if the property values don't match
164 if ($existing -is [Array]) {
165 (Compare-Object -ReferenceObject $existing -DifferenceObject $new -SyncWindow 0).Length -ne 0
166 } else {
167 $existing -cne $new
168 }
169 }
170
171 Function Get-DiffValue {
172 param(
173 [Parameter(Mandatory=$true)][Microsoft.Win32.RegistryValueKind]$Type,
174 [Parameter(Mandatory=$true)][Object]$Value
175 )
176
177 $diff = @{ type = $Type.ToString(); value = $Value }
178
179 $enum = [Microsoft.Win32.RegistryValueKind]
180 if ($Type -in @($enum::Binary, $enum::None)) {
181 $diff.value = [System.Collections.Generic.List`1[String]]@()
182 foreach ($dec_value in $Value) {
183 $diff.value.Add("0x{0:x2}" -f $dec_value)
184 }
185 } elseif ($Type -eq $enum::DWord) {
186 $diff.value = "0x{0:x8}" -f $Value
187 } elseif ($Type -eq $enum::QWord) {
188 $diff.value = "0x{0:x16}" -f $Value
189 }
190
191 return $diff
192 }
193
194 Function Set-StateAbsent {
195 param(
196 # Used for diffs and exception messages to match up against Ansible input
197 [Parameter(Mandatory=$true)][String]$PrintPath,
198 [Parameter(Mandatory=$true)][Microsoft.Win32.RegistryKey]$Hive,
199 [Parameter(Mandatory=$true)][String]$Path,
200 [String]$Name,
201 [Switch]$DeleteKey
202 )
203
204 $key = $Hive.OpenSubKey($Path, $true)
205 if ($null -eq $key) {
206 # Key does not exist, no need to delete anything
207 return
208 }
209
210 try {
211 if ($DeleteKey -and -not $Name) {
212 # delete_key=yes is set and name is null/empty, so delete the entire key
213 $key.Dispose()
214 $key = $null
215 if (-not $check_mode) {
216 try {
217 $Hive.DeleteSubKeyTree($Path, $false)
218 } catch {
219 Fail-Json -obj $result -message "failed to delete registry key at $($PrintPath): $($_.Exception.Message)"
220 }
221 }
222 $result.changed = $true
223
224 if ($diff_mode) {
225 $result.diff.before = @{$PrintPath = @{}}
226 $result.diff.after = @{}
227 }
228 } else {
229 # delete_key=no or name is not null/empty, delete the property not the full key
230 $property = $key.GetValue($Name)
231 if ($null -eq $property) {
232 # property does not exist
233 return
234 }
235 $property_type = $key.GetValueKind($Name) # used for the diff
236
237 if (-not $check_mode) {
238 try {
239 $key.DeleteValue($Name)
240 } catch {
241 Fail-Json -obj $result -message "failed to delete registry property '$Name' at $($PrintPath): $($_.Exception.Message)"
242 }
243 }
244
245 $result.changed = $true
246 if ($diff_mode) {
247 $diff_value = Get-DiffValue -Type $property_type -Value $property
248 $result.diff.before = @{ $PrintPath = @{ $Name = $diff_value } }
249 $result.diff.after = @{ $PrintPath = @{} }
250 }
251 }
252 } finally {
253 if ($key) {
254 $key.Dispose()
255 }
256 }
257 }
258
259 Function Set-StatePresent {
260 param(
261 [Parameter(Mandatory=$true)][String]$PrintPath,
262 [Parameter(Mandatory=$true)][Microsoft.Win32.RegistryKey]$Hive,
263 [Parameter(Mandatory=$true)][String]$Path,
264 [String]$Name,
265 [Object]$Data,
266 [Microsoft.Win32.RegistryValueKind]$Type
267 )
268
269 $key = $Hive.OpenSubKey($Path, $true)
270 try {
271 if ($null -eq $key) {
272 # the key does not exist, create it so the next steps work
273 if (-not $check_mode) {
274 try {
275 $key = $Hive.CreateSubKey($Path)
276 } catch {
277 Fail-Json -obj $result -message "failed to create registry key at $($PrintPath): $($_.Exception.Message)"
278 }
279 }
280 $result.changed = $true
281
282 if ($diff_mode) {
283 $result.diff.before = @{}
284 $result.diff.after = @{$PrintPath = @{}}
285 }
286 } elseif ($diff_mode) {
287 # Make sure the diff is in an expected state for the key
288 $result.diff.before = @{$PrintPath = @{}}
289 $result.diff.after = @{$PrintPath = @{}}
290 }
291
292 if ($null -eq $key -or $null -eq $Data) {
293 # Check mode and key was created above, we cannot do any more work, or $Data is $null which happens when
294 # we create a new key but haven't explicitly set the data
295 return
296 }
297
298 $property = $key.GetValue($Name, $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
299 if ($null -ne $property) {
300 # property exists, need to compare the values and type
301 $existing_type = $key.GetValueKind($name)
302 $change_value = $false
303
304 if ($Type -ne $existing_type) {
305 $change_value = $true
306 $result.data_type_changed = $true
307 $data_mismatch = Compare-RegistryProperties -existing $property -new $Data
308 if ($data_mismatch) {
309 $result.data_changed = $true
310 }
311 } else {
312 $data_mismatch = Compare-RegistryProperties -existing $property -new $Data
313 if ($data_mismatch) {
314 $change_value = $true
315 $result.data_changed = $true
316 }
317 }
318
319 if ($change_value) {
320 if (-not $check_mode) {
321 try {
322 $key.SetValue($Name, $Data, $Type)
323 } catch {
324 Fail-Json -obj $result -message "failed to change registry property '$Name' at $($PrintPath): $($_.Exception.Message)"
325 }
326 }
327 $result.changed = $true
328
329 if ($diff_mode) {
330 $result.diff.before.$PrintPath.$Name = Get-DiffValue -Type $existing_type -Value $property
331 $result.diff.after.$PrintPath.$Name = Get-DiffValue -Type $Type -Value $Data
332 }
333 } elseif ($diff_mode) {
334 $diff_value = Get-DiffValue -Type $existing_type -Value $property
335 $result.diff.before.$PrintPath.$Name = $diff_value
336 $result.diff.after.$PrintPath.$Name = $diff_value
337 }
338 } else {
339 # property doesn't exist just create a new one
340 if (-not $check_mode) {
341 try {
342 $key.SetValue($Name, $Data, $Type)
343 } catch {
344 Fail-Json -obj $result -message "failed to create registry property '$Name' at $($PrintPath): $($_.Exception.Message)"
345 }
346 }
347 $result.changed = $true
348
349 if ($diff_mode) {
350 $result.diff.after.$PrintPath.$Name = Get-DiffValue -Type $Type -Value $Data
351 }
352 }
353 } finally {
354 if ($key) {
355 $key.Dispose()
356 }
357 }
358 }
359
360 # convert property names "" to $null as "" refers to (Default)
361 if ($name -eq "") {
362 $name = $null
363 }
364
365 # convert the data to the required format
366 if ($type -in @("binary", "none")) {
367 if ($null -eq $data) {
368 $data = ""
369 }
370
371 # convert the data from string to byte array if in hex: format
372 if ($data -is [String]) {
373 $data = [byte[]](Convert-RegExportHexStringToByteArray -string $data)
374 } elseif ($data -is [Int]) {
375 if ($data -gt 255) {
376 Fail-Json $result "cannot convert binary data '$data' to byte array, please specify this value as a yaml byte array or a comma separated hex value string"
377 }
378 $data = [byte[]]@([byte]$data)
379 } elseif ($data -is [Array]) {
380 $data = [byte[]]$data
381 }
382 } elseif ($type -in @("dword", "qword")) {
383 # dword's and dword's don't allow null values, set to 0
384 if ($null -eq $data) {
385 $data = 0
386 }
387
388 if ($data -is [String]) {
389 # if the data is a string we need to convert it to an unsigned int64
390 # it needs to be unsigned as Ansible passes in an unsigned value while
391 # powershell uses a signed data type. The value will then be converted
392 # below
393 $data = [UInt64]$data
394 }
395
396 if ($type -eq "dword") {
397 if ($data -gt [UInt32]::MaxValue) {
398 Fail-Json $result "data cannot be larger than 0xffffffff when type is dword"
399 } elseif ($data -gt [Int32]::MaxValue) {
400 # when dealing with larger int32 (> 2147483647 or 0x7FFFFFFF) powershell
401 # automatically converts it to a signed int64. We need to convert this to
402 # signed int32 by parsing the hex string value.
403 $data = "0x$("{0:x}" -f $data)"
404 }
405 $data = [Int32]$data
406 } else {
407 if ($data -gt [UInt64]::MaxValue) {
408 Fail-Json $result "data cannot be larger than 0xffffffffffffffff when type is qword"
409 } elseif ($data -gt [Int64]::MaxValue) {
410 $data = "0x$("{0:x}" -f $data)"
411 }
412 $data = [Int64]$data
413 }
414 } elseif ($type -in @("string", "expandstring") -and $name) {
415 # a null string or expandstring must be empty quotes
416 # Only do this if $name has been defined (not the default key)
417 if ($null -eq $data) {
418 $data = ""
419 }
420 } elseif ($type -eq "multistring") {
421 # convert the data for a multistring to a String[] array
422 if ($null -eq $data) {
423 $data = [String[]]@()
424 } elseif ($data -isnot [Array]) {
425 $new_data = New-Object -TypeName String[] -ArgumentList 1
426 $new_data[0] = $data.ToString([CultureInfo]::InvariantCulture)
427 $data = $new_data
428 } else {
429 $new_data = New-Object -TypeName String[] -ArgumentList $data.Count
430 foreach ($entry in $data) {
431 $new_data[$data.IndexOf($entry)] = $entry.ToString([CultureInfo]::InvariantCulture)
432 }
433 $data = $new_data
434 }
435 }
436
437 # convert the type string to the .NET class
438 $type = [System.Enum]::Parse([Microsoft.Win32.RegistryValueKind], $type, $true)
439
440 $registry_hive = switch(Split-Path -Path $path -Qualifier) {
441 "HKCR:" { [Microsoft.Win32.Registry]::ClassesRoot }
442 "HKCC:" { [Microsoft.Win32.Registry]::CurrentConfig }
443 "HKCU:" { [Microsoft.Win32.Registry]::CurrentUser }
444 "HKLM:" { [Microsoft.Win32.Registry]::LocalMachine }
445 "HKU:" { [Microsoft.Win32.Registry]::Users }
446 }
447 $loaded_hive = $null
448 try {
449 if ($hive) {
450 if (-not (Test-Path -LiteralPath $hive)) {
451 Fail-Json -obj $result -message "hive at path '$hive' is not valid or accessible, cannot load hive"
452 }
453
454 $original_tmp = $env:TMP
455 $env:TMP = $_remote_tmp
456 Add-Type -TypeDefinition $registry_util
457 $env:TMP = $original_tmp
458
459 try {
460 Set-AnsiblePrivilege -Name SeBackupPrivilege -Value $true
461 Set-AnsiblePrivilege -Name SeRestorePrivilege -Value $true
462 } catch [System.ComponentModel.Win32Exception] {
463 Fail-Json -obj $result -message "failed to enable SeBackupPrivilege and SeRestorePrivilege for the current process: $($_.Exception.Message)"
464 }
465
466 if (Test-Path -Path HKLM:\ANSIBLE) {
467 Add-Warning -obj $result -message "hive already loaded at HKLM:\ANSIBLE, had to unload hive for win_regedit to continue"
468 try {
469 [Ansible.WinRegedit.Hive]::UnloadHive("ANSIBLE")
470 } catch [System.ComponentModel.Win32Exception] {
471 Fail-Json -obj $result -message "failed to unload registry hive HKLM:\ANSIBLE from $($hive): $($_.Exception.Message)"
472 }
473 }
474
475 try {
476 $loaded_hive = New-Object -TypeName Ansible.WinRegedit.Hive -ArgumentList "ANSIBLE", $hive
477 } catch [System.ComponentModel.Win32Exception] {
478 Fail-Json -obj $result -message "failed to load registry hive from '$hive' to HKLM:\ANSIBLE: $($_.Exception.Message)"
479 }
480 }
481
482 if ($state -eq "present") {
483 Set-StatePresent -PrintPath $path -Hive $registry_hive -Path $registry_path -Name $name -Data $data -Type $type
484 } else {
485 Set-StateAbsent -PrintPath $path -Hive $registry_hive -Path $registry_path -Name $name -DeleteKey:$delete_key
486 }
487 } finally {
488 $registry_hive.Dispose()
489 if ($loaded_hive) {
490 $loaded_hive.Dispose()
491 }
492 }
493
494 Exit-Json $result
495