This repository has been archived by the owner on Jun 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 286
/
GroupPolicy.psm1
1739 lines (1332 loc) · 66.3 KB
/
GroupPolicy.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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#requires -Version 3
Set-StrictMode -Version 3
Function Get-GPClientSideExtensions() {
<#
.SYNOPSIS
Gets information about Group Policy Client Side Extensions available on the system.
.DESCRIPTION
Gets information about Group Policy Client Side Extensions available on the system.
.EXAMPLE
Get-GPClientSideExtensions
#>
[CmdletBinding()]
[OutputType([System.Collections.Hashtable])]
Param()
$cseDefinitions = @{}
$systemRoot = $env:SystemRoot
$gptExtPaths = [string[]]@('hklm:\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\GPExtensions\','hklm:\Software\Wow6432Node\Microsoft\Windows NT\CurrentVersion\Winlogon\GPExtensions\')
$gptExtPaths | ForEach-Object {
# can't use below code because it skips the registry CSE GUID due to the subkey not having any defined value names (other default, which is empty) under it
#Get-ChildItem $_ | Get-ItemProperty -Name 'PSChildName','(default)','DisplayName','DllName','ProcessGroupPolicy','ProcessGroupPolicyEx' -ErrorAction SilentlyContinue | ForEach-Object {
$cseRootPath = $_
(Get-Item $cseRootPath).GetSubKeyNames() | ForEach-Object {
$cseGuid = $_
Write-Verbose -Message ('Processing {0}' -f $cseGuid)
$valueNames = Get-Item ('{0}\{1}' -f $cseRootPath,$cseGuid) | Get-ItemProperty -Name 'PSChildName','(default)','DisplayName','DllName','ProcessGroupPolicy','ProcessGroupPolicyEx' -ErrorAction SilentlyContinue
$cseName = ''
$cseDll = ''
if ($cseGuid -eq '{35378EAC-683F-11D2-A89A-00C04FBBCFA2}') {
$cseName = 'Registry'
}
if ($valueNames -ne $null) {
if ($valueNames.PSObject.Properties.Name -contains '(default)') {
$cseName = $valueNames.'(default)'
}
# if $cseName -eq '' then use LoadLibrary($cseDll), LoadString($cseDisplayName offset, if it has a value), FreeLibrary
#$cseDisplayName = ''
#if ($_.PSObject.Properties.Name -contains 'DisplayName') {
# $cseDisplayName = $_.DisplayName
#}
$cseProcessName = ''
if ($valueNames.PSObject.Properties.Name -contains 'ProcessGroupPolicy') {
$cseProcessName = $valueNames.ProcessGroupPolicy
}
if ($cseName -eq '' -and $cseProcessName -ne '') {
$cseName = $cseProcessName
$cseName = $cseName.Replace('GroupPolicy','').Replace('Process','')
}
$cseProcessNameEx = ''
if ($valueNames.PSObject.Properties.Name -contains 'ProcessGroupPolicyEx') {
$cseProcessNameEx = $valueNames.ProcessGroupPolicyEx
$cseName = $cseName.Replace('GroupPolicyEx','').Replace('Process','')
}
if ($cseName -eq '' -and $cseProcessNameEx -ne '') {
$cseName = $cseProcessNameEx
}
$cseDll = $valueNames.DllName
if (-not([System.IO.Path]::IsPathRooted($cseDll))) {
$cseDll = '{0}\System32\{1}' -f $systemRoot,$cseDll
}
if (-not(Test-Path -Path $cseDll)) {
Write-Warning -Message ('{0} does not exist' -f $cseDll)
}
}
$cse = [pscustomobject]@{
Guid = $cseGuid;
#DisplayName = $cseDisplayName;
Name = $cseName;
Dll = $cseDll;
}
if (-not($cseDefinitions.ContainsKey($cseGuid))) {
$cseDefinitions.Add($cseGuid,$cse)
}
}
}
return $cseDefinitions
}
Function Get-GPOBackupClientSideExtensions() {
<#
.SYNOPSIS
Gets information about Group Policy Client Side Extensions that are listed as being used in the GPO backup.
.DESCRIPTION
Gets information about Group Policy Client Side Extensions that are listed as being used in the GPO backup.
.EXAMPLE
Get-GPOBackupClientSideExtensions -Path '.\Secure-Host-Baseline\Windows\Group Policy Objects\Computer\{A2A38432-E322-437F-9975-B7CC7F16F4AA}'
#>
[CmdletBinding()]
[OutputType([System.Collections.Hashtable])]
Param(
[Parameter(Mandatory=$true, HelpMessage='The path of the GPO backup folder')]
[ValidateNotNullOrEmpty()]
[ValidateScript({Test-Path -Path $_ -PathType Container})]
[ValidateScript({[System.IO.Directory]::Exists($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($_))})]
[string]$Path
)
$Path = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)
$gpoBackupExtensions = @{}
$backupXmlFile = 'Backup.xml'
$backupXmlFilePath = Join-Path -Path $Path -ChildPath $backupXmlFile
if(-not(Test-Path -Path $backupXmlFilePath)) {
throw "$backupXmlFilePath does not exist"
}
$backupXml = [xml](Get-Content -Path $backupXmlFilePath)
# note the extension GUIDs from the backup XML are two different types of extensions:
# 1. client side extension GUIDs which is what we care about
# 2. MMC snap-in GUIDs (can be enumerated under hklm:\SOFTWARE\Microsoft\MMC\SnapIns\ and hklm:\SOFTWARE\WOW6432Node\Microsoft\MMC\SnapIns\, FYI some have FX: prepended) which we don't care about
$machineExtensions = [string[]]@()
if ($backupXml.GroupPolicyBackupScheme.GroupPolicyObject.GroupPolicyCoreSettings.MachineExtensionGuids -is [System.Xml.XmlElement]) {
$machineExtensions = [string[]]($backupXml.GroupPolicyBackupScheme.GroupPolicyObject.GroupPolicyCoreSettings.MachineExtensionGuids.'#cdata-section'.Replace('[','').Replace(']','').Replace('}{','},{').Split(','))
}
$userExtensions = [string[]]@()
if ($backupXml.GroupPolicyBackupScheme.GroupPolicyObject.GroupPolicyCoreSettings.UserExtensionGuids -is [System.Xml.XmlElement]) {
$userExtensions = [string[]]($backupXml.GroupPolicyBackupScheme.GroupPolicyObject.GroupPolicyCoreSettings.UserExtensionGuids.'#cdata-section'.Replace('[','').Replace(']','').Replace('}{','},{').Split(','))
}
$extensions = Get-GPClientSideExtensions
# filter out the MMC snap-in GUIDs by only returning the CSE GUIDs
[string[]]($machineExtensions + $userExtensions) | ForEach-Object {
if ($extensions.ContainsKey($_)) {
if (-not($gpoBackupExtensions.ContainsKey($_))) {
$gpoBackupExtensions.Add($_, $extensions[$_])
}
}
}
return $gpoBackupExtensions
}
Function Get-GPOBackupInformation() {
<#
.SYNOPSIS
Gets Group Policy Object backup information.
.DESCRIPTION
Gets Group Policy Object backup information by parsing the bkupInfo.xml file from the GPO backup folder.
.PARAMETER Path
The path of the GPO backup folder. The path should end with a GUID and a bkupInfo.xml should be inside the folder.
.EXAMPLE
Get-GPOBackupInformation -Path '.\{BD6E70EE-4F8E-4BBA-A3C3-F1B715A2A028}'
#>
[CmdletBinding()]
[OutputType([pscustomobject])]
Param(
[Parameter(Mandatory=$true, HelpMessage='The path of the GPO backup folder')]
[ValidateNotNullOrEmpty()]
[ValidateScript({Test-Path -Path $_ -PathType Container})]
[ValidateScript({[System.IO.Directory]::Exists($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($_))})]
[string]$Path
)
$Path = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)
$backupXmlFile = 'bkupInfo.xml'
$backupXmlFilePath = Join-Path -Path $Path -ChildPath $backupXmlFile
if(-not(Test-Path -Path $backupXmlFilePath)) {
throw "$backupXmlFilePath does not exist"
}
$backupXml = [xml](Get-Content -Path $backupXmlFilePath)
$backupInstNode = $backupXml.BackupInst
$gpoGuid = [System.Guid]$backupInstNode.GPOGuid.'#cdata-section'
$gpoDomain = [string]$backupInstNode.GPODomain.'#cdata-section'
$gpoDomainGuid = [System.Guid]$backupInstNode.GPODomainGuid.'#cdata-section'
$gpoDC = [string]$backupInstNode.GPODomainController.'#cdata-section'
$backupTime = [System.DateTime]([System.DateTime]::ParseExact($backupInstNode.BackupTime.'#cdata-section', 'yyyy-MM-ddTHH:mm:ss', [System.Globalization.CultureInfo]::CurrentCulture).ToLocalTime())
$id = [System.Guid]$backupInstNode.ID.'#cdata-section' # the GUID that the backup folder is named is this GUID
$comment = [string]$backupInstNode.Comment.'#cdata-section'
$gpoDisplayName = [string]$backupInstNode.GPODisplayName.'#cdata-section'
$gpo = [pscustomobject]@{
Guid = $gpoGuid;
Domain = $gpoDomain;
DomainGuid = $gpoDomainGuid;
DomainContoller = $gpoDC;
BackupTime = $backupTime;
BackupGuid = $id;
Comment = $comment;
DisplayName = $gpoDisplayName
}
return $gpo
}
Function Update-GPOBackup() {
<#
.SYNOPSIS
Updates an existing Group Policy Object backup with data from a different GPO backup.
.DESCRIPTION
Updates an existing Group Policy Object backup with data from a different GPO backup but keeps the current GPO backup GUID (aka the ID) in the backup metadata.
.PARAMETER CurrentGPOBackupPath
The path of the current GPO backup folder. The path should end with a GUID and a bkupInfo.xml should be inside the folder.
.PARAMETER NewGPOBackupPath
The path of the new GPO backup folder.
.EXAMPLE
Update-GPOBackup -CurrentGPOBackupPath '.\{BD6E70EE-4F8E-4BBA-A3C3-F1B715A2A028}' -NewGPOBackupPath '.\'
#>
[CmdletBinding(SupportsShouldProcess=$True)]
[OutputType([void])]
Param(
[Parameter(Mandatory=$true, HelpMessage='The path of the current GPO backup folder.')]
[ValidateNotNullOrEmpty()]
[ValidateScript({Test-Path -Path $_ -PathType Container})]
[ValidateScript({[System.IO.Directory]::Exists($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($_))})]
[string]$CurrentGPOBackupPath,
[Parameter(Mandatory=$true, HelpMessage='The path of the new GPO backup folder.')]
[ValidateNotNullOrEmpty()]
[ValidateScript({Test-Path -Path $_ -PathType Container})]
[ValidateScript({[System.IO.Directory]::Exists($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($_))})]
[string]$NewGPOBackupPath
)
$CurrentGPOBackupPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($CurrentGPOBackupPath)
$NewGPOBackupPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($NewGPOBackupPath)
$backupXmlFile = 'bkupInfo.xml'
$newBackupXmlFilePath = Join-Path -Path $NewGPOBackupPath -ChildPath $backupXmlFile
$currentBackupXmlFilePath = Join-Path -Path $CurrentGPOBackupPath -ChildPath $backupXmlFile
if(-not(Test-Path -Path $newBackupXmlFilePath)) {
throw "$newBackupXmlFilePath does not exist"
}
if(-not(Test-Path -Path $currentBackupXmlFilePath)) {
throw "$currentBackupXmlFilePath does not exist"
}
$newBackupInfo = Get-GPOBackupInformation -GPOBackupPath $NewGPOBackupPath
$currentBackupInfo = Get-GPOBackupInformation -GPOBackupPath $CurrentGPOBackupPath
$newGuid = $newBackupInfo.ID.ToString('B').ToUpper()
Write-Verbose -Message ('New Guid: {0}' -f $newGuid)
$currentGuid = $currentBackupInfo.ID.ToString('B').ToUpper()
Write-Verbose -Message ('Current Guid: {0}' -f $currentGuid)
if($newGuid -ne $currentGuid) {
Remove-Item -Path $CurrentGPOBackupPath -Recurse -Force
Copy-Item -Path $NewGPOBackupPath\* -Destination $CurrentGPOBackupPath -Container -Force -Recurse
$xml = Get-Content -Path $currentBackupXmlFilePath
$updatedXml = $xml.Replace($newGuid, $currentGuid)
if($xml -ne $updatedXml) {
Set-Content -Path $currentBackupXmlFilePath -Value $updatedXml -NoNewLine
Write-Verbose -Message ('Replaced {0} with {1} in {2}' -f $newGuid,$currentGuid,$currentBackupXmlFilePath)
} else {
Write-Verbose -Message ('Did not update {0} because {1} was not found in the file' -f $currentBackupXmlFilePath,$newGuid)
}
} else {
Write-Verbose -Message ('Both GPO backup IDs are the same so {0} was not updated' -f $currentBackupXmlFilePath)
}
}
Function Test-IsGuid() {
<#
.SYNOPSIS
Tests if the value is a GUID.
.DESCRIPTION
Tests if the value is a GUID.
.PARAMETER Value
A value to test.
.EXAMPLE
Test-IsGuid -Value '{AC662460-6494-4818-A303-FADC513B9876}'
#>
[CmdletBinding()]
[OutputType([System.IO.DirectoryInfo[]])]
Param(
[Parameter(Mandatory=$true, HelpMessage='A value to test')]
[ValidateNotNullOrEmpty()]
[string]$Value
)
$isGuid = $false;
try {
[System.Guid]::Parse($Value) | Out-Null
$isGuid = $true
} catch { }
return $isGuid
}
Function Get-GPOBackupFolders() {
<#
.SYNOPSIS
Gets folders containing Group Policy Object backups.
.DESCRIPTION
Gets folders containing Group Policy Object backups.
.PARAMETER Path
A path containing GPO backup folders.
.EXAMPLE
Get-GPOBackupFolders -Path '.\Secure-Host-Baseline'
#>
[CmdletBinding()]
[OutputType([System.IO.DirectoryInfo[]])]
Param(
[Parameter(Mandatory=$true, HelpMessage='A path containing GPO backup folders.')]
[ValidateNotNullOrEmpty()]
[ValidateScript({Test-Path -Path $_ -PathType Container})]
[ValidateScript({[System.IO.Directory]::Exists($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($_))})]
[string]$Path
)
$Path = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)
return ,[System.IO.DirectoryInfo[]]@(Get-ChildItem -Path $Path -Recurse | Where-Object { $_.PsIsContainer -eq $true } | Where-Object { Test-Path -Path (Join-Path -Path $_.FullName -ChildPath 'bkupInfo.xml') -PathType Leaf} | Where-Object { (Test-IsGuid -Value ($_.Name)) -eq $true })
}
Function Test-IsGPOBackupFolder() {
<#
.SYNOPSIS
Tests if a path is a Group Policy Object backup folder.
.DESCRIPTION
Tests if a path is a Group Policy Object backup folder.
.PARAMETER Path
A path of a GPO backup folder.
.EXAMPLE
Test-IsGPOBackupFolder -Path '.\Secure-Host-Baseline\Windows\Group Policy Objects\Computer\{AC662460-6494-4818-A303-FADC513B9876}'
#>
[CmdletBinding()]
[OutputType([bool])]
Param(
[Parameter(Mandatory=$true, HelpMessage='A path of a GPO backup folders.')]
[ValidateNotNullOrEmpty()]
[ValidateScript({Test-Path -Path $_ -PathType Container})]
[ValidateScript({[System.IO.Directory]::Exists($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($_))})]
[string]$Path
)
$Path = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)
$folder = [System.IO.DirectoryInfo[]]$Path
$backupFiles = [System.IO.FileInfo[]]@(Get-ChildItem -Path $Path | Where-Object { $_.Name -eq 'bkupInfo.xml' })
return ($backupFiles.Count -eq 1) -and (Test-IsGuid -Value ($folder.Name))
}
Function Get-GPODefinitions() {
<#
.SYNOPSIS
Gets the definitions of the Group Policy Objects.
.DESCRIPTION
Gets the definitions of the Group Policy Objects based on policy.json files that describe them.
.PARAMETER Path
A path the contains policy.json files.
.EXAMPLE
Get-GPODefinitions -Path '.\Secure-Host-Baseline\'
#>
[CmdletBinding()]
[OutputType([System.Collections.Generic.List[object]])]
Param(
[Parameter(Mandatory=$true, HelpMessage='A path containing policy.json files.')]
[ValidateNotNullOrEmpty()]
[ValidateScript({Test-Path -Path $_ -PathType Container})]
[ValidateScript({[System.IO.Directory]::Exists($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($_))})]
[string]$Path
)
$Path = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)
$policyFiles = [System.IO.FileInfo[]]@(Get-ChildItem -Path $Path -Recurse | Where-Object { $_.PsIsContainer -eq $false -and $_.Name -eq 'policy.json' })
$policyDefinitions = New-Object System.Collections.Generic.List[object]
$policyFiles | ForEach-Object {
$policyDefinition = Get-Content -Path $_.FullName -Raw | ConvertFrom-Json
$gpoPaths = Get-GPOBackupFolders -Path $_.DirectoryName
$gpoPath = $gpoPaths[0].FullName
$policyDefinition | Add-Member -MemberType NoteProperty -Name 'PolicyObjectPath' -Value $gpoPath
Write-Verbose -Message ('GPO Path: {0}' -f $gpoPath)
# Resolve-Path will throw an error if the path is wrong (does not exist) which is the desired behavior
$gptPath = Resolve-Path -Path (@($_.DirectoryName,$policyDefinition.PolicyTemplatePath,'Group Policy Templates') -join [System.IO.Path]::DirectorySeparatorChar)
$policyDefinition.PolicyTemplatePath = $gptPath
Write-Verbose -Message ('GPT Path: {0}' -f $gptPath)
$gpoInformation = Get-GPOBackupInformation -Path $gpoPath
$policyDefinition | Add-Member -MemberType NoteProperty -Name 'PolicyInformation' -Value $gpoInformation
$policyDefinitions.Add($policyDefinition)
}
return ,[System.Collections.Generic.List[object]]$policyDefinitions
}
Function Get-Intersection() {
<#
.SYNOPSIS
Gets the set intersection of two string arrays.
.DESCRIPTION
Gets the set intersection of two string arrays.
.PARAMETER ReferenceObject
An array of string objects used as a reference for comparison.
.PARAMETER DifferenceObject
An array of string objects compared to the reference objects.
.EXAMPLE
Get-Intersection -ReferenceObject 'test1','test2' -DifferenceObject 'test1','test3'
#>
[CmdletBinding()]
[OutputType([string[]])]
Param(
[Parameter(Mandatory=$true, HelpMessage='An array of string objects used as a reference for comparison')]
[ValidateNotNullOrEmpty()]
[string[]]$ReferenceObject,
[Parameter(Mandatory=$true, HelpMessage='An array of string objects compared to the reference objects')]
[ValidateNotNullOrEmpty()]
[string[]]$DifferenceObject
)
$result = [string[]]@(Compare-Object $ReferenceObject $DifferenceObject -PassThru -IncludeEqual -ExcludeDifferent)
return ,$result
}
Function Test-IsModuleAvailable() {
<#
.SYNOPSIS
Tests if a PowerShell module is available on a system.
.DESCRIPTION
Tests if a PowerShell module is available on a system.
.PARAMETER Name
The module name.
.EXAMPLE
Test-IsModuleAvailable -Name 'ActiveDirectory'
#>
[CmdletBinding()]
[OutputType([bool])]
Param(
[Parameter(Mandatory=$true, HelpMessage='The module name')]
[ValidateNotNullOrEmpty()]
[string]$Name
)
$ProgressPreference = [System.Management.Automation.ActionPreference]::SilentlyContinue
$isAvailable = $false
$error.Clear()
Import-Module -Name $Name -ErrorAction SilentlyContinue
$isAvailable = ($error.Count -eq 0)
$error.Clear()
return $isAvailable
}
Function Get-DomainSecurityIdentifier() {
<#
.SYNOPSIS
Gets the domain specific security identifier (SID) value.
.DESCRIPTION
Gets the domain specific security identifier (SID) value.
.EXAMPLE
Get-DomainSecurityIdentifier
#>
[CmdletBinding()]
[OutputType([string])]
Param()
#$context = ([adsi]'LDAP://RootDSE').defaultNamingContext
#$domainSidBytes = ([adsi]"LDAP://$context").Properties['objectsid'].Value
#$domainSid = New-Object -TypeName System.Security.Principal.SecurityIdentifier -ArgumentList $domainSidBytes,0
#return $domainSid.Value
if (-not(Test-IsModuleAvailable -Name 'ActiveDirectory')) {
throw 'ActiveDirectory module not available'
}
$ProgressPreference = [System.Management.Automation.ActionPreference]::SilentlyContinue
Import-Module ActiveDirectory
return (Get-ADDomain).DomainSid.Value
}
Function Test-IsAdministrator() {
<#
.SYNOPSIS
Tests if current user is an administrator.
.DESCRIPTION
Tests if current user is an administrator.
.PARAMETER AdministratorType
The type of administrator to test for.
.EXAMPLE
Test-IsAdministrator
.EXAMPLE
Test-IsAdministrator -AdministratorType 'Domain'
.EXAMPLE
Test-IsAdministrator -AdministratorType 'Local'
#>
[CmdletBinding()]
[OutputType([bool])]
Param (
[Parameter(Mandatory=$false, HelpMessage='The type of administrator to test for')]
[ValidateNotNullOrEmpty()]
[ValidateSet('Domain', 'Local', IgnoreCase=$true)]
[string]$AdministratorType
)
$currentPrincipal = New-Object System.Security.Principal.WindowsPrincipal -ArgumentList ([System.Security.Principal.WindowsIdentity]::GetCurrent())
$isAdministrator = $false
$builtInAdministratorSid = [System.Security.Principal.SecurityIdentifier]'S-1-5-32-544'
$domainAdministratorsRid = 0x200
if ('Domain' -eq $AdministratorType -or (Test-IsDomainJoined)) {
$domainSid = Get-DomainSecurityIdentifier
$domainAdministratorsSid = [System.Security.Principal.SecurityIdentifier]('{0}-{1}' -f $domainSid,$domainAdministratorsRid)
}
# using a SID for IsInRole has a number of advantages:
# 1. using RID method didn't work when on a domain and using the domain admin RID
# 2. don't have to worry about name ambiguity
# 3. don't have to prepend names with domain name
# 4. documentation says its more efficient
# https://msdn.microsoft.com/en-us/library/86wd8zba(v=vs.110).aspx
switch ($AdministratorType.ToLower()) {
'domain' {
$isAdministrator = $currentPrincipal.IsInRole($domainAdministratorsSid)
break
}
'local' {
$isAdministrator = $currentPrincipal.IsInRole($builtInAdministratorSid)
break
}
'' {
$isAdministrator = $currentPrincipal.IsInRole($builtInAdministratorSid) -or $currentPrincipal.IsInRole($domainAdministratorsSid)
break
}
default {
throw "Unexpected administrator type of $AdministratorType"
}
}
return $isAdministrator
}
Function Invoke-Process() {
<#
.SYNOPSIS
Executes a process.
.DESCRIPTION
Executes a process and waits for it to exit.
.PARAMETER Path
The path of the file to execute.
.PARAMETER Arguments
THe arguments to pass to the executable. Arguments with spaces in them are automatically quoted.
.PARAMETER PassThru
Return the results as an object.
.EXAMPLE
Invoke-Process -Path 'C:\Windows\System32\whoami.exe'
.EXAMPLE
Invoke-Process -Path 'C:\Windows\System32\whoami.exe' -Arguments '/groups'
.EXAMPLE
Invoke-Process -Path 'C:\Windows\System32\whoami.exe' -Arguments '/groups' -PassThru
.EXAMPLE
Invoke-Process -Path 'lgpo.exe' -Arguments '/g','C:\path to gpo folder' -PassThru
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true, HelpMessage='The path of the file to execute')]
[ValidateNotNullOrEmpty()]
[ValidateScript({Test-Path -Path $_ -PathType Leaf})]
[ValidateScript({[System.IO.File]::Exists($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($_))})]
[string]$Path,
[Parameter(Mandatory=$false, HelpMessage='The arguments to pass to the executable')]
[ValidateNotNullOrEmpty()]
[string[]]$Arguments,
[Parameter(Mandatory=$false, HelpMessage='Return the results as an object')]
[switch]$PassThru
)
$Path = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)
$parameters = $PSBoundParameters
$escapedArguments = ''
if ($parameters.ContainsKey('Arguments')) {
$Arguments | ForEach-Object {
if ($_.Contains(' ')) {
$escapedArguments = $escapedArguments,("`"{0}`"" -f $_) -join ' '
} else {
$escapedArguments = $escapedArguments,$_ -join ' '
}
}
}
$processInfo = New-Object System.Diagnostics.ProcessStartInfo
$processInfo.FileName = $Path
$processInfo.RedirectStandardError = $true
$processInfo.RedirectStandardOutput = $true
$processInfo.UseShellExecute = $false
$processInfo.CreateNoWindow = $true
$processInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden
$processInfo.Arguments = $escapedArguments.Trim()
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $processInfo
$process.Start() | Out-Null
$output = $process.StandardOutput.ReadToEnd()
$process.WaitForExit()
$exitCode = $process.ExitCode
if($PassThru) {
return [pscustomobject]@{
'ExitCode' = $exitCode;
'Output' = $output;
'Process' = $process;
}
}
}
Function Test-IsElevated() {
<#
.SYNOPSIS
Tests if the current user is running in an elevated context.
.DESCRIPTION
Tests if the current user is running in an elevated context.
.EXAMPLE
Test-IsElevated
#>
[CmdletBinding()]
[OutputType([bool])]
Param()
#todo: P\Invoke OpenProcessToken, GetTokenInformation with TokenIntegrityLevel instead. TOKEN_GROUP.Groups (SID_AND_ATTRIBUTES) see https://msdn.microsoft.com/en-us/library/bb625963.aspx
$path = $env:SYSTEMROOT,'System32','whoami.exe' -join [System.IO.Path]::DirectorySeparatorChar
$result = Invoke-Process -Path $path -Arguments '/groups' -PassThru
$highIntegrityLevelSid = 'S-1-16-12288'
$isElevated = ($result.Output) -match $highIntegrityLevelSid
return $isElevated
}
Function Test-IsDomainController() {
<#
.SYNOPSIS
Tests if the system is a domain controller.
.DESCRIPTION
Tests if the system is a domain controller.
.EXAMPLE
Test-IsDomainController
#>
[CmdletBinding()]
[OutputType([bool])]
Param()
$os = Get-WmiObject -Class 'Win32_OperatingSystem' -Filter 'Primary=true' | Select-Object ProductType
# 1 = workstation, 2 = domain controller, 3 = member server
return $os.ProductType -eq 2
}
Function Test-IsDomainJoined() {
<#
.SYNOPSIS
Tests if a system is joined to a domain.
.DESCRIPTION
Tests if a system is joined to a domain.
.EXAMPLE
Test-IsDomainJoined
#>
[CmdletBinding()]
[OutputType([bool])]
Param()
$computer = Get-WmiObject -Class 'Win32_ComputerSystem' | Select-Object PartOfDomain
return $computer.PartOfDomain
}
Function Get-GroupPolicyTemplateFolderPath() {
<#
.SYNOPSIS
Gets the path where Group Policy templates are stored.
.DESCRIPTION
Gets the path where Group Policy templates are stored. For a domain joined system, it will check if a Group Policy Central Store exists.
.PARAMETER TemplatePathType
The type of the template folder path to get.
.EXAMPLE
Get-GroupPolicyTemplateFolderPath
.EXAMPLE
Get-GroupPolicyTemplateFolderPath -TemplatePathType 'Domain'
.EXAMPLE
Get-GroupPolicyTemplateFolderPath -TemplatePathType 'Local'
#>
[CmdletBinding()]
[OutputType([string])]
Param(
[Parameter(Mandatory=$false, HelpMessage='The type of the template folder path to get.')]
[ValidateNotNullOrEmpty()]
[ValidateSet('Domain', 'Local', IgnoreCase=$true)]
[string]$TemplatePathType
)
# default to using the local template path
$path = '{0}\PolicyDefinitions' -f $env:SystemRoot
if (-not(Test-Path -Path $path)) {
throw "Unable to access policy template path of $path"
}
if ('Domain' -eq $TemplatePathType -and -not(Test-IsDomainJoined)) {
throw 'Must be joined to a domain'
}
if (('Domain' -eq $TemplatePathType) -or (Test-IsDomainJoined)) {
# $env:UserDnsDomain only has a value when a user is logged
# NV Domain registry value contains the computer's primary DNS suffix. The Domain registry value contains the computer's primary DNS domain.
# NV Domain is the domain the system is joined to
$dnsDomain = Get-ItemProperty -Path hklm:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters | Select-Object -ExpandProperty 'NV Domain'
# central store format: \\Fully Qualified Domain Name\SYSVOL\Fully Qualified Domain Name\Policies\PolicyDefinitions\
# see https://support.microsoft.com/en-us/kb/3087759
$centralStorePath = '\\{0}\SYSVOL\{1}\Policies\PolicyDefinitions' -f $dnsDomain,$dnsDomain
# use the central store path if it exists
if (Test-Path -Path $centralStorePath -PathType Container) {
$path = $centralStorePath
}
}
return $path
}
Function Import-LocalPolicyObject() {
<#
.SYNOPSIS
Imports a local Group Policy object.
.DESCRIPTION
Imports a local Group Policy object.
.PARAMETER Path
The path of the GPO to import.
.PARAMETER ToolPath
The path to the LGPO tool.
.EXAMPLE
Import-LocalPolicyObject -Path '.\Secure-Host-Baseline\Windows\Group Policy Objects\Computer\{AC662460-6494-4818-A303-FADC513B9876}' -ToolPath '.\Secure-Host-Baseline\LGPO\lgpo.exe'
#>
[CmdletBinding()]
[OutputType([void])]
Param(
[Parameter(Mandatory=$true, HelpMessage='The path of the GPO to import')]
[ValidateNotNullOrEmpty()]
[ValidateScript({Test-Path -Path $_ -PathType Container})]
[ValidateScript({[System.IO.Directory]::Exists($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($_))})]
[string]$Path,
[Parameter(Mandatory=$true, HelpMessage='The path to the LGPO tool')]
[ValidateNotNullOrEmpty()]
[ValidateScript({([System.IO.FileInfo]$_).Name -eq 'lgpo.exe'})]
[ValidateScript({Test-Path -Path $_ -PathType Leaf})]
[ValidateScript({[System.IO.File]::Exists($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($_))})]
[string]$ToolPath
)
$Path = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)
$ToolPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($ToolPath)
if (-not(Test-IsGPOBackupFolder -Path $Path)) {
throw "$Path is not a Group Policy backup folder path"
}
$extensions = Get-GPOBackupClientSideExtensions -Path $Path
$extensionArguments = [string[]]@()
$extensions.Keys | ForEach-Object {
$extensionArguments += '/e'
$extensionArguments += $_
}
$arguments = [string[]]@([string[]]@('/g',$Path) + $extensionArguments)
$result = Invoke-Process -Path $ToolPath -Arguments $arguments -PassThru
$exitCode = $result.ExitCode
$output = $result.Output
if (0 -ne $exitCode) {
Write-Warning -Message 'LGPO import might have not executed correctly'
Write-Warning -Message ('Exit code: {0}' -f $exitCode)
if ($output -ne $null -and $output -ne '') {
Write-Warning -Message ('Output: {0}{1}' -f [System.Environment]::NewLine,$output)
}
}
}
Function Test-DomainPolicyExists() {
<#
.SYNOPSIS
Checks if a domain Group Policy object exists.
.DESCRIPTION
Checks if a domain Group Policy object exists by policy name or policy GUID.
.PARAMETER Guid
The GUID of the domain policy object.
.PARAMETER Name
The display name of the domain policy object.
.EXAMPLE
Test-DomainPolicyExists -Guid '{343866EE-1828-4BB7-B706-4989C511FEE9}'
.EXAMPLE
Test-DomainPolicyExists -Name 'Adobe Reader DC'
#>
[CmdletBinding()]
[OutputType([void])]
Param(
[Parameter(Mandatory=$false, HelpMessage='The GUID of the domain policy object')]
[ValidateNotNullOrEmpty()]
[System.Guid]$Guid,
[Parameter(Mandatory=$false, HelpMessage='The display name of the domain policy object')]
[ValidateNotNullOrEmpty()]
[string]$Name
)
$parameters = $PSBoundParameters
if (-not($parameters.ContainsKey('Guid')) -and -not($parameters.ContainsKey('Name'))) {
throw 'Must specified a domain policy name or domain policy guid'
}
$gpo = $null
if ($parameters.ContainsKey('Guid')) {
$gpo = Get-GPO -Guid $guid -ErrorAction SilentlyContinue
}
if ($parameters.ContainsKey('Name')) {
$gpo = Get-GPO -Name $Name -ErrorAction SilentlyContinue
}
return $null -ne $gpo
}
Function Import-DomainPolicyObject() {
<#
.SYNOPSIS
Imports a domain Group Policy object.
.DESCRIPTION
Imports a domain Group Policy object.
.PARAMETER Path
The path of the Group Policy object to import.
.PARAMETER Name
The display name of the Group Policy object.
.PARAMETER BackupGuid
The GUID of the Group Policy object backup.
.EXAMPLE
Import-DomainPolicyObject -Path '.\Secure-Host-Baseline\Windows\Group Policy Objects\Computer\' -Name 'DoD Windows 10 STIG - Computer' -BackupGuid '{AC662460-6494-4818-A303-FADC513B9876}'
#>
[CmdletBinding()]
[OutputType([void])]
Param(
[Parameter(Mandatory=$true, HelpMessage='The path of the Group Policy object to import')]
[ValidateNotNullOrEmpty()]
[ValidateScript({Test-Path -Path $_ -PathType Container})]
[ValidateScript({[System.IO.Directory]::Exists($ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($_))})]
[string]$Path,
[Parameter(Mandatory=$true, HelpMessage='The display name of the Group Policy object')]
[ValidateNotNullOrEmpty()]
[string]$Name,
[Parameter(Mandatory=$true, HelpMessage='The GUID of the Group Policy object backup')]
[ValidateNotNullOrEmpty()]
[System.Guid]$BackupGuid