Parsers/GPO/Registry.ps1

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
$ParsersRoot = Get-Item $PsScriptRoot | ForEach-Object {$_.Parent} | ForEach-Object {$_.FullName}
$ModuleRoot = Get-Item $ParsersRoot | ForEach-Object {$_.Parent} | ForEach-Object {$_.FullName}
$Helpers = Join-Path $ModuleRoot 'Helpers'

# Create a variable so we can set DependsOn values between passes.
New-Variable -Name GlobalDependsOn -Value @() -Option AllScope -Scope Script -Force
$GlobalDependsOn = @()

Function Resolve-RegistrySpecialCases
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$true)]
        $regHash
    )

    # Special Cases.
    switch -regex ((Join-Path -Path $regHash.Key -ChildPath $regHash.ValueName))
    {
        "HKLM:\\System\\CurrentControlSet\\Control\\SecurePipeServers\\Winreg\\(AllowedExactPaths|AllowedPaths)\\Machine"
        {
            # $regHash.ValueData = $regHash.ValueData -split ","
        }

        "HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System\\LegalNoticeText"
        {
            #Special case LegalNoticeText, written as a REG_MULTI_SZ by Group Policy Editor but written to registry as REG_SZ
            #Replacing comma with LF (line feed) and CR (Carriage Return)
            $values = $regHash.ValueData -split ","
            $regHash.ValueData = ""
            $values[0..($values.count-2)] | ForEach-Object{$regHash.ValueData += $_ +"`r`n"}
            $regHash.ValueData += $values[($values.count-1)]
            #Change the type to REG_SZ
            $regHash.ValueType = "String"
        } 

    }
}

Function Add-RegistryDELVALDependsOn
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        $regHash
    )

    $DependsOn = @()
    $delVals = "DELVALS_$($regHash.Key.TrimStart("HKLM:"))"
    if ($script:GlobalDependsOn -contains $delVals -and $ExclusiveFlagAvailable)
    {
        $DependsOn += "[Registry]$delVals"
    }

    $delVal_ValueName = "DEL_$((Join-Path -Path $regHash.Key -ChildPath $regHash.ValueName).TrimStart("HKLM:"))"
    if ($script:GlobalDependsOn -contains $delVal_ValueName)
    {
        $DependsOn += "[Registry]$delVal_ValueName"
    }

    $deleteKeys = "DELETEKEY_$($regHash.Key.TrimStart("HKLM:"))"
    if ($script:GlobalDependsOn -contains $deleteKeys)
    {
        $DependsOn += "[Registry]$deleteKeys"
    }

    $deleteValue = "DELETEVALUES_$((Join-Path -Path $regHash.Key -ChildPath $regHash.ValueName).TrimStart("HKLM:"))"
    if ($script:GlobalDependsOn -contains $deleteValue)
    {
        $DependsOn += "[Registry]$deleteValue"
    }

    if ($DependsOn.count -gt 0)
    {
        $regHash.DependsOn = $DependsOn
    }
}

Function Register-RegistryDELVALDependsOn
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        $regHash
    )

    $CommentOUT = $false
    # Process any pol instructions.
    switch -regex ($regHash.ValueName)
    {
        "\*\*del\.(?<ValueName>.*)$" 
        {
            $regHash.ValueName = $Matches.ValueName
            $regHash.Ensure = "Absent"
            $Name = "DEL_$((Join-Path -Path $regHash.Key -ChildPath $regHash.ValueName).TrimStart("HKLM:"))"
            
            $script:GlobalDependsOn += $Name

            # This is only a delete so return from here.
            return Write-DSCString -Resource -Name $Name -Type 'RegistryPolicyFile' -Parameters $regHash -CommentOUT:$CommentOUT
        }

        "\*\*delvals\."
        {
            $regHash.Ensure = "Present"
            $regHash.ValueName = ""
            $regHash.Exclusive = $true
            $Name = "DELVALS_$($regHash.Key.TrimStart("HKLM:"))"

            $script:GlobalDependsOn += $Name
            # This is only a delete so return from here.
            return Write-DSCString -Resource -Name $Name -Type 'RegistryPolicyFile' -Parameters $regHash -CommentOUT:(!$ExclusiveFlagAvailable)
        }

        "\*\*DeleteValues"
        {
            $Data.ValueData = $Data.ValueData -replace "[^\u0020-\u007E]", ""
            foreach ($ValueName in ($Data.ValueData -split ";"))
            {          
                $regHash.Ensure = "Absent"
                $Name = "DELETEVALUES_$((Join-Path -Path $regHash.Key -ChildPath $regHash.ValueName).TrimStart("HKLM:"))"

                $script:GlobalDependsOn += $Name

                # This is only a delete so return from here.
                Write-DSCString -Resource -Name $Name -Type 'RegistryPolicyFile' -Parameters $regHash -CommentOUT:$CommentOUT
            }

            return
        }

        "\*\*DeleteKeys"
        {
            $Data.ValueData = $Data.ValueData -replace "[^\u0020-\u007E]", ""
            foreach ($Key in ($Data.ValueData -split ";"))
            {          
                $regHash.Ensure = "Absent"
                $Name = "DELETEKEYS_$($regHash.Key.TrimStart("HKLM:"))"

                $script:GlobalDependsOn += $Name

                # This is only a delete so return from here.
                Write-DSCString -Resource -Name $Name -Type 'RegistryPolicyFile' -Parameters $regHash -CommentOUT:$CommentOUT
            }

            return
        }

        "\*\*SecureKey"
        {
            $Name = "SECUREKEY_$($regHash.Key)"

            # This is only a delete so return from here.
            return Write-DSCString -Resource -Name $Name -Type 'RegistryPolicyFile' -Parameters $regHash -CommentOUT:$true
        }
    }

    return $null
}

