-
Notifications
You must be signed in to change notification settings - Fork 43
/
Update-EidscaTests.ps1
413 lines (351 loc) · 14.6 KB
/
Update-EidscaTests.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
<#
.Synopsis
Generates Maester tests for the Entra ID Security Config Analyzer defined at https://github.com/Cloud-Architekt/AzureAD-Attack-Defense
.DESCRIPTION
* Downloads the latest version from https://raw.githubusercontent.com/Cloud-Architekt/AzureAD-Attack-Defense/AADSCAv4/config/EidscaConfig.json
* Generates Maester tests for each test defined in the JSON file
.EXAMPLE
./build/eidsca/Update-EidscaTests.ps1
#>
param (
# Folder where generated test file should be written to.
[string] $TestFilePath = "./tests/EIDSCA/Test-EIDSCA.Generated.Tests.ps1",
# Folder where docs should be generated
[string] $DocsPath = "./website/docs/tests/eidsca",
[string] $PowerShellFunctionsPath = "./powershell/public/eidsca",
# Control name to filter on
[string] $ControlName = "*",
# URL to the EIDSCA config file
[string] $AadSecConfigUrl = 'https://raw.githubusercontent.com/Cloud-Architekt/AzureAD-Attack-Defense/AADSCAv4/config/EidscaConfig.json'
)
Function GetRelativeUri($graphUri) {
$relativeUri = $graphUri -replace 'https://graph.microsoft.com/v1.0/', ''
$relativeUri = $relativeUri -replace 'https://graph.microsoft.com/beta/', ''
return $relativeUri
}
Function GetVersion($graphUri) {
$apiVersion = 'v1.0'
if ($graphUri.Contains('beta')) {
$apiVersion = 'beta'
}
return $apiVersion
}
Function GetRecommendedValue($RecommendedValue) {
$compareOperators = @(">=",">","<")
foreach ($compareOperator in $compareOperators) {
if ($RecommendedValue.StartsWith($compareOperator)) {
$RecommendedValue = $RecommendedValue.Replace($compareOperator, "")
}
}
return "'$RecommendedValue'"
}
Function GetCompareOperator($RecommendedValue) {
if ($RecommendedValue.StartsWith(">=")) {
$compareOperator = [PSCustomObject]@{
name = '>='
pester = 'BeGreaterOrEqual'
powershell = 'ge'
text = 'is greater than or equal to'
}
} elseif ($RecommendedValue.StartsWith(">")) {
$compareOperator = [PSCustomObject]@{
name = '>'
pester = 'BeGreaterThan'
powershell = 'gt'
text = 'is greater than'
}
} elseif ($RecommendedValue.StartsWith("<")) {
$compareOperator = [PSCustomObject]@{
name = '<'
pester = 'BeLessThan'
powershell = 'lt'
text = 'is less than'
}
} else {
$compareOperator = [PSCustomObject]@{
name = '='
pester = 'Be'
powershell = 'eq'
text = 'is'
}
}
return $compareOperator
}
Function GetPageTitle($uri) {
$isValidUri = ($uri -as [System.URI]).AbsoluteURI -ne $null
$title = ''
if ($isValidUri) {
$result = Invoke-WebRequest -Uri $uri
$output = $uri
if ($result.Content -match "<title>(?<title>.*)</title>") {
$title = $Matches['title']
}
}
return $title
}
Function GetPageMarkdownLink($uri) {
$output = $uri
$title = GetPageTitle($uri)
if ($title -ne '') {
$title = $title.Replace('|', '-')
$output = "[$title]($uri)"
}
return $output
}
Function GetGraphExplorerMarkDownLink($relativeUri, $apiVersion) {
$graphExplorerUrl = "https://developer.microsoft.com/en-us/graph/graph-explorer?request=$relativeUri&method=GET&version=$apiVersion&GraphUrl=https://graph.microsoft.com"
return "[Open in Graph Explorer]($graphExplorerUrl)"
}
Function GetMitreUrl($item) {
$item = $item.Trim()
$urlPart = ''
if ($item -ne '') {
if ($item.StartsWith('TA')) {
$urlPart = "tactics" #The json includes the heading, split it and get just the code
$item = $item.Split(" ")[0]
} elseif ($item.StartsWith('T')) {
$urlPart = "techniques"
} elseif ($item.StartsWith('M')) {
$urlPart = "mitigations"
}
}
if ($urlPart -eq '') {
return $null
}
$itemUrl = $item.Replace('.', '/') #Sub items
$url = "https://attack.mitre.org/$urlPart/$itemUrl"
return $url
}
Function GetMitreTitle($item) {
$url = GetMitreUrl($item)
if ($null -eq $url) {
return $item
}
$title = GetPageTitle($url)
$cleanHeading = $title.Split(",")[0] # Remove rest of headings
$title = "$item - $cleanHeading"
return $title
}
Function GetMitreItems($items) {
$output = ""
$isFirst = $true
foreach ($item in $items) {
if ($isFirst) {
$isFirst = $false
} else {
$output += [System.Environment]::NewLine
}
$title = GetMitreTitle($item)
$output += " $title"
}
return $output
}
Function GetMitreMarkdownLink($item) {
$url = GetMitreUrl($item)
if ($null -eq $url) {
return $item
}
$title = GetMitreTitle($item)
$output = "[$title]($url)"
return $output
}
Function GetMitreMarkdownLinks($items) {
$output = ""
$isFirst = $true
foreach ($item in $items) {
if ($isFirst) {
$isFirst = $false
} else {
$output += "<br/>"
}
$output += GetMitreMarkdownLink($item)
}
return $output
}
Function GetMitreDiagram($controlItem) {
if ($controlItem.MitreTactic.Length -le 0) {
return ''
}
$mermaid = @'
## MITRE ATT&CK
```mermaid
mindmap
root{{MITRE ATT&CK}}
(Tactic)
%Tactics%
(Mitigation)
%Mitigations%
(Technique)
%Techniques%
```
|Tactic|Technique|Mitigation|
|---|---|---|
|%TacticUrls%|%TechniqueUrls%|%MitigationUrls%|
'@
$tactics = GetMitreItems($controlItem.MitreTactic)
$techniques = GetMitreItems($controlItem.MitreTechnique)
$mitigations = GetMitreItems($controlItem.MitreMitigation)
$tacticsLinks = GetMitreMarkdownLinks($controlItem.MitreTactic)
$techniquesLinks = GetMitreMarkdownLinks($controlItem.MitreTechnique)
$mitigationsLinks = GetMitreMarkdownLinks($controlItem.MitreMitigation)
$mermaid = $mermaid -replace '%Tactics%', $tactics
$mermaid = $mermaid -replace '%Mitigations%', $mitigations
$mermaid = $mermaid -replace '%Techniques%', $techniques
$mermaid = $mermaid -replace '%TacticUrls%', $tacticsLinks
$mermaid = $mermaid -replace '%MitigationUrls%', $mitigationsLinks
$mermaid = $mermaid -replace '%TechniqueUrls%', $techniquesLinks
return $mermaid
}
Function GetMarkdownLink($uri, $title, [switch]$lookupTitle) {
if([string]::IsNullOrEmpty($uri)) { return '' }
if($lookupTitle) {
$pageTitle = GetPageTitle($uri)
if(![string]::IsNullOrEmpty($pageTitle)) {
$title = $pageTitle
}
}
return "- [$title]($uri)"
}
Function GetPortalDeepLinkMarkdown($portalDeepLink) {
$result = $portalDeepLink
if (![string]::IsNullOrEmpty($portalDeepLink)) {
$domain = ($uri -as [System.URI]).Host
$result = GetMarkdownLink -uri $portalDeepLink -title "[View in $domain]" # Set default markdown
if ($portalDeepLink -like "*entra.microsoft.com*" -or $portalDeepLink -like "*Microsoft_AAD_IAM*") {
$result = GetMarkdownLink -uri $portalDeepLink -title "View in Microsoft Entra admin center"
} elseif ($portalDeepLink -like "*admin.microsoft.com*") {
$result = GetMarkdownLink -uri $portalDeepLink -title "Open in Microsoft 365 admin center"
}
}
return $result
}
Function UpdateTemplate($template, $control, $controlItem, $docName, $isDoc) {
$relativeUri = GetRelativeUri($control.GraphUri)
$apiVersion = GetVersion($control.GraphUri)
$recommendedValue = GetRecommendedValue($controlItem.RecommendedValue)
$compareOperator = GetCompareOperator($controlItem.RecommendedValue)
$currentValue = $controlItem.CurrentValue
$psFunctionName = GetEidscaPsFunctionName -controlItem $controlItem
$portalDeepLinkMarkdown = GetPortalDeepLinkMarkdown -portalDeepLink $controlItem.PortalDeepLink
$graphDocsUrlMarkdown = GetMarkdownLink -uri $control.GraphDocsUrl -title "Graph Docs" -lookupTitle
$output = ''
if ($currentValue -eq '' -or $control.ControlName -eq '') {
Write-Warning 'Skipping'
} else {
$graphExplorerUrl = GetGraphExplorerMarkDownLink -relativeUri $relativeUri -apiVersion $apiVersion
if ($isDoc) {
# Only do this for docs
$graphDocsUrl = GetPageMarkdownLink($control.GraphDocsUrl)
$recommendation = GetPageMarkdownLink($controlItem.Recommendation)
$mitreDiagram = GetMitreDiagram -controlItem $controlItem
}
$output = $template
$output = $output -replace '%DocName%', $docName
$output = $output -replace '%ControlName%', $control.ControlName
$output = $output -replace '%Description%', $control.Description
$output = $output -replace '%ControlItemDescription%', $controlItem.Description
$output = $output -replace '%Severity%', $controlItem.Severity
$output = $output -replace '%DisplayName%', $controlItem.DisplayName
$output = $output -replace '%Name%', $controlItem.Name
$output = $output -replace '%CheckId%', $controlItem.CheckId
$output = $output -replace '%Recommendation%', $recommendation
$output = $output -replace '%MitreTactic%', $controlItem.MitreTactic
$output = $output -replace '%MitreTechnique%', $controlItem.MitreTechnique
$output = $output -replace '%MitreMitigation%', $controlItem.MitreMitigation
$output = $output -replace '%PortalDeepLink%', $portalDeepLink
$output = $output -replace '%DefaultValue%', $controlItem.DefaultValue
$output = $output -replace '%RelativeUri%', $relativeUri
$output = $output -replace '%ApiVersion%', $apiVersion
$output = $output -replace '%ShouldOperator%', $compareOperator.pester.Replace("'", "")
$output = $output -replace '%CompareOperatorText%', $compareOperator.Text
$output = $output -replace '%CompareOperator%', $compareOperator.Name
$output = $output -replace '%PwshCompareOperator%', $compareOperator.powershell.Replace("'", "")
$output = $output -replace '%RecommendedValue%', $recommendedValue
$output = $output -replace '%CurrentValue%', $CurrentValue
$output = $output -replace '%GraphEndPoint%', $control.GraphEndpoint
$output = $output -replace '%GraphDocsUrl%', $graphDocsUrl
$output = $output -replace '%GraphExplorerUrl%', $graphExplorerUrl
$output = $output -replace '%MitreDiagram%', $mitreDiagram
$output = $output -replace '%PSFunctionName%', $psFunctionName
$output = $output -replace '%PortalDeepLinkMarkdown%', $portalDeepLinkMarkdown
$output = $output -replace '%GraphDocsUrlMarkdown%', $graphDocsUrlMarkdown
}
return $output
}
# Returns the contents of a file named @template.txt at the given folder path
Function GetTemplate($folderPath, $templateFileName = "@template.txt") {
$templateFilePath = Join-Path $folderPath $templateFileName
return Get-Content $templateFilePath -Raw
}
Function CreateFile($folderPath, $fileName, $content) {
$filePath = Join-Path $folderPath $fileName
$content | Out-File $filePath -Encoding utf8
}
Function GetEidscaPsFunctionName($controlItem) {
$powerShellFunctionName = "Test-Mt$($controlItem.CheckId)"
$powerShellFunctionName = $powerShellFunctionName.Replace("EIDSCA.", "Eidsca")
return $powerShellFunctionName
}
# Start by getting the latest EIDSCA config
$aadsc = Invoke-WebRequest -Uri $AadSecConfigUrl | ConvertFrom-Json
$aadsc = ($aadsc | Where-Object {$_.CollectedBy -eq "Maester"}).ControlArea
$Discovery = ($aadsc | where-Object {$_.discovery -ne ""}).Discovery
# Remove previously generated files
Get-ChildItem -Path $DocsPath -Filter "*.md" -Exclude "readme.md" | Remove-Item -Force
Get-ChildItem -Path $PowerShellFunctionsPath -Filter "*" -Exclude "@template*" | Remove-Item -Force
$docsTemplate = GetTemplate $DocsPath
$psTemplate = GetTemplate $PowerShellFunctionsPath "@templateps1.txt" # Use the .txt extension to avoid running the script
$psMarkdownTemplate = GetTemplate $PowerShellFunctionsPath "@template.md"
$sb = [System.Text.StringBuilder]::new()
if ($null -ne $ControlName) {
$aadsc = $aadsc | Where-Object { $_.ControlName -like $ControlName }
}
foreach ($control in $aadsc) {
Write-Verbose "Generating test for $($control.ControlName)"
$testOutputList = [System.Text.StringBuilder]::new()
foreach ($controlItem in $control.Controls) {
# Export check only if RecommendedValue is set
if (($null -ne $controlItem.RecommendedValue -and $controlItem.RecommendedValue -ne "")) {
$docName = $controlItem.CheckId
$testTemplate = @'
Describe "%ControlName%" -Tag "EIDSCA", "Security", "All", "%CheckId%" {
It "%CheckId%: %ControlName% - %DisplayName%. See https://maester.dev/docs/tests/%DocName%" {
<#
Check if "https://graph.microsoft.com/%ApiVersion%/%RelativeUri%"
.%CurrentValue% %CompareOperator% %RecommendedValue%
#>
%PSFunctionName% | Should -%ShouldOperator% %RecommendedValue%
}
}
'@
# Add condition to test template if defined in EidscaTest
if ($controlItem.SkipCondition -ne "") {
$testTemplate = $testTemplate.Replace( '"%CheckId%"', '"%CheckId%" -Skip:( ' + $controlItem.SkipCondition + ' )')
}
$testOutput = UpdateTemplate -template $testTemplate -control $control -controlItem $controlItem -docName $docName
$docsOutput = UpdateTemplate -template $docsTemplate -control $control -controlItem $controlItem -docName $docName -isDoc $true
$psOutput = UpdateTemplate -template $psTemplate -control $control -controlItem $controlItem -docName $docName
$psMarkdownOutput = UpdateTemplate -template $psMarkdownTemplate -control $control -controlItem $controlItem -docName $docName -isDoc $true
if ($testOutput -ne '') {
[void]$testOutputList.AppendLine($testOutput)
CreateFile $DocsPath "$docName.md" $docsOutput
$psFunctionName = GetEidscaPsFunctionName -controlItem $controlItem
CreateFile $PowerShellFunctionsPath "$psFunctionName.ps1" $psOutput
CreateFile $PowerShellFunctionsPath "$psFunctionName.md" $psMarkdownOutput
}
} else {
Write-Warning "$($controlItem.CheckId) - $($controlItem.DisplayName) has no recommended value!"
}
}
if ($testOutputList.Length -ne 0) {
[void]$sb.AppendLine($testOutputList)
}
}
$output = @'
BeforeDiscovery {
<DiscoveryFromJson>}
'@
# Replace placeholder with Discovery checks from definition in EIDSCA JSON
$output = $output.Replace('<DiscoveryFromJson>',($Discovery | Out-String))
$output += $sb.ToString()
$output | Out-File $TestFilePath -Encoding utf8