-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShadowDeployv1.0.ps1
More file actions
1718 lines (1463 loc) · 65.6 KB
/
Copy pathShadowDeployv1.0.ps1
File metadata and controls
1718 lines (1463 loc) · 65.6 KB
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 5.1
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
Add-Type -AssemblyName Microsoft.VisualBasic
$PolicyPrefix = "MDE"
$script:LastResults = @()
function New-MDEPolicyResult {
param([string]$Name,[string]$Status,[string]$Details)
[pscustomobject]@{ Name=$Name; Status=$Status; Details=$Details; Time=Get-Date }
}
function Get-MDEPolicyName {
param([string]$Name)
"$PolicyPrefix - $Name"
}
function Assert-Mg {
if (-not (Get-MgContext)) {
throw "Not connected to Microsoft Graph. Click Initialize Graph first."
}
}
function Get-MDELogFolder {
$path = Join-Path $PSScriptRoot "Logs"
if (-not (Test-Path -LiteralPath $path)) {
New-Item -ItemType Directory -Path $path -Force | Out-Null
}
return $path
}
function Get-MDEReportFolder {
$path = Join-Path $PSScriptRoot "Reports"
if (-not (Test-Path -LiteralPath $path)) {
New-Item -ItemType Directory -Path $path -Force | Out-Null
}
return $path
}
function Get-MDEBackupFolderRoot {
$path = Join-Path $PSScriptRoot "Backups"
if (-not (Test-Path -LiteralPath $path)) {
New-Item -ItemType Directory -Path $path -Force | Out-Null
}
return $path
}
function Write-MDELogFile {
param([string]$Message)
try {
$logPath = Join-Path (Get-MDELogFolder) "deployment.log"
Add-Content -LiteralPath $logPath -Value "[$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] $Message"
}
catch { }
}
function Get-MDEJsonBody {
param([string]$Path)
if (-not (Test-Path -LiteralPath $Path)) {
throw "JSON file not found: $Path"
}
$raw = Get-Content -LiteralPath $Path -Raw
if ([string]::IsNullOrWhiteSpace($raw)) {
throw "JSON file is empty: $Path"
}
$raw | ConvertFrom-Json
}
function Test-MDEJsonPolicyFile {
param([string]$JsonPath)
$name = Split-Path $JsonPath -Leaf
try {
$json = Get-MDEJsonBody -Path $JsonPath
if (-not ($json.PSObject.Properties.Name -contains "settings")) {
return New-MDEPolicyResult $name "Invalid" "Missing settings array"
}
if (-not $json.settings -or $json.settings.Count -lt 1) {
return New-MDEPolicyResult $name "Invalid" "Settings array is empty"
}
return New-MDEPolicyResult $name "Valid" "JSON passed basic validation"
}
catch {
return New-MDEPolicyResult $name "Invalid" $_.Exception.Message
}
}
function Find-MDEConfigPolicyByName {
param([string]$PolicyName)
Assert-Mg
$escaped = $PolicyName.Replace("'","''")
$uri = "https://graph.microsoft.com/beta/deviceManagement/configurationPolicies?`$filter=name eq '$escaped'"
$result = Invoke-MgGraphRequest -Method GET -Uri $uri -OutputType PSObject
if ($result.value -and $result.value.Count -gt 0) {
return $result.value[0]
}
return $null
}
function Test-MDEConfigPolicyExists {
param([string]$Name)
$displayName = Get-MDEPolicyName $Name
try {
$policy = Find-MDEConfigPolicyByName -PolicyName $displayName
return [bool]$policy
}
catch {
return $false
}
}
function Get-MDEConfigPolicyId {
param([string]$PolicyDisplayName)
$policy = Find-MDEConfigPolicyByName -PolicyName $PolicyDisplayName
if (-not $policy) {
throw "Policy not found: $PolicyDisplayName"
}
return $policy.id
}
function Get-MDEGroupIdByName {
param([string]$GroupName)
Assert-Mg
$escaped = $GroupName.Replace("'","''")
$uri = "https://graph.microsoft.com/v1.0/groups?`$filter=displayName eq '$escaped'"
$result = Invoke-MgGraphRequest -Method GET -Uri $uri -OutputType PSObject
if (-not $result.value -or $result.value.Count -eq 0) {
throw "Group not found: $GroupName"
}
if ($result.value.Count -gt 1) {
throw "Multiple groups found with name: $GroupName"
}
return $result.value[0].id
}
function Add-MDEConfigPolicyAssignment {
param(
[string]$PolicyDisplayName,
[string]$GroupName
)
Assert-Mg
try {
$policyId = Get-MDEConfigPolicyId -PolicyDisplayName $PolicyDisplayName
$groupId = Get-MDEGroupIdByName -GroupName $GroupName
$body = @{
assignments = @(
@{
target = @{
"@odata.type" = "#microsoft.graph.groupAssignmentTarget"
groupId = $groupId
}
}
)
} | ConvertTo-Json -Depth 20 -Compress
$uri = "https://graph.microsoft.com/beta/deviceManagement/configurationPolicies/$policyId/assign"
Invoke-MgGraphRequest `
-Method POST `
-Uri $uri `
-Body $body `
-ContentType "application/json" | Out-Null
return New-MDEPolicyResult $PolicyDisplayName "Assigned" "Assigned to group: $GroupName"
}
catch {
return New-MDEPolicyResult $PolicyDisplayName "Failed" $_.Exception.Message
}
}
function New-MDEConfigPolicyFromJson {
param(
[string]$Name,
[string]$JsonPath,
[switch]$WhatIf
)
Assert-Mg
$displayName = Get-MDEPolicyName $Name
try {
if (Test-MDEConfigPolicyExists -Name $Name) {
return New-MDEPolicyResult $displayName "Skipped" "Policy already exists"
}
$body = Get-MDEJsonBody -Path $JsonPath
$body.name = $displayName
$json = $body | ConvertTo-Json -Depth 100 -Compress
if ($WhatIf) {
return New-MDEPolicyResult $displayName "WhatIf" "Validated JSON only: $JsonPath"
}
Invoke-MgGraphRequest `
-Method POST `
-Uri "https://graph.microsoft.com/beta/deviceManagement/configurationPolicies" `
-Body $json `
-ContentType "application/json" | Out-Null
return New-MDEPolicyResult $displayName "Success" "Created configuration policy"
}
catch {
return New-MDEPolicyResult $displayName "Failed" $_.Exception.Message
}
}
function Export-MDEConfigPolicyJson {
param(
[string]$PolicyName,
[string]$OutputPath
)
Assert-Mg
try {
$policy = Find-MDEConfigPolicyByName -PolicyName $PolicyName
if (-not $policy) {
throw "Policy not found: $PolicyName"
}
$settingsUri = "https://graph.microsoft.com/beta/deviceManagement/configurationPolicies/$($policy.id)/settings"
$settings = Invoke-MgGraphRequest -Method GET -Uri $settingsUri -OutputType PSObject
if (-not $settings.value -or $settings.value.Count -eq 0) {
throw "Policy found, but no settings were returned: $PolicyName"
}
$body = [ordered]@{
name = $policy.name
description = $policy.description
platforms = $policy.platforms
technologies = $policy.technologies
roleScopeTagIds = @($policy.roleScopeTagIds)
settings = @($settings.value)
}
if ($policy.PSObject.Properties.Name -contains "templateReference" -and $policy.templateReference) {
$body.templateReference = $policy.templateReference
}
$folder = Split-Path $OutputPath -Parent
if ($folder -and -not (Test-Path -LiteralPath $folder)) {
New-Item -ItemType Directory -Path $folder -Force | Out-Null
}
$body | ConvertTo-Json -Depth 100 | Set-Content -LiteralPath $OutputPath -Encoding UTF8
return New-MDEPolicyResult $PolicyName "Success" "Exported to $OutputPath"
}
catch {
return New-MDEPolicyResult $PolicyName "Failed" $_.Exception.Message
}
}
function Get-MDEFriendlyPolicyNameFromFile {
param([string]$FileName)
switch ($FileName.ToLower()) {
"antivirus.json" { return "Antivirus" }
"firewall.json" { return "Firewall" }
"asr.json" { return "ASR" }
"edr.json" { return "EDR" }
"windows-security-experience.json" { return "Windows Security Experience" }
"avc-update-controls.json" { return "AVC Update Controls" }
default {
$base = [System.IO.Path]::GetFileNameWithoutExtension($FileName)
return (($base -replace '-', ' ') -replace '_', ' ')
}
}
}
function Get-MDEJsonPolicyCatalog {
$folder = Join-Path $PSScriptRoot "Config\SettingsCatalog"
if (-not (Test-Path -LiteralPath $folder)) {
New-Item -ItemType Directory -Path $folder -Force | Out-Null
}
Get-ChildItem -Path $folder -Filter "*.json" | Sort-Object Name | ForEach-Object {
[pscustomobject]@{
Name = Get-MDEFriendlyPolicyNameFromFile -FileName $_.Name
Category = "Settings Catalog"
JsonPath = $_.FullName
}
}
}
function Get-MDESettingValue {
param($Setting)
$instance = $Setting.settingInstance
if (-not $instance) {
return ""
}
if ($instance.PSObject.Properties.Name -contains "choiceSettingValue") {
return [string]$instance.choiceSettingValue.value
}
if ($instance.PSObject.Properties.Name -contains "simpleSettingValue") {
return [string]$instance.simpleSettingValue.value
}
if ($instance.PSObject.Properties.Name -contains "simpleSettingCollectionValue") {
return ($instance.simpleSettingCollectionValue | ConvertTo-Json -Depth 20 -Compress)
}
return ""
}
function Get-MDESettingsInventory {
$inventory = @()
foreach ($policy in Get-MDEJsonPolicyCatalog) {
if (-not (Test-Path -LiteralPath $policy.JsonPath)) {
continue
}
try {
$json = Get-MDEJsonBody -Path $policy.JsonPath
foreach ($setting in $json.settings) {
$instance = $setting.settingInstance
if (-not $instance) {
continue
}
$inventory += [pscustomobject]@{
Policy = $policy.Name
SettingId = $instance.settingDefinitionId
Type = $instance.'@odata.type'
Value = Get-MDESettingValue -Setting $setting
}
}
}
catch {
$inventory += [pscustomobject]@{
Policy = $policy.Name
SettingId = "Inventory Error"
Type = "Error"
Value = $_.Exception.Message
}
}
}
return $inventory
}
function Get-MDEZeroTrustChecks {
return @(
@{
Policy = "Firewall"
Label = "Firewall policy exists in repo"
Type = "FileExists"
JsonPath = "Config\SettingsCatalog\firewall.json"
},
@{
Policy = "Firewall"
Label = "Firewall contains settings"
Type = "HasSettings"
JsonPath = "Config\SettingsCatalog\firewall.json"
},
@{
Policy = "Firewall"
Label = "Firewall has default inbound block settings"
Type = "ContainsAnySetting"
JsonPath = "Config\SettingsCatalog\firewall.json"
Match = @("defaultinboundaction", "default_inbound", "inbound")
},
@{
Policy = "Firewall"
Label = "Firewall has logging visibility settings"
Type = "ContainsAnySetting"
JsonPath = "Config\SettingsCatalog\firewall.json"
Match = @("log", "logging", "dropped")
},
@{
Policy = "ASR"
Label = "ASR policy exists in repo"
Type = "FileExists"
JsonPath = "Config\SettingsCatalog\asr.json"
},
@{
Policy = "ASR"
Label = "ASR contains configured rules"
Type = "HasSettings"
JsonPath = "Config\SettingsCatalog\asr.json"
},
@{
Policy = "ASR"
Label = "ASR contains attack surface reduction configuration"
Type = "ContainsAnySetting"
JsonPath = "Config\SettingsCatalog\asr.json"
Match = @("attacksurfacereduction", "asr", "defender")
},
@{
Policy = "EDR"
Label = "EDR policy exists in repo"
Type = "FileExists"
JsonPath = "Config\SettingsCatalog\edr.json"
},
@{
Policy = "EDR"
Label = "EDR excludes connector onboarding secret"
Type = "DoesNotContainSetting"
JsonPath = "Config\SettingsCatalog\edr.json"
Match = @("device_vendor_msft_windowsadvancedthreatprotection_onboarding_fromconnector")
},
@{
Policy = "Windows Security Experience"
Label = "Windows Security Experience policy exists in repo"
Type = "FileExists"
JsonPath = "Config\SettingsCatalog\windows-security-experience.json"
},
@{
Policy = "AVC Update Controls"
Label = "AVC Update Controls policy exists in repo"
Type = "FileExists"
JsonPath = "Config\SettingsCatalog\avc-update-controls.json"
}
)
}
function Test-MDEZeroTrustAlignment {
$results = @()
foreach ($check in Get-MDEZeroTrustChecks) {
$fullPath = Join-Path $PSScriptRoot $check.JsonPath
$passed = $false
$found = ""
$details = ""
try {
switch ($check.Type) {
"FileExists" {
$passed = Test-Path -LiteralPath $fullPath
$found = if ($passed) { "File found" } else { "Missing file" }
$details = $fullPath
}
"HasSettings" {
if (Test-Path -LiteralPath $fullPath) {
$json = Get-MDEJsonBody -Path $fullPath
$passed = [bool]($json.settings -and $json.settings.Count -gt 0)
$found = "$($json.settings.Count) settings"
}
else {
$found = "Missing file"
}
$details = $fullPath
}
"ContainsAnySetting" {
if (Test-Path -LiteralPath $fullPath) {
$raw = (Get-Content -LiteralPath $fullPath -Raw).ToLower()
foreach ($term in $check.Match) {
if ($raw -like "*$($term.ToLower())*") {
$passed = $true
$found = "Matched: $term"
break
}
}
if (-not $passed) {
$found = "No matching setting found"
}
}
else {
$found = "Missing file"
}
$details = "Expected one of: $($check.Match -join ', ')"
}
"DoesNotContainSetting" {
if (Test-Path -LiteralPath $fullPath) {
$raw = (Get-Content -LiteralPath $fullPath -Raw).ToLower()
$passed = $true
foreach ($term in $check.Match) {
if ($raw -like "*$($term.ToLower())*") {
$passed = $false
$found = "Found blocked setting: $term"
break
}
}
if ($passed) {
$found = "Blocked setting not found"
}
}
else {
$found = "Missing file"
}
$details = "Must not contain: $($check.Match -join ', ')"
}
}
}
catch {
$passed = $false
$found = "Error"
$details = $_.Exception.Message
}
$results += [pscustomobject]@{
Policy = $check.Policy
Control = $check.Label
Result = if ($passed) { "Pass" } else { "Review" }
Found = $found
Details = $details
}
}
return $results
}
function ConvertTo-HtmlEncoded {
param([string]$Text)
if ($null -eq $Text) {
return ""
}
return [System.Net.WebUtility]::HtmlEncode($Text)
}
function New-MDEDeploymentReport {
param([array]$Results)
$reportFolder = Get-MDEReportFolder
$reportPath = Join-Path $reportFolder "deployment-report.html"
$generated = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$inventory = Get-MDESettingsInventory
$ztChecks = Test-MDEZeroTrustAlignment
$totalResults = @($Results).Count
$successCount = @($Results | Where-Object { $_.Status -in @("Success","Assigned","Valid") }).Count
$reviewCount = @($Results | Where-Object { $_.Status -in @("WhatIf","Skipped","Missing") }).Count
$failedCount = @($Results | Where-Object { $_.Status -in @("Failed","Invalid") }).Count
$assignedCount = @($Results | Where-Object { $_.Status -eq "Assigned" }).Count
$inventoryCount = @($inventory).Count
$ztTotal = @($ztChecks).Count
$ztPass = @($ztChecks | Where-Object { $_.Result -eq "Pass" }).Count
$ztReview = @($ztChecks | Where-Object { $_.Result -ne "Pass" }).Count
if ($ztTotal -gt 0) {
$ztScore = [math]::Round(($ztPass / $ztTotal) * 100)
}
else {
$ztScore = 0
}
if ($failedCount -gt 0) {
$overallClass = "bad"
$overallLabel = "Action Required"
}
elseif ($reviewCount -gt 0 -or $ztReview -gt 0) {
$overallClass = "warn"
$overallLabel = "Review"
}
else {
$overallClass = "good"
$overallLabel = "Ready"
}
function Get-MDEReportPillClass {
param([string]$Status)
switch ($Status) {
"Success" { return "good" }
"Assigned" { return "good" }
"Valid" { return "good" }
"Pass" { return "good" }
"WhatIf" { return "warn" }
"Skipped" { return "warn" }
"Missing" { return "warn" }
"Review" { return "warn" }
"Failed" { return "bad" }
"Invalid" { return "bad" }
default { return "neutral" }
}
}
$bladeData = @{}
$bladeIndex = 0
$deploymentRows = foreach ($r in $Results) {
$bladeIndex++
$bladeKey = "result_$bladeIndex"
$pillClass = Get-MDEReportPillClass -Status $r.Status
$safeTime = ConvertTo-HtmlEncoded $r.Time
$safeName = ConvertTo-HtmlEncoded $r.Name
$safeStatus = ConvertTo-HtmlEncoded $r.Status
$safeDetails = ConvertTo-HtmlEncoded $r.Details
$bladeHtml = @"
<div class='blade-kv'><span>Time</span><strong>$safeTime</strong></div>
<div class='blade-kv'><span>Name</span><strong>$safeName</strong></div>
<div class='blade-kv'><span>Status</span><strong>$safeStatus</strong></div>
<div class='blade-block'><span>Details</span><pre>$safeDetails</pre></div>
"@
$bladeData[$bladeKey] = @{ title = "Deployment Result"; html = $bladeHtml }
"<tr><td>$safeTime</td><td>$safeName</td><td><span class='pill $pillClass'>$safeStatus</span></td><td>$safeDetails</td><td><button class='blade-btn' data-blade='$bladeKey'>Details</button></td></tr>"
}
$ztRows = foreach ($z in $ztChecks) {
$bladeIndex++
$bladeKey = "zt_$bladeIndex"
$pillClass = Get-MDEReportPillClass -Status $z.Result
$checked = if ($z.Result -eq "Pass") { "checked" } else { "" }
$safePolicy = ConvertTo-HtmlEncoded $z.Policy
$safeControl = ConvertTo-HtmlEncoded $z.Control
$safeResult = ConvertTo-HtmlEncoded $z.Result
$safeFound = ConvertTo-HtmlEncoded $z.Found
$safeDetails = ConvertTo-HtmlEncoded $z.Details
$bladeHtml = @"
<div class='blade-kv'><span>Policy</span><strong>$safePolicy</strong></div>
<div class='blade-kv'><span>Control</span><strong>$safeControl</strong></div>
<div class='blade-kv'><span>Result</span><strong>$safeResult</strong></div>
<div class='blade-kv'><span>Found</span><strong>$safeFound</strong></div>
<div class='blade-block'><span>Details</span><pre>$safeDetails</pre></div>
"@
$bladeData[$bladeKey] = @{ title = "Zero Trust Check"; html = $bladeHtml }
"<tr><td><input type='checkbox' disabled $checked></td><td>$safePolicy</td><td>$safeControl</td><td><span class='pill $pillClass'>$safeResult</span></td><td>$safeFound</td><td><button class='blade-btn' data-blade='$bladeKey'>Review</button></td></tr>"
}
$inventoryRows = foreach ($i in $inventory) {
$safePolicy = ConvertTo-HtmlEncoded $i.Policy
$safeSettingId = ConvertTo-HtmlEncoded $i.SettingId
$safeType = ConvertTo-HtmlEncoded $i.Type
$safeValue = ConvertTo-HtmlEncoded $i.Value
"<tr><td>$safePolicy</td><td><code>$safeSettingId</code></td><td>$safeType</td><td><code>$safeValue</code></td></tr>"
}
$policyCards = foreach ($group in ($inventory | Group-Object Policy | Sort-Object Name)) {
$bladeIndex++
$bladeKey = "policy_$bladeIndex"
$safePolicyName = ConvertTo-HtmlEncoded $group.Name
$settingCount = @($group.Group).Count
$settingsRows = foreach ($setting in $group.Group) {
$sid = ConvertTo-HtmlEncoded $setting.SettingId
$stype = ConvertTo-HtmlEncoded $setting.Type
$svalue = ConvertTo-HtmlEncoded $setting.Value
"<tr><td><code>$sid</code></td><td>$stype</td><td><code>$svalue</code></td></tr>"
}
$bladeHtml = @"
<div class='blade-kv'><span>Policy</span><strong>$safePolicyName</strong></div>
<div class='blade-kv'><span>Total Settings</span><strong>$settingCount</strong></div>
<table class='blade-table'><thead><tr><th>Setting ID</th><th>Type</th><th>Value</th></tr></thead><tbody>$($settingsRows -join "`n")</tbody></table>
"@
$bladeData[$bladeKey] = @{ title = "Policy Settings Inventory"; html = $bladeHtml }
"<div class='mini-card'><div><span>Policy</span><strong>$safePolicyName</strong></div><div class='mini-value'>$settingCount settings</div><button class='blade-btn' data-blade='$bladeKey'>View Settings</button></div>"
}
$failedRows = foreach ($r in ($Results | Where-Object { $_.Status -in @("Failed","Invalid") })) {
"<tr><td>$(ConvertTo-HtmlEncoded $r.Time)</td><td>$(ConvertTo-HtmlEncoded $r.Name)</td><td><span class='pill bad'>$(ConvertTo-HtmlEncoded $r.Status)</span></td><td>$(ConvertTo-HtmlEncoded $r.Details)</td></tr>"
}
if (-not $failedRows -or @($failedRows).Count -eq 0) {
$failedRows = @("<tr><td colspan='4'>No failed deployment results were recorded in this report.</td></tr>")
}
$opsCards = @(
"<div class='note'><strong>Scope</strong><br>Defender for Endpoint Settings Catalog deployment module.</div>",
"<div class='note'><strong>Preserved Logic</strong><br>Graph authentication, deployment execution, JSON validation, assignment, export, backup, and report actions remain tied to the original tool functions.</div>",
"<div class='note'><strong>Review Guidance</strong><br>Investigate failed or invalid results before broad assignment. WhatIf and skipped results should be reviewed before production rollout.</div>",
"<div class='note'><strong>Shadow Suite Standard</strong><br>Dark dashboard presentation aligned with Shadow Trace Ops and Shadow Verify reporting style.</div>"
)
$bladeJson = ($bladeData | ConvertTo-Json -Depth 20 -Compress).Replace('</script>','<\/script>')
$html = @"
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Shadow Deploy | Defender for Endpoint</title>
<style>
:root {
--bg:#090a0f;
--surface:#12141d;
--surface2:#191c27;
--border:#3a4052;
--text:#f5f7fa;
--muted:#a8b0be;
--accent:#7c3aed;
--accent2:#2563eb;
--good:#15803d;
--warn:#b45309;
--bad:#b91c1c;
--neutral:#475569;
}
* { box-sizing:border-box; }
html { scroll-behavior:smooth; }
body {
margin:0;
background:radial-gradient(circle at top left, rgba(124,58,237,.25), transparent 34%), radial-gradient(circle at bottom right, rgba(37,99,235,.16), transparent 30%), var(--bg);
color:var(--text);
font-family:"Segoe UI", Arial, sans-serif;
}
.layout { display:grid; grid-template-columns:280px 1fr; min-height:100vh; }
aside {
border-right:1px solid var(--border);
background:rgba(18,20,29,.96);
padding:26px 20px;
position:sticky;
top:0;
height:100vh;
}
.brand { color:var(--muted); font-size:12px; letter-spacing:.18em; font-weight:800; text-transform:uppercase; }
h1 { margin:8px 0 8px; font-size:30px; line-height:1.1; }
.subtitle { color:var(--muted); font-size:13px; line-height:1.5; }
.nav { margin-top:28px; display:grid; gap:10px; }
.nav a { color:var(--text); text-decoration:none; border:1px solid var(--border); background:var(--surface2); border-radius:14px; padding:11px 12px; font-size:13px; transition:.16s ease; }
.nav a:hover { border-color:rgba(124,58,237,.75); transform:translateX(2px); }
main { padding:30px; }
.hero {
border:1px solid var(--border);
border-radius:24px;
background:linear-gradient(135deg, rgba(124,58,237,.26), rgba(37,99,235,.10)), var(--surface);
padding:26px;
box-shadow:0 22px 60px rgba(0,0,0,.32);
}
.hero-top { display:flex; align-items:flex-start; justify-content:space-between; gap:20px; }
.badge { display:inline-flex; align-items:center; border:1px solid var(--border); border-radius:999px; padding:8px 12px; color:var(--muted); background:rgba(9,10,15,.48); font-size:12px; font-weight:800; }
.state.good { color:#bbf7d0; border-color:rgba(21,128,61,.65); }
.state.warn { color:#fed7aa; border-color:rgba(180,83,9,.65); }
.state.bad { color:#fecaca; border-color:rgba(185,28,28,.65); }
.cards { display:grid; grid-template-columns:repeat(6,minmax(0,1fr)); gap:14px; margin:22px 0 0; }
.card { border:1px solid var(--border); border-radius:20px; background:rgba(18,20,29,.86); padding:18px; }
.card .label { color:var(--muted); font-size:11px; text-transform:uppercase; letter-spacing:.08em; }
.card .value { font-size:28px; margin-top:8px; font-weight:800; }
section { margin-top:22px; border:1px solid var(--border); border-radius:22px; background:rgba(18,20,29,.88); padding:22px; box-shadow:0 14px 40px rgba(0,0,0,.18); }
.section-head { display:flex; align-items:center; justify-content:space-between; gap:14px; margin-bottom:14px; }
h2 { margin:0; font-size:18px; }
table { width:100%; border-collapse:collapse; overflow:hidden; border-radius:14px; }
th,td { text-align:left; padding:12px 14px; border-bottom:1px solid rgba(58,64,82,.7); vertical-align:top; font-size:13px; }
th { color:var(--muted); background:rgba(25,28,39,.92); font-size:12px; letter-spacing:.07em; text-transform:uppercase; }
tr:hover td { background:rgba(124,58,237,.08); }
code { color:#bfdbfe; word-break:break-all; }
.pill { display:inline-flex; min-width:78px; justify-content:center; border-radius:999px; padding:5px 9px; font-weight:800; font-size:12px; border:1px solid transparent; }
.pill.good { background:rgba(21,128,61,.22); color:#bbf7d0; border-color:rgba(21,128,61,.52); }
.pill.warn { background:rgba(180,83,9,.22); color:#fed7aa; border-color:rgba(180,83,9,.52); }
.pill.bad { background:rgba(185,28,28,.22); color:#fecaca; border-color:rgba(185,28,28,.52); }
.pill.neutral { background:rgba(71,85,105,.22); color:#e2e8f0; border-color:rgba(71,85,105,.52); }
.note-grid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:14px; }
.note { border:1px solid var(--border); background:var(--surface2); border-radius:16px; padding:15px; color:var(--muted); line-height:1.5; }
.policy-grid { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:14px; }
.mini-card { border:1px solid var(--border); background:var(--surface2); border-radius:16px; padding:16px; display:grid; gap:10px; }
.mini-card span { color:var(--muted); font-size:11px; text-transform:uppercase; letter-spacing:.08em; }
.mini-card strong { display:block; margin-top:4px; }
.mini-value { color:#bfdbfe; font-weight:700; }
.blade-btn { cursor:pointer; border:1px solid rgba(124,58,237,.72); background:rgba(124,58,237,.18); color:#ddd6fe; border-radius:999px; padding:6px 10px; font-weight:800; font-size:12px; }
.blade-btn:hover { background:rgba(124,58,237,.32); }
.drawer-overlay { position:fixed; inset:0; background:rgba(0,0,0,.58); opacity:0; pointer-events:none; transition:.18s ease; z-index:50; }
.drawer-overlay.open { opacity:1; pointer-events:auto; }
.drawer { position:fixed; top:0; right:-560px; width:min(560px, 94vw); height:100vh; background:#0f111a; border-left:1px solid var(--border); box-shadow:-20px 0 60px rgba(0,0,0,.45); transition:.22s ease; z-index:60; padding:22px; overflow:auto; }
.drawer.open { right:0; }
.drawer-head { display:flex; align-items:flex-start; justify-content:space-between; gap:14px; margin-bottom:18px; }
.drawer h2 { font-size:22px; }
.close-btn { border:1px solid var(--border); background:var(--surface2); color:var(--text); border-radius:12px; padding:8px 10px; cursor:pointer; }
.blade-kv { border:1px solid var(--border); border-radius:14px; background:var(--surface2); padding:12px; margin-bottom:10px; }
.blade-kv span, .blade-block span { display:block; color:var(--muted); font-size:11px; text-transform:uppercase; letter-spacing:.08em; margin-bottom:6px; }
.blade-kv strong { color:var(--text); }
.blade-block { border:1px solid var(--border); border-radius:14px; background:var(--surface2); padding:12px; margin-top:10px; }
pre { white-space:pre-wrap; word-break:break-word; color:#bfdbfe; margin:0; font-family:Consolas, monospace; }
.blade-table { margin-top:12px; }
.footer { color:var(--muted); margin-top:22px; font-size:12px; }
@media(max-width:1180px){ .cards{grid-template-columns:repeat(3,1fr);} .policy-grid{grid-template-columns:repeat(2,1fr);} }
@media(max-width:960px){ .layout{grid-template-columns:1fr;} aside{position:relative;height:auto;} .cards{grid-template-columns:repeat(2,1fr);} .note-grid{grid-template-columns:1fr;} .policy-grid{grid-template-columns:1fr;} }
</style>
</head>
<body>
<div class="layout">
<aside>
<div class="brand">Shadow Suite</div>
<h1>Shadow Deploy</h1>
<div class="subtitle">Defender for Endpoint deployment dashboard. Modern report presentation while preserving the original deployment engine.</div>
<div class="nav">
<a href="#summary">Executive Summary</a>
<a href="#results">Deployment Results</a>
<a href="#zt">Zero Trust Alignment</a>
<a href="#policies">Policy Blades</a>
<a href="#inventory">Settings Inventory</a>
<a href="#failures">Failures / Review</a>
<a href="#ops">Operational Notes</a>
</div>
</aside>
<main>
<div class="hero" id="summary">
<div class="hero-top">
<div>
<div class="brand">Defender for Endpoint Deployment Module</div>
<h1>Deployment Execution Report</h1>
<div class="subtitle">Generated: $generated</div>
</div>
<span class="badge state $overallClass">$overallLabel</span>
</div>
<div class="cards">
<div class="card"><div class="label">Total Results</div><div class="value">$totalResults</div></div>
<div class="card"><div class="label">Successful</div><div class="value">$successCount</div></div>
<div class="card"><div class="label">Review</div><div class="value">$reviewCount</div></div>
<div class="card"><div class="label">Failed</div><div class="value">$failedCount</div></div>
<div class="card"><div class="label">Assigned</div><div class="value">$assignedCount</div></div>
<div class="card"><div class="label">Zero Trust Score</div><div class="value">$ztScore%</div></div>
</div>
</div>
<section id="results">
<div class="section-head"><h2>Deployment Results</h2><span class="badge">Execution History</span></div>
<table>
<thead><tr><th>Time</th><th>Name</th><th>Status</th><th>Details</th><th>Blade</th></tr></thead>
<tbody>
$($deploymentRows -join "`n")
</tbody>
</table>
</section>
<section id="zt">
<div class="section-head"><h2>Zero Trust Alignment Checklist</h2><span class="badge">$ztPass / $ztTotal passed</span></div>
<table>
<thead><tr><th>Aligned</th><th>Policy</th><th>Control</th><th>Result</th><th>Found</th><th>Blade</th></tr></thead>
<tbody>
$($ztRows -join "`n")
</tbody>
</table>
</section>
<section id="policies">
<div class="section-head"><h2>Policy Settings Blades</h2><span class="badge">$inventoryCount settings inventoried</span></div>
<div class="policy-grid">
$($policyCards -join "`n")
</div>
</section>
<section id="inventory">
<div class="section-head"><h2>Settings Inventory</h2><span class="badge">Raw Setting Detail</span></div>
<table>
<thead><tr><th>Policy</th><th>Setting ID</th><th>Type</th><th>Value</th></tr></thead>
<tbody>
$($inventoryRows -join "`n")
</tbody>
</table>
</section>
<section id="failures">
<div class="section-head"><h2>Failures / Manual Review</h2><span class="badge state $overallClass">$overallLabel</span></div>
<table>
<thead><tr><th>Time</th><th>Name</th><th>Status</th><th>Details</th></tr></thead>
<tbody>
$($failedRows -join "`n")
</tbody>
</table>
</section>
<section id="ops">
<div class="section-head"><h2>Operational Notes</h2><span class="badge">Guidance</span></div>
<div class="note-grid">
$($opsCards -join "`n")
</div>
</section>
<div class="footer">Shadow Deploy | Defender for Endpoint Module | Generated locally by the deployment toolkit.</div>
</main>
</div>
<div class="drawer-overlay" id="drawerOverlay"></div>
<div class="drawer" id="drawer">
<div class="drawer-head">
<div>
<div class="brand">Shadow Deploy Blade</div>
<h2 id="drawerTitle">Details</h2>
</div>
<button class="close-btn" id="drawerClose">Close</button>
</div>
<div id="drawerBody"></div>
</div>
<script>
const bladeData = $bladeJson;
const drawer = document.getElementById('drawer');
const overlay = document.getElementById('drawerOverlay');
const drawerTitle = document.getElementById('drawerTitle');
const drawerBody = document.getElementById('drawerBody');
function openBlade(key) {
const data = bladeData[key];
if (!data) { return; }
drawerTitle.textContent = data.title || 'Details';
drawerBody.innerHTML = data.html || '';
drawer.classList.add('open');
overlay.classList.add('open');
}
function closeBlade() {
drawer.classList.remove('open');
overlay.classList.remove('open');
}
document.querySelectorAll('.blade-btn').forEach(function(btn) {
btn.addEventListener('click', function() { openBlade(btn.getAttribute('data-blade')); });
});
document.getElementById('drawerClose').addEventListener('click', closeBlade);
overlay.addEventListener('click', closeBlade);
document.addEventListener('keydown', function(event) { if (event.key === 'Escape') { closeBlade(); } });
</script>
</body>
</html>
"@
$html | Set-Content -LiteralPath $reportPath -Encoding UTF8
return $reportPath
}
function Backup-MDEAllPolicies {
Assert-Mg
try {
$timestamp = Get-Date -Format "yyyy-MM-dd_HH-mm"
$backupRoot = Get-MDEBackupFolderRoot
$backupFolder = Join-Path $backupRoot $timestamp
if (-not (Test-Path -LiteralPath $backupFolder)) {
New-Item -ItemType Directory -Path $backupFolder -Force | Out-Null
}
$summaryPath = Join-Path $backupFolder "backup-summary.txt"
Set-Content -LiteralPath $summaryPath -Value "MDE Backup Summary - $timestamp" -Encoding UTF8
Add-Content -LiteralPath $summaryPath -Value "Backup Folder: $backupFolder"
Add-Content -LiteralPath $summaryPath -Value ""
foreach ($policy in Get-MDEJsonPolicyCatalog) {
$safeName = $policy.Name.ToLower() -replace '\s+','-' -replace '[\\/:*?""<>|]',''
$outputPath = Join-Path $backupFolder "$safeName.json"
$candidateNames = @()
$candidateNames += Get-MDEPolicyName $policy.Name
$candidateNames += $policy.Name
try {
$json = Get-MDEJsonBody -Path $policy.JsonPath
if ($json.PSObject.Properties.Name -contains "name") {
if (-not [string]::IsNullOrWhiteSpace($json.name)) {
if ($json.name -ne "__POLICY_NAME__") {
$candidateNames += $json.name
}
}
}
}
catch { }
$candidateNames = $candidateNames |
Where-Object { -not [string]::IsNullOrWhiteSpace($_) } |
Select-Object -Unique
$backedUp = $false
$lastError = ""
foreach ($candidate in $candidateNames) {
try {
$found = Find-MDEConfigPolicyByName -PolicyName $candidate