Function Update-RegistryHashtable
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        $regHash
    )
    
    $regHash.ValueName = $regHash.ValueName -replace "[^\u0020-\u007E]", ""

    if ([string]::IsNullOrEmpty($regHash.ValueName))
    {
        $regHash.Remove("ValueData")
    }
    $typeHash = @{"REG_SZ" = "String"; "REG_NONE" = "None"; "REG_DWORD" = "Dword"; "REG_EXPAND_SZ" = "ExpandString"; "REG_QWORD" = "Qword"; "REG_BINARY" = "Binary"; "REG_MULTI_SZ" = "MultiString"}

    if ($regHash.ValueType -in $typeHash.Keys)
    {
        $regHash.ValueType = $typeHash[$regHash.ValueType.ToString()]
    }
    else
    {
        $regHash.ValueType = "None"
    }

    if ($regHash.ContainsKey("ValueData") -and $regHash.ValueData -ne $null)
    {
        switch ($regHash.ValueType)
        {
            "String"
            {
                [string]$regHash.ValueData = "'$($regHash.ValueData)'"# -replace "[^\u0020-\u007E]", ""
            }
            
            "None" 
            { 
                $regHash.Remove("ValueData") | Out-Null
            }

            "ExpandString" 
            { 
                # Contains unexpanded Environment Paths. Should I expand them?
                [string]$regHash.ValueData = "'$($regHash.ValueData)'"# -replace "[^\u0020-\u007E]", ""
            }
            
            "Dword" 
            { 
                $ValueData = 1
                if ($regHash.ValueData -match "(Disabled|Enabled|Not Defined|True|False)" -or $ValueData -eq "''")
                {
                    # This is supposed to be an INT and it's a String
                    [int]$regHash.ValueData = @{"Disabled" = 0; "Enabled" = 1; "Not Defined" = 0; "True" = 1; "False" = 0; '' = 0}.$ValueData
                }
                elseif (([int]::TryParse($regHash.ValueData, [ref]$ValueData)))
                {
                    [int]$regHash.ValueData = $ValueData
                }
                else
                {
                    # If it doesn't parse as an integer, try parsing as hexadecimal.
                    Try 
                    {
                        [int]$regHash.ValueData = [Convert]::ToInt32($regHash.ValueData, 16)
                    }
                    Catch
                    {
                        # Other wise fail over for now until a better option comes along.
                        $regHash.Remove("ValueData") | Out-Null
                    }
                }
            }

            "Qword"
            { 

            }    

            "Binary" 
            { 
                $reghash.ValueType = "Binary" 
                if ($regHash.ContainsKey("ValueData"))
                {
                    if ($regHash.ValueData.Count -gt 1)
                    {
                        Try
                        {
                            [string]$hexified = ($regHash.ValueData | ForEach-Object ToString X2) -join ''
                            [string]$regHash.ValueData = $hexified
                        }
                        Catch
                        {
                            Write-Error "Error Processing Binary Data for Key ($(Join-Path -Path $regHash.Key -ChildPath $regHash.ValueName))"
                            $regHash.CommentOut = $true
                            Add-ProcessingHistory -Type 'RegistryPolicyFile' -Name "Registry(INF): $(Join-Path -Path $regHash.Key -ChildPath $regHash.ValueName)" -ParsingError
                        }
                    }
                    else
                    {
                        $regHash.ValueData = "$($regHash.ValueData)"
                    }
                }
                
                $regHash.ValueType = "Binary"
            }  

            "MultiString" 
            { 
                if ($regHash.ValueData -isnot [System.Array])
                {
                     # Does this have to be done in the Calling Function instead?
                    $regHash.ValueData = @"
$($regHash.ValueData)
"@
# -replace "[^\u0020-\u007E]", ""
               
                }

                $reghash.ValueType = "MultiString" 
            }

            Default { $regHash.ValueType = "None" }
        }
    }

    if ($regHash.ValueType -eq "None")
    {
        # The REG_NONE is not allowed by the Registry resource.
        $regHash.Remove("ValueType")
    }

    if ([string]::IsNullOrEmpty($regHash.ValueName))
    {
        $regHash.Remove("ValueData")
    }

    Resolve-RegistrySpecialCases $reghash
}

