-
Notifications
You must be signed in to change notification settings - Fork 214
/
KillChain.ps1
1471 lines (1226 loc) · 59.5 KB
/
KillChain.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
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
#
# This file contains functions for Azure AD / Office 365 kill chain
#
# Invokes information gathering as an outsider
# Jun 16th 2020
function Invoke-ReconAsOutsider
{
<#
.SYNOPSIS
Starts tenant recon of the given domain.
.DESCRIPTION
Starts tenant recon of the given domain. Gets all verified domains of the tenant and extracts information such as their type.
Also checks whether Desktop SSO (aka Seamless SSO) is enabled for the tenant.
DNS: Does the DNS record exists?
MX: Does the MX point to Office 365?
SPF: Does the SPF contain Exchange Online?
Type: Federated or Managed
DMARC: Is the DMARC record configured?
DKIM: Is the DKIM record configured?
MTA-STS: Is the MTA-STS record configured?
STS: The FQDN of the federated IdP's (Identity Provider) STS (Security Token Service) server
RPS: Relaying parties of STS (AD FS)
.Parameter DomainName
Any domain name of the Azure AD tenant.
.Parameter Single
If the switch is used, doesn't get other domains of the tenant.
.Parameter GetRelayingParties
Tries to get relaying parties from STS. Returned if STS is AD FS and idpinitiatedsignon.aspx is enabled.
.Example
Invoke-AADIntReconAsOutsider -Domain company.com | Format-Table
Tenant brand: Company Ltd
Tenant name: company.onmicrosoft.com
Tenant id: 05aea22e-32f3-4c35-831b-52735704feb3
Tenant region: NA
DesktopSSO enabled: False
MDI instance: company.atp.azure.com
Name DNS MX SPF DMARC DKIM MTA-STS Type STS
---- --- -- --- ----- ---- ------- ---- ---
company.com True True True True True True Federated sts.company.com
company.mail.onmicrosoft.com True True True True True False Managed
company.onmicrosoft.com True True True False True False Managed
int.company.com False False False False True False Managed
.Example
Invoke-AADIntReconAsOutsider -Domain company.com -GetRelayingParties | Format-Table
Tenant brand: Company Ltd
Tenant name: company.onmicrosoft.com
Tenant id: 05aea22e-32f3-4c35-831b-52735704feb3
Tenant region: NA
Uses cloud sync: True
DesktopSSO enabled: False
MDI instance: company.atp.azure.com
Name DNS MX SPF DMARC DKIM MTA-STS Type STS
---- --- -- --- ----- ---- ------- ---- ---
company.com True True True True True True Federated sts.company.com
company.mail.onmicrosoft.com True True True True True False Managed
company.onmicrosoft.com True True True False True False Managed
int.company.com False False False False True False Managed
.Example
Invoke-AADIntReconAsOutsider -UserName user@company.com | Format-Table
Tenant brand: Company Ltd
Tenant name: company.onmicrosoft.com
Tenant id: 05aea22e-32f3-4c35-831b-52735704feb3
Tenant region: NA
DesktopSSO enabled: False
MDI instance: company.atp.azure.com
Uses cloud sync: True
CBA enabled: True
Name DNS MX SPF DMARC DKIM MTA-STS Type STS
---- --- -- --- ----- ---- ------- ---- ---
company.com True True True True True True Federated sts.company.com
company.mail.onmicrosoft.com True True True True True False Managed
company.onmicrosoft.com True True True False True False Managed
int.company.com False False False False True False Managed
#>
[cmdletbinding()]
Param(
[Parameter(ParameterSetName="domain",Mandatory=$True)]
[String]$DomainName,
[Parameter(ParameterSetName="user",Mandatory=$True)]
[String]$UserName,
[Switch]$Single,
[Switch]$GetRelayingParties
)
Process
{
if([string]::IsNullOrEmpty($DomainName))
{
$DomainName = $UserName.Split("@")[1]
Write-Verbose "Checking CBA status."
$tenantCBA = HasCBA -UserName $UserName
}
Write-Verbose "Checking if the domain $DomainName is registered to Azure AD"
$tenantId = Get-TenantID -Domain $DomainName
if([string]::IsNullOrEmpty($tenantId))
{
throw "Domain $DomainName is not registered to Azure AD"
}
$openIDConfiguration = Get-OpenIDConfiguration -Domain $DomainName
$tenantName = ""
$tenantBrand = ""
$tenantRegion = $openIDConfiguration.tenant_region_scope
$tenantSubscope = Get-TenantSubscope -OpenIDConfiguration $openIDConfiguration
$tenantSSO = ""
Write-Verbose "`n*`n* EXAMINING TENANT $tenantId`n*"
Write-Verbose "Getting domains.."
$domains = Get-TenantDomains -Domain $DomainName -SubScope $tenantSubscope
Write-Verbose "Found $($domains.count) domains!"
# Create an empty list
$domainInformation = @()
# Counter
$c=1
# Loop through the domains
foreach($domain in $domains)
{
# Define variables
$exists = $false
$hasCloudMX = $false
$hasCloudSPF = $false
$hasCloudDKIM = $false
$hasCloudMTASTS = $false
if(-not $Single)
{
Write-Progress -Activity "Getting DNS information" -Status $domain -PercentComplete (($c/$domains.count)*100)
}
$c++
# Check if this is "the initial" domain
if([string]::IsNullOrEmpty($tenantName) -and $domain.ToLower() -match '^[^.]*\.onmicrosoft.((com)|(us))$')
{
$tenantName = $domain
Write-Verbose "TENANT NAME: $tenantName"
}
# Check if the tenant has the Desktop SSO (aka Seamless SSO) enabled
if([string]::IsNullOrEmpty($tenantSSO))
{
$tenantSSO = HasDesktopSSO -Domain $domain -SubScope $tenantSubscope
}
if(-not $Single -or ($Single -and $DomainName -eq $domain))
{
# Check whether the domain exists in DNS
try { $exists = (Resolve-DnsName -Name $Domain -ErrorAction SilentlyContinue -DnsOnly -NoHostsFile -NoIdn).count -gt 0 } catch{}
if($exists)
{
# Check the MX record
$hasCloudMX = HasCloudMX -Domain $domain -SubScope $tenantSubscope
# Check the SPF record
$hasCloudSPF = HasCloudSPF -Domain $domain -SubScope $tenantSubscope
# Check the DMARC record
$hasDMARC = HasDMARC -Domain $domain
# Check the DKIM record
$hasCloudDKIM = HasCloudDKIM -Domain $domain -SubScope $tenantSubscope
# Check the MTA-STS record
$hasCloudMTASTS = HasCloudMTASTS -Domain $domain -SubScope $tenantSubscope
}
# Get the federation information
$realmInfo = Get-UserRealmV2 -UserName "nn@$domain" -SubScope $tenantSubscope
if([string]::IsNullOrEmpty($tenantBrand))
{
$tenantBrand = $realmInfo.FederationBrandName
Write-Verbose "TENANT BRAND: $tenantBrand"
}
if($authUrl = $realmInfo.AuthUrl)
{
# Try to read relaying parties
if($GetRelayingParties)
{
try
{
$idpUrl = $realmInfo.AuthUrl.Substring(0,$realmInfo.AuthUrl.LastIndexOf("/")+1)
$idpUrl += "idpinitiatedsignon.aspx"
Write-Verbose "Getting relaying parties for $domain from $idpUrl"
[xml]$page = Invoke-RestMethod -Uri $idpUrl -TimeoutSec 3
$selectElement = $page.html.body.div.div[2].div.div.div.form.div[1].div[1].select.option
$relayingParties = New-Object string[] $selectElement.Count
Write-Verbose "Got $relayingParties relaying parties from $idpUrl"
for($o = 0; $o -lt $selectElement.Count; $o++)
{
$relayingParties[$o] = $selectElement[$o].'#text'
}
}
catch{} # Okay
}
# Get just the server name
$authUrl = $authUrl.split("/")[2]
}
# Set the return object properties
$attributes=[ordered]@{
"Name" = $domain
"DNS" = $exists
"MX" = $hasCloudMX
"SPF" = $hasCloudSPF
"DMARC" = $hasDMARC
"DKIM" = $hasCloudDKIM
"MTA-STS" = $hasCloudMTASTS
"Type" = $realmInfo.NameSpaceType
"STS" = $authUrl
}
if($GetRelayingParties)
{
$attributes["RPS"] = $relayingParties
}
Remove-Variable "relayingParties" -ErrorAction SilentlyContinue
$domainInformation += New-Object psobject -Property $attributes
}
}
Write-Host "Tenant brand: $tenantBrand"
Write-Host "Tenant name: $tenantName"
Write-Host "Tenant id: $tenantId"
Write-Host "Tenant region: $tenantRegion"
if(![string]::IsNullOrEmpty($tenantSubscope))
{
Write-Host "Tenant sub region: $tenantSubscope"
}
# DesktopSSO status not definitive with a single domain
if(!$Single -or $tenantSSO -eq $true)
{
Write-Host "DesktopSSO enabled: $tenantSSO"
}
# MDI instance not definitive, may have different instance name than the tenant name.
if(![string]::IsNullOrEmpty($tenantName))
{
$tenantMDI = GetMDIInstance -Tenant $tenantName
if($tenantMDI)
{
Write-Host "MDI instance: $tenantMDI"
}
}
# Cloud sync not definitive, may use different domain name
if(DoesUserExists -User "ADToAADSyncServiceAccount@$($tenantName)")
{
Write-Host "Uses cloud sync: $true"
}
# CBA status definitive if username was provided
if($tenantCBA)
{
Write-Host "CBA enabled: $tenantCBA"
}
return $domainInformation
}
}
# Tests whether the user exists in Azure AD or not
# Jun 16th 2020
function Invoke-UserEnumerationAsOutsider
{
<#
.SYNOPSIS
Checks whether the given user exists in Azure AD or not. Returns $True or $False or empty.
.DESCRIPTION
Checks whether the given user exists in Azure AD or not. Works also with external users! Supports following enumeration methods: Normal, Login, Autologon, and RST2.
The Normal method seems currently work with all tenants. Previously it required Desktop SSO (aka Seamless SSO) to be enabled for at least one domain.
The Login method works with any tenant, but enumeration queries will be logged to Azure AD sign-in log as failed login events!
The Autologon method doesn't seem to work with all tenants anymore. Probably requires that DesktopSSO or directory sync is enabled.
Returns $True or $False if existence can be verified and empty if not.
.Parameter UserName
List of User names or email addresses of the users.
.Parameter External
Whether the given user name is for external user. Requires also -Domain parater!
.Parameter Domain
The initial domain of the given tenant.
.Parameter Method
The used enumeration method. One of "Normal","Login","Autologon","RST2"
.Example
Invoke-AADIntUserEnumerationAsOutsider -UserName user@company.com
UserName Exists
-------- ------
user@company.com True
.Example
Invoke-AADIntUserEnumerationAsOutsider -UserName external.user@gmail.com -External -Domain company.onmicrosoft.com
UserName Exists
-------- ------
external.user_gmail.com#EXT#@company.onmicrosoft.com True
.Example
Invoke-AADIntUserEnumerationAsOutsider -UserName user@company.com,user2@company.com -Method Autologon
UserName Exists
-------- ------
user@company.com True
user2@company.com False
.Example
Get-Content .\users.txt | Invoke-AADIntUserEnumerationAsOutsider
UserName Exists
-------- ------
user@company.com True
user2@company.com False
user@company.net
external.user_gmail.com#EXT#@company.onmicrosoft.com True
external.user_outlook.com#EXT#@company.onmicrosoft.com False
.Example
Get-Content .\users.txt | Invoke-AADIntUserEnumerationAsOutsider -Method Login
UserName Exists
-------- ------
user@company.com True
user2@company.com False
user@company.net True
external.user_gmail.com#EXT#@company.onmicrosoft.com True
external.user_outlook.com#EXT#@company.onmicrosoft.com False
#>
[cmdletbinding()]
Param(
[Parameter(ParameterSetName="Normal", Mandatory=$True,ValueFromPipeline)]
[Parameter(ParameterSetName="External",Mandatory=$True,ValueFromPipeline)]
[String[]]$UserName,
[Parameter(ParameterSetName="External", Mandatory=$True)]
[Switch]$External,
[Parameter(ParameterSetName="External",Mandatory=$True)]
[String]$Domain,
[Parameter(Mandatory=$False)]
[ValidateSet("Normal","Login","Autologon","RST2")]
[String]$Method="Normal"
)
Process
{
foreach($User in $UserName)
{
$tenantSubscope = Get-TenantSubscope -Domain $UserName.Split("@")[1]
# If the user is external, change to correct format
if($Method -eq "Normal" -and $External)
{
$User="$($User.Replace("@","_"))#EXT#@$domain"
}
new-object psobject -Property ([ordered]@{"UserName"=$User;"Exists" = $(DoesUserExists -User $User -Method $Method -SubScope $tenantSubscope)})
}
}
}
# Invokes information gathering as a guest user
# Jun 16th 2020
function Invoke-ReconAsGuest
{
<#
.SYNOPSIS
Starts tenant recon of Azure AD tenant. Prompts for tenant.
.DESCRIPTION
Starts tenant recon of Azure AD tenant. Prompts for tenant.
Retrieves information from Azure AD tenant, such as, the number of Azure AD objects and quota, and the number of domains (both verified and unverified).
.Example
Get-AADIntAccessTokenForAzureCoreManagement -SaveToCache
PS C:\>$results = Invoke-AADIntReconAsGuest
PS C:\>$results.allowedActions
application : {read}
domain : {read}
group : {read}
serviceprincipal : {read}
tenantdetail : {read}
user : {read, update}
serviceaction : {consent}
.Example
Get-AADIntAccessTokenForAzureCoreManagement -SaveToCache
PS C:\>Get-AADIntAzureTenants
Id Country Name Domains
-- ------- ---- -------
221769d7-0747-467c-a5c1-e387a232c58c FI Firma Oy {firma.mail.onmicrosoft.com, firma.onmicrosoft.com, firma.fi}
6e3846ee-e8ca-4609-a3ab-f405cfbd02cd US Company Ltd {company.onmicrosoft.com, company.mail.onmicrosoft.com,company.com}
PS C:\>Get-AADIntAccessTokenForAzureCoreManagement -SaveToCache -Tenant 6e3846ee-e8ca-4609-a3ab-f405cfbd02cd
$results = Invoke-AADIntReconAsGuest
Tenant brand: Company Ltd
Tenant name: company.onmicrosoft.com
Tenant id: 6e3846ee-e8ca-4609-a3ab-f405cfbd02cd
Azure AD objects: 520/500000
Domains: 6 (4 verified)
Non-admin users restricted? True
Users can register apps? True
Directory access restricted? False
Guest access: Normal
CA policies: 7
PS C:\>$results.allowedActions
application : {read}
domain : {read}
group : {read}
serviceprincipal : {read}
tenantdetail : {read}
user : {read, update}
serviceaction : {consent}
#>
[cmdletbinding()]
Param()
Begin
{
# Choises
$choises="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ!""#%&/()=?*+-_"
}
Process
{
# Get access token from cache
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Get the list of tenants the user has access to
$tenants = Get-AzureTenants -AccessToken $AccessToken
$tenantNames = $tenants | Select-Object -ExpandProperty Name
# Prompt for tenant choice if more than one
if($tenantNames.count -gt 1)
{
$options = [System.Management.Automation.Host.ChoiceDescription[]]@()
for($p=0; $p -lt $tenantNames.count; $p++)
{
$options += New-Object System.Management.Automation.Host.ChoiceDescription "&$($choises[$p % $choises.Length]) $($tenantNames[$p])"
}
$opt = $host.UI.PromptForChoice("Choose the tenant","Choose the tenant to recon",$options,0)
}
else
{
$opt=0
}
$tenantInfo = $tenants[$opt]
$tenant = $tenantInfo.Id
# Get the tenant information
$tenantInformation = Get-AzureInformation -Tenant $tenant
# Guest access
if(!$tenantInformation.authorizationPolicy)
{
$tenantInformation.guestAccess = "unknown"
}
# Print out some relevant information
Write-Host "Tenant brand: $($tenantInformation.displayName)"
Write-Host "Tenant name: $($tenantInformation.domains | Where-Object isInitial -eq "True" | Select-Object -ExpandProperty id)"
Write-Host "Tenant id: $($tenantInformation.objectId)"
Write-Host "Azure AD objects: $($tenantInformation.directorySizeQuota.used)/$($tenantInformation.directorySizeQuota.total)"
Write-Host "Domains: $($tenantInformation.domains.Count) ($(($tenantInformation.domains | Where-Object isVerified -eq "True").Count) verified)"
Write-Host "Non-admin users restricted? $($tenantInformation.restrictNonAdminUsers)"
Write-Host "Users can register apps? $($tenantInformation.usersCanRegisterApps)"
Write-Host "Directory access restricted? $($tenantInformation.restrictDirectoryAccess)"
Write-Host "Guest access: $($tenantInformation.guestAccess)"
Write-Host "CA policies: $($tenantInformation.conditionalAccessPolicy.Count)"
Write-Host "Access package admins: $($tenantInformation.accessPackageAdmins.Count)"
# Return
return $tenantInformation
}
}
# Starts crawling the organisation for user names and groups
# Jun 16th 2020
function Invoke-UserEnumerationAsGuest
{
<#
.SYNOPSIS
Crawls the target organisation for user names and groups.
.DESCRIPTION
Crawls the target organisation for user names, groups, and roles. The starting point is the signed-in user, a given username, or a group id.
The crawl can be controlled with switches. Group members are limited to 1000 entries per group.
Groups: Include user's groups
GroupMembers: Include members of user's groups
Roles: Include roles of user and group members. Can be very time consuming!
Manager: Include user's manager
Subordinates: Include user's subordinates (direct reports)
UserName: User principal name (UPN) of the user to search.
GroupId: Id of the group. If this is given, only the members of the group are included.
.Example
$results = Invoke-AADIntUserEnumerationAsGuest -UserName user@company.com
Tenant brand: Company Ltd
Tenant name: company.onmicrosoft.com
Tenant id: 6e3846ee-e8ca-4609-a3ab-f405cfbd02cd
Logged in as: live.com#user@outlook.com
Users: 5
Groups: 2
Roles: 0
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$UserName,
[Switch]$Groups,
[Switch]$GroupMembers,
[Switch]$Subordinates,
[Switch]$Manager,
[Switch]$Roles,
[Parameter(Mandatory=$False)]
[String]$GroupId
)
Begin
{
# Choises
$choises="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ!""#%&/()=?*+-_"
}
Process
{
# Get access token from cache
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Get the list of tenants the user has access to
Write-Verbose "Getting list of user's tenants.."
$tenants = Get-AzureTenants -AccessToken $AccessToken
$tenantNames = $tenants | Select-Object -ExpandProperty Name
# Prompt for tenant choice if more than one
if($tenantNames.count -gt 1)
{
$options = [System.Management.Automation.Host.ChoiceDescription[]]@()
for($p=0; $p -lt $tenantNames.count; $p++)
{
$options += New-Object System.Management.Automation.Host.ChoiceDescription "&$($choises[$p % $choises.Length]) $($tenantNames[$p])"
}
$opt = $host.UI.PromptForChoice("Choose the tenant","Choose the tenant to recon",$options,0)
}
else
{
$opt=0
}
$tenantInfo = $tenants[$opt]
$tenant = $tenantInfo.Id
# Create a new AccessToken for graph.microsoft.com
$refresh_token = Get-RefreshTokenFromCache -ClientID "d3590ed6-52b3-4102-aeff-aad2292ab01c" -Resource "https://management.core.windows.net"
if([string]::IsNullOrEmpty($refresh_token))
{
throw "No refresh token found! Use Get-AADIntAccessTokenForAzureCoreManagement with -SaveToCache switch"
}
try
{
$AccessToken = Get-AccessTokenWithRefreshToken -Resource "https://graph.microsoft.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" -TenantId $tenant -RefreshToken $refresh_token -SaveToCache $true
}
catch
{
Throw "Unable to get access token for Microsoft Graph API"
}
# Get the initial domain
$domains = Get-MSGraphDomains -AccessToken $AccessToken
$tenantDomain = $domains | Where-Object isInitial -eq "True" | Select-Object -ExpandProperty id
if([string]::IsNullOrEmpty($tenantDomain))
{
Throw "No initial domain found for the tenant $tenant!"
}
Write-Verbose "Tenant $Tenant / $tenantDomain selected."
# If GroupID is given, dump only the members of that group
if($GroupId)
{
# Create users object
$ht_users=@{}
# Get group members
$members = Get-MSGraphGroupMembers -AccessToken $AccessToken -GroupId $GroupId
# Create a variable for members
$itemMembers = @()
# Loop trough the members
foreach($member in $members)
{
$ht_users[$member.Id] = $member
$itemMembers += $member.userPrincipalName
}
}
else
{
# If user name not given, try to get one from the access token
if([string]::IsNullOrEmpty($UserName))
{
$UserName = (Read-Accesstoken -AccessToken $AccessToken).upn
# If upn not found, this is probably live.com user, so use email instead of upn
if([string]::IsNullOrEmpty($UserName))
{
$UserName = (Read-Accesstoken -AccessToken $AccessToken).email
}
if(-not ($UserName -like "*#EXT#*"))
{
# As this must be an extrernal user, convert to external format
$UserName = "$($UserName.Replace("@","_"))#EXT#@$tenantDomain"
}
}
Write-Verbose "Getting user information for user $UserName"
# Get the user information
$user = Get-MSGraphUser -UserPrincipalName $UserName -AccessToken $AccessToken
if([string]::IsNullOrEmpty($user))
{
throw "User $UserName not found!"
}
# Create the users object
$ht_users=@{
$user.id = $user
}
# Create the groups object
$ht_groups=@{}
# Create the roles object
$ht_roles=@{}
Write-Verbose "User found: $($user.id) ($($user.userPrincipalName))"
# Loop through the user's subordinates
if($Subordinates)
{
# Copy the keys as the hashtable may change
$so_keys = New-Object string[] $ht_users.Count
$ht_users.Keys.CopyTo($so_keys,0)
# Loop through the users
foreach($userId in $so_keys)
{
$user = $ht_users[$userId].userPrincipalName
Write-Verbose "Getting subordinates of $user"
# Get user's subordinates
$userSubordinates = Get-MSGraphUserDirectReports -AccessToken $AccessToken -UserPrincipalName $user
# Loop trough the users
foreach($subordinate in $userSubordinates)
{
$ht_users[$subordinate.Id] = $subordinate
}
}
}
# Get user's manager
if($Manager)
{
try{$userManager= Get-MSGraphUserManager -AccessToken $AccessToken -UserPrincipalName $UserName}catch{}
if($userManager)
{
$ht_users[$userManager.id] = $userManager
}
}
# Loop through the users' groups
if($Groups -or $GroupMembers)
{
foreach($userId in $ht_users.Keys)
{
$groupUser = $ht_users[$userId].userPrincipalName
Write-Verbose "Getting groups of $groupUser"
# Get user's groups
$userGroups = Get-MSGraphUserMemberOf -AccessToken $AccessToken -UserPrincipalName $groupUser
# Loop trough the groups
foreach($group in $userGroups)
{
# This is a normal group
if($group.'@odata.type' -eq "#microsoft.graph.group")
{
$ht_groups[$group.id] = $group
#$itemGroups += $group.id
}
}
}
}
# Loop through the group members
if($GroupMembers)
{
foreach($groupId in $ht_groups.Keys)
{
Write-Verbose "Getting groups of $groupUser"
# Get group members
$members = Get-MSGraphGroupMembers -AccessToken $AccessToken -GroupId $groupId
# Create a variable for members
$itemMembers = @()
# Loop trough the members
foreach($member in $members)
{
$ht_users[$member.Id] = $member
$itemMembers += $member.userPrincipalName
}
# Add members to the group
$ht_groups[$groupId] | Add-Member -NotePropertyName "members" -NotePropertyValue $itemMembers
# Get group owners
$owners = Get-MSGraphGroupOwners -AccessToken $AccessToken -GroupId $groupId
# Create a variable for members
$itemOwners = @()
# Loop trough the members
foreach($owner in $owners)
{
$ht_users[$owner.Id] = $owner
$itemOwners += $owner.userPrincipalName
}
# Add members to the group
$ht_groups[$groupId] | Add-Member -NotePropertyName "owners" -NotePropertyValue $itemOwners
}
}
# Loop through the users' roles
if($Roles)
{
foreach($userId in $ht_users.Keys)
{
$roleUser = $ht_users[$userId].userPrincipalName
Write-Verbose "Getting roles of $roleUser"
# Get user's roles
$userRoles = Get-MSGraphUserMemberOf -AccessToken $AccessToken -UserPrincipalName $roleUser
# Loop trough the groups
foreach($userRole in $userRoles)
{
if($userRole.'@odata.type' -eq "#microsoft.graph.directoryRole")
{
# Try to get the existing role first
$role = $ht_roles[$userRole.id]
if($role)
{
# Add a new member to the role
$role.members+=$ht_users[$userId].userPrincipalName
}
else
{
# Create a members attribute
$userRole | Add-Member -NotePropertyName "members" -NotePropertyValue @($ht_users[$userId].userPrincipalName)
$role = $userRole
}
$ht_roles[$role.id] = $role
}
}
}
}
# Loop through the role members
if($Roles)
{
foreach($roleId in $ht_roles.Keys)
{
$members = $null
Write-Verbose "Getting role members for '$($ht_roles[$roleId].displayName)'"
# Try to get role members, usually fails
try{$members = Get-MSGraphRoleMembers -AccessToken $AccessToken -RoleId $roleId}catch{ }
if($members)
{
# Create a variable for members
$itemMembers = @()
# Loop trough the members
foreach($member in $members)
{
$ht_users[$member.Id] = $member
$itemMembers += $member.userPrincipalName
}
# Add members to the role
$ht_roles[$roleId] | Add-Member -NotePropertyName "members" -NotePropertyValue $itemMembers -Force
}
}
}
}
# Print out some relevant information
Write-Host "Tenant brand: $($tenantInfo.Name)"
Write-Host "Tenant name: $tenantDomain"
Write-Host "Tenant id: $($tenantInfo.id)"
Write-Host "Logged in as: $((Read-Accesstoken -AccessToken $AccessToken).unique_name)"
Write-Host "Users: $($ht_users.count)"
Write-Host "Groups: $($ht_groups.count)"
Write-Host "Roles: $($ht_roles.count)"
# Create the return value
$attributes=@{
"Users" = $ht_users.values
"Groups" = $ht_groups.Values
"Roles" = $ht_roles.Values
}
return New-Object psobject -Property $attributes
}
}
# Invokes information gathering as an internal user
# Aug 4th 2020
function Invoke-ReconAsInsider
{
<#
.SYNOPSIS
Starts tenant recon of Azure AD tenant.
.DESCRIPTION
Starts tenant recon of Azure AD tenant.
.Example
Get-AADIntAccessTokenForAzureCoreManagement
PS C:\>$results = Invoke-AADIntReconAsInsider
Tenant brand: Company Ltd
Tenant name: company.onmicrosoft.com
Tenant id: 6e3846ee-e8ca-4609-a3ab-f405cfbd02cd
Tenant SKU: E3
Azure AD objects: 520/500000
Domains: 6 (4 verified)
Non-admin users restricted? True
Users can register apps? True
Directory access restricted? False
Directory sync enabled? true
Global admins: 3
CA policies: 8
MS Partner IDs:
MS Partner DAP enabled? False
MS Partner contracts: 0
MS Partners: 1
PS C:\>$results.roleInformation | Where-Object Members -ne $null | Select-Object Name,Members
Name Members
---- -------
Company Administrator {@{DisplayName=MOD Administrator; UserPrincipalName=admin@company.onmicrosoft.com}, @{D...
User Account Administrator @{DisplayName=User Admin; UserPrincipalName=useradmin@company.com}
Directory Readers {@{DisplayName=Microsoft.Azure.SyncFabric; UserPrincipalName=}, @{DisplayName=MicrosoftAzur...
Directory Synchronization Accounts {@{DisplayName=On-Premises Directory Synchronization Service Account; UserPrincipalName=Syn...
#>
[cmdletbinding()]
Param()
Begin
{
}
Process
{
# Get access token from cache
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Get the refreshtoken from the cache and create AAD token
$tenantId = (Read-Accesstoken $AccessToken).tid
$refresh_token = Get-RefreshTokenFromCache -AccessToken $AccessToken
$AAD_AccessToken = Get-AccessTokenWithRefreshToken -RefreshToken $refresh_token -Resource "https://graph.windows.net" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" -TenantId $tenantId
$MSPartner_AccessToken = Get-AccessTokenWithRefreshToken -RefreshToken $refresh_token -Resource "fa3d9a0c-3fb0-42cc-9193-47c7ecd2edbd" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" -TenantId $tenantId
$AdminAPI_AccessToken = Get-AccessTokenWithRefreshToken -RefreshToken $refresh_token -Resource "https://admin.microsoft.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" -TenantId $tenantId
# Get the tenant information
Write-Verbose "Getting company information"
$companyInformation = Get-CompanyInformation -AccessToken $AAD_AccessToken
# Get the sharepoint information
Write-Verbose "Getting SharePoint Online information"
$sharePointInformation = Get-SPOServiceInformation -AccessToken $AAD_AccessToken
# Get the admins
Write-Verbose "Getting role information"
$roles = Get-Roles -AccessToken $AAD_AccessToken
$roleInformation=@()
$sortedRoles = $roles.Role | Sort-Object -Property Name
foreach($role in $roles.Role)
{
Write-Verbose "Getting members of role ""$($role.Name)"""
$attributes=[ordered]@{}
$attributes["Name"] = $role.Name
$attributes["IsEnabled"] = $role.IsEnabled
$attributes["IsSystem"] = $role.IsSystem
$attributes["ObjectId"] = $role.ObjectId
$members = Get-RoleMembers -AccessToken $AAD_AccessToken -RoleObjectId $role.ObjectId | Select-Object @{N='DisplayName'; E={$_.DisplayName}},@{N='UserPrincipalName'; E={$_.EmailAddress}}
$attributes["Members"] = $members
$roleInformation += New-Object psobject -Property $attributes
}
# Get the tenant information
Write-Verbose "Getting tenant information"
$tenantInformation = Get-AzureInformation -Tenant $tenantId
# Get basic partner information
Write-Verbose "Getting basic partner information"
$partnerInformation = Get-PartnerInformation -AccessToken $AAD_AccessToken
# Get partner organisation information
Write-Verbose "Getting partner organisation information"
$partnerOrganisations = @(Get-MSPartnerOrganizations -AccessToken $MSPartner_AccessToken)
# Get partner role information
Write-Verbose "Getting partner role information"
$partnerRoleInformation = @(Get-MSPartnerRoleMembers -AccessToken $MSPartner_AccessToken)
# Get partner contracts (customers)
Write-Verbose "Getting partner contracts (customers)"
try
{
$partnerContracts = @(Get-MSPartnerContracts -AccessToken $AAD_AccessToken)
}
catch
{
# Okay, not all are partner organisations :)
}
# Get partners
Write-Verbose "Getting partners"
try
{
$partners = @(Get-MSPartners -AccessToken $AdminAPI_AccessToken)
}
catch
{
# Okay
}
# AzureAD SKU
$tenantSku = @()
if($tenantInformation.skuInfo.aadPremiumBasic)