-
Notifications
You must be signed in to change notification settings - Fork 0
/
New-WDACPolicy.psm1
760 lines (640 loc) · 35.4 KB
/
New-WDACPolicy.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
$ThisIsASignedModule = $false
if ((Split-Path (Get-Item $PSScriptRoot) -Leaf) -eq "SignedModules") {
$PSModuleRoot = Join-Path $PSScriptRoot -ChildPath "..\"
$ThisIsASignedModule = $true
} else {
$PSModuleRoot = $PSScriptRoot
}
if (Test-Path (Join-Path $PSModuleRoot -ChildPath "SignedModules\Resources\JSON-LocalStorageTools.psm1")) {
Import-Module (Join-Path $PSModuleRoot -ChildPath "SignedModules\Resources\JSON-LocalStorageTools.psm1")
} else {
Import-Module (Join-Path $PSModuleRoot -ChildPath "Resources\JSON-LocalStorageTools.psm1")
}
if (Test-Path (Join-Path $PSModuleRoot -ChildPath "SignedModules\Resources\Code-Signing-Tools.psm1")) {
Import-Module (Join-Path $PSModuleRoot -ChildPath "SignedModules\Resources\Code-Signing-Tools.psm1")
} else {
Import-Module (Join-Path $PSModuleRoot -ChildPath "Resources\Code-Signing-Tools.psm1")
}
if (Test-Path (Join-Path $PSModuleRoot -ChildPath "SignedModules\Resources\SQL-TrustDBTools.psm1")) {
Import-Module (Join-Path $PSModuleRoot -ChildPath "SignedModules\Resources\SQL-TrustDBTools.psm1")
} else {
Import-Module (Join-Path $PSModuleRoot -ChildPath "Resources\SQL-TrustDBTools.psm1")
}
function Test-InvalidValidFileNameChars {
#Invalid characters: \ / : * ? " < > |
[CmdletBinding()]
param(
[ValidateNotNullOrEmpty()]
[Parameter(Mandatory=$true)]
[string]$FileChars
)
return ($FileChars -match "(\\|\/|\:|\*|\?|\`"|\<|\>|\|)")
}
function Remove-CurlyBracesPolicyID {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
$InputPolicyString
)
if (-not $InputPolicyString) {
return $null
}
if ($InputPolicyString -match "\{") {
$InputPolicyString = $InputPolicyString.replace('{','');
}
if ($InputPolicyString -match "\}") {
$InputPolicyString = $InputPolicyString.replace('}','');
}
return $InputPolicyString
}
function New-WDACPolicy {
<#
.SYNOPSIS
Creates a new WDAC policy .XML file and places it in the working policies directory.
.DESCRIPTION
Create a WDAC policy based on user supplied parameters including merging with Microsoft-recommended block rules as well
as setting other policy options. Does not generate the resultant .cip file (that is accomplished by "Deploy-WDACPolicies").
Adds important information about this policy to the trust database.
Author: Nathan Jepson
License: MIT License
.PARAMETER Pillar
When this flag is set, you specify that you want the policy to be a pillar--that is, a base policy which is applied to every computer irrespective of group membership.
.PARAMETER PolicyName
Specify the name of the policy as a string. (Required.) You must use valid characters which can be part of a file path / file name.
.PARAMETER PolicyID
This is an optional way to set the non-GUID Policy ID.
.PARAMETER FilePath
If you have already created the WDAC policy XML file and just want to set some options, specify its filepath with this.
.PARAMETER BasePolicyID
If you are creating a supplemental policy, then specify the BasePolicyID (otherwise it must be pulled from the .xml file designated by FilePath)
.PARAMETER AddPSCodeSigner
Adds a new signer rule for the PowerShell code signing certificate to this new WDAC policy.
.PARAMETER UpdatePolicySigner
Creates a new signer rule for the WDAC Policy Signing certificate--for updating this policy--obtained from LocalStorage.json (i.e., the WDACPolicySigningCertificate)
.PARAMETER SupplementalPolicySigner
Creates a new signer rule for the WDAC Policy Signing certificate--for signing a supplemental policy--obtained from LocalStorage.json (i.e., the WDACPolicySigningCertificate)
.PARAMETER DoNotCacheRecommended
When this is set, Microsoft's recommended policy rules will be purged (not stored locally after pulling from Github)
.PARAMETER DenyByDefaultPolicy
This policy will deny apps by default.
.PARAMETER AllowByDefaultPolicy
This policy will allow apps by default.
.PARAMETER DriverBlockRules
When this is set, this policy will be merged with Microsoft's recommended driver block rules.
.PARAMETER OtherBlockRules
When this is set, this policy will be merged with Microsoft's recommended user mode block rules.
.PARAMETER DefaultWindowsMode
When this is set, the policy will be merged with the Default Windows Mode WDAC policy provided by Microsoft.
.PARAMETER AllowMicrosoftMode
When this is set, the policy will be merged with the Allow Microsoft Mode WDAC policy provided by Microsoft.
.PARAMETER Supplemental
When this parameter is set, you signify that you want this policy to be a supplemental policy (and you will need to designate the base policy ID as well.)
.PARAMETER Signed
.PARAMETER Unsigned
.PARAMETER Audit
.PARAMETER Enforced
.PARAMETER UMCI
.PARAMETER BootMenuProtection
.PARAMETER WHQL
.PARAMETER DisableFlightSigning
.PARAMETER InheritDefaultPolicy
.PARAMETER AllowDebugPolicyAugmented
.PARAMETER RequireEVSigners
.PARAMETER AdvancedBootOptionsMenu
.PARAMETER BootAuditOnFailure
.PARAMETER DisableScriptEnforcement
.PARAMETER EnforceStoreApps
.PARAMETER EnableManagedInstaller
.PARAMETER ISG
.PARAMETER InvalidateEAsOnReboot
.PARAMETER UpdatePolicyNoReboot
.PARAMETER AllowSupplementalPolicies
.PARAMETER DisableRuntimeFilepathRules
.PARAMETER DynamicCodeSecurity
.PARAMETER TreatRevokedAsUnsigned
.EXAMPLE
New-WDACPolicy -Deny -PolicyName "CashiersBottomFloor2" -PolicyID "CodeInteg12" -DriverBlockRules -OtherBlockRules -Signed -Enforce -AddPSCodeSigner -UpdatePolicySigner -SupplementalPolicySigner -DynamicCodeSecurity -DisableRuntimeFilepathRules -HVCI -BootMenuProtection -AllowSupplementalPolicies -Verbose
.EXAMPLE
New-WDACPolicy -Allow -PolicyName "Cashiers" -Supplemental -BasePolicyID "A244370E-44C9-4C06-B551-F6016E563076" -Windows -Audit -Unsigned -DynamicCodeSecurity -DisableRuntimeFilepathRules -HVCI -DoNotCacheRecommended -BootMenuProtection -BootAuditOnFailure -AdvancedBootOptionsMenu -ISG
.EXAMPLE
New-WDACPolicy -FilePath "C:\Users\JohnSmith\WDAC Policies\AlreadyExistingPolicy.XML" -Deny -PolicyName "Support Staff" -Microsoft -Enforced -Signed -HVCI -ISG -BootMenuProtection -BootAuditOnFailure -AdvancedBootOptionsMenu -UpdatePolicyNoReboot
#>
[CmdletBinding()]
Param (
[switch]$Pillar,
[ValidateNotNullOrEmpty()]
[Parameter(Mandatory=$true)]
[string]$PolicyName,
[ValidateNotNullOrEmpty()]
[string]$PolicyID,
[ValidateNotNullOrEmpty()]
[ValidatePattern('\.xml$')]
[ValidateScript({Test-Path $_}, ErrorMessage = "Cannot find the file that you provided.")]
[string]$FilePath,
[ValidateNotNullOrEmpty()]
[ValidateScript({-not ($_ -match "(\{|\})")}, ErrorMessage = "Please provide the base policy ID without curly braces.")]
[string]$BasePolicyID,
[switch]$Supplemental,
[switch]$AddPSCodeSigner,
[switch]$UpdatePolicySigner,
[switch]$SupplementalPolicySigner,
[Alias("NoCache")]
[switch]$DoNotCacheRecommended,
[Alias("Deny")]
[ValidateScript({-not $AllowByDefaultPolicy}, ErrorMessage = "Cannot have both an allow-by-default and a deny-by-default policy.")]
[switch]$DenyByDefaultPolicy,
[Alias("Allow")]
[ValidateScript({-not $DenyByDefaultPolicy}, ErrorMessage = "Cannot have both an allow-by-default and a deny-by-default policy.")]
[switch]$AllowByDefaultPolicy,
[switch]$DriverBlockRules,
[Alias("UserModeBlockRules")]
[switch]$OtherBlockRules,
[Alias("Windows")]
[switch]$DefaultWindowsMode,
[Alias("Microsoft")]
[switch]$AllowMicrosoftMode,
[ValidateScript({-not $Unsigned}, ErrorMessage = "A policy cannot be both signed and unsigned. You cannot serve two masters.")]
[switch]$Signed,
[ValidateScript({-not $Signed}, ErrorMessage = "A policy cannot be both signed and unsigned. You cannot serve two masters.")]
[switch]$Unsigned,
[ValidateScript({-not $Enforced}, ErrorMessage = "A policy cannot be both an Audit policy and an Enforced policy. This is according to the Law of non-contradiction. The philosphers are laughing you to scorn.")]
[switch]$Audit,
[Alias("Enforce")]
[ValidateScript({-not $Audit}, ErrorMessage = "A policy cannot be both an Audit policy and an Enforced policy. This is according to the Law of non-contradiction. The philosphers are laughing you to scorn.")]
[switch]$Enforced,
[Alias("UserModeCodeIntegrity")]
[switch]$UMCI,
[switch]$BootMenuProtection,
[switch]$WHQL,
[switch]$DisableFlightSigning,
[switch]$InheritDefaultPolicy,
[switch]$AllowDebugPolicyAugmented,
[switch]$RequireEVSigners,
[switch]$AdvancedBootOptionsMenu,
[switch]$BootAuditOnFailure,
[switch]$DisableScriptEnforcement,
[Alias("Store")]
[switch]$EnforceStoreApps,
[switch]$EnableManagedInstaller,
[Alias("IntelligentSecurityGraph")]
[switch]$ISG,
[switch]$InvalidateEAsOnReboot,
[switch]$UpdatePolicyNoReboot,
[switch]$AllowSupplementalPolicies,
[switch]$DisableRuntimeFilepathRules,
[switch]$DynamicCodeSecurity,
[switch]$TreatRevokedAsUnsigned,
[switch]$HVCI
)
begin {
if ($ThisIsASignedModule) {
Write-Verbose "The current file is in the SignedModules folder."
}
if (Test-InvalidValidFileNameChars -FileChars $PolicyName) {
throw "The policy name contains invalid characters. Please use valid characters which are valid for file paths and file names."
}
if (-not $DenyByDefaultPolicy -and -not $AllowByDefaultPolicy -and (-not $Supplemental)) {
throw "You must set either `"-DenyByDefaultPolicy`" or `"-AllowByDefaultPolicy`" "
}
if ($AllowDebugPolicyAugmented -or $RequireEVSigners) {
throw "`"Debug Policy Augmented`" or `"Require EV Signers`" is not yet supported by Microsoft."
}
if ($Supplemental -and (-not $FilePath -and -not $BasePolicyID)) {
#TODO: Give the user a list of vaild Base Policy IDs from the database
throw "Please provide the BasePolicy ID"
}
if ($Supplemental -and $SupplementalPolicySigner) {
throw "Cannot add a supplemental policy signer to a supplemental policy; it must be added to a base policy."
}
if (-not $Signed -and -not $Unsigned) {
#Unsigned policy is the default
$Unsigned = $true
}
if (-not $Audit -and -not $Enforced) {
#Audit policy is the default
$Audit = $true
}
if ($Signed) {
if (-not $UpdatePolicySigner -and -not $SupplementalPolicySigner) {
#For a signed policy, the default behavior is to add both a supplemental and an update policy signer
$UpdatePolicySigner = $true
if ($AllowSupplementalPolicies) {
$SupplementalPolicySigner = $true #TODO: Is this option able to be enabled for a supplemental policy without breaking anything?
}
}
} else {
if ($UpdatePolicySigner -or $SupplementalPolicySigner) {
throw "-UpdatePolicySigner and -SupplementalPolicySigner are only valid options for a signed policy (i.e., the -Signed flag is set.)"
}
}
#This is the optional non-GUID Policy ID which the user can supply
$OtherPolicyID = $null
if ($PolicyID) {
$OtherPolicyID = $PolicyID
}
}
process {
try {
$WorkingPoliciesLocation = (Get-LocalStorageJSON -ErrorAction Stop)."WorkingPoliciesDirectory"."Location"
$WorkingPoliciesLocationType = (Get-LocalStorageJSON -ErrorAction Stop)."WorkingPoliciesDirectory"."Type"
if (-not $WorkingPoliciesLocation -or -not $WorkingPoliciesLocationType -or "" -eq $WorkingPoliciesLocation -or "" -eq $WorkingPoliciesLocationType) {
throw "Null or invalid values provided for Working Policies location (or the location type)"
}
} catch {
Write-Verbose $_
throw "Trouble in retrieving your working policies location."
}
if ($Signed) {
try {
$WDACodeSigner = (Get-LocalStorageJSON -ErrorAction Stop)."WDACPolicySigningCertificate"
if (-not $WDACodeSigner -or "" -eq $WDACodeSigner) {
throw "Error: Empty or null value for WDAC Policy signing certificate retreived from Local Storage."
} elseif (-not ($WDACodeSigner.ToLower() -match "cert\:\\")) {
throw "Local cache does not specify a valid certificate path for the WDAC policy signing certificate. Please use a valid path. Example of a valid certificate path: `"Cert:\\CurrentUser\\My\\005A924AA26ABD88F84D6795CCC0AB09A6CE88E3`""
}
} catch {
Write-Error $_
return;
}
}
if ($AddPSCodeSigner) {
try {
$PSCodeSigner = (Get-LocalStorageJSON -ErrorAction Stop)."PowerShellCodeSigningCertificate"
if (-not $PSCodeSigner -or "" -eq $PSCodeSigner) {
throw "Error: Empty or null value for PowerShell code signing certificate retreived from Local Storage."
} elseif (-not ($PSCodeSigner.ToLower() -match "cert\:\\")) {
throw "Local cache does not specify a valid certificate path for the PowerShell code signing certificate. Please use a valid path. Example of a valid certificate path: `"Cert:\\CurrentUser\\My\\005A924AA26ABD88F84D6795CCC0AB09A6CE88E3`""
}
} catch {
Write-Error $_
return;
}
}
try {
if (Find-WDACPolicyByName -PolicyName $PolicyName -ErrorAction Stop) {
Write-Error "A policy with the name $PolicyName already exists."
return;
}
if ($OtherPolicyID) {
if (Find-WDACPolicyByID -PolicyID $OtherPolicyID -ErrorAction SilentlyContinue) {
Write-Warning "Other policy with instance of ID $OtherPolicyID already exists in the database."
}
}
} catch {
Write-Verbose $_
throw "Failed to import Sqlite OR a problem with connecting to the trust database."
}
$TempPolicyPath = (Join-Path -Path $PSModuleRoot -ChildPath ".\.WDACFrameworkData\$PolicyName.xml")
if (Test-Path $TempPolicyPath) {
try {
Remove-Item $TempPolicyPath -Force -ErrorAction Stop
} catch {
$RandomGUID = New-Guid
$TempPolicyPath = (Join-Path -Path $PSModuleRoot -ChildPath ".\.WDACFrameworkData\$($PolicyName)_$RandomGUID.xml")
}
}
try {
if ($FilePath) {
Copy-Item $FilePath -Destination $TempPolicyPath -Force -ErrorAction Stop
[xml]$TempXML = Get-Content -Path $TempPolicyPath
$PolicyID = $TempXML.SiPolicy.PolicyID
$BasePolicyID = $TempXML.SiPolicy.BasePolicyID
if (-not $PolicyID -or -not $BasePolicyID) {
throw "No valid PolicyID or BasePolicyID was found in the provided file."
}
if ($Supplemental) {
if ($PolicyID -eq $BasePolicyID) {
throw "Error: Supplemental flag is set but base policy ID and PolicyID are identical."
}
}
if (Find-WDACPolicy -PolicyGUID (Remove-CurlyBracesPolicyID -InputPolicyString $PolicyID) -ErrorAction Stop) {
throw "A base policy of ID $PolicyID already exists in the database."
}
Set-CIPolicyIdInfo -FilePath $TempPolicyPath -PolicyName $PolicyName -ErrorAction Stop
} elseif ($Supplemental) {
Copy-Item (Join-Path -Path $PSModuleRoot -ChildPath ".\Resources\SupplementalShell.xml") -Destination $TempPolicyPath -Force
} elseif ($AllowByDefaultPolicy) {
Copy-Item (Join-Path -Path $PSModuleRoot -ChildPath ".\Resources\AllowAll.xml") -Destination $TempPolicyPath -Force
} elseif ($DenyByDefaultPolicy) {
Copy-Item (Join-Path -Path $PSModuleRoot -ChildPath ".\Resources\DenyAllAudit.xml") -Destination $TempPolicyPath -Force
}
if (-not $FilePath) {
#Only reset the policy ID if the filepath to a policy isn't already provided. I may change this behavior later.
if ($Supplemental) {
$PolicyID = Set-CIPolicyIdInfo -FilePath $TempPolicyPath -ResetPolicyID -PolicyName $PolicyName -SupplementsBasePolicyID $BasePolicyID -ErrorAction Stop
} else {
$PolicyID = Set-CIPolicyIdInfo -FilePath $TempPolicyPath -ResetPolicyID -PolicyName $PolicyName -ErrorAction Stop
}
}
if ($OtherPolicyID) {
Set-CIPolicyIdInfo -FilePath $TempPolicyPath -PolicyId $OtherPolicyID
}
if ($DriverBlockRules) {
#This needs to be wrapped in a PowerShell 5.1 block because some functionallity of ConfigCI isn't supported in PowerShell Core :(
$DriverBlockRulesTask = PowerShell {
[CmdletBinding()]
Param(
$TempPolicyPath,
$PSModuleRoot,
$DenyByDefaultPolicy,
$DoNotCacheRecommended,
$IsVerbose
)
try {
Import-Module (Join-Path -Path $PSModuleRoot -ChildPath ".\Resources\Microsoft-Recommended-Rules.psm1") -ErrorAction Stop;
$driverrules = Get-DriverBlockRules -DoNotCacheRecommended $DoNotCacheRecommended -ErrorAction Stop -Verbose:$IsVerbose;
if ($DenyByDefaultPolicy) {
#Remove the rule with the asterisk if it is a deny by default policy
$driverrules = $driverrules | Where-Object {-not ($_.attributes["FileName"] -eq "*")}
}
Merge-CIPolicy -OutputFilePath $TempPolicyPath -PolicyPaths $TempPolicyPath -Rules $driverrules -ErrorAction Stop | Out-Null;
} catch {
Write-Error $_
return $false
}
return $true
} -args $TempPolicyPath,$PSModuleRoot,$DenyByDefaultPolicy,$DoNotCacheRecommended.ToBool(),$VerbosePreference
if (-not $DriverBlockRulesTask) {
throw "Unable to merge with driver block rules. Error occurred."
}
}
if ($OtherBlockRules) {
#This needs to be wrapped in a PowerShell 5.1 block because some functionallity of ConfigCI isn't supported in PowerShell Core :(
$UserModeBlockRulesTask = PowerShell {
[CmdletBinding()]
Param(
$TempPolicyPath,
$PSModuleRoot,
$DenyByDefaultPolicy,
$DoNotCacheRecommended,
$IsVerbose
)
try {
Import-Module (Join-Path -Path $PSModuleRoot -ChildPath ".\Resources\Microsoft-Recommended-Rules.psm1") -ErrorAction Stop;
$usermoderules = Get-UserModeBlockRules -DoNotCacheRecommended $DoNotCacheRecommended -ErrorAction Stop -Verbose:$IsVerbose;
if ($DenyByDefaultPolicy) {
#Remove the rule with the asterisk if it is a deny by default policy
$usermoderules = $usermoderules | Where-Object {-not ($_.attributes["FileName"] -eq "*")}
}
Merge-CIPolicy -OutputFilePath $TempPolicyPath -PolicyPaths $TempPolicyPath -Rules $usermoderules -ErrorAction Stop | Out-Null;
} catch {
Write-Error $_
return $false
}
return $true
} -args $TempPolicyPath,$PSModuleRoot,$DenyByDefaultPolicy,$DoNotCacheRecommended.ToBool(),$VerbosePreference
if (-not $UserModeBlockRulesTask) {
throw "Unable to merge with user mode block rules. Error occurred."
}
}
if ($DefaultWindowsMode) {
#This needs to be wrapped in a PowerShell 5.1 block because some functionallity of ConfigCI isn't supported in PowerShell Core :(
$WindowsModeTask = PowerShell {
[CmdletBinding()]
Param(
$TempPolicyPath,
$PSModuleRoot,
$DoNotCacheRecommended,
$IsVerbose
)
try {
Import-Module (Join-Path -Path $PSModuleRoot -ChildPath ".\Resources\Microsoft-Recommended-Rules.psm1") -ErrorAction Stop;
$rules = Get-WindowsModeRules -DoNotCacheRecommended $DoNotCacheRecommended -ErrorAction Stop -Verbose:$IsVerbose;
Merge-CIPolicy -OutputFilePath $TempPolicyPath -PolicyPaths $TempPolicyPath -Rules $rules -ErrorAction Stop | Out-Null;
} catch {
Write-Error $_
return $false
}
return $true
} -args $TempPolicyPath,$PSModuleRoot,$DoNotCacheRecommended.ToBool(),$VerbosePreference
if (-not $WindowsModeTask) {
throw "Unable to merge with Default Windows Mode rules. Error occurred."
}
}
if ($AllowMicrosoftMode) {
#This needs to be wrapped in a PowerShell 5.1 block because some functionallity of ConfigCI isn't supported in PowerShell Core :(
$AddMicrosoftModeTask = PowerShell {
[CmdletBinding()]
Param(
$TempPolicyPath,
$PSModuleRoot,
$DoNotCacheRecommended,
$IsVerbose
)
try {
Import-Module (Join-Path -Path $PSModuleRoot -ChildPath ".\Resources\Microsoft-Recommended-Rules.psm1") -ErrorAction Stop;
$rules = Get-AllowMicrosoftModeRules -DoNotCacheRecommended $DoNotCacheRecommended -ErrorAction Stop -Verbose:$IsVerbose;
Merge-CIPolicy -OutputFilePath $TempPolicyPath -PolicyPaths $TempPolicyPath -Rules $rules -ErrorAction Stop | Out-Null;
} catch {
Write-Error $_
return $false
}
return $true
} -args $TempPolicyPath,$PSModuleRoot,$DoNotCacheRecommended.ToBool(),$VerbosePreference
if (-not $AddMicrosoftModeTask) {
throw "Unable to merge with Microsoft Mode rules. Error occurred."
}
}
#Add Code Signing / Policy Signing Rules: =====================================================================
if ($AddPSCodeSigner) {
Export-CodeSignerAsCER -Destination (Join-Path -Path $PSModuleRoot -ChildPath ".\.WDACFrameworkData") -PSCodeSigner -ErrorAction Stop | Out-Null
Add-SignerRule -FilePath $TempPolicyPath -CertificatePath (Join-Path -Path $PSModuleRoot -ChildPath ".\.WDACFrameworkData\PSCodeSigning.cer") -User -Kernel -ErrorAction Stop
}
if ($UpdatePolicySigner -or $SupplementalPolicySigner) {
Export-CodeSignerAsCER -Destination (Join-Path -Path $PSModuleRoot -ChildPath ".\.WDACFrameworkData") -WDACCodeSigner -ErrorAction Stop | Out-Null
if ($UpdatePolicySigner) {
Add-SignerRule -FilePath $TempPolicyPath -CertificatePath (Join-Path -Path $PSModuleRoot -ChildPath ".\.WDACFrameworkData\WDACCodeSigning.cer") -Update -ErrorAction Stop
}
if ($SupplementalPolicySigner -and (-not $Supplemental)) {
Add-SignerRule -FilePath $TempPolicyPath -CertificatePath (Join-Path -Path $PSModuleRoot -ChildPath ".\.WDACFrameworkData\WDACCodeSigning.cer") -Supplemental -ErrorAction Stop
}
}
#==============================================================================================================
#Apply Policy Options ======================================================
#Case 0: 'Enabled:UMCI'
if ($UMCI -and (-not $Supplemental)) {
Set-RuleOption -FilePath $TempPolicyPath -Option 0
} else {
Set-RuleOption -FilePath $TempPolicyPath -Option 0 -Delete
}
#Case 1: 'Enabled:Boot Menu Protection'
if ($BootMenuProtection -and (-not $Supplemental)) {
Set-RuleOption -FilePath $TempPolicyPath -Option 1
} else {
Set-RuleOption -FilePath $TempPolicyPath -Option 1 -Delete
}
#Case 2: 'Required:WHQL'
if ($WHQL -and (-not $Supplemental)) {
Set-RuleOption -FilePath $TempPolicyPath -Option 2
} else {
Set-RuleOption -FilePath $TempPolicyPath -Option 2 -Delete
}
#Case 3: 'Enabled:Audit Mode'
if ($Audit -and (-not $Supplemental)) {
Set-RuleOption -FilePath $TempPolicyPath -Option 3
} else {
Set-RuleOption -FilePath $TempPolicyPath -Option 3 -Delete
}
#Case 4: 'Disabled:Flight Signing'
if ($DisableFlightSigning -and (-not $Supplemental)) {
Set-RuleOption -FilePath $TempPolicyPath -Option 4
} else {
Set-RuleOption -FilePath $TempPolicyPath -Option 4 -Delete
}
#Case 5: 'Enabled:Inherit Default Policy'
if ($InheritDefaultPolicy) {
Set-RuleOption -FilePath $TempPolicyPath -Option 5
} else {
Set-RuleOption -FilePath $TempPolicyPath -Option 5 -Delete
}
#Case 6: 'Enabled:Unsigned System Integrity Policy'
if ($Unsigned) {
Set-RuleOption -FilePath $TempPolicyPath -Option 6
} else {
Set-RuleOption -FilePath $TempPolicyPath -Option 6 -Delete
}
#Case 7: 'Allowed:Debug Policy Augmented'
#Not yet supported by Microsoft
#Case 8: 'Required:EV Signers'
#Not yet supported by Microsoft
#Case 9: 'Enabled:Advanced Boot Options Menu'
if ($AdvancedBootOptionsMenu -and (-not $Supplemental)) {
Set-RuleOption -FilePath $TempPolicyPath -Option 9
} else {
Set-RuleOption -FilePath $TempPolicyPath -Option 9 -Delete
}
#Case 10: 'Enabled:Boot Audit On Failure'
if ($BootAuditOnFailure -and (-not $Supplemental)) {
Set-RuleOption -FilePath $TempPolicyPath -Option 10
} else {
Set-RuleOption -FilePath $TempPolicyPath -Option 10 -Delete
}
#Case 11: 'Disabled:Script Enforcement'
if ($DisableScriptEnforcement -and (-not $Supplemental)) {
Set-RuleOption -FilePath $TempPolicyPath -Option 11
} else {
Set-RuleOption -FilePath $TempPolicyPath -Option 11 -Delete
}
#Case 12: 'Required:Enforce Store Applications'
if ($EnforceStoreApps -and (-not $Supplemental)) {
Set-RuleOption -FilePath $TempPolicyPath -Option 12
} else {
Set-RuleOption -FilePath $TempPolicyPath -Option 12 -Delete
}
#Case 13: 'Enabled:Managed Installer'
if ($EnableManagedInstaller) {
Set-RuleOption -FilePath $TempPolicyPath -Option 13
} else {
Set-RuleOption -FilePath $TempPolicyPath -Option 13 -Delete
}
#Case 14:'Enabled:Intelligent Security Graph Authorization'
if ($ISG) {
Set-RuleOption -FilePath $TempPolicyPath -Option 14
} else {
Set-RuleOption -FilePath $TempPolicyPath -Option 14 -Delete
}
#Case 15:'Enabled:Invalidate EAs on Reboot'
if ($InvalidateEAsOnReboot -and (-not $Supplemental)) {
Set-RuleOption -FilePath $TempPolicyPath -Option 15
} else {
Set-RuleOption -FilePath $TempPolicyPath -Option 15 -Delete
}
#Case 16:'Enabled:Update Policy No Reboot'
if ($UpdatePolicyNoReboot -and (-not $Supplemental)) {
Set-RuleOption -FilePath $TempPolicyPath -Option 16
} else {
Set-RuleOption -FilePath $TempPolicyPath -Option 16 -Delete
}
#Case 17:'Enabled:Allow Supplemental Policies'
if ($AllowSupplementalPolicies -and (-not $Supplemental)) {
Set-RuleOption -FilePath $TempPolicyPath -Option 17
} else {
Set-RuleOption -FilePath $TempPolicyPath -Option 17 -Delete
}
#Case 18:'Disabled:Runtime FilePath Rule Protection'
if ($DisableRuntimeFilepathRules) {
Set-RuleOption -FilePath $TempPolicyPath -Option 18
} else {
Set-RuleOption -FilePath $TempPolicyPath -Option 18 -Delete
}
#Case 19:'Enabled:Dynamic Code Security'
if ($DynamicCodeSecurity -and (-not $Supplemental)) {
Set-RuleOption -FilePath $TempPolicyPath -Option 19
} else {
Set-RuleOption -FilePath $TempPolicyPath -Option 19 -Delete
}
#Case 20:'Enabled:Revoked Expired As Unsigned'
if ($TreatRevokedAsUnsigned -and (-not $Supplemental)) {
Set-RuleOption -FilePath $TempPolicyPath -Option 20
} else {
Set-RuleOption -FilePath $TempPolicyPath -Option 20 -Delete
}
#Case HVCI: Whether HVCI is enabled
if ($HVCI) {
Set-HVCIOptions -Enabled -FilePath $TempPolicyPath
} else {
#TODO: Provide an option to set the -strict flag (which will set it to "2").
#You can use Edit-WDACPolicy in order to set it to strict currently.
}
#===========================================================================
#==========Add policy to database=====================================
[xml]$PolicyXML = Get-Content -Path $TempPolicyPath -ErrorAction Stop
$VersionNumber = $PolicyXML.SiPolicy.VersionEx
$Connection = New-SQLiteConnection -ErrorAction Stop
$Transaction = $Connection.BeginTransaction()
if (-not $FilePath) {
if (-not (Add-WDACPolicy -PolicyGUID (Remove-CurlyBracesPolicyID -InputPolicyString ($PolicyID.Substring(11))) -PolicyID $OtherPolicyID -PolicyName $PolicyName -PolicyVersion $VersionNumber -ParentPolicyGUID (Remove-CurlyBracesPolicyID -InputPolicyString $BasePolicyID) -BaseOrSupplemental $Supplemental.ToBool() -IsSigned $Signed.ToBool() -AuditMode $Audit.ToBool() -IsPillar $Pillar.ToBool() -OriginLocation $WorkingPoliciesLocation -OriginLocationType $WorkingPoliciesLocationType -Connection $Connection -ErrorAction Stop)) {
throw "Failed to add this policy to the database."
}
} else {
#No need to cut off 11 characters if the policy ID was provided from a file
if (-not (Add-WDACPolicy -PolicyGUID (Remove-CurlyBracesPolicyID -InputPolicyString $PolicyID) -PolicyID $OtherPolicyID -PolicyName $PolicyName -PolicyVersion $VersionNumber -ParentPolicyGUID (Remove-CurlyBracesPolicyID -InputPolicyString $BasePolicyID) -BaseOrSupplemental $Supplemental.ToBool() -IsSigned $Signed.ToBool() -AuditMode $Audit.ToBool() -IsPillar $Pillar.ToBool() -OriginLocation $WorkingPoliciesLocation -OriginLocationType $WorkingPoliciesLocationType -Connection $Connection -ErrorAction Stop)) {
throw "Failed to add this policy to the database."
}
}
#======================================================================
} catch {
Write-Error $_
return
}
try {
$NewFileName = ($PolicyName + "_v" + ($VersionNumber.replace('.','_')) + ".xml")
if ($WorkingPoliciesLocationType.ToLower() -eq "local") {
Copy-Item $TempPolicyPath -Destination (Join-Path $WorkingPoliciesLocation -ChildPath $NewFileName) -Force -ErrorAction Stop
} else {
#TODO: Other working policies directory types
}
$Transaction.Commit()
$Connection.Close()
Remove-Variable Transaction, Connection -ErrorAction SilentlyContinue
} catch {
Write-Verbose $_
throw "There was a problem placing the new policy file into your working policies directory."
}
Write-Host "Policy creation successful, with Policy GUID $PolicyID" -ForegroundColor Green
}
end {
if ($TempPolicyPath) {
if (Test-Path $TempPolicyPath) {
Remove-Item $TempPolicyPath -Force
}
}
if ($Transaction -and $Connection) {
if ($Connection.AutoCommit -eq $false) {
$Transaction.Rollback()
}
}
if ($Connection) {
$Connection.Close()
}
if ($PSModuleRoot) {
if (Test-Path (Join-Path -Path $PSModuleRoot -ChildPath ".\.WDACFrameworkData\PSCodeSigning.cer")) {
Remove-Item (Join-Path -Path $PSModuleRoot -ChildPath ".\.WDACFrameworkData\PSCodeSigning.cer") -Force
}
if (Test-Path (Join-Path -Path $PSModuleRoot -ChildPath ".\.WDACFrameworkData\WDACCodeSigning.cer")) {
Remove-Item (Join-Path -Path $PSModuleRoot -ChildPath ".\.WDACFrameworkData\WDACCodeSigning.cer") -Force
}
}
}
}
Export-ModuleMember -Function New-WDACPolicy