-
Notifications
You must be signed in to change notification settings - Fork 214
/
KillChain_utils.ps1
429 lines (393 loc) · 13.5 KB
/
KillChain_utils.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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
# Checks whether the domain has MX records pointing to MS cloud
# Jun 16th 2020
# Aug 30th 2022: Fixed by maxgrim
function HasCloudMX
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$Domain,
[Parameter(Mandatory=$False)]
[String]$SubScope
)
Process
{
# Use the correct filter
switch($SubScope)
{
"DOD" # DoD
{
$filter = "*.protection.office365.us"
}
"DODCON" # GCC-High
{
$filter = "*.protection.office365.us"
}
default # Commercial/GCC
{
$filter = "*.mail.protection.outlook.com"
}
}
$results=Resolve-DnsName -Name $Domain -Type MX -DnsOnly -NoHostsFile -NoIdn -ErrorAction SilentlyContinue | Select-Object nameexchange | Select-Object -ExpandProperty nameexchange
$filteredResults=$results -like $filter
return ($filteredResults -eq $true) -and ($filteredResults.Count -gt 0)
}
}
# Checks whether the domain has SPF records allowing sending from cloud
# Jun 16th 2020
function HasCloudSPF
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$Domain,
[Parameter(Mandatory=$False)]
[String]$SubScope
)
Process
{
# Use the correct filter
switch($SubScope)
{
"DOD" # DoD
{
$filter = "*include:spf.protection.office365.us*"
}
"DODCON" # GCC-High
{
$filter = "*include:spf.protection.office365.us*"
}
default # Commercial/GCC
{
$filter = "*include:spf.protection.outlook.com*"
}
}
$results=Resolve-DnsName -Name $Domain -Type txt -DnsOnly -NoHostsFile -NoIdn -ErrorAction SilentlyContinue | Select-Object strings | Select-Object -ExpandProperty strings
return ($results -like $filter).Count -gt 0
}
}
# Checks whether the domain has SPF records allowing sending from cloud
# Sep 23rd 2020
function HasDMARC
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$Domain
)
Process
{
try
{
$results=Resolve-DnsName -Name "_dmarc.$Domain" -Type txt -DnsOnly -NoHostsFile -NoIdn -ErrorAction SilentlyContinue | Select-Object strings | Select-Object -ExpandProperty strings
}catch{}
return ($results -like "v=DMARC1*").Count -gt 0
}
}
# Checks whether the domain has DKIM records for Exchange Online
# Aug 14rd 2023
function HasCloudDKIM
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$Domain,
[Parameter(Mandatory=$False)]
[String]$SubScope
)
Process
{
# Use the correct filter
switch($SubScope)
{
"DOD" # DoD
{
$filter = "*_domainkey.*.onmicrosoft.us*"
}
"DODCON" # GCC-High
{
$filter = "*_domainkey.*.onmicrosoft.us*"
}
default # Commercial/GCC
{
$filter = "*_domainkey.*.onmicrosoft.com*"
}
}
$selectors = @("selector1", "selector2")
foreach ($selector in $selectors)
{
try
{
$results = Resolve-DnsName -Name "$selector._domainkey.$($Domain)" -Type CNAME -DnsOnly -NoHostsFile -NoIdn -ErrorAction SilentlyContinue
if($results.NameHost -like $filter)
{
return $true
}
}catch {}
}
return $false
}
}
# Checks whether the domain has MTA-STS records for Exchange Online
# Aug 14rd 2023
function HasCloudMTASTS {
param (
[Parameter(Mandatory=$True)]
[string]$Domain,
[Parameter(Mandatory=$False)]
[String]$SubScope
)
Process
{
# Use the correct filter
switch($SubScope)
{
"DOD" # DoD
{
$filter = "*include:spf.protection.office365.us*"
}
"DODCON" # GCC-High
{
$filter = "*mx: *.mail.protection.office365.us*"
}
default # Commercial/GCC
{
$filter = "*mx: *.mail.protection.outlook.com*"
}
}
$url = "https://mta-sts.$Domain/.well-known/mta-sts.txt"
$mtaStsFound = $false
$outlookMxFound = $false
try {
$mtaStsResponse = Invoke-WebRequest -UseBasicParsing -Uri $url -ErrorAction Stop -Headers @{"User-agent" = Get-UserAgent}
$mtaStsContent = $mtaStsResponse.Content
$mtaStsLines = $mtaStsContent -split "`r?`n"
foreach ($line in $mtaStsLines) {
if ($line -like "version: STSv1") {
$mtaStsFound = $true
}
if ($line -like $filter) {
$outlookMxFound = $true
}
}
} catch {
$mtaStsFound = $false
$outlookMxFound = $false
}
return ($mtaStsFound -eq $true) -and ($outlookMxFound -eq $true)
}
}
# Checks whether the domain has DesktopSSO enabled
# Jun 16th 2020
function HasDesktopSSO
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$Domain,
[Parameter(Mandatory=$False)]
[String]$SubScope
)
Process
{
(Get-CredentialType -UserName "nn@$domain" -SubScope $Subscope).EstsProperties.DesktopSsoEnabled -eq "True"
}
}
# Checks whether the domain has CBA enabled
# Jun 17th 2022
function HasCBA
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$UserName,
[Parameter(Mandatory=$False)]
[String]$SubScope
)
Process
{
(Get-CredentialType -UserName $UserName -SubScope $SubScope).Credentials.HasCertAuth -eq "True"
}
}
# Checks whether the user exists in Azure AD or not
# Jun 16th 2020
function DoesUserExists
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$User,
[Parameter(Mandatory=$False)]
[ValidateSet("Normal","Login","Autologon","RST2")]
[String]$Method="Normal",
[Parameter(Mandatory=$False)]
[String]$SubScope
)
Process
{
$exists = $false
# Get Tenant Region subscope from Open ID configuration if not provided
if([string]::IsNullOrEmpty($SubScope))
{
$SubScope = Get-TenantSubscope -Domain $User.Split("@")[1]
}
if($Method -eq "Normal")
{
# Get the credential type information
$credType=Get-CredentialType -UserName $User -SubScope $SubScope
# Works only if desktop sso (aka. Seamless SSO) is enabled
# Since August 2021 this seems to work for all tenants!
#if($credType.EstsProperties.DesktopSsoEnabled -eq "True")
#{
# Return empty if throttling
if($credType.ThrottleStatus -eq 1)
{
Write-Warning "Requests throttled!"
Remove-Variable exists
}
else
{
$exists = $credType.IfExistsResult -eq 0 -or $credType.IfExistsResult -eq 6
}
#}
#else
#{
# Remove-Variable exists
#}
}
else
{
if($Method -eq "Login")
{
# Try to log in as the user
$randomGuid = New-Guid
$body = @{
"resource"=$randomGuid
"client_id"=$randomGuid
"grant_type"="password"
"username"=$User
"password"="none"
"scope"="openid"
}
try
{
$jsonResponse=Invoke-RestMethod -UseBasicParsing -Uri "$(Get-TenantLoginUrl -SubScope $SubScope)/common/oauth2/token" -ContentType "application/x-www-form-urlencoded" -Method POST -Body $body -Headers @{"User-agent" = Get-UserAgent}
$exists = $True # May be should change password..?
}
catch
{
$errorDetails = ($_.ErrorDetails.Message | convertfrom-json).error_description
}
}
elseif("Autologon","RST2".Contains($Method))
{
$requestId = (New-Guid).ToString()
$domain = $User.Split("@")[1]
$password = "none"
$now = Get-Date
$created = $now.toUniversalTime().toString("o")
$expires = $now.addMinutes(10).toUniversalTime().toString("o")
if($Method -eq "RST2")
{
# RST2
$url = "$(Get-TenantLoginUrl -SubScope $SubScope)/RST2.srf"
$endPoint = "sharepoint.com"
}
else
{
# AutoLogon
$url = "https://autologon.microsoftazuread-sso.com/$domain/winauth/trust/2005/usernamemixed?client-request-id=$requestid"
$endPoint = "urn:federation:MicrosoftOnline"
}
$exists = $false
try
{
$response = Get-RSTToken -Url $url -EndpointAddress $endPoint -UserName $User -Password $password
$exists = $true # Very bad password
}
catch
{
$errorDetails = $_.Exception.Message
}
}
# Parse the error code. Only AADSTS50034 would need to be checked but good to know other errors too.
if(!$exists -and $errorDetails)
{
if($errorDetails.startsWith("AADSTS50053")) # The account is locked, you've tried to sign in too many times with an incorrect user ID or password.
{
$exists = $True
}
elseif($errorDetails.StartsWith("AADSTS50126")) # Error validating credentials due to invalid username or password.
{
$exists = $True
}
elseif($errorDetails.StartsWith("AADSTS50076")) # Due to a configuration change made by your administrator, or because you moved to a new location, you must use multi-factor authentication to access '{resource}'
{
$exists = $True
}
elseif($errorDetails.StartsWith("AADSTS700016")) # Application with identifier '{appIdentifier}' was not found in the directory '{tenantName}'. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You may have sent your authentication request to the wrong tenant.
{
$exists = $True
}
elseif($errorDetails.StartsWith("AADSTS70046")) # The session has expired or is invalid due to re-authentication checks by conditional access. (= Blocked due to risky sign-in)
{
$exists = $True
}
elseif($errorDetails.StartsWith("AADSTS50034")) # The user account {identifier} does not exist in the {tenant} directory. To sign into this application, the account must be added to the directory.
{
$exists = $False
}
elseif($errorDetails.StartsWith("AADSTS50059")) # No tenant-identifying information found in either the request or implied by any provided credentials.
{
$exists = $False
}
elseif($errorDetails.StartsWith("AADSTS81016")) # Invalid STS request.
{
Write-Warning "Got Invalid STS request. The tenant may not have DesktopSSO or Directory Sync enabled."
Remove-Variable exists
}
else
{
# Can't be sure so return empty
Remove-Variable exists
}
}
}
return $exists
}
}
# Checks whether the tenant has MDI enabled
# Mar 11th 2023
function GetMDIInstance
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$Tenant
)
Process
{
# Ref: https://learn.microsoft.com/en-us/defender-for-identity/configure-proxy#enable-access-to-defender-for-identity-service-urls-in-the-proxy-server
# Ref: https://github.com/thalpius/Microsoft-Defender-for-Identity-Check-Instance
# The MDI url is <instance>.atp.azure.com where instance is the tenant or tenant-onmicrosoft-com
# Get the instance part if FQDN is provided
if($Tenant.IndexOf(".") -ge 0)
{
$Tenant=$Tenant.Substring(0,$Tenant.IndexOf("."))
}
Write-Verbose "Getting MDI Instance for $Tenant"
$domains =@(
"$tenant.atp.azure.com",
"$tenant-onmicrosoft-com.atp.azure.com"
)
foreach($domain in $domains)
{
$results=Resolve-DnsName -Name $Domain -DnsOnly -NoHostsFile -NoIdn -ErrorAction SilentlyContinue
if($results)
{
return $domain
}
}
return $null
}
}