-
Notifications
You must be signed in to change notification settings - Fork 7
/
GPRegistryPolicyFileParser.psm1
715 lines (602 loc) · 21.1 KB
/
GPRegistryPolicyFileParser.psm1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
Import-LocalizedData -BindingVariable localizedData -FileName GPRegistryPolicyFileParser.strings.psd1
<#
.SYNOPSIS
Reads and parses a .pol file.
.DESCRIPTION
Reads a .pol file, parses it and returns an array of Group Policy registry settings.
.PARAMETER Path
Specifies the path to the .pol file.
.EXAMPLE
C:\PS> Parse-PolFile -Path "C:\Registry.pol"
#>
function Read-GPRegistryPolicyFile
{
[OutputType([array])]
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[System.String]
$Path
)
[System.Array] $registryPolicies = @()
$index = 0
[System.String] $policyContents = Get-Content $Path -Raw
$encodingParameter = Get-ByteStreamParameter
[System.Byte[]] $policyContentInBytes = Get-Content $Path -Raw @encodingParameter
# 4 bytes are the signature PReg
$signature = [System.Text.Encoding]::ASCII.GetString($policyContents[0..3])
$index += 4
Assert-Condition -Condition ($signature -eq 'PReg') -ErrorMessage ($script:localizedData.InvalidHeader -f $Path)
# 4 bytes are the version
$version = [System.BitConverter]::ToInt32($policyContentInBytes, 4)
$index += 4
Assert-Condition -Condition ($version -eq 1) -ErrorMessage ($script:localizedData.InvalidVersion -f $Path)
# Start processing at byte 8
while ($index -lt $policyContents.Length - 2)
{
[System.String] $key = $null
[System.String] $valueName = $null
[System.Int32] $valueType = $null
[System.Int32] $valueLength = $null
[object]$value = $null
# Next UNICODE character should be a [
$leftbracket = [System.BitConverter]::ToChar($policyContentInBytes, $index)
Assert-Condition -Condition ($leftbracket -eq '[') -ErrorMessage $script:localizedData.MissingOpeningBracket
$index += 2
# Next UNICODE string will continue until the ; less the null terminator
$semicolon = $policyContents.IndexOf(';', $index)
Assert-Condition -Condition ($semicolon -ge 0) -ErrorMessage $script:localizedData.MissingTrailingSemicolonAfterKey
$Key = [System.Text.Encoding]::UNICODE.GetString($policyContents[($index)..($semicolon - 3)]) # -3 to exclude the null termination and ';' characters
$index = $semicolon + 2
# Next UNICODE string will continue until the ; less the null terminator
$semicolon = $policyContents.IndexOf(';', $index)
Assert-Condition -Condition ($semicolon -ge 0) -ErrorMessage $script:localizedData.MissingTrailingSemicolonAfterName
$valueName = [System.Text.Encoding]::UNICODE.GetString($policyContents[($index)..($semicolon - 3)]) # -3 to exclude the null termination and ';' characters
$index = $semicolon + 2
# Next DWORD will continue until the ;
$semicolon = $index + 4 # DWORD Size
Assert-Condition -Condition ([System.BitConverter]::ToChar($policyContentInBytes, $semicolon) -eq ';') -ErrorMessage $script:localizedData.MissingTrailingSemicolonAfterType
$valueType = [System.BitConverter]::ToInt32($policyContentInBytes, $index)
$index = $semicolon + 2 # Skip ';'
# Next DWORD will continue until the ;
$semicolon = $index + 4 # DWORD Size
Assert-Condition -Condition ([System.BitConverter]::ToChar($policyContentInBytes, $semicolon) -eq ';') -ErrorMessage $script:localizedData.MissingTrailingSemicolonAfterLength
$valueLength = Convert-StringToInt -ValueString $policyContentInBytes[$index..($index + 3)]
$index = $semicolon + 2 # Skip ';'
if ($valueLength -gt 0)
{
<#
String types less the null terminator for REG_SZ and REG_EXPAND_SZ
REG_SZ: string type (ASCII)
#>
if ($valueType -eq [RegType]::REG_SZ)
{
# -3 to exclude the null termination and ']' characters
[System.String] $value = [System.Text.Encoding]::UNICODE.GetString($policyContents[($index)..($index + $valueLength - 3)])
$index += $valueLength
}
# REG_EXPAND_SZ: string, includes %ENVVAR% (expanded by caller) (ASCII)
if ($valueType -eq [RegType]::REG_EXPAND_SZ)
{
# -3 to exclude the null termination and ']' characters
[System.String] $value = [System.Text.Encoding]::UNICODE.GetString($policyContents[($index)..($index + $valueLength - 3)])
$index += $valueLength
}
<#
For REG_MULTI_SZ leave the last null terminator
REG_MULTI_SZ: multiple strings, delimited by \0, terminated by \0\0 (ASCII)
#>
if ($valueType -eq [RegType]::REG_MULTI_SZ)
{
[System.String] $rawValue = [System.Text.Encoding]::UNICODE.GetString($policyContents[($index)..($index + $valueLength - 3)])
$value = Format-MultiStringValue -MultiStringValue $rawValue
$index += $valueLength
}
# REG_BINARY: binary values
if ($valueType -eq [RegType]::REG_BINARY)
{
[System.Byte[]] $value = $policyContentInBytes[($index)..($index + $valueLength - 1)]
$index += $valueLength
}
}
# DWORD: (4 bytes) in little endian format
if ($valueType -eq [RegType]::REG_DWORD)
{
$value = Convert-StringToInt -ValueString $policyContentInBytes[$index..($index + 3)]
$index += 4
}
# QWORD: (8 bytes) in little endian format
if ($valueType -eq [RegType]::REG_QWORD)
{
$value = Convert-StringToInt -ValueString $policyContentInBytes[$index..($index + 7)]
$index += 8
}
# Next UNICODE character should be a ] Skip over null data value if one exists
$rightbracket = $policyContents.IndexOf(']', $index)
Assert-Condition -Condition ($rightbracket -ge 0) -ErrorMessage $script:localizedData.MissingClosingBracket
$index = $rightbracket + 2
$entry = New-GPRegistryPolicy -Key $Key -ValueName $valueName -ValueType $valueType -ValueLength $valueLength -ValueData $value
$registryPolicies += $entry
}
return $registryPolicies
}
<#
.SYNOPSIS
Asserts a condition and throws error if condition fails.
.PARAMETER Condition
Specifies the condition to test.
.PARAMETER ErrorMessage
Specifies the error message to throw if the assertion fails.
#>
function Assert-Condition
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[System.Boolean]
$Condition,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.String]
$ErrorMessage
)
if ($Condition -eq $false)
{
throw $ErrorMessage
}
}
<#
.SYNOPSIS
Create a GPRegistryPolicy Object
.PARAMETER Key
Indicates the path of the registry key for which you want to ensure a specific state. This path must include the hive.
.PARAMETER ValueName
Indicates the name of the registry value.
.PARAMETER ValueData
The data for the registry value.
.PARAMETER ValueType
Indicates the type of the value.
.PARAMETER ValueLength
Specifies the size of the policy.
#>
function New-GPRegistryPolicy
{
[CmdletBinding()]
[OutputType([GPRegistryPolicy])]
param
(
[Parameter(Mandatory = $true, Position = 0)]
[ValidateNotNullOrEmpty()]
[System.String]
$Key,
[Parameter(Position = 1)]
[System.String]
$ValueName = $null,
[Parameter(Position = 2)]
[RegType]
$ValueType = [RegType]::REG_NONE,
[Parameter(Position = 3)]
[System.String]
$ValueLength = $null,
[Parameter(Position = 4)]
[System.Object[]]
$ValueData = $null
)
$Policy = [GPRegistryPolicy]::new($Key, $ValueName, $ValueType, $ValueLength, $ValueData)
return $Policy
}
<#
.SYNOPSIS
Creates a file and initializes it with Group Policy Registry file format signature.
.DESCRIPTION
Creates a file and initializes it with Group Policy Registry file format signature.
.PARAMETER Path
Path to a file (.pol extension).
#>
function New-GPRegistryPolicyFile
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[System.String]
$Path
)
$policyFileSignature = 0x67655250 # PRef
$policyFileVersion = 0x00000001 #Initially defined as 1, then incremented each time the file format is changed.
$null = Remove-Item -Path $Path -Force -ErrorAction SilentlyContinue
Write-Verbose -Message ($script:localizedData.CreateNewPolFile -f $polFilePath)
$null = New-Item -Path $Path -Force -ErrorAction Stop
$encodingParameter = Get-ByteStreamParameter
[System.BitConverter]::GetBytes($policyFileSignature) | Add-Content -Path $Path @encodingParameter
[System.BitConverter]::GetBytes($policyFileVersion) | Add-Content -Path $Path @encodingParameter
}
<#
.SYNOPSIS
Creates a .pol file entry byte array from a GPRegistryPolicy instance.
.DESCRIPTION
Creates a .pol file entry byte array from a GPRegistryPolicy instance. This entry can be written in a .pol file later.
.PARAMETER RegistryPolicy
Specifies the registry policy entry.
#>
function New-GPRegistrySettingsEntry
{
[CmdletBinding()]
[OutputType([System.Byte[]])]
param
(
[Parameter(Mandatory = $true)]
[GPRegistryPolicy[]]
$RegistryPolicy
)
[byte[]] $entry = @()
# openning bracket
$entry += [System.Text.Encoding]::Unicode.GetBytes('[')
$entry += [System.Text.Encoding]::Unicode.GetBytes($RegistryPolicy.Key + "`0")
# semicolon as delimiter
$entry += [System.Text.Encoding]::Unicode.GetBytes(';')
$entry += [System.Text.Encoding]::Unicode.GetBytes($RegistryPolicy.ValueName + "`0")
# semicolon as delimiter
$entry += [System.Text.Encoding]::Unicode.GetBytes(';')
$entry += [System.BitConverter]::GetBytes([Int32]$RegistryPolicy.ValueType)
# semicolon as delimiter
$entry += [System.Text.Encoding]::Unicode.GetBytes(';')
# get data bytes then compute byte size based on data and type
switch ($RegistryPolicy.ValueType)
{
{ @([RegType]::REG_SZ, [RegType]::REG_EXPAND_SZ) -contains $_ }
{
$dataBytes = [System.Text.Encoding]::Unicode.GetBytes($RegistryPolicy.ValueData + "`0")
$dataSize = $dataBytes.Count
}
([RegType]::REG_MULTI_SZ)
{
<#
When REG_MULTI_SZ ValueData contains an array, we need to null terminate each item. Furthermore
"Data in the Data field to be interpreted as a sequence of characters terminated by two null Unicode
characters, and within that sequence zero or more null-terminated Unicode strings can exist."
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-gpreg/5c092c22-bf6b-4e7f-b180-b20743d368f5
#>
$valueDataNullTermJoin = $RegistryPolicy.ValueData -join "`0"
$dataBytes = [System.Text.Encoding]::Unicode.GetBytes($valueDataNullTermJoin + "`0`0")
$dataSize = $dataBytes.Count
}
([RegType]::REG_BINARY)
{
$dataBytes = [System.Text.Encoding]::Unicode.GetBytes($RegistryPolicy.ValueData)
$dataSize = $dataBytes.Count
}
([RegType]::REG_DWORD)
{
$dataBytes = [System.BitConverter]::GetBytes([Int32] ([string]$RegistryPolicy.ValueData))
$dataSize = 4
}
([RegType]::REG_QWORD)
{
$dataBytes = [System.BitConverter]::GetBytes([Int64]$RegistryPolicy.ValueData)
$dataSize = 8
}
default
{
$dataBytes = [System.Text.Encoding]::Unicode.GetBytes("")
$dataSize = 0
}
}
$entry += [System.BitConverter]::GetBytes($dataSize)
# semicolon as delimiter
$entry += [System.Text.Encoding]::Unicode.GetBytes(';')
$entry += $dataBytes
# closing bracket
$entry += [System.Text.Encoding]::Unicode.GetBytes(']')
return $entry
}
<#
.SYNOPSIS
Replaces or adds a registry policy to a .pol file.
.PARAMETER Path
Path to a file (.pol extension).
.PARAMETER RegistryPolicy
Specifies the GPRegistryPolicy object to add to the .pol file.
#>
function Set-GPRegistryPolicyFileEntry
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[System.String]
$Path,
[Parameter(Mandatory = $true)]
[GPRegistryPolicy]
$RegistryPolicy
)
$desiredEntries = @()
$currentPolicies = Read-GPRegistryPolicyFile -Path $Path
# first check if a entry exists with same key
$matchingEntries = $currentPolicies | Where-Object -FilterScript { $PSItem.Key -eq $RegistryPolicy.Key -and $PSItem.ValueName -eq $RegistryPolicy.ValueName }
# if found compare it current policies to validate no duplicate entries
if ($matchingEntries)
{
# compare value data
foreach ($policy in $matchingEntries)
{
if ($policy.ValueData -eq $RegistryPolicy.ValueData)
{
Write-Verbose -Message ($script:localizedData.GPRegistryPolicyExists -f $policy.Key, $policy.ValeName, $policy.ValueData)
return
}
}
}
# at this point we have validated the desired entry doesn't match any of the current entries so we can add it to existing entries
$desiredEntries += $currentPolicies | Where-Object -FilterScript { $PSItem.Key -ne $RegistryPolicy.Key -or $PSItem.ValueName -ne $RegistryPolicy.ValueName }
$desiredEntries += $RegistryPolicy
# convert entries to byte array
New-GPRegistryPolicyFile -Path $Path
$encodingParameter = Get-ByteStreamParameter
foreach ($desiredEntry in $desiredEntries)
{
[System.Byte[]] $entry = New-GPRegistrySettingsEntry -RegistryPolicy $desiredEntry
$entry | Add-Content -Path $Path -Force @encodingParameter
}
}
<#
.SYNOPSIS
Removes a registry policy from a .pol file.
.PARAMETER Path
Path to a file (.pol extension).
.PARAMETER RegistryPolicy
Specifies the GPRegistryPolicy object to remove from the .pol file.
#>
function Remove-GPRegistryPolicyFileEntry
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[System.String]
$Path,
[Parameter(Mandatory = $true)]
[GPRegistryPolicy]
$RegistryPolicy
)
# read pol file
$currentPolicies = Read-GPRegistryPolicyFile -Path $Path
# first check if a entry exists with same key
$matchingEntries = $currentPolicies | Where-Object -FilterScript { $PSItem.Key -eq $RegistryPolicy.Key -and $PSItem.ValueName -eq $RegistryPolicy.ValueName }
# validate entry exists before removing it.
if ($null -eq $matchingEntries)
{
Write-Verbose -Message ($script:localizedData.NoMatchingPolicies)
return
}
$desiredEntries = $currentPolicies | Where-Object -FilterScript { $PSItem.Key -ne $RegistryPolicy.Key -or $PSItem.ValueName -ne $RegistryPolicy.ValueName }
# write entries to file
New-GPRegistryPolicyFile -Path $Path
$encodingParameter = Get-ByteStreamParameter
if ($null -ne $desiredEntries)
{
foreach ($desiredEntry in $desiredEntries)
{
[System.Byte[]] $entry = New-GPRegistrySettingsEntry -RegistryPolicy $desiredEntry
$entry | Add-Content -Path $Path -Force @encodingParameter
}
}
}
<#
.SYNOPSIS
Converts a sting to it's unicode characters.
.PARAMETER ValueString
Specifies the string to convert.
#>
function Convert-StringToInt
{
[CmdletBinding()]
[OutputType([System.Int32[]])]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.Object]
$ValueString
)
if ($ValueString.Length -le 4)
{
[int32] $result = 0
}
elseif ($ValueString.Length -le 8)
{
[int64] $result = 0
}
else
{
throw $script:localizedData.InvalidIntegerSize
}
for ($i = $ValueString.Length - 1 ; $i -ge 0 ; $i -= 1)
{
$result = $result -shl 8
$result = $result + ([int][char]$ValueString[$i])
}
return $result
}
<#
.SYNOPSIS
Retrieves the correct parameter to add a byte stream to a file that will be used by the Add-Content cmdlet.
.DESCRIPTION
Retrieves the correct parameter to add a byte stream to a file that will be used by the Add-Content cmdlet.
Add-Content in PS Core uses AsByteStream switch
Add-Content in PS 5.1 uses -Encoding Byte
#>
function Get-ByteStreamParameter
{
[CmdletBinding()]
[OutputType([Hashtable])]
param ()
if ($PSVersionTable.PSEdition -eq 'Core')
{
return @{
AsByteStream = $true
}
}
return @{
Encoding = 'Byte'
}
}
<#
.SYNOPSIS
Formats a multistring value.
.DESCRIPTION
Formats a multistring value by first spliting on \0 and the removing the terminating \0\0.
This is need to match the desired valueData
#>
function Format-MultiStringValue
{
[CmdletBinding()]
[OutputType([System.String[]])]
param
(
[Parameter()]
[System.Object]
$MultiStringValue
)
$result = @()
if ($MultiStringValue -match '\0')
{
[System.Collections.ArrayList] $array = $MultiStringValue.TrimEnd([char]0) -split '\0'
# Remove the terminating \0 from all indexes
foreach ($item in $array)
{
$result += $item.TrimEnd([char]0)
}
return $result
}
else
{
# If no terminating 0's are found split on whitespace
return (-split $MultiStringValue)
}
}
enum RegType
{
REG_NONE = 0 # No value type
REG_SZ = 1 # Unicode null terminated string
REG_EXPAND_SZ = 2 # Unicode null terminated string (with environmental variable references)
REG_BINARY = 3 # Free form binary
REG_DWORD = 4 # 32-bit number
REG_DWORD_LITTLE_ENDIAN = 4 # 32-bit number (same as REG_DWORD)
REG_DWORD_BIG_ENDIAN = 5 # 32-bit number
REG_LINK = 6 # Symbolic link (Unicode)
REG_MULTI_SZ = 7 # Multiple Unicode strings, delimited by \0, terminated by \0\0
REG_RESOURCE_LIST = 8 # Resource list in resource map
REG_FULL_RESOURCE_DESCRIPTOR = 9 # Resource list in hardware description
REG_RESOURCE_REQUIREMENTS_LIST = 10
REG_QWORD = 11 # 64-bit number
REG_QWORD_LITTLE_ENDIAN = 11 # 64-bit number (same as REG_QWORD)
}
<#
.SYNOPSIS
Class to create and manage registry policy objects
#>
class GPRegistryPolicy
{
[System.String] $Key
[System.String] $ValueName
[RegType] $ValueType
[System.String] $ValueLength
[System.Object] $ValueData
GPRegistryPolicy()
{
$this.Key = $Null
$this.ValueName = $null
$this.ValueType = [RegType]::REG_NONE
$this.ValueLength = 0
$this.ValueData = $Null
}
GPRegistryPolicy(
[System.String] $Key,
[System.String] $ValueName,
[RegType] $ValueType,
[System.String] $ValueLength,
[System.Object] $ValueData
)
{
$this.Key = $Key
$this.ValueName = $ValueName
$this.ValueType = $ValueType
$this.ValueLength = $ValueLength
$this.ValueData = $ValueData
}
[System.String] GetRegTypeString()
{
[System.String] $result = ''
switch ($this.ValueType)
{
([RegType]::REG_SZ)
{
$Result = 'String'
}
([RegType]::REG_EXPAND_SZ)
{
$Result = 'ExpandString'
}
([RegType]::REG_BINARY)
{
$Result = 'Binary'
}
([RegType]::REG_DWORD)
{
$Result = 'DWord'
}
([RegType]::REG_MULTI_SZ)
{
$Result = 'MultiString'
}
([RegType]::REG_QWORD)
{
$Result = 'QWord'
}
default
{
$Result = ''
}
}
return $result
}
static [RegType] GetRegTypeFromString([System.String] $Type)
{
$result = [RegType]::REG_NONE
switch ($Type)
{
'String'
{
$result = [RegType]::REG_SZ
}
'ExpandString'
{
$result = [RegType]::REG_EXPAND_SZ
}
'Binary'
{
$result = [RegType]::REG_BINARY
}
'DWord'
{
$result = [RegType]::REG_DWORD
}
'MultiString'
{
$result = [RegType]::REG_MULTI_SZ
}
'QWord'
{
$result = [RegType]::REG_QWORD
}
default
{
$result = [RegType]::REG_NONE
}
}
return $result
}
}