Function Write-GPORegistryPOLData
{
    [CmdletBinding()]
    [OutputType([String])]
    param
    (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [psobject]$Data,

        [Parameter()]
        [ValidateSet("HKLM", "HKCU")]
        [string]$Hive = "HKLM"
    )

    $regHash = @{}
    $regHash.ValueName = ""
    $regHash.Key = "$($Hive):\"

    $CommentOUT = $false
    if ($Hive -eq "HKCU")
    {
        Write-Verbose "Write-GPORegistryPOLData: CurrentUser settings are currently not supported"
        $CommentOut = $true
    }

    $regHash.ValueName = $Data.ValueName
    $regHash.Key = Join-Path -Path $regHash.Key -ChildPath $Data.KeyName
    $regHash.ValueType = $Data.ValueType.ToString()
    
    # TODO this likely will need additional types in the future
    $regHash.TargetType = 'ComputerConfiguration'

    if ($Data.ValueData -eq "$([char]0)")
    {
        $regHash.ValueData = $null
    }
    else
    {
        $regHash.ValueData = $Data.ValueData
    }

    Update-RegistryHashtable $regHash
    
    $output = Register-RegistryDELVALDependsOn $regHash

    if ($output -ne $null)
    {
        return $output
    }
        
    Add-RegistryDELVALDependsOn $regHash

    $comment = ""
    if ($regHash.ValueData -eq $null)
    {
        $Comment = "`tThis MultiString Value has a value of `$null, `n`tSome Security Policies require Registry Values to be `$null`n`tIf you believe ' ' is the correct value for this string, you may change it here."
    }  
    
    Write-DSCString -Resource -Name "Registry(POL): $(Join-Path -Path $regHash.Key -ChildPath $regHash.ValueName)" -Type 'RegistryPolicyFile' -Parameters $regHash -CommentOUT:$CommentOUT -Comment $Comment
}

Function Write-GPORegistryINFData
{
    [CmdletBinding()]
    [OutputType([String])]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$Key,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$ValueData
    )

    # Regsitry keys set by Security Policy (secedit.exe) should not be set directly
    # The info from gpttmpl.inf is the path to the key and the data
    # SecurityOption resource takes each setting by name, not path (so this is sort of a reverse of SecurityOption resource)
    # There is no need to use seperate entries per key, but it is the easiest to support at first

    # Loading SecurityOptionData (this file was copied from SecurityPolicyDSC module)
    $securityOptionData = Import-PowerShellDataFile (Join-Path $Helpers 'SecurityOptionData.psd1')
    $securityOptionRegistry = $securityOptionData.GetEnumerator() | Where-Object {$_.Value.Section -eq 'Registry Values'}
    $securityOption = $securityOptionRegistry | Where-Object {$_.Value.Value -eq $Key}
    $Name = $securityOption.Name
    if ($null -eq $Name) {
        throw "The GptTmpl.inf file contains an entry '$Key' in the Registry section that is an unknown value in the module file Helpers\SecurityOptionData.psd1."
    }

    # Create a hash table containing the DSC resource parameters

    $resHash = @{}
    $resHash.Name = $Name
    $resHash.$Name = ""

    $CommentOUT = $false

    Try
    {
        # if valid data, lookup the name for the value used by securityoption resource
        if ($ValueData -match "^(\d),")
        {
            $valueType = $Matches.1
            $value = $securityOption.value.option.getenumerator() | Where-Object {$_.value -eq $ValueData}
            $resHash.$Name = $value.Name
        }
        else
        {
            throw "Malformed data"
        }
    }
    catch
    {
        $resHash.$Name = $null
        continue    
    }
            
    if (!$Key.StartsWith("MACHINE"))
    {
        Write-Verbose "Write-GPORegistryINFData: Current User Registry settings are not yet supported."
        $CommentOUT = $true
    }

    $typeHash = @{"1" = "REG_SZ"; "7" = "REG_MULTI_SZ"; "4" = "REG_DWORD"; "3" = "REG_BINARY"}
    if (!$typeHash.ContainsKey($valueType))
    {
        Write-Verbose "Write-GPORegistryINFData: $($values[0]) ValueType is not yet supported"
        # Add this resource to the processing history.
        Add-ProcessingHistory -Type 'SecurityOption' -Name "SecurityRegistry(INF): $Name" -ParsingError
        $CommentOUT = $true
    }
    
    Write-DSCString -Resource -Name "SecurityRegistry(INF): $Name" -Type 'SecurityOption' -Parameters $resHash -CommentOUT:$CommentOUT
}