-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDeploy-WDACPolicies.psm1
1864 lines (1601 loc) · 112 KB
/
Deploy-WDACPolicies.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
$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\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")
}
if (Test-Path (Join-Path $PSModuleRoot -ChildPath "SignedModules\Resources\SQL-TrustDBTools_Part3.psm1")) {
Import-Module (Join-Path $PSModuleRoot -ChildPath "SignedModules\Resources\SQL-TrustDBTools_Part3.psm1")
} else {
Import-Module (Join-Path $PSModuleRoot -ChildPath "Resources\SQL-TrustDBTools_Part3.psm1")
}
if (Test-Path (Join-Path $PSModuleRoot -ChildPath "SignedModules\Resources\WorkingPolicies-and-DB-IO.psm1")) {
Import-Module (Join-Path $PSModuleRoot -ChildPath "SignedModules\Resources\WorkingPolicies-and-DB-IO.psm1")
} else {
Import-Module (Join-Path $PSModuleRoot -ChildPath "Resources\WorkingPolicies-and-DB-IO.psm1")
}
if (Test-Path (Join-Path $PSModuleRoot -ChildPath "SignedModules\Resources\Restart-WDACDevices.psm1")) {
Import-Module (Join-Path $PSModuleRoot -ChildPath "SignedModules\Resources\Restart-WDACDevices.psm1")
} else {
Import-Module (Join-Path $PSModuleRoot -ChildPath "Resources\Restart-WDACDevices.psm1")
}
if (Test-Path (Join-Path $PSModuleRoot -ChildPath "SignedModules\Resources\Copy-StagedWDACPolicies.psm1")) {
Import-Module (Join-Path $PSModuleRoot -ChildPath "SignedModules\Resources\Copy-StagedWDACPolicies.psm1")
} else {
Import-Module (Join-Path $PSModuleRoot -ChildPath "Resources\Copy-StagedWDACPolicies.psm1")
}
if (Test-Path (Join-Path $PSModuleRoot -ChildPath "SignedModules\Resources\Invoke-ActivateAndRefreshWDACPolicy.psm1")) {
Import-Module (Join-Path $PSModuleRoot -ChildPath "SignedModules\Resources\Invoke-ActivateAndRefreshWDACPolicy.psm1")
} else {
Import-Module (Join-Path $PSModuleRoot -ChildPath "Resources\Invoke-ActivateAndRefreshWDACPolicy.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\Test-ValidWDACSignedPolicySignature.psm1")) {
Import-Module (Join-Path $PSModuleRoot -ChildPath "SignedModules\Resources\Test-ValidWDACSignedPolicySignature.psm1")
} else {
Import-Module (Join-Path $PSModuleRoot -ChildPath "Resources\Test-ValidWDACSignedPolicySignature.psm1")
}
function Get-X86Path {
$X86_Path = (Get-LocalStorageJSON -ErrorAction Stop)."RefreshTool_x86"
if (-not $X86_Path -or ("" -eq $X86_Path)) {
throw "For remote machines with AMD64 architecture, specify the path of the AMD64 refresh tool in LocalStorage.json."
}
if (-not (Test-Path $X86_Path)) {
throw "Please provide the full, valid path of the X86 refresh tool executable in LocalStorage.json."
}
return $X86_Path
}
function Get-AMD64Path {
$AMD64_Path = (Get-LocalStorageJSON -ErrorAction Stop)."RefreshTool_AMD64"
if (-not $AMD64_Path -or ("" -eq $AMD64_Path)) {
throw "For remote machines with AMD64 architecture, specify the path of the AMD64 refresh tool in LocalStorage.json."
}
if (-not (Test-Path $AMD64_Path)) {
throw "Please provide the full, valid path of the AMD64 refresh tool executable in LocalStorage.json."
}
return $AMD64_Path
}
function Get-ARM64Path {
$ARM64_Path = (Get-LocalStorageJSON -ErrorAction Stop)."RefreshTool_ARM64"
if (-not $ARM64_Path -or ("" -eq $ARM64_Path)) {
throw "For remote machines with ARM64 architecture, specify the path of the ARM64 refresh tool in LocalStorage.json."
}
if (-not (Test-Path $ARM64_Path)) {
throw "Please provide the full, valid path of the ARM64 refresh tool executable in LocalStorage.json."
}
return $ARM64_Path
}
function Get-YesOrNoPrompt {
[CmdletBinding()]
Param (
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
$Prompt
)
Write-Host ($Prompt + " (Y/N): ") -NoNewline
while ($true) {
$InputString = Read-Host
if ($InputString.ToLower() -eq "y") {
return $true
} elseif ($InputString.ToLower() -eq "n") {
return $false
} else {
Write-Host "Not a valid option. Please supply y or n."
}
}
}
function Set-MachineDeferred {
[cmdletbinding()]
Param (
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$PolicyGUID,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$DeviceName,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$Comment,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[System.Data.SQLite.SQLiteConnection]$Connection
)
if (-not (Set-WDACDeviceDeferredStatus -DeviceName $DeviceName -Connection $Connection -ErrorAction Stop)) {
throw "Unable to update deferred status for $DeviceName"
}
if (-not (Test-PolicyDeferredOnDevice -PolicyGUID $PolicyGUID -WorkstationName $DeviceName -Connection $Connection -ErrorAction Stop)) {
$PolicyVersion = Get-WDACPolicyLastDeployedVersion -PolicyGUID $PolicyGUID -Connection $Connection -ErrorAction Stop
$DeferredPolicy = $null
if (Test-DeferredWDACPolicy -DeferredDevicePolicyGUID $PolicyGUID -PolicyVersion $PolicyVersion -Connection $Connection -ErrorAction Stop) {
$DeferredPolicy = Get-DeferredWDACPolicy -DeferredDevicePolicyGUID $PolicyGUID -PolicyVersion $PolicyVersion -Connection $Connection -ErrorAction Stop
} else {
if (-not (Add-DeferredWDACPolicy -PolicyGUID $PolicyGUID -Connection $Connection -ErrorAction Stop)) {
throw "Cannot add deferred WDAC policy of GUID $PolicyGUID and version $PolicyVersion"
}
$DeferredPolicy = Get-DeferredWDACPolicy -DeferredDevicePolicyGUID $PolicyGUID -PolicyVersion $PolicyVersion -Connection $Connection -ErrorAction Stop
}
if (-not (Add-DeferredWDACPolicyAssignment -DeferredPolicyIndex $DeferredPolicy.DeferredPolicyIndex -DeviceName $DeviceName -Comment $Comment -Connection $Connection -ErrorAction Stop)) {
throw "Unable to add deferred policy assignment of deferred policy index $($DeferredPolicy.DeferredPolicyIndex) to device $DeviceName"
}
}
}
function Remove-MachineDeferred {
[cmdletbinding()]
Param (
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$PolicyGUID,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$DeviceName,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[System.Data.SQLite.SQLiteConnection]$Connection
)
$DeferredPolicies = Get-DeferredWDACPolicies -DeferredDevicePolicyGUID $PolicyGUID -Connection $Connection -ErrorAction Stop
foreach ($DeferredPolicy in $DeferredPolicies) {
if (Test-SpecificDeferredPolicyOnDevice -DeferredPolicyIndex $DeferredPolicy.DeferredPolicyIndex -WorkstationName $DeviceName -Connection $Connection -ErrorAction Stop) {
if (-not (Remove-DeferredWDACPolicyAssignment -DeferredPolicyIndex $DeferredPolicy.DeferredPolicyIndex -DeviceName $DeviceName -Connection $Connection -ErrorAction Stop)) {
throw "Unsuccessful in removing deferred policy assignment of this policy on device $DeviceName : $($DeferredPolicy.DeferredPolicyIndex)"
} else {
if (-not (Test-AnyDeferredWDACPolicyAssignments -DeferredPolicyIndex $DeferredPolicy.DeferredPolicyIndex -Connection $Connection -ErrorAction Stop)) {
if (-not (Remove-DeferredWDACPolicy -DeferredPolicyIndex $DeferredPolicy.DeferredPolicyIndex -Connection $Connection -ErrorAction Stop)) {
throw "Trouble removing deferred policy with index $($DeferredPolicy.DeferredPolicyIndex) after the removal of its last assignment."
}
}
}
}
}
if (-not (Test-AnyPoliciesDeferredOnDevice -WorkstationName $DeviceName -Connection $Connection -ErrorAction Stop)) {
if (-not (Set-WDACDeviceDeferredStatus -DeviceName $DeviceName -Unset -Connection $Connection -ErrorAction Stop)) {
throw "Unable to reset deferred status on device $DeviceName back to normal. (This is the UpdateDeferring flag in the database)"
}
}
}
function Deploy-WDACPolicies {
<#
.SYNOPSIS
This function deploys WDAC policies specified by parameter input --
ONLY IF the latest version hasn't yet been deployed -- signs them (if applicable)
and copies them to the relevant machines which have those policies assigned.
Then a RefreshPolicy action is enacted on that machine.
.DESCRIPTION
This function determines what machines have the designated policy assigned to them, by checking group assignments, ad-hoc assignments,
and the policy "pillar" attribute. (A policy set as a pillar is deployed to every device listed in the trust database.)
It signs policies which need to be signed. (Using the SignTool.)
Then, that designated policy (the signed / unsigned .CIP file) is deployed to each machine (ONLY IF the DB shows that that version has not been deployed yet.)
For machines which cannot have their policy updated, the last deployed policy is recorded -- with all its parameters, in the deferred_policies table,
and an entry for that particular device is made in the deferred_policies_assignments table.
Then, if a policy is signed, it is also placed in the UEFI partition for the machine.
Finally, a refresh policy is performed on the relevant machine (if the machine runs on Windows 11, the CiTool is used, otherwise, RefreshPolicy.exe is used.)
When a selection of TestComputers is designated, the remaining computers which are not test computers are set with the policy_deferring flag until the
Restore-WDACWorkstations cmdlet is used to bring those computers up-to-date with the most recent policy version.
Author: Nathan Jepson
License: MIT License
.PARAMETER PolicyGUID
ID of the policy (NOT the alternate ID which WDAC policies also have, although you can use the alias "PolicyID" for this parameter)
.PARAMETER PolicyName
Name of the policy (exact)
.PARAMETER Local
WARNING: When running with this parameter, the cmdlet makes no reference to group assignments or the last deployed policy version. Use at your own risk.
Use this switch if you merely want to update the policy on your current machine (local)
.PARAMETER RemoveUEFISignedLocal
This parameter only valid when "Local" also selected. Use this flag for when you want to remove the old, signed policy from the EFI partition
on your local machine.
.PARAMETER TestComputers
Specify test computers where you would like to deploy the policy first. First, a check is performed if a test computer is actually assigned the particular policy.
Once you can verify that a policy was successfully deployed on the test machines, then run the Restore-WDACWorkstations cmdlet to deploy the relevant policy
to the remaining machines which have the policy assigned.
.PARAMETER TestForce
Force deployment of policy to machines -- even if they are not assigned the relevant policy. (Only if "TestComputers" is provided.)
.PARAMETER SkipSetup
Cmdlet will not check whether staging directory or refresh tools are present on a device.
.PARAMETER ForceRestart
WARNING: Disruptive action.
All devices* will be forced to restart! -- *Only applies to when a signed base policy is
deployed on a device for the first time or when you are modifying a policy that is signed to be unsigned.
.PARAMETER SleepTime
This is how long to wait for before continuing script execution after a restart job is performed to remove boot-protection for signed
WDAC policies -- this ONLY applies when a previously signed policy becomes unsigned.
.EXAMPLE
Deploy-WDACPolicies -PolicyGUID "4ac96917-6f84-43c3-ab68-e9a7bc87eb8f"
.EXAMPLE
Deploy-WDACPolicies -PolicyGUID "4ac96917-6f84-43c3-ab68-e9a7bc87eb8f" -TestComputers PC1,PC2
.EXAMPLE
Deploy-WDACPolicies -PolicyGUID "4ac96917-6f84-43c3-ab68-e9a7bc87eb8f" -TestComputers PC1,StandoutPC -TestForce -SkipSetup -ForceRestart
#>
[cmdletbinding()]
Param (
[ValidateNotNullOrEmpty()]
[Alias("PolicyID","id")]
[string]$PolicyGUID,
[ValidateNotNullOrEmpty()]
[string]$PolicyName,
[switch]$Local,
[Alias("LocalRemoveUEFI","EFILocalRemove","RemoveUEFI","RemoveSignedLocal")]
[switch]$RemoveUEFISignedLocal,
[Alias("TestMachines","TestMachine","TestDevices","TestDevice","TestComputer")]
[string[]]$TestComputers,
[Alias("Force")]
[switch]$TestForce,
[switch]$SkipSetup,
[switch]$ForceRestart,
[int]$SleepTime=480
)
if ($ThisIsASignedModule) {
Write-Verbose "The current file is in the SignedModules folder."
}
if ($PolicyName -and $PolicyGUID) {
throw "Cannot provide both a policy name and policy GUID."
}
if ($TestForce -and (-not $TestComputers)) {
throw "Cannot set TestForce without providing a list of test computers."
}
if ($RemoveUEFISignedLocal -and (-not $Local)) {
throw "Cannot set the -RemoveUEFISignedLocal flag when the -Local flag is also not set."
}
if (-not $Local) {
$RemoteStagingDirectory = (Get-LocalStorageJSON -ErrorAction Stop)."RemoteStagingDirectory"
if (-not $RemoteStagingDirectory -or ("" -eq $RemoteStagingDirectory)) {
throw "When deploying staged policies to remote machines, you must designate a RemoteStagingDirectory in LocalStorage.json."
}
try {
Split-Path $RemoteStagingDirectory -Qualifier -ErrorAction Stop | Out-Null
} catch {
throw "The RemoteStagingDirectory must have a qualifier such as `"C:\`" or `"D:\`" at the beginning."
}
}
$Connection = $null
$Transaction = $null
$SignedStagedPolicyPath = $null
$UnsignedStagedPolicyPath = $null
$RestartLocalDevice = $false
$ClearUEFIBootLocalDevice = $false
$LocalDeviceName = HOSTNAME.EXE
$ComputerMapDeferredDevices = $null
try {
$Connection = New-SQLiteConnection -ErrorAction Stop
$Transaction = $Connection.BeginTransaction()
if ($PolicyName) {
$PolicyInfo = Get-WDACPolicyByName -PolicyName $PolicyName -Connection $Connection -ErrorAction Stop
$PolicyGUID = $PolicyInfo.PolicyGUID
} elseif ($PolicyGUID) {
$PolicyInfo = Get-WDACPolicy -PolicyGUID $PolicyGUID -Connection $Connection -ErrorAction Stop
}
$SignedToUnsigned = Test-MustRemoveSignedPolicy -PolicyGUID $PolicyGUID -Connection $Connection -ErrorAction Stop
if ( ($PolicyInfo.IsSigned -eq $true) -or $SignedToUnsigned) {
#Check if all local variables are correctly set to be able to sign and deploy WDAC policies
$WDACodeSigningCert = (Get-LocalStorageJSON -ErrorAction Stop)."WDACPolicySigningCertificate"
if (-not $WDACodeSigningCert -or "" -eq $WDACodeSigningCert) {
throw "Error: Empty or null value for WDAC Policy signing certificate retreived from Local Storage."
} elseif (-not ($WDACodeSigningCert.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`""
}
#See if it's in the Local Cert Store
$cert = Get-ChildItem -Path $WDACodeSigningCert -ErrorAction Stop
$SignTool = (Get-LocalStorageJSON -ErrorAction Stop)."SignTool"
if (-not $SignTool -or ("" -eq $SignTool) -or ("Full_Path_To_SignTool.exe" -eq $SignTool)) {
throw "Error: Empty, default, or null value for WDAC Policy signing certificate retreived from Local Storage."
} elseif (-not (Test-Path $SignTool)) {
throw "Path for Sign tool does not exist or not a valid path."
}
if (-not ($cert.Subject -match "(?<=CN=)(.*?)($|(?=,\s?[^\s,]+=))")) {
throw "WDACCodeSigningCert subject name not in the correct format. Example: CN=WDACSigningCertificate "
}
}
if ($Local) {
$UnsignedStagedPolicyPath = (Join-Path -Path $PSModuleRoot -ChildPath ".\.WDACFrameworkData\{$($PolicyInfo.PolicyGUID)}.cip")
$PolicyPath = Get-FullPolicyPath -PolicyGUID $PolicyGUID -Connection $Connection -ErrorAction Stop
ConvertFrom-CIPolicy -BinaryFilePath $UnsignedStagedPolicyPath -XmlFilePath $PolicyPath -ErrorAction Stop | Out-Null
$CPU = cmd.exe /c "echo %PROCESSOR_ARCHITECTURE%"
$Windows11 = $false
$RefreshToolPath = $null
if ($PSVersionTable.PSEdition -eq "Core") {
$Windows11 = (Get-CimInstance -Class Win32_OperatingSystem -Property Caption -ErrorAction Stop | Select-Object -ExpandProperty Caption) -Match "Windows 11"
} elseif ($PSVersionTable.PSEdition -eq "Desktop") {
$Windows11 = (Get-WmiObject Win32_OperatingSystem -ErrorAction Stop).Caption -Match "Windows 11"
}
$LegacyBIOS = $false
if ($env:firmware_type -eq "Legacy") {
$LegacyBIOS = $true
}
$CiToolPresent = $false
if ($Windows11 -and (Test-Path "$env:windir\System32\CiTool.exe")) {
$CiToolPresent = $true
}
if ($CPU -eq "X86") {
$RefreshToolPath = Get-X86Path -ErrorAction Stop
} elseif ($CPU -eq "AMD64") {
$RefreshToolPath = Get-AMD64Path -ErrorAction Stop
} elseif ($CPU -eq "ARM64") {
$RefreshToolPath = Get-ARM64Path -ErrorAction Stop
} else {
if (-not $Windows11) {
throw "CPU architecture for local device not supported."
}
}
if ($PolicyInfo.IsSigned -eq $true) {
#Get Signed
$SignedStagedPolicyPath = Invoke-SignTool -CIPPolicyPath $UnsignedStagedPolicyPath -DestinationDirectory (Join-Path -Path $PSModuleRoot -ChildPath ".\.WDACFrameworkData") -ErrorAction Stop
Remove-Item -Path $UnsignedStagedPolicyPath -Force -ErrorAction Stop
Rename-Item -Path $SignedStagedPolicyPath -NewName (Split-Path $UnsignedStagedPolicyPath -Leaf) -Force -ErrorAction Stop
$SignedStagedPolicyPath = $UnsignedStagedPolicyPath
if (-not (Test-ValidWDACSignedPolicySignature -CISignedPolicyFile $SignedStagedPolicyPath)) {
throw "Invalid signature for the signed WDAC policy, is invalid for this device."
}
#Copy to EFI Mount
#Put the signed WDAC policy into the UEFI partition
if (-not $LegacyBIOS) {
#Instructions Provided by Microsoft:
#https://learn.microsoft.com/en-us/windows/security/application-security/application-control/windows-defender-application-control/deployment/deploy-wdac-policies-with-script
$MountPoint = "$env:SystemDrive\EFIMount"
$EFIDestinationFolder = "$MountPoint\EFI\Microsoft\Boot\CiPolicies\Active"
#Note: For devices that don't have an EFI System Partition, this will just return the C: drive usually
$EFIPartition = (Get-Partition | Where-Object IsSystem).AccessPaths[0]
if (-Not (Test-Path $MountPoint)) { New-Item -Path $MountPoint -Type Directory -Force -ErrorAction Stop | Out-Null }
mountvol $MountPoint $EFIPartition | Out-Null
if (-Not (Test-Path $EFIDestinationFolder)) { New-Item -Path $EFIDestinationFolder -Type Directory -Force -ErrorAction Stop | Out-Null }
Copy-Item -Path $SignedStagedPolicyPath -Destination $EFIDestinationFolder -Force -ErrorAction Stop
if (Test-Path "$($Env:Windir)\System32\CodeIntegrity\CiPolicies\Active\{$($PolicyInfo.PolicyGUID)}.cip") {
#Remove from System32 location to prevent blue-screens
try {
Remove-Item "$($Env:Windir)\System32\CodeIntegrity\CiPolicies\Active\{$($PolicyInfo.PolicyGUID)}.cip" -Force -ErrorAction Stop
} catch {
throw "CRITICAL: Unable to remove policy from System32 location. This means there is a policy in both the EFI partition `
and System32 locations, which might lead to a blue-screen. Please remove the policy from the System32 location as soon as you are able!"
}
}
mountvol $MountPoint /D | Out-Null
} else {
#Legacy BIOS
Write-Warning "Legacy BIOS detected, so putting signed policy in System32 location instead of EFI partition."
Copy-item -Path $SignedStagedPolicyPath -Destination "$($Env:Windir)\System32\CodeIntegrity\CiPolicies\Active" -Force -ErrorAction Stop
}
#Either Restart Device or Use Refresh Tool
if ($PolicyInfo.BaseOrSupplemental -eq $true) {
if ($CiToolPresent) {
$CiToolRefreshResult = (CiTool --refresh -json)
$RefreshJSON = $CiToolRefreshResult | ConvertFrom-Json
if ($RefreshJSON.OperationResult -ne 0) {
throw "Refresh unsuccessful. CiTool returned error $('0x{0:x}' -f [int32]($RefreshJSON).OperationResult)"
}
Write-Host "Refresh completed successfully."
} elseif ($RefreshToolPath) {
Start-Process $RefreshToolPath -NoNewWindow -Wait -ErrorAction Stop
Write-Host "Refresh completed successfully."
} else {
Write-Warning "No way found to refresh the policy."
}
} elseif (Get-YesOrNoPrompt -Prompt "If this is the first time this signed base policy has been deployed locally, select `"Y`" to restart your device, otherwise select `"N`" to use the refresh tool.") {
Restart-Computer -Force
} else {
if ($CiToolPresent) {
$CiToolRefreshResult = (CiTool --refresh -json)
$RefreshJSON = $CiToolRefreshResult | ConvertFrom-Json
if ($RefreshJSON.OperationResult -ne 0) {
throw "Refresh unsuccessful. CiTool returned error $('0x{0:x}' -f [int32]($RefreshJSON).OperationResult)"
}
Write-Host "Refresh completed successfully."
} elseif ($RefreshToolPath) {
Start-Process $RefreshToolPath -NoNewWindow -Wait -ErrorAction Stop
Write-Host "Refresh completed successfully."
} else {
Write-Warning "No way found to refresh the policy."
}
}
if ($SignedStagedPolicyPath) {
if (Test-Path $SignedStagedPolicyPath) {
Remove-Item -Path $SignedStagedPolicyPath -Force -ErrorAction SilentlyContinue
}
}
} else {
if ($RemoveUEFISignedLocal -and (-not $LegacyBIOS)) {
$CIPolicyFileName = Split-Path $UnsignedStagedPolicyPath -Leaf
$MountPoint = "$env:SystemDrive\EFIMount"
$EFIDestinationFolder = "$MountPoint\EFI\Microsoft\Boot\CiPolicies\Active"
#Note: For devices that don't have an EFI System Partition, this will just return the C: drive usually
$EFIPartition = (Get-Partition | Where-Object IsSystem).AccessPaths[0]
if (-Not (Test-Path $MountPoint)) { New-Item -Path $MountPoint -Type Directory -Force -ErrorAction Stop | Out-Null }
mountvol $MountPoint $EFIPartition | Out-Null
if (Test-Path (Join-Path $EFIDestinationFolder -ChildPath $CIPolicyFileName)) {
Remove-Item -Path (Join-Path $EFIDestinationFolder -ChildPath $CIPolicyFileName) -Force -ErrorAction Stop | Out-Null
} else {
Write-Warning "No policy file with name $CIPolicyFileName located in the EFI partition."
}
mountvol $MountPoint /D | Out-Null
}
#Copy to C:\Windows\System32\CodeIntegrity\CiPolicies\Active
Copy-item -Path $UnsignedStagedPolicyPath -Destination "$($Env:Windir)\System32\CodeIntegrity\CiPolicies\Active" -Force -ErrorAction Stop
#Use Refresh Tool
if ($CiToolPresent) {
$CiToolRefreshResult = (CiTool --refresh -json)
$RefreshJSON = $CiToolRefreshResult | ConvertFrom-Json
if ($RefreshJSON.OperationResult -ne 0) {
throw "Refresh unsuccessful. CiTool returned error $('0x{0:x}' -f [int32]($RefreshJSON).OperationResult)"
}
} elseif ($RefreshToolPath) {
Start-Process $RefreshToolPath -NoNewWindow -Wait -ErrorAction Stop
} else {
Write-Warning "No way found to refresh the policy."
}
if ($UnsignedStagedPolicyPath) {
if (Test-Path $UnsignedStagedPolicyPath) {
Remove-Item -Path $UnsignedStagedPolicyPath -Force -ErrorAction SilentlyContinue
}
}
}
$Transaction.Commit()
$Connection.Close()
Write-Host "Policy has been locally deployed."
} else {
#Push to Remote Machines
if (($null -ne $PolicyInfo.PolicyVersion) -and ($null -ne $PolicyInfo.LastDeployedPolicyVersion)) {
if ((Test-ValidVersionNumber -VersionNumber $PolicyInfo.PolicyVersion) -and (Test-ValidVersionNumber -VersionNumber $PolicyInfo.LastDeployedPolicyVersion)) {
if ((Compare-Versions -Version1 $PolicyInfo.PolicyVersion -Version2 $PolicyInfo.LastDeployedPolicyVersion) -le 0) {
throw "Latest version of this policy is already deployed."
}
}
}
if ($PolicyInfo.IsPillar -eq $true) {
$ComputerMap = Get-WDACDevicesAllNamesAndCPUInfo -Connection $Connection -ErrorAction Stop
$ComputerMapDeferredDevices = Get-WDACDevicesAllNamesAndCPUInfo -Deferred -Connection $Connection -ErrorAction Stop
} else {
$ComputerMap = Get-WDACDevicesNeedingWDACPolicy -PolicyGUID $PolicyGUID -Connection $Connection -ErrorAction Stop
$ComputerMapDeferredDevices = Get-WDACDevicesNeedingWDACPolicy -Deferred -PolicyGUID $PolicyGUID -Connection $Connection -ErrorAction Stop
}
if ( (($null -eq $ComputerMap) -or $ComputerMap.Count -le 0) -and (-not ($TestComputers -and $TestForce)) ) {
if ($ComputerMapDeferredDevices -and ($ComputerMapDeferredDevices.Count -gt 0)) {
#Since these devices are behind on this deployment, then they must be deferred on this policy
foreach ($DeferredMachine in $ComputerMapDeferredDevices.GetEnumerator()) {
try {
if ($TestComputers) {
if ($TestForce) {
Set-MachineDeferred -PolicyGUID $PolicyGUID -DeviceName $DeferredMachine.Name -Comment ("Device is deferred on another WDAC policy and will be deferred on this one on deployment.") -Connection $Connection -ErrorAction Stop
} elseif ($TestComputers -contains $DeferredMachine.Name) {
Set-MachineDeferred -PolicyGUID $PolicyGUID -DeviceName $DeferredMachine.Name -Comment ("Device is deferred on another WDAC policy and will be deferred on this one on deployment.") -Connection $Connection -ErrorAction Stop
}
} else {
Set-MachineDeferred -PolicyGUID $PolicyGUID -DeviceName $DeferredMachine.Name -Comment ("Device is deferred on another WDAC policy and will be deferred on this one on deployment.") -Connection $Connection -ErrorAction Stop
}
} catch {
Write-Verbose ($_ | Format-List -Property * | Out-String)
}
}
$Transaction.Commit()
}
throw "No non-deferred workstations currently assigned to policy $PolicyGUID"
}
$PolicyPath = Get-FullPolicyPath -PolicyGUID $PolicyGUID -Connection $Connection -ErrorAction Stop
$X86_Path = $null
$AMD64_Path = $null
$ARM64_Path = $null
$NewComputerMap = @()
foreach ($Computer in $ComputerMap.GetEnumerator()) {
$thisComputer = $Computer.Name
$CPU = $Computer.Value
if ($null -eq $CPU -or ($CPU -eq "") -or ($CPU -is [System.DBNull])) {
$Architecture = $null
try {
$Architecture = Invoke-Command -ComputerName $thisComputer -ScriptBlock {cmd.exe /c "echo %PROCESSOR_ARCHITECTURE%"} -ErrorAction Stop
} catch {
Write-Verbose "Device $thisComputer not available for PowerShell remoting."
$NewComputerMap += @{DeviceName = $thisComputer; CPU = $CPU; NewlyDeferred = $true; TestMachine = $false}
continue
}
if ($Architecture) {
if (-not (Add-WDACWorkstationProcessorArchitecture -DeviceName $thisComputer -ProcessorArchitecture $Architecture -Connection $Connection -ErrorAction Stop)) {
Write-Verbose "Could not write CPU architecture $Architecture of device $thisComputer to database."
}
$CPU = $Architecture
}
}
if ($CPU -eq "AMD64") {
if ($null -eq $AMD64_Path) {
$AMD64_Path = Get-AMD64Path
}
} elseif ($CPU -eq "ARM64") {
if ($null -eq $ARM64_Path) {
$ARM64_Path = Get-ARM64Path
}
} elseif ($CPU -eq "X86") {
if ($null -eq $X86_Path) {
$X86_Path = Get-X86Path
}
} else {
#The reason we commit here is because database values were written for CPU architectures
$Transaction.Commit()
$Connection.Close()
throw "$CPU CPU architecture not supported for device $thisComputer"
}
if ($TestComputers) {
if ( ($TestComputers -contains $thisComputer)) {
$NewComputerMap += @{DeviceName = $thisComputer; CPU = $CPU; NewlyDeferred = $false; TestMachine = $true}
} else {
$NewComputerMap += @{DeviceName = $thisComputer; CPU = $CPU; NewlyDeferred = $true; TestMachine = $false}
}
} else {
$NewComputerMap += @{DeviceName = $thisComputer; CPU = $CPU; NewlyDeferred = $false; TestMachine = $false}
}
}
if ($TestForce) {
foreach ($thisTestMachine in $TestComputers) {
$Assigned = $false
$CPU = $null
foreach ($Computer in $ComputerMap.GetEnumerator()) {
if ($thisTestMachine -eq $Computer.Name) {
$Assigned = $true
}
}
if (-not $Assigned) {
#$NewComputerMap += @{DeviceName = $thisTestMachine; CPU = }
$CPU = Get-WDACWorkstationProcessorArchitecture -DeviceName $thisTestMachine -Connection $Connection -ErrorAction Stop
if ($null -eq $CPU -or ($CPU -eq "") -or ($CPU -is [System.DBNull])) {
$Architecture = $null
try {
$Architecture = Invoke-Command -ComputerName $thisComputer -ScriptBlock {cmd.exe /c "echo %PROCESSOR_ARCHITECTURE%"} -ErrorAction Stop
} catch {
Write-Verbose "Device $thisComputer not available for PowerShell remoting."
#We don't add this device to the $NewComputerMap because it was never assigned the policy in the first place and we don't want to defer it
continue
}
if ($Architecture) {
if (-not (Add-WDACWorkstationProcessorArchitecture -DeviceName $thisComputer -ProcessorArchitecture $Architecture -Connection $Connection -ErrorAction Stop)) {
Write-Verbose "Could not write CPU architecture $Architecture of device $thisComputer to database."
}
$CPU = $Architecture
} elseif (($null -eq $Architecture) -or ("" -eq $Architecture)) {
Write-Verbose "Could not retrieve valid CPU architecture from $thisComputer"
continue
}
}
if ($CPU -eq "AMD64") {
if ($null -eq $AMD64_Path) {
$AMD64_Path = Get-AMD64Path
}
} elseif ($CPU -eq "ARM64") {
if ($null -eq $ARM64_Path) {
$ARM64_Path = Get-ARM64Path
}
} elseif ($CPU -eq "X86") {
if ($null -eq $X86_Path) {
$X86_Path = Get-X86Path
}
} elseif (($null -ne $CPU) -and ("" -ne $CPU)) {
#The reason we commit here is because database values were written for CPU architectures
$Transaction.Commit()
$Connection.Close()
throw "$CPU CPU architecture not supported for device $thisComputer"
}
if ($CPU) {
$NewComputerMap += @{DeviceName = $thisComputer; CPU = $CPU; NewlyDeferred = $false; TestMachine = $true}
}
}
}
}
if ($X86_Path) {
$X86_RefreshToolName = Split-Path $X86_Path -Leaf
}
if ($AMD64_Path) {
$AMD64_RefreshToolName = Split-Path $AMD64_Path -Leaf
}
if ($ARM64_Path) {
$ARM64_RefreshToolName = Split-Path $ARM64_Path -Leaf
}
$CustomPSObjectComputerMap = $NewComputerMap | ForEach-Object { New-Object -TypeName PSCustomObject | Add-Member -NotePropertyMembers $_ -PassThru }
if ($TestComputers -and (-not $TestForce)) {
if ( -not ($CustomPSObjectComputerMap | Where-Object { ($_.NewlyDeferred -eq $false) -and ($_.TestMachine -eq $true)} )) {
if ($ComputerMapDeferredDevices -and ($ComputerMapDeferredDevices.Count -gt 0)) {
#Since these devices are behind on this deployment, then they must be deferred on this policy
foreach ($DeferredMachine in $ComputerMapDeferredDevices.GetEnumerator()) {
try {
Set-MachineDeferred -PolicyGUID $PolicyGUID -DeviceName $DeferredMachine.Name -Comment ("Device is deferred on another WDAC policy and will be deferred on this one on deployment.") -Connection $Connection -ErrorAction Stop
} catch {
Write-Verbose ($_ | Format-List -Property * | Out-String)
}
}
$Transaction.Commit()
}
throw "No non-deferred workstations in `"TestComputers`" currently assigned to policy $PolicyGUID"
}
}
$UnsignedStagedPolicyPath = (Join-Path -Path $PSModuleRoot -ChildPath ".\.WDACFrameworkData\{$($PolicyInfo.PolicyGUID)}.cip")
if (Test-Path $UnsignedStagedPolicyPath) {
Remove-Item -Path $UnsignedStagedPolicyPath -Force -ErrorAction Stop
}
$SignedStagedPolicyPath = $null
ConvertFrom-CIPolicy -BinaryFilePath $UnsignedStagedPolicyPath -XmlFilePath $PolicyPath -ErrorAction Stop | Out-Null
##Check if Restart is Required on Devices. If there is a mix of statuses, then defer the ones which haven't been deployed yet and set $RestartRequired to $false.
$RestartRequired = $false
if ($PolicyInfo.IsSigned -eq $true -and (-not ($PolicyInfo.BaseOrSupplemental -eq $true))) {
#A policy does not necessitate a restart if it's a supplemental policy
$RestartRequired = $true
foreach ($ComputerInfo in $CustomPSObjectComputerMap) {
$Name = $ComputerInfo.DeviceName
if (Test-FirstSignedPolicyDeployment -PolicyGUID $PolicyGUID -DeviceName $Name -Connection $Connection -ErrorAction Stop) {
$RestartRequired = $false
}
}
if (-not $RestartRequired) {
#Go through each device and if they have never received a deployment yet, then defer them (since other devices already were restarted)
for ($i=0; $i -lt $CustomPSObjectComputerMap.Count; $i++) {
if (-not (Test-FirstSignedPolicyDeployment -PolicyGUID $PolicyGUID -DeviceName ($CustomPSObjectComputerMap[$i].DeviceName) -Connection $Connection -ErrorAction Stop)) {
$CustomPSObjectComputerMap[$i].NewlyDeferred = $true
Set-MachineDeferred -PolicyGUID $PolicyGUID -DeviceName ($CustomPSObjectComputerMap[$i].DeviceName) -Comment "Machine has not yet received first signed deployment while other machines have." -Connection $Connection -ErrorAction Stop
}
}
}
}
##############################################################################################################################
$Machines = $null
$results = $null
$Test = $false
if (($CustomPSObjectComputerMap | Where-Object {$_.TestMachine -eq $true} | Select-Object DeviceName).Count -ge 1) {
$Test = $true
}
if ($Test) {
$Machines = ($CustomPSObjectComputerMap | Where-Object {($_.NewlyDeferred -eq $false) -and ($_.TestMachine -eq $true) -and ($null -ne $_.CPU)} | Select-Object DeviceName).DeviceName
} else {
$Machines = ($CustomPSObjectComputerMap | Where-Object {($_.NewlyDeferred -eq $false) -and ($null -ne $_.CPU)} | Select-Object DeviceName).DeviceName
}
if ($Machines.Count -le 0) {
#This handles the case where a test machine didn't have a FirstSignedPolicy deployment, and was deferred because of it, and there
#are not machines left to deploy a policy to
Write-Warning "Some devices needed to be deferred, and no devices received this policy. There are a few reasons for this, but is often caused by a new device receiving a signed policy which has not yet been initally restarted."
for ($i=0; $i -lt $CustomPSObjectComputerMap.Count; $i++) {
if (($CustomPSObjectComputerMap[$i].TestMachine -eq $false) -and ($Test)) {
Set-MachineDeferred -PolicyGUID $PolicyGUID -DeviceName ($CustomPSObjectComputerMap[$i].DeviceName) -Comment "Device was not one of the test machines." -Connection $Connection -ErrorAction Stop
} elseif ($CustomPSObjectComputerMap[$i].NewlyDeferred -eq $true) {
Set-MachineDeferred -PolicyGUID $PolicyGUID -DeviceName ($CustomPSObjectComputerMap[$i].DeviceName) -Comment "Machine had been deferred prior to deployment action (possibly because it has not yet been restarted for inistial deployment of signed policy)." -Connection $Connection -ErrorAction Stop
}
}
if (Test-Path $UnsignedStagedPolicyPath) {
Remove-Item -Path $UnsignedStagedPolicyPath -Force -ErrorAction SilentlyContinue
}
$Transaction.Commit()
$Connection.Close()
return
}
$SuccessfulMachines = @()
#This list is only used when SignedToUnsigned is set to true
#Copy WDAC Policies and Refresh Tools
##======================================================================================
if ($SignedToUnsigned) {
if (-not (Get-YesOrNoPrompt -Prompt "Devices will require a restart to fully remove UEFI boot protection of old, signed policy. Continue with script execution?")) {
$Transaction.Rollback()
$Connection.Close()
return
}
#Get Signed First
$SignedStagedPolicyPath = Invoke-SignTool -CIPPolicyPath $UnsignedStagedPolicyPath -DestinationDirectory (Join-Path -Path $PSModuleRoot -ChildPath ".\.WDACFrameworkData") -ErrorAction Stop
Remove-Item -Path $UnsignedStagedPolicyPath -Force -ErrorAction Stop
Rename-Item -Path $SignedStagedPolicyPath -NewName (Split-Path $UnsignedStagedPolicyPath -Leaf) -Force -ErrorAction Stop
$SignedStagedPolicyPath = $UnsignedStagedPolicyPath
#Copy to Machine(s)
Copy-StagedWDACPolicies -CIPolicyPath $SignedStagedPolicyPath -ComputerMap $CustomPSObjectComputerMap -X86_Path $X86_Path -AMD64_Path $AMD64_Path -ARM64_Path $ARM64_Path -RemoteStagingDirectory $RemoteStagingDirectory -Test:($Test -and ($TestComputers.Count -ge 1)) -SkipSetup:$SkipSetup -Signed -Verbose:$VerbosePreference
#Copy to CiPolicies\Active and Use Refresh Tool and Set Policy as Deployed
#NOTE: The "restartrequired" flag is not used here because that would prevent the refresh tool from being used
#...Instead, devices will simply be restarted below after the first initial transaction commit
$results = Invoke-ActivateAndRefreshWDACPolicy -Machines $Machines -CIPolicyFileName (Split-Path $SignedStagedPolicyPath -Leaf) -X86_RefreshToolName $X86_RefreshToolName -AMD64_RefreshToolName $AMD64_RefreshToolName -ARM64_RefreshToolName $ARM64_RefreshToolName -RemoteStagingDirectory $RemoteStagingDirectory -Signed -LocalMachineName $LocalDeviceName -ErrorAction Stop
$results | ForEach-Object {
if ($_.RefreshCompletedSuccessfully -eq $true) {
$SuccessfulMachines += $_.PSComputerName
} else {
Set-MachineDeferred -PolicyGUID $PolicyGUID -DeviceName $_.PSComputerName -Comment ("Unable to deploy initial signed policy before deploying unsigned policy." + $_.ResultMessage) -Connection $Connection -ErrorAction Stop
}
}
#Set most recently deployed version in Database
try {
if (-not (Set-WDACPolicyLastDeployedVersion -PolicyGUID $PolicyGUID -Connection $Connection -ErrorAction Stop)) {
throw "Unable to set LastDeployedPolicyVersion to match the temporary signed one just deployed."
}
} catch {
Write-Verbose ($_ | Format-List -Property * | Out-String)
throw "Unable to set the LastDeployedPolicyVersion to be equal to the temporary signed PolicyVersion: $($PolicyInfo.PolicyVersion)"
}
#Set this temporary signed version number as the most recent signed version
try {
if (-not (Set-WDACPolicyLastSignedVersion -PolicyGUID $PolicyGUID -Connection $Connection -ErrorAction Stop)) {
throw "Unable to set LastSignedVersion to match the temporary signed one just deployed."
}
} catch {
throw "Unable to set the LastSignedVersion to be equal to the temporary signed PolicyVersion: $($PolicyInfo.PolicyVersion)"
}
#Increment Version Number
New-WDACPolicyVersionIncrementOne -PolicyGUID $PolicyGUID -CurrentVersion $PolicyInfo.PolicyVersion -Connection $Connection -ErrorAction Stop
#Set deferred those devices which were not initially deployed with temporary signed policy
for ($i=0; $i -lt $CustomPSObjectComputerMap.Count; $i++) {
if (-not ($SuccessfulMachines -contains $CustomPSObjectComputerMap[$i].DeviceName)) {
$CustomPSObjectComputerMap[$i].NewlyDeferred = $true
} elseif ($CustomPSObjectComputerMap[$i].NewlyDeferred -eq $true) {
Set-MachineDeferred -PolicyGUID $PolicyGUID -DeviceName $CustomPSObjectComputerMap[$i].DeviceName -Comment "Pre-script checks for device not satisfied or device not a test machine." -Connection $Connection -ErrorAction Stop
}
}
$Transaction.Commit()
$Transaction = $Connection.BeginTransaction()
#Remove Local Machine from Devices that Need to Be Restarted
if ($SuccessfulMachines -contains $LocalDeviceName) {
$SuccessfulMachines = $SuccessfulMachines | Where-Object {$_ -ne $LocalDeviceName}
$ClearUEFIBootLocalDevice = $true
}
#Restart Machines to Remove UEFI boot protection on Signed Policy
if (($SuccessfulMachines.Count -ge 1)) {
if ($ForceRestart) {
Write-Host "Performing a restart of some workstations..."
Restart-WDACDevices -Devices $SuccessfulMachines
} else {
$DevicesWithComma = $SuccessfulMachines -join ","
if (Get-YesOrNoPrompt -Prompt "Some devices will require a restart to fully remove UEFI boot protection of old, signed policy. Restart these devices now? Users will lose unsaved work: $DevicesWithComma `n") {
Restart-WDACDevices -Devices $SuccessfulMachines
} else {
#There's got to be a better way of doing this
while (-not (Get-YesOrNoPrompt -Prompt "This script cannot continue execution until devices can be restarted. `n Device might blue-screen if you do not restart them. To restart, select `"Y`"")) {
continue
}
Restart-WDACDevices -Devices $SuccessfulMachines
}
}
}
#Remove Local Machine from CustomPSObjectComputerMap if ClearUEFIBootLocalDevice is true
if ($ClearUEFIBootLocalDevice) {
$CustomPSObjectComputerMap = $CustomPSObjectComputerMap | Where-Object {$_.DeviceName -ne $LocalDeviceName}
}
#Wait for machines to boot back up, default 8 minutes
if (($SuccessfulMachines.Count -ge 1) -and ($CustomPSObjectComputerMap.Count -ge 1)) {
Write-Host "Sleeping for $SleepTime seconds while waiting for machines to power back on..."
Start-Sleep -Seconds $SleepTime
#Get Unsigned Second
$PolicyPath = Get-FullPolicyPath -PolicyGUID $PolicyGUID -Connection $Connection -ErrorAction Stop
ConvertFrom-CIPolicy -BinaryFilePath $UnsignedStagedPolicyPath -XmlFilePath $PolicyPath -ErrorAction Stop | Out-Null
#Copy to Machine(s)
Copy-StagedWDACPolicies -CIPolicyPath $UnsignedStagedPolicyPath -ComputerMap $CustomPSObjectComputerMap -X86_Path $X86_Path -AMD64_Path $AMD64_Path -ARM64_Path $ARM64_Path -RemoteStagingDirectory $RemoteStagingDirectory -Test:($Test -and ($TestComputers.Count -ge 1)) -SkipSetup:$SkipSetup -Verbose:$VerbosePreference
#Copy to CiPolicies\Active and Use Refresh Tool and Set Policy as Deployed
$results = Invoke-ActivateAndRefreshWDACPolicy -Machines $SuccessfulMachines -CIPolicyFileName (Split-Path $UnsignedStagedPolicyPath -Leaf) -X86_RefreshToolName $X86_RefreshToolName -AMD64_RefreshToolName $AMD64_RefreshToolName -ARM64_RefreshToolName $ARM64_RefreshToolName -RemoteStagingDirectory $RemoteStagingDirectory -RemoveUEFI -LocalMachineName $LocalDeviceName -ErrorAction Stop
}
#Set this new policy version as the most recent Unsigned Version number
try {
if (-not (Set-WDACPolicyLastUnsignedVersion -PolicyGUID $PolicyGUID -Connection $Connection -ErrorAction Stop)) {
throw "Unable to set LastUnsigned version to match the Policy just deployed."
}
} catch {
Write-Warning "Unable to set the LastUnsignedSignedVersion to be equal to the current PolicyVersion: $($PolicyInfo.PolicyVersion)"
}
#If there are no results, or null is returned, then no WinRM session was successful
if (-not $results) {
for ($i=0; $i -lt $CustomPSObjectComputerMap.Count; $i++) {
if (($CustomPSObjectComputerMap[$i].DeviceName -eq $LocalDeviceName) -and ($ClearUEFIBootLocalDevice)) {
continue
}
$CustomPSObjectComputerMap[$i].NewlyDeferred = $true
Set-MachineDeferred -PolicyGUID $PolicyGUID -DeviceName $CustomPSObjectComputerMap[$i].DeviceName -Comment "Unable to establish WinRM connection to machine to apply unsigned policy to machine after deploying temporary signed policy." -Connection $Connection -ErrorAction Stop
}
} else {
#Remove all entries in "first_signed_policy_deployments" for this policy
if (-not (Remove-AllFirstSignedPolicyDeployments -PolicyGUID $PolicyGUID -Connection $Connection -ErrorAction Stop)) {
Write-Warning "Unable to remove all entries first_signed_policy_deployments or unsetting DeployedSigned flag for Policy $PolicyGUID `n It is recommended to clear these entries out before next running this script."
}
}
} else {
if ($PolicyInfo.IsSigned -eq $true) {
#Get Signed
$SignedStagedPolicyPath = Invoke-SignTool -CIPPolicyPath $UnsignedStagedPolicyPath -DestinationDirectory (Join-Path -Path $PSModuleRoot -ChildPath ".\.WDACFrameworkData") -ErrorAction Stop
Remove-Item -Path $UnsignedStagedPolicyPath -Force -ErrorAction Stop
Rename-Item -Path $SignedStagedPolicyPath -NewName (Split-Path $UnsignedStagedPolicyPath -Leaf) -Force -ErrorAction Stop
$SignedStagedPolicyPath = $UnsignedStagedPolicyPath
#Copy to Machine(s)
Copy-StagedWDACPolicies -CIPolicyPath $SignedStagedPolicyPath -ComputerMap $CustomPSObjectComputerMap -X86_Path $X86_Path -AMD64_Path $AMD64_Path -ARM64_Path $ARM64_Path -RemoteStagingDirectory $RemoteStagingDirectory -Test:($Test -and ($TestComputers.Count -ge 1)) -SkipSetup:$SkipSetup -Signed -Verbose:$VerbosePreference
#Copy to CiPolicies\Active and Use Refresh Tool and Set Policy as Deployed
$results = Invoke-ActivateAndRefreshWDACPolicy -Machines $Machines -CIPolicyFileName (Split-Path $SignedStagedPolicyPath -Leaf) -X86_RefreshToolName $X86_RefreshToolName -AMD64_RefreshToolName $AMD64_RefreshToolName -ARM64_RefreshToolName $ARM64_RefreshToolName -RemoteStagingDirectory $RemoteStagingDirectory -Signed -RestartRequired:$RestartRequired -ForceRestart:$ForceRestart -LocalMachineName $LocalDeviceName -ErrorAction Stop
} else {
#Copy to Machine(s)
Copy-StagedWDACPolicies -CIPolicyPath $UnsignedStagedPolicyPath -ComputerMap $CustomPSObjectComputerMap -X86_Path $X86_Path -AMD64_Path $AMD64_Path -ARM64_Path $ARM64_Path -RemoteStagingDirectory $RemoteStagingDirectory -Test:($Test -and ($TestComputers.Count -ge 1)) -SkipSetup:$SkipSetup -Verbose:$VerbosePreference
#Copy to CiPolicies\Active and Use Refresh Tool and Set Policy as Deployed
$results = Invoke-ActivateAndRefreshWDACPolicy -Machines $Machines -CIPolicyFileName (Split-Path $UnsignedStagedPolicyPath -Leaf) -X86_RefreshToolName $X86_RefreshToolName -AMD64_RefreshToolName $AMD64_RefreshToolName -ARM64_RefreshToolName $ARM64_RefreshToolName -RemoteStagingDirectory $RemoteStagingDirectory -LocalMachineName $LocalDeviceName -ErrorAction Stop
}
}
##======================================================================================
$DevicesToRestart = @()
if ($CustomPSObjectComputerMap -and $results) {
#Assign devices as deferred in the database which have failed to apply the new WDAC policy
#......If it is a first signed deployment, then restart devices and add relevant "first_signed_policy_deployment" entries (only for successes)
if ($VerbosePreference) {
if ($SignedToUnsigned) {
$results | Select-Object PSComputerName,ResultMessage,WinRMSuccess,RefreshToolAndPolicyPresent,CopyToCIPoliciesActiveSuccessfull,RefreshCompletedSuccessfully,UEFIRemoveSuccess | Format-List -Property *
} elseif ($PolicyInfo.IsSigned -eq $true) {
$results | Select-Object PSComputerName,ResultMessage,WinRMSuccess,RefreshToolAndPolicyPresent,CopyToEFIMount,RefreshCompletedSuccessfully,ReadyForARestart | Format-List -Property *
} else {
$results | Select-Object PSComputerName,ResultMessage,WinRMSuccess,RefreshToolAndPolicyPresent,CopyToCIPoliciesActiveSuccessfull,RefreshCompletedSuccessfully | Format-List -Property *
}
}
$RemoveEFIFailure = @()
$SuccessIterator = $false
$results | ForEach-Object {
if (-not $SuccessIterator) {
if ($PolicyInfo.IsSigned -eq $true) {
# The Add-FirstSignedPolicyDeployment function already checks whether the flag is set, this is just a fallback to
# cover supplemental policies which don't utilize those types of DB entries -- since those are only used to check
# whether a device needs to restart or not
if ((($_.ReadyForARestart -eq $true) -or ($_.RefreshCompletedSuccessfully -eq $true)) -and ($_.CopyToEFIMount -eq $true)) {
try {
if (-not (Get-DeployedSignedPolicyStatus -PolicyGUID $PolicyGUID -Connection $Connection -ErrorAction Stop)) {
if (-not (Set-ToggledDeployedSignedStatus -PolicyGUID $PolicyGUID -Connection $Connection -ErrorAction Stop)) {
throw "Unable to set DeployedSigned flag for policy $PolicyGUID"
}
}
} catch {
Write-Warning "Unable to set DeployedSigned flag for this signed policy."
}
}
}
$SuccessIterator = $true
}
if ($SignedToUnsigned) {
if ( (-not ($SuccessfulMachines -contains $_.PSComputerName)) -and (($_.PSComputerName -ne $LocalDeviceName) -or ( ($_.PSComputerName -eq $LocalDeviceName) -and (-not $ClearUEFIBootLocalDevice)))) {
#Defer
Set-MachineDeferred -PolicyGUID $PolicyGUID -DeviceName $_.PSComputerName -Comment "Device did not deploy initial signed policy successfully before subsequent unsigned policy." -Connection $Connection -ErrorAction Stop
} elseif ( (($_.UEFIRemoveSuccess -eq $false) -or (-not $_.UEFIRemoveSuccess)) -and ($_.CopyToCIPoliciesActiveSuccessfull -eq $true)) {
#Don't defer, but add to a list of devices and send warning console using the list
$RemoveEFIFailure += $_.PSComputerName
} elseif ( ($_.WinRMSuccess -eq $false) -or ($_.RefreshCompletedSuccessfully -eq $false) -or ($_.CopyToCIPoliciesActiveSuccessfull -eq $false)) {
#Defer
Set-MachineDeferred -PolicyGUID $PolicyGUID -DeviceName $_.PSComputerName -Comment $_.ResultMessage -Connection $Connection -ErrorAction Stop