forked from mlcsec/Graphpython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraphpython.py
More file actions
7256 lines (6258 loc) · 333 KB
/
graphpython.py
File metadata and controls
7256 lines (6258 loc) · 333 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
#!/usr/bin/env python3
import sys
import requests
import json
import jwt
import time
import argparse
import textwrap
import os
import re
import dns.resolver
import base64
from tqdm import tqdm
from tabulate import tabulate
from datetime import datetime, timedelta, timezone
import hashlib
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.serialization import pkcs12
from cryptography.hazmat.backends import default_backend
from urllib.parse import urlencode, urlparse, parse_qs
import uuid
import xml.etree.ElementTree as ET
from bs4 import BeautifulSoup
def print_yellow(message):
print(f"\033[93m{message}\033[0m")
def print_green(message):
print(f"\033[92m{message}\033[0m")
def print_red(message):
print(f"\033[91m{message}\033[0m")
def list_commands():
outsider_commands = [
["Invoke-ReconAsOutsider", "Perform outsider recon of the target domain"],
["Invoke-UserEnumerationAsOutsider", "Checks whether the uer exists within Azure AD"]
]
auth_commands = [
["Get-GraphTokens", "Obtain graph token via device code phish (saved to graph_tokens.txt)"],
["Get-TenantID", "Get tenant ID for target domain"],
["Get-TokenScope", "Get scope of supplied token"],
["Decode-AccessToken", "Get all token payload attributes"],
["Invoke-RefreshToMSGraphToken", "Convert refresh token to Microsoft Graph token (saved to new_graph_tokens.txt)"],
["Invoke-RefreshToAzureManagementToken", "Convert refresh token to Azure Management token (saved to az_tokens.txt)"],
["Invoke-RefreshToVaultToken", "Convert refresh token to Azure Vault token (saved to vault_tokens.txt)"],
["Invoke-RefreshToMSTeamsToken", "Convert refresh token to MS Teams token (saved to teams_tokens.txt)"],
["Invoke-RefreshToOfficeAppsToken", "Convert refresh token to Office Apps token (saved to officeapps_tokens.txt)"],
["Invoke-RefreshToOfficeManagementToken", "Convert refresh token to Office Management token (saved to officemanagement_tokens.txt)"],
["Invoke-RefreshToOutlookToken", "Convert refresh token to Outlook token (saved to outlook_tokens.txt)"],
["Invoke-RefreshToSubstrateToken", "Convert refresh token to Substrate token (saved to substrate_tokens.txt)"],
["Invoke-RefreshToYammerToken", "Convert refresh token to Yammer token (saved to yammer_tokens.txt)"],
["Invoke-RefreshToIntuneEnrollmentToken", "Convert refresh token to Intune Enrollment token (saved to intune_tokens.txt)"],
["Invoke-RefreshToOneDriveToken", "Convert refresh token to OneDrive token (saved to onedrive_tokens.txt)"],
["Invoke-RefreshToSharePointToken", "Convert refresh token to SharePoint token (saved to sharepoint_tokens.txt)"],
["Invoke-CertToAccessToken", "Convert Azure Application certificate to JWT access token (saved to cert_tokens.txt)"],
["Invoke-ESTSCookieToAccessToken", "Convert ESTS cookie to MS Graph access token (saved to estscookie_tokens.txt)"],
["Invoke-AppSecretToAccessToken", "Convert Azure Application secretText credentials to access token (saved to appsecret_tokens.txt)"],
["New-SignedJWT", "Construct JWT and sign using Key Vault PEM certificate (Azure Key Vault access token required) then generate Azure Management token"]
]
post_authenum_commands = [
["Get-CurrentUser", "Get current user profile"],
["Get-CurrentUserActivity", "Get recent activity and actions of current user"],
["Get-OrgInfo", "Get information relating to the target organisation"],
["Get-Domains", "Get domain objects"],
["Get-User", "Get all users (default) or target user (--id)"],
["Get-UserProperties", "Get current user properties (default) or target user (--id)"],
["Get-UserPrivileges", "Get group/AU memberships and directory roles assgined for current user (default) or target user (--id)"],
["Get-UserTransitiveGroupMembership", "Get transitive group memberships for current user (default) or target user (--id)"],
["Get-Group", "Get all groups (default) or target group (-id)"],
["Get-GroupMember", "Get all members of target group"],
["Get-UserAppRoleAssignments", "Get user app role assignments for current user (default) or target user (--id)"],
["Get-ConditionalAccessPolicy", "Get conditional access policy properties"],
["Get-Application", "Get Enterprise Application details for app (NOT object) ID (--id)"],
["Get-AppServicePrincipal", "Get details of the application's service principal from the app ID (--id)"],
["Get-ServicePrincipal", "Get all or specific Service Principal details (--id)"],
["Get-ServicePrincipalAppRoleAssignments", "Get Service Principal app role assignments (shows available admin consent permissions that are already granted)"],
["Get-PersonalContacts", "Get contacts of the current user"],
["Get-CrossTenantAccessPolicy", "Get cross tenant access policy properties"],
["Get-PartnerCrossTenantAccessPolicy", "Get partner cross tenant access policy"],
["Get-UserChatMessages", "Get ALL messages from all chats for target user (Chat.Read.All)"],
["Get-AdministrativeUnitMember", "Get members of administrative unit"],
["Get-OneDriveFiles", "Get all accessible OneDrive files for current user (default) or target user (--id)"],
["Get-UserPermissionGrants", "Get permission grants of current user (default) or target user (--id)"],
["Get-oauth2PermissionGrants", "Get oauth2 permission grants for current user (default) or target user (--id)"],
["Get-Messages", "Get all messages in signed-in user's mailbox (default) or target user (--id)"],
["Get-TemporaryAccessPassword", "Get TAP details for current user (default) or target user (--id)"],
["Get-Password", "Get passwords registered to current user (default) or target user (--id)"],
["List-AuthMethods", "List authentication methods for current user (default) or target user (--id)"],
["List-DirectoryRoles", "List all directory roles activated in the tenant"],
["List-Notebooks", "List current user notebooks (default) or target user (--id)"],
["List-ConditionalAccessPolicies", "List conditional access policy objects"],
["List-ConditionalAuthenticationContexts", "List conditional access authentication context"],
["List-ConditionalNamedLocations", "List conditional access named locations"],
["List-SharePointRoot", "List root SharePoint site properties"],
["List-SharePointSites", "List any available SharePoint sites"],
["List-SharePointURLs", "List SharePoint site web URLs visible to current user"],
["List-ExternalConnections", "List external connections"],
["List-Applications", "List all Azure Applications"],
["List-ServicePrincipals", "List all service principals"],
["List-Tenants", "List tenants"],
["List-JoinedTeams", "List joined teams for current user (default) or target user (--id)"],
["List-Chats", "List chats for current user (default) or target user (--id)"],
["List-ChatMessages", "List messages in target chat (--id)"],
["List-Devices", "List devices"],
["List-AdministrativeUnits", "List administrative units"],
["List-OneDrives", "List current user OneDrive (default) or target user (--id)"],
["List-RecentOneDriveFiles", "List current user recent OneDrive files"],
["List-SharedOneDriveFiles", "List OneDrive files shared with the current user"],
["List-OneDriveURLs", "List OneDrive web URLs visible to current user"]
]
post_authexploit_commands = [
["Invoke-CustomQuery", "Custom GET query to target Graph API endpoint"],
["Invoke-Search", "Search for string within entity type (driveItem, message, chatMessage, site, event)"],
["Find-PrivilegedRoleUsers", "Find users with privileged roles assigned"],
["Find-PrivilegedApplications", "Find privileged apps (via their service principal) with granted admin consent API permissions"],
["Find-UpdatableGroups", "Find groups which can be updated by the current user"],
["Find-SecurityGroups", "Find security groups and group members"],
["Find-DynamicGroups", "Find groups with dynamic membership rules"],
["Update-UserPassword", "Update the passwordProfile of the target user (NewUserS3cret@Pass!)"],
["Update-UserProperties", "Update the user properties of the target user"],
["Add-UserTAP", "Add new Temporary Access Password (TAP) to target user"],
["Add-GroupMember", "Add member to target group"],
["Add-ApplicationPassword", "Add client secret to target application"],
["Add-ApplicationCertificate", "Add client certificate to target application"],
["Add-ApplicationPermission", "Add permission to target application e.g. Mail.Send and attempt to grant admin consent"],
["Grant-AppAdminConsent", "Grant admin consent for Graph API permission already assigned to enterprise application"],
["Create-Application", "Create new enterprise application with default settings"],
["Create-NewUser", "Create new Entra ID user"],
["Invite-GuestUser", "Invite guest user to Entra ID"],
["Assign-PrivilegedRole", "Assign chosen privileged role to user/group/object"],
["Open-OWAMailboxInBrowser", "Open an OWA Office 365 mailbox in BurpSuite's embedded Chromium browser using either a Substrate.Office.com or Outlook.Office.com access token"],
["Dump-OWAMailbox", "Dump OWA Office 365 mailbox"],
["Spoof-OWAEmailMessage", "Send email from current user's Outlook mailbox or spoof another user (--id) (Mail.Send)"]
]
intune_enum = [
["Get-ManagedDevices", "Get managed devices"],
["Get-UserDevices", "Get user devices"],
["Get-CAPs", "Get conditional access policies"],
["Get-DeviceCategories", "Get device categories"],
["Get-DeviceComplianceSummary", "Get device compliance summary"],
["Get-DeviceConfigurations", "Get device configurations"],
["Get-DeviceConfigurationPolicies", "Get device configuration policies and assignment details (av, asr, diskenc, etc.)"],
["Get-DeviceConfigurationPolicySettings", "Get device configuration policy settings"],
["Get-DeviceEnrollmentConfigurations", "Get device enrollment configurations"],
["Get-DeviceGroupPolicyConfigurations", "Get device group policy configurations and assignment details"],
["Get-DeviceGroupPolicyDefinition", "Get device group policy definition"],
["Get-RoleDefinitions", "Get role definitions"],
["Get-RoleAssignments", "Get role assignments"],
["Get-DeviceCompliancePolicies", "Get all device compliance policies (AV, ASR, Bitlocker, Firewall, EDR, LAPS) and assignments"]
]
intune_exploit = [
["Dump-DeviceManagementScripts", "Dump device management PowerShell scripts"],
["Dump-WindowsApps", "Dump managed Windows OS applications (exe, msi, appx, msix, etc.)"],
["Dump-iOSApps", "Dump managed iOS/iPadOS mobile applications"],
["Dump-macOSApps", "Dump managed macOS applications"],
["Dump-AndroidApps", "Dump managed Android mobile applications"],
["Get-ScriptContent", "Get device management script content"],
["Backdoor-Script", "Add malicious code to pre-existing device management script"],
["Deploy-MaliciousScript", "Deploy new malicious device management PowerShell script"],
["Deploy-MaliciousWebLink", "Deploy malicious Windows web link application"],
# Deploy-MaliciousWin32Exe - Deploy malicious exe to managed devices
# Deploy-MaliciousWin32MSI - Deploy malicious MSI to managed devices
["Display-AVPolicyRules", "Display antivirus policy rules"],
["Display-ASRPolicyRules", "Display Attack Surface Reduction (ASR) policy rules"],
["Display-DiskEncryptionPolicyRules", "Display disk encryption policy rules"],
["Display-FirewallConfigPolicyRules", "Display firewall configuration policy rules"],
["Display-FirewallRulePolicyRules", "Display firewall RULE policy rules"],
["Display-EDRPolicyRules", "Display EDR policy rules"],
["Display-LAPSAccountProtectionPolicyRules", "Display LAPS account protection policy rules"],
["Display-UserGroupAccountProtectionPolicyRules", "Display user group account protection policy rules"],
["Add-ExclusionGroupToPolicy", "Bypass av, asr, etc. rules by adding an exclusion group containing compromised user or device"],
["Reboot-Device", "Reboot managed device"],
["Retire-Device", "Retire managed device"],
["Lock-Device", "Lock managed device"],
["Shutdown-Device", "Shutdown managed device"],
["Update-DeviceConfig", "Update properties of the managed device configuration"]
]
cleanup_commands = [
["Delete-User", "Delete a user"],
["Delete-Group", "Delete a group"],
["Remove-GroupMember", "Remove user from a group"],
["Delete-Application", "Delete an application"],
["Delete-Device", "Delete managed device"],
["Wipe-Device", "Wipe managed device"],
]
locator_commands = [
["Locate-ObjectID", "Locate object ID and display object properties"],
["Locate-PermissionID", "Locate Graph permission details (application/delegated, description, admin consent required, ...) for ID"]
]
print("\nOutsider")
print("=" * 80)
print(tabulate(outsider_commands, tablefmt="plain"))
print("\nAuthentication")
print("=" * 80)
print(tabulate(auth_commands, tablefmt="plain"))
print("\nPost-Auth Enumeration")
print("=" * 80)
print(tabulate(post_authenum_commands, tablefmt="plain"))
print("\nPost-Auth Exploitation")
print("=" * 80)
print(tabulate(post_authexploit_commands, tablefmt="plain"))
print("\nPost-Auth Intune Enumeration")
print("=" * 80)
print(tabulate(intune_enum, tablefmt="plain"))
print("\nPost-Auth Intune Exploitation")
print("=" * 80)
print(tabulate(intune_exploit, tablefmt="plain"))
print("\nCleanup")
print("=" * 80)
print(tabulate(cleanup_commands, tablefmt="plain"))
print("\nLocators")
print("=" * 80)
print(tabulate(locator_commands, tablefmt="plain"))
print("\n")
def forge_user_agent(device=None, browser=None):
user_agent = ''
if device == 'Mac':
if browser == 'Chrome':
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'
elif browser == 'Firefox':
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:70.0) Gecko/20100101 Firefox/70.0'
elif browser == 'Edge':
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/604.1 Edg/91.0.100.0'
elif browser == 'Safari':
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Safari/605.1.15'
else:
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Safari/605.1.15'
elif device == 'Windows':
if browser == 'IE':
user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko'
elif browser == 'Chrome':
user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'
elif browser == 'Firefox':
user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:70.0) Gecko/20100101 Firefox/70.0'
elif browser == 'Edge':
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19042'
else:
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19042'
elif device == 'AndroidMobile':
if browser == 'Android':
user_agent = 'Mozilla/5.0 (Linux; U; Android 4.0.2; en-us; Galaxy Nexus Build/ICL53F) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30'
elif browser == 'Chrome':
user_agent = 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Mobile Safari/537.36'
elif browser == 'Firefox':
user_agent = 'Mozilla/5.0 (Android 4.4; Mobile; rv:70.0) Gecko/70.0 Firefox/70.0'
elif browser == 'Edge':
user_agent = 'Mozilla/5.0 (Linux; Android 8.1.0; Pixel Build/OPM4.171019.021.D1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.109 Mobile Safari/537.36 EdgA/42.0.0.2057'
else:
user_agent = 'Mozilla/5.0 (Linux; U; Android 4.0.2; en-us; Galaxy Nexus Build/ICL53F) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30'
elif device == 'iPhone':
if browser == 'Chrome':
user_agent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/91.0.4472.114 Mobile/15E148 Safari/604.1'
elif browser == 'Firefox':
user_agent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 8_3 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) FxiOS/1.0 Mobile/12F69 Safari/600.1.4'
elif browser == 'Edge':
user_agent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.1 EdgiOS/44.5.0.10 Mobile/15E148 Safari/604.1'
elif browser == 'Safari':
user_agent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1'
else:
user_agent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1'
else:
if browser == 'Android':
user_agent = 'Mozilla/5.0 (Linux; U; Android 4.0.2; en-us; Galaxy Nexus Build/ICL53F) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30'
elif browser == 'IE':
user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko'
elif browser == 'Chrome':
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36'
elif browser == 'Firefox':
user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:70.0) Gecko/20100101 Firefox/70.0'
elif browser == 'Safari':
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Safari/605.1.15'
else:
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19042'
return user_agent
def get_user_agent(args):
if args.device:
if args.browser:
return forge_user_agent(device=args.device, browser=args.browser)
else:
return forge_user_agent(device=args.device)
else:
if args.browser:
return forge_user_agent(browser=args.browser)
else:
return forge_user_agent()
def get_access_token(token_input):
if os.path.isfile(token_input):
encodings = ['utf-8', 'utf-16', 'ascii', 'iso-8859-1']
for encoding in encodings:
try:
with open(token_input, 'r', encoding=encoding) as file:
access_token = file.read().strip()
return access_token
except UnicodeDecodeError:
continue
raise ValueError(f"Unable to decode the file {token_input} with any of the tried encodings.")
else:
access_token = token_input
return access_token
def read_file_content(file_path):
try:
with open(file_path, 'r', encoding='utf-8') as file:
return file.read()
except UnicodeDecodeError:
with open(file_path, 'r', encoding='utf-16') as file:
return file.read()
def format_list_style(data):
if not data.get('value'):
print_red("[-] No data found")
return
for d in data.get('value', []):
for key, value in d.items():
print(f"{key} : {value}")
print("\n")
def graph_api_get(access_token, url, args):
try:
output_returned = False
while url:
user_agent = get_user_agent(args)
headers = {
"Authorization": f"Bearer {access_token}",
"User-Agent": user_agent
}
response = requests.get(url, headers=headers)
response.raise_for_status()
response_body = response.json()
filtered_data = {key: value for key, value in response_body.items() if not key.startswith("@odata")}
if filtered_data:
format_list_style(filtered_data)
output_returned = True
url = response_body.get("@odata.nextLink")
if not output_returned:
print_red("[-] No data found")
except requests.exceptions.RequestException as ex:
print_red(f"[-] HTTP Error: {ex}")
def get_tenant_domains(domain):
domains = [domain]
try:
openid_config_url = f"https://login.microsoftonline.com/{domain}/.well-known/openid-configuration"
response = requests.get(openid_config_url)
response.raise_for_status()
openid_config = response.json()
tenant_region_sub_scope = openid_config.get("tenant_region_sub_scope", "")
if tenant_region_sub_scope == "DOD":
autodiscover_url = "https://autodiscover-s-dod.office365.us/autodiscover/autodiscover.svc"
elif tenant_region_sub_scope == "DODCON":
autodiscover_url = "https://autodiscover-s.office365.us/autodiscover/autodiscover.svc"
else:
autodiscover_url = "https://autodiscover-s.outlook.com/autodiscover/autodiscover.svc"
autodiscover_body = f"""
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:exm="http://schemas.microsoft.com/exchange/services/2006/messages"
xmlns:ext="http://schemas.microsoft.com/exchange/services/2006/types"
xmlns:a="http://www.w3.org/2005/08/addressing"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Header>
<a:Action soap:mustUnderstand="1">http://schemas.microsoft.com/exchange/2010/Autodiscover/Autodiscover/GetFederationInformation</a:Action>
<a:To soap:mustUnderstand="1">{autodiscover_url}</a:To>
<a:ReplyTo>
<a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
</a:ReplyTo>
</soap:Header>
<soap:Body>
<GetFederationInformationRequestMessage xmlns="http://schemas.microsoft.com/exchange/2010/Autodiscover">
<Request>
<Domain>{domain}</Domain>
</Request>
</GetFederationInformationRequestMessage>
</soap:Body>
</soap:Envelope>
""".strip()
headers = {
"Content-Type": "text/xml; charset=utf-8",
"SOAPAction": '"http://schemas.microsoft.com/exchange/2010/Autodiscover/Autodiscover/GetFederationInformation"',
"User-Agent": "AutodiscoverClient"
}
autodiscover_response = requests.post(autodiscover_url, data=autodiscover_body, headers=headers)
autodiscover_response.raise_for_status()
autodiscover_xml = autodiscover_response.content
tree = ET.ElementTree(ET.fromstring(autodiscover_xml))
namespaces = {
's': 'http://schemas.xmlsoap.org/soap/envelope/',
'a': 'http://www.w3.org/2005/08/addressing',
'm': 'http://schemas.microsoft.com/exchange/services/2006/messages',
't': 'http://schemas.microsoft.com/exchange/services/2006/types',
'ns2': 'http://schemas.microsoft.com/exchange/2010/Autodiscover'
}
found_domains = [elem.text for elem in tree.findall('.//ns2:Domain', namespaces)]
if domain not in found_domains:
found_domains.append(domain)
domains = sorted(found_domains)
except Exception as e:
print(f"An unexpected error occurred: {e}")
return domains
def get_credential_type(username, flow_token=None, original_request=None):
body = {
"username": username,
"isOtherIdpSupported": True,
"checkPhones": True,
"isRemoteNGCSupported": False,
"isCookieBannerShown": False,
"isFidoSupported": False,
"originalRequest": original_request,
"flowToken": flow_token
}
if original_request:
body["isAccessPassSupported"] = True
try:
response = requests.post("https://login.microsoftonline.com/common/GetCredentialType",
json=body,
headers={"Content-Type": "application/json; charset=UTF-8"})
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Error in Get-CredentialType: {e}")
return None
def get_rst_token(url, endpoint_address, username, password="none"):
request_id = str(uuid.uuid4())
now = datetime.utcnow()
created = now.isoformat() + "Z"
expires = (now + timedelta(minutes=10)).isoformat() + "Z"
body = f"""
<?xml version='1.0' encoding='UTF-8'?>
<s:Envelope xmlns:s='http://www.w3.org/2003/05/soap-envelope' xmlns:wsse='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd' xmlns:saml='urn:oasis:names:tc:SAML:1.0:assertion' xmlns:wsp='http://schemas.xmlsoap.org/ws/2004/09/policy' xmlns:wsu='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd' xmlns:wsa='http://www.w3.org/2005/08/addressing' xmlns:wssc='http://schemas.xmlsoap.org/ws/2005/02/sc' xmlns:wst='http://schemas.xmlsoap.org/ws/2005/02/trust' xmlns:ic='http://schemas.xmlsoap.org/ws/2005/05/identity'>
<s:Header>
<wsa:Action s:mustUnderstand='1'>http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</wsa:Action>
<wsa:To s:mustUnderstand='1'>{url}</wsa:To>
<wsa:MessageID>urn:uuid:{str(uuid.uuid4())}</wsa:MessageID>
<wsse:Security s:mustUnderstand="1">
<wsu:Timestamp wsu:Id="_0">
<wsu:Created>{created}</wsu:Created>
<wsu:Expires>{expires}</wsu:Expires>
</wsse:Timestamp>
<wsse:UsernameToken wsu:Id="uuid-{str(uuid.uuid4())}">
<wsse:Username>{username}</wsse:Username>
<wsse:Password>{password}</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</s:Header>
<s:Body>
<wst:RequestSecurityToken Id='RST0'>
<wst:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</wst:RequestType>
<wsp:AppliesTo>
<wsa:EndpointReference>
<wsa:Address>{endpoint_address}</wsa:Address>
</wsp:AppliesTo>
<wst:KeyType>http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey</wst:KeyType>
</wst:RequestSecurityToken>
</s:Body>
</s:Envelope>
"""
try:
response = requests.post(url,
data=body,
headers={"Content-Type": "application/soap+xml; charset=UTF-8"},
timeout=10)
response.raise_for_status()
response_xml = response.content
# parse the response XML (might need to check this)
if "urn:oasis:names:tc:SAML:1.0:assertion" in response_xml.decode():
return True
return False
except requests.exceptions.RequestException as e:
print(f"Error in Get-RSTToken: {e}")
return None
def does_user_exist(user, method="Normal"):
exists = False
error_details = ""
if method == "Normal":
cred_type = get_credential_type(user)
if cred_type:
if cred_type.get('ThrottleStatus') == 1:
print("Requests throttled!")
return None
exists = cred_type.get('IfExistsResult') in [0, 6]
else:
if method == "Login":
random_guid = str(uuid.uuid4())
body = {
"resource": random_guid,
"client_id": random_guid,
"grant_type": "password",
"username": user,
"password": "none",
"scope": "openid"
}
try:
response = requests.post("https://login.microsoftonline.com/common/oauth2/token",
data=body,
headers={"Content-Type": "application/x-www-form-urlencoded"})
response.raise_for_status()
exists = True
except requests.exceptions.RequestException as e:
error_details = e.response.json().get("error_description", "")
elif method in ["Autologon", "RST2"]:
request_id = str(uuid.uuid4())
domain = user.split("@")[1]
password = "none"
now = datetime.utcnow()
created = now.isoformat() + "Z"
expires = (now + timedelta(minutes=10)).isoformat() + "Z"
if method == "RST2":
url = "https://login.microsoftonline.com/RST2.srf"
end_point = "sharepoint.com"
else:
url = f"https://autologon.microsoftazuread-sso.com/{domain}/winauth/trust/2005/usernamemixed?client-request-id={request_id}"
end_point = "urn:federation:MicrosoftOnline"
try:
response = get_rst_token(url, end_point, user, password)
exists = response is not None
except Exception as e:
error_details = str(e)
if not exists and error_details:
if error_details.startswith("AADSTS50053"):
exists = True
elif error_details.startswith("AADSTS50126"):
exists = True
elif error_details.startswith("AADSTS50076"):
exists = True
elif error_details.startswith("AADSTS700016"):
exists = True
elif error_details.startswith("AADSTS50034"):
exists = False
elif error_details.startswith("AADSTS50059"):
exists = False
elif error_details.startswith("AADSTS81016"):
print("Got Invalid STS request. The tenant may not have DesktopSSO or Directory Sync enabled.")
return None
else:
return None
return exists
def main():
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=textwrap.dedent('''\
examples:
graphpython.py --command invoke-reconasoutsider --domain company.com
graphpython.py --command invoke-userenumerationasoutsider --username <[email protected]/emails.txt>
graphpython.py --command get-graphtokens
graphpython.py --command invoke-refreshtoazuremanagementtoken --tenant <tenant-id> --token refresh-token
graphpython.py --command get-users --token eyJ0... -- select displayname,id [--id <userid>]
graphpython.py --command list-recentonedrivefiles --token token
graphpython.py --command invoke-search --search "credentials" --entity driveItem --token token
graphpython.py --command invoke-customquery --query https://graph.microsoft.com/v1.0/sites/{siteId}/drives --token token
graphpython.py --command assign-privilegedrole --token token
graphpython.py --command spoof-owaemailmessage [--id <userid to spoof>] --token token --email email-body.txt
graphpython.py --command get-manageddevices --token intune-token
graphpython.py --command deploy-maliciousscript --script malicious.ps1 --token token
graphpython.py --command backdoor-script --id <scriptid> --script backdoored-script.ps1 --token token
graphpython.py --command add-exclusiongrouptopolicy --id <policyid> --token token
graphpython.py --command reboot-device --id <deviceid> --token eyj0...
''')
)
parser.add_argument("--command", help="Command to execute")
parser.add_argument("--list-commands", action="store_true", help="List available commands")
parser.add_argument("--token", help="Microsoft Graph access token or refresh token for FOCI abuse")
parser.add_argument("--estsauthcookie", help="'ESTSAuth' or 'ESTSAuthPersistent' cookie value")
parser.add_argument("--use-cae", action="store_true", help="Flag to use Continuous Access Evaluation (CAE) - add 'cp1' as client claim to get an access token valid for 24 hours")
parser.add_argument("--cert", help="X509Certificate path (.pfx)")
parser.add_argument("--domain", help="Target domain")
parser.add_argument("--tenant", help="Target tenant ID")
parser.add_argument("--username", help="Username or file containing username (invoke-userenumerationasoutsider)")
parser.add_argument("--secret", help="Enterprise application secretText (invoke-appsecrettoaccesstoken)")
parser.add_argument("--id", help="ID of target object")
parser.add_argument("--select", help="Fields to select from output")
parser.add_argument("--query", help="Raw API query (GET only)")
parser.add_argument("--search", help="Search string")
parser.add_argument("--entity", choices=['driveItem', 'message', 'chatMessage', 'site', 'event'],help="Search entity type: driveItem(OneDrive), message(Mail), chatMessage(Teams), site(SharePoint), event(Calenders)")
parser.add_argument("--device", choices=['mac', 'windows', 'androidmobile', 'iphone'], help="Device type for User-Agent forging")
parser.add_argument("--browser", choices=['android', 'IE', 'chrome', 'firefox', 'edge', 'safari'], help="Browser type for User-Agent forging")
parser.add_argument("--only-return-cookies", action="store_true", help="Only return cookies from the request (open-owamailboxinbrowser)")
parser.add_argument("--mail-folder", choices=['allitems', 'inbox', 'archive', 'drafts', 'sentitems', 'deleteditems', 'recoverableitemsdeletions'], help="Mail folder to dump (dump-owamailbox)")
parser.add_argument("--top", type=int, help="Number (int) of messages to retrieve (dump-owamailbox)")
parser.add_argument("--script", help="File containing the script content (deploy-maliciousscript and backdoor-script)")
parser.add_argument("--email", help="File containing OWA email message body content (spoof-owaemailmessage)")
args = parser.parse_args()
if len(sys.argv) == 1:
parser.print_help()
sys.exit()
available_commands = [
"invoke-reconasoutsider","invoke-userenumerationasoutsider","get-graphtokens", "get-tenantid", "get-tokenscope", "decode-accesstoken",
"invoke-refreshtomsgraphtoken", "invoke-refreshtoazuremanagementtoken", "invoke-refreshtovaulttoken",
"invoke-refreshtomsteamstoken", "invoke-refreshtoofficeappstoken", "invoke-refreshtoofficemanagementtoken",
"invoke-refreshtooutlooktoken", "invoke-refreshtosubstratetoken", "invoke-refreshtoyammertoken", "invoke-refreshtointuneenrollment",
"invoke-refreshtoonedrivetoken", "invoke-refreshtosharepointtoken", "invoke-certtoaccesstoken", "invoke-estscookietoaccesstoken", "invoke-appsecrettoaccesstoken",
"new-signedjwt", "get-currentuser", "get-currentuseractivity", "get-orginfo", "get-domains", "get-user", "get-userproperties",
"get-userprivileges", "get-usertransitivegroupmembership", "get-group", "get-groupmember", "get-userapproleassignments", "get-serviceprincipalapproleassignments",
"get-conditionalaccesspolicy", "get-personalcontacts", "get-crosstenantaccesspolicy", "get-partnercrosstenantaccesspolicy",
"get-userchatmessages", "get-administrativeunitmember", "get-onedrivefiles", "get-userpermissiongrants", "get-oauth2permissiongrants",
"get-messages", "get-temporaryaccesspassword", "get-password", "list-authmethods", "list-directoryroles", "list-notebooks",
"list-conditionalaccesspolicies", "list-conditionalauthenticationcontexts", "list-conditionalnamedlocations", "list-sharepointroot",
"list-sharepointsites","list-sharepointurls", "list-externalconnections", "list-applications", "list-serviceprincipals", "list-tenants", "list-joinedteams",
"list-chats", "list-chatmessages", "list-devices", "list-administrativeunits", "list-onedrives", "list-recentonedrivefiles", "list-onedriveurls",
"list-sharedonedrivefiles", "invoke-customquery", "invoke-search", "find-privilegedroleusers", "find-updatablegroups", "find-dynamicgroups","find-securitygroups",
"locate-objectid", "update-userpassword", "add-applicationpassword", "add-usertap", "add-groupmember", "create-application",
"create-newuser", "invite-guestuser", "assign-privilegedrole", "open-owamailboxinbrowser", "dump-owamailbox", "spoof-owaemailmessage",
"delete-user", "delete-group", "remove-groupmember", "delete-application", "delete-device", "wipe-device", "retire-device",
"get-manageddevices", "get-userdevices", "get-caps", "get-devicecategories", "get-devicecompliancepolicies", "update-deviceconfig",
"get-devicecompliancesummary", "get-deviceconfigurations", "get-deviceconfigurationpolicies", "get-deviceconfigurationpolicysettings",
"get-deviceenrollmentconfigurations", "get-devicegrouppolicyconfigurations","update-userproperties", "dump-windowsapps", "dump-iosapps", "dump-androidapps",
"get-devicegrouppolicydefinition", "dump-devicemanagementscripts", "get-scriptcontent", "find-privilegedapplications", "dump-macosapps", "deploy-maliciousweblink",
"get-roledefinitions", "get-roleassignments", "display-avpolicyrules", "display-asrpolicyrules", "display-diskencryptionpolicyrules", "display-firewallconfigpolicyrules",
"display-firewallrulepolicyrules", "display-lapsaccountprotectionpolicyrules", "display-usergroupaccountprotectionpolicyrules", "get-appserviceprincipal",
"display-edrpolicyrules","add-exclusiongrouptopolicy", "deploy-maliciousscript", "reboot-device", "shutdown-device", "lock-device", "backdoor-script",
"add-applicationpermission", "new-signedjwt", "add-applicationcertificate", "get-application", "locate-permissionid", "get-serviceprincipal", "grant-appadminconsent"
]
properties = [
"aboutMe", "accountEnabled", "ageGroup", "assignedLicenses", "assignedPlans",
"birthday", "businessPhones", "city", "companyName", "consentProvidedForMinor",
"country", "createdDateTime", "department", "displayName", "employeeId",
"faxNumber", "givenName", "hireDate", "id", "imAddresses", "interests",
"isResourceAccount", "jobTitle", "lastPasswordChangeDateTime", "legalAgeGroupClassification",
"licenseAssignmentStates", "mail", "mailboxSettings", "mailNickname", "mobilePhone",
"mySite", "officeLocation", "onPremisesDistinguishedName", "onPremisesDomainName",
"onPremisesImmutableId", "onPremisesLastSyncDateTime", "onPremisesSecurityIdentifier",
"onPremisesSyncEnabled", "onPremisesSamAccountName", "onPremisesUserPrincipalName",
"otherMails", "passwordPolicies", "passwordProfile", "pastProjects", "preferredDataLocation",
"preferredLanguage", "preferredName", "proxyAddresses", "responsibilities",
"schools", "showInAddressList", "skills", "state", "streetAddress",
"surname", "usageLocation", "userPrincipalName", "userType", "webUrl"
]
roles = [
{"displayName": "Password Administrator", "roleTemplateId": "966707d0-3269-4727-9be2-8c3a10f19b9d", "description": "Can reset passwords for non-administrators and Password Administrators."},
{"displayName": "Global Reader", "roleTemplateId": "f2ef992c-3afb-46b9-b7cf-a126ee74c451", "description": "Can read everything that a Global Administrator can, but not update anything."},
{"displayName": "Directory Synchronization Accounts", "roleTemplateId": "d29b2b05-8046-44ba-8758-1e26182fcf32", "description": "Only used by Microsoft Entra Connect and Microsoft Entra Cloud Sync services."},
{"displayName": "Security Reader", "roleTemplateId": "5d6b6bb7-de71-4623-b4af-96380a352509", "description": "Can read security information and reports in Microsoft Entra ID and Office 365."},
{"displayName": "Privileged Authentication Administrator", "roleTemplateId": "7be44c8a-adaf-4e2a-84d6-ab2649e08a13", "description": "Can access to view, set and reset authentication method information for any user (admin or non-admin)."},
{"displayName": "Azure AD Joined Device Local Administrator", "roleTemplateId": "9f06204d-73c1-4d4c-880a-6edb90606fd8", "description": "Users with this role can locally administer Azure AD joined devices."},
{"displayName": "Authentication Administrator", "roleTemplateId": "c4e39bd9-1100-46d3-8c65-fb160da0071f", "description": "Can access to view, set and reset authentication method information for any non-admin user."},
{"displayName": "Groups Administrator", "roleTemplateId": "fdd7a751-b60b-444a-984c-02652fe8fa1c", "description": "Can manage all aspects of groups and group settings like naming and expiration policies."},
{"displayName": "Application Administrator", "roleTemplateId": "9b895d92-2cd3-44c7-9d02-a6ac2d5ea5c3", "description": "Can create and manage all aspects of app registrations and enterprise apps."},
{"displayName": "Helpdesk Administrator", "roleTemplateId": "729827e3-9c14-49f7-bb1b-9608f156bbb8", "description": "Can reset passwords for non-administrators and Helpdesk Administrators."},
{"displayName": "Directory Readers", "roleTemplateId": "88d8e3e3-8f55-4a1e-953a-9b9898b8876b", "description": "Can read basic directory information. Not intended for granting access to applications."},
{"displayName": "User Administrator", "roleTemplateId": "fe930be7-5e62-47db-91af-98c3a49a38b1", "description": "Can manage all aspects of users and groups, including resetting passwords for limited admins."},
{"displayName": "Global Administrator", "roleTemplateId": "62e90394-69f5-4237-9190-012177145e10", "description": "Can manage all aspects of Microsoft Entra ID and Microsoft services that use Microsoft Entra identities."},
{"displayName": "Intune Administrator", "roleTemplateId": "3a2c62db-5318-420d-8d74-23affee5d9d5", "description": "Can manage all aspects of the Intune product."},
{"displayName": "Application Developer", "roleTemplateId": "cf1c38e5-3621-4004-a7cb-879624dced7c", "description": "Can create application registrations independent of the 'Users can register applications' setting."},
{"displayName": "Authentication Extensibility Administrator", "roleTemplateId": "25a516ed-2fa0-40ea-a2d0-12923a21473a", "description": "Customize sign in and sign up experiences for users by creating and managing custom authentication extensions."},
{"displayName": "B2C IEF Keyset Administrator", "roleTemplateId": "aaf43236-0c0d-4d5f-883a-6955382ac081", "description": "Can manage secrets for federation and encryption in the Identity Experience Framework (IEF)."},
{"displayName": "Cloud Application Administrator", "roleTemplateId": "158c047a-c907-4556-b7ef-446551a6b5f7", "description": "Can create and manage all aspects of app registrations and enterprise apps except App Proxy."},
{"displayName": "Cloud Device Administrator", "roleTemplateId": "7698a772-787b-4ac8-901f-60d6b08affd2", "description": "Limited access to manage devices in Microsoft Entra ID."},
{"displayName": "Conditional Access Administrator", "roleTemplateId": "b1be1c3e-b65d-4f19-8427-f6fa0d97feb9", "description": "Can manage Conditional Access capabilities."},
{"displayName": "Directory Writers", "roleTemplateId": "9360feb5-f418-4baa-8175-e2a00bac4301", "description": "Can read and write basic directory information. For granting access to applications, not intended for users."},
{"displayName": "Domain Name Administrator", "roleTemplateId": "8329153b-31d0-4727-b945-745eb3bc5f31", "description": "Can manage domain names in cloud and on-premises."},
{"displayName": "External Identity Provider Administrator", "roleTemplateId": "be2f45a1-457d-42af-a067-6ec1fa63bc45", "description": "Can configure identity providers for use in direct federation."},
{"displayName": "Hybrid Identity Administrator", "roleTemplateId": "8ac3fc64-6eca-42ea-9e69-59f4c7b60eb2", "description": "Manage Active Directory to Microsoft Entra cloud provisioning, Microsoft Entra Connect, pass-through authentication (PTA), password hash synchronization (PHS), seamless single sign-on (seamless SSO), and federation settings. Does not have access to manage Microsoft Entra Connect Health."},
{"displayName": "Lifecycle Workflows Administrator", "roleTemplateId": "59d46f88-662b-457b-bceb-5c3809e5908f", "description": "Create and manage all aspects of workflows and tasks associated with Lifecycle Workflows in Microsoft Entra ID."},
{"displayName": "Privileged Role Administrator", "roleTemplateId": "e8611ab8-c189-46e8-94e1-60213ab1f814", "description": "Can manage role assignments in Microsoft Entra ID, and all aspects of Privileged Identity Management."},
{"displayName": "Security Administrator", "roleTemplateId": "194ae4cb-b126-40b2-bd5b-6091b380977d", "description": "Can read security information and reports, and manage configuration in Microsoft Entra ID and Office 365."},
{"displayName": "Security Operator", "roleTemplateId": "5f2222b1-57c3-48ba-8ad5-d4759f1fde6f", "description": "Creates and manages security events."}
]
if args.list_commands:
list_commands()
return
if args.command and args.command.lower() in [
"invoke-refreshtomsgraphtoken", "invoke-refreshtoazuremanagementtoken",
"invoke-refreshtovaulttoken", "invoke-refreshtomsteamstoken",
"invoke-refreshtoofficeappstoken", "invoke-refreshtoofficemanagementtoken",
"invoke-refreshtooutlooktoken","invoke-refreshtosubstratetoken", "invoke-refreshtoyammertoken",
"invoke-refreshtointuneenrollmenttoken", "invoke-refreshtoonedrivetoken", "invoke-refreshtosharepointtoken",
"get-tokenscope", "decode-accesstoken", "get-manageddevices", "get-userdevices", "get-user",
"get-userproperties", "get-userprivileges", "get-usertransitivegroupmembership", "get-group",
"get-groupmember", "get-userapproleassignments", "get-conditionalaccesspolicy", "get-personalcontacts",
"get-crosstenantaccesspolicy", "get-partnercrosstenantaccesspolicy", "get-userchatmessages",
"get-administrativeunitmember", "get-onedrivefiles", "get-userpermissiongrants", "get-oauth2permissiongrants",
"get-messages", "get-temporaryaccesspassword", "get-password", "get-currentuser",
"get-currentuseractivities", "get-orginfo", "get-domains", "list-authmethods", "list-directoryroles",
"list-notebooks", "list-conditionalaccesspolicies", "list-conditionalauthenticationcontexts",
"list-conditionalnamedlocations", "list-sharepointroot", "list-sharepointsites", "list-sharepointurls","list-externalconnections",
"list-applications", "list-serviceprincipals", "list-tenants", "list-joinedteams", "list-chats", "deploy-maliciousweblink",
"list-chatmessages", "list-devices", "list-administrativeunits", "list-onedrives", "list-recentonedrivefiles", "list-onedriveurls",
"list-sharedonedrivefiles", "invoke-customquery", "invoke-search", "find-privilegedroleusers", "display-firewallconfigpolicyrules",
"find-updatablegroups", "find-dynamicgroups","find-securitygroups", "locate-objectid", "update-userpassword", "add-applicationpassword",
"add-usertap", "add-groupmember", "create-application", "create-newuser", "invite-guestuser", "update-deviceconfig",
"assign-privilegedrole", "open-owamailboxinbrowser", "dump-owamailbox", "spoof-owaemailmessage", "dump-androidapps",
"delete-user", "delete-group", "remove-groupmember", "delete-application", "delete-device", "wipe-device", "retire-device",
"get-caps", "get-devicecategories", "display-devicecompliancepolicies", "get-devicecompliancesummary", "dump-macosapps",
"get-deviceconfigurations", "get-deviceconfigurationpolicies", "get-deviceconfigurationpolicysettings", "dump-iosapps",
"get-deviceenrollmentconfigurations", "get-devicegrouppolicyconfigurations", "grant-appadminconsent", "dump-windowsapps",
"get-devicegrouppolicydefinition", "dump-devicemanagementscripts", "update-userproperties", "find-privilegedapplications",
"get-scriptcontent", "get-roledefinitions", "get-roleassignments", "display-avpolicyrules","get-appserviceprincipal",
"display-asrpolicyrules", "display-diskencryptionpolicyrules", "display-firewallrulepolicyrules", "backdoor-script",
"display-edrpolicyrules", "display-lapsaccountprotectionpolicyrules", "display-usergroupaccountprotectionpolicyrules",
"add-exclusiongrouptopolicy","deploy-maliciousscript", "reboot-device", "add-applicationpermission", "new-signedjwt",
"add-applicationcertificate", "get-application", "get-serviceprincipal", "get-serviceprincipalapproleassignments"]:
if not args.token:
print_red(f"[-] Error: --token is required for command")
return
access_token = get_access_token(args.token)
elif args.command and args.command.lower() not in available_commands:
print_red(f"[-] Error: Unknown command '{args.command}'. Use --list-commands to see available commands")
############
# Outsider #
############
# invoke-reconasoutsider
elif args.command and args.command.lower() == "invoke-reconasoutsider":
if not args.domain:
print_red("[-] Error: --domain argument is required for Invoke-ReconAsOutsider command")
return
print_yellow("\n[*] Invoke-ReconAsOutsider")
print("=" * 80)
domain = args.domain
# get tenant id
tenant_id = ""
try:
response = requests.get(f"https://login.microsoftonline.com/{domain}/.well-known/openid-configuration")
if response.status_code == 200:
tenant_id = response.json().get('token_endpoint', '').split('/')[3]
except:
print_red("[-] Failed to retrieve tenant ID")
if not tenant_id:
print_red(f"[-] Domain {domain} is not registered to Azure AD")
print("=" * 80)
return
tenant_name = ""
tenant_brand = ""
tenant_region = ""
tenant_sso = ""
# tenant info
try:
response = requests.get(f"https://login.microsoftonline.com/{domain}/.well-known/openid-configuration")
if response.status_code == 200:
data = response.json()
tenant_region = data.get('tenant_region_scope', "Unknown")
except:
print_red("[-] Failed to retrieve tenant info")
additional_domains = get_tenant_domains(domain)
additional_domains_count = len(additional_domains)
print(f"Domains: {additional_domains_count}")
domain_information = []
# show progress bar
custom_bar = '╢{bar:50}╟'
for domain in tqdm((additional_domains),bar_format='{l_bar}'+custom_bar+'{r_bar}', leave=False, colour='yellow'):
if domain.lower().endswith('.onmicrosoft.com') and not tenant_name:
tenant_name = domain
# desktop sso
if not tenant_sso:
try:
url = f"https://autologon.microsoftazuread-sso.com/{domain}/winauth/trust/2005/usernamemixed?client-request-id={'0' * 32}"
response = requests.get(url)
tenant_sso = response.status_code == 401
except:
pass
# DNS checks
exists = False
has_cloud_mx = False
has_cloud_spf = False
has_dmarc = False
has_cloud_dkim = False
has_cloud_mta_sts = False
try:
dns.resolver.resolve(domain)
exists = True
except:
pass
if exists:
try:
mx_records = dns.resolver.resolve(domain, 'MX')
has_cloud_mx = any('mail.protection.outlook.com' in str(mx.exchange) for mx in mx_records)
except:
pass
try:
txt_records = dns.resolver.resolve(domain, 'TXT')
has_cloud_spf = any('v=spf1' in str(record) and 'include:spf.protection.outlook.com' in str(record) for record in txt_records)
except:
pass
try:
dmarc_records = dns.resolver.resolve(f'_dmarc.{domain}', 'TXT')
has_dmarc = any('v=DMARC1' in str(record) for record in dmarc_records)
except:
pass
try:
selectors = ["selector1", "selector2"]
for selector in selectors:
dkim_records = dns.resolver.resolve(f'{selector}._domainkey.{domain}', 'CNAME')
has_cloud_dkim = any('onmicrosoft.com' in str(record) for record in dkim_records)
if has_cloud_dkim:
break
except:
pass
try:
url = f"https://mta-sts.{domain}/.well-known/mta-sts.txt"
mta_sts_response = requests.get(url)
if mta_sts_response.status_code == 200:
mta_sts_content = mta_sts_response.text
mta_sts_lines = mta_sts_content.split("\n")
has_cloud_mta_sts = any("version: STSv1" in line for line in mta_sts_lines) and any("mx: *.mail.protection.outlook.com" in line for line in mta_sts_lines)
except:
pass
# federation info
user_realm = {}
try:
username = f"nn@{domain}"
response = requests.get(f"https://login.microsoftonline.com/GetUserRealm.srf?login={username}")
if response.status_code == 200:
user_realm = response.json()
except:
print_red("[-] Failed to retrieve user realm information") # pass
if not tenant_brand:
tenant_brand = user_realm.get("FederationBrandName", "")
auth_url = user_realm.get("AuthURL")
if auth_url:
auth_url = auth_url.split('?')[0]
domain_info = {
"Name": domain,
"DNS": exists,
"MX": has_cloud_mx,
"SPF": has_cloud_spf,
"DMARC": has_dmarc,
"DKIM": has_cloud_dkim,
"MTA-STS": has_cloud_mta_sts,
"Type": user_realm.get("NameSpaceType", "Unknown"),
"STS": auth_url
}
domain_information.append(domain_info)
print(f"Tenant brand: {tenant_brand}")
print(f"Tenant name: {tenant_name}")
print(f"Tenant id: {tenant_id}")
print(f"Tenant region: {tenant_region}")
if tenant_sso is not None:
print(f"DesktopSSO enabled: {tenant_sso}")
if tenant_name:
# check MDI instance
tenant = tenant_name.split('.')[0] if '.' in tenant_name else tenant_name
mdi_domains = [
f"{tenant}.atp.azure.com",
f"{tenant}-onmicrosoft-com.atp.azure.com"
]
tenant_mdi = None
for mdi_domain in mdi_domains:
try:
dns.resolver.resolve(mdi_domain)
tenant_mdi = mdi_domain
break
except dns.resolver.NXDOMAIN:
continue
except Exception as e:
print(f"An error occurred while resolving {mdi_domain}: {str(e)}")
if tenant_mdi:
print(f"MDI instance: {tenant_mdi}")
else:
print("MDI instance: Not found")
# check cloud sync
if tenant_name:
sync_service_account = f"ADToAADSyncServiceAccount@{tenant_name}"
exists = None
try:
url = "https://login.microsoftonline.com/common/GetCredentialType"
data = {
"username": sync_service_account,
"isOtherIdpSupported": True,
"checkPhones": False,
"isRemoteNGCSupported": True,
"isCookieBannerShown": False,
"isFidoSupported": True,
"originalRequest": "",
"country": "US",
"forceotclogin": False,
"isExternalFederationDisallowed": False,
"isRemoteConnectSupported": False,
"federationFlags": 0,
"isSignup": False,
"flowToken": "",
"isAccessPassSupported": True
}
response = requests.post(url, json=data)
if response.status_code == 200:
result = response.json()
exists = result.get('IfExistsResult', 0) == 0
except:
pass
uses_cloud_sync = exists
print(f"Uses cloud sync: {uses_cloud_sync}")
print("\nName DNS MX SPF DMARC DKIM MTA-STS Type STS")
print("---- --- --- ---- ----- ---- ------- ---- ---")
for domain_info in domain_information:
print(f"{domain_info['Name']:<42} {str(domain_info['DNS']):<5} {str(domain_info['MX']):<5} {str(domain_info['SPF']):<6} {str(domain_info['DMARC']):<7} {str(domain_info['DKIM']):<6} {str(domain_info['MTA-STS']):<8} {domain_info['Type']:<11} {domain_info['STS'] or ''}")
print("=" * 80)
# invoke-userenumerationasoutsider
# - only uses Normal method from Killchain.ps1
elif args.command and args.command.lower() == "invoke-userenumerationasoutsider":
if not args.username:
print_red("[-] Error: --username argument is required for Invoke-UserEnumerationAsOutsider command")
return
print_yellow("\n[*] Invoke-UserEnumerationAsOutsider")
print("=" * 80)
usernames = []