-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathateam.py
More file actions
1211 lines (1054 loc) · 240 KB
/
ateam.py
File metadata and controls
1211 lines (1054 loc) · 240 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 sqlite3
import requests
import dns.resolver
import concurrent.futures
import logging
from typing import List, Optional, Dict
from urllib.parse import urlparse
import json
import time
import re
import argparse
import sys
import csv
from datetime import datetime
import urllib3
import os
# Configure logging
logging.basicConfig(
level=logging.INFO, # Set root logger to INFO by default
format='%(asctime)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO) # Set this specific logger to INFO by default
# Suppress only the single InsecureRequestWarning
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
class AzureTenantFinder:
def __init__(self, db_path: str = "azure_tenants.db", verbose: bool = False):
"""Initialize the Azure Tenant Finder with SQLite database."""
self.db_path = db_path
if verbose:
logger.setLevel(logging.DEBUG)
self._init_db()
def _init_db(self):
"""Initialize SQLite database with required tables."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS resource_info (
id INTEGER PRIMARY KEY AUTOINCREMENT,
resource_uri TEXT NOT NULL,
resource_type TEXT NOT NULL,
tenant_id TEXT,
company_display_name TEXT,
discovered_at TIMESTAMP DEFAULT (datetime('now', 'localtime')),
UNIQUE(resource_uri)
)
''')
conn.commit()
# Constants for reuse
NULL_TENANT_ID = '00000000-0000-0000-0000-000000000000'
DEVOPS_POTENTIAL_HEADERS = [
'X-VSS-ResourceTenant',
'X-TFS-FedAuthIssuer',
'X-VSS-AuthorizationEndpoint',
'X-TFS-ServiceError',
'X-TFS-FedAuthRealm',
'X-TFS-FedAuthRedirect'
]
def _extract_tenant_from_www_authenticate(self, auth_header: str, key: str = 'authorization_uri', index: int = 3) -> Optional[str]:
"""Extract tenant ID from WWW-Authenticate header."""
try:
if f'{key}="' in auth_header:
auth_uri = auth_header.split(f'{key}="')[1].split('"')[0]
tenant_id = auth_uri.split('/')[index]
if tenant_id and tenant_id != self.NULL_TENANT_ID:
return tenant_id
elif f'{key}=' in auth_header:
auth_uri = auth_header.split(f'{key}=')[1].split(' ')[0]
tenant_id = auth_uri.split('/')[index]
if tenant_id and tenant_id != self.NULL_TENANT_ID:
return tenant_id
except Exception as e:
self._log_exception_details(e, 'extract_tenant_from_www_authenticate')
return None
def _extract_tenant_from_oauth_redirect(self, location: str) -> Optional[str]:
"""Extract tenant ID from OAuth redirect URL."""
try:
if 'login.microsoftonline.com' in location:
tenant_id = location.split('login.microsoftonline.com/')[1].split('/')[0]
if tenant_id and tenant_id != 'common' and len(tenant_id) == 36:
return tenant_id
except Exception as e:
self._log_exception_details(e, 'extract_tenant_from_oauth_redirect')
return None
def _validate_tenant_id(self, tenant_id: str) -> bool:
return tenant_id and tenant_id != self.NULL_TENANT_ID and tenant_id != 'common'
def _extract_company_display_name(self, tenant_id: str) -> Optional[str]:
"""Extract company display name from Microsoft's login page for a given tenant ID.
Args:
tenant_id: The tenant ID to lookup
Returns:
Optional[str]: The company display name if found, None otherwise
"""
if not tenant_id or tenant_id == 'common' or tenant_id == self.NULL_TENANT_ID:
return None
try:
# Use the same client_id from the sample request
client_id = "966dc5e4-3e67-44a4-9fa5-7b3959808439"
url = f"https://login.microsoftonline.com/{tenant_id}/adminconsent?client_id={client_id}&sso_reload=true"
logger.debug(f"Looking up company display name for tenant {tenant_id}")
headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate, br',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1'
}
response = requests.get(url, headers=headers, timeout=10, verify=False)
if response.status_code == 200:
content = response.text
# Look for the sCompanyDisplayName in the response
import re
pattern = r'"sCompanyDisplayName"\s*:\s*"([^"]+)"'
match = re.search(pattern, content)
if match:
company_name = match.group(1)
# Decode HTML entities
import html
company_name = html.unescape(company_name)
# Handle double-escaped Unicode sequences
if '\\u' in company_name:
company_name = company_name.encode('utf-8').decode('unicode_escape')
logger.debug(f"Found company display name '{company_name}' for tenant {tenant_id}")
return company_name
else:
logger.debug(f"No company display name found in response for tenant {tenant_id}")
else:
logger.debug(f"HTTP {response.status_code} when looking up company display name for tenant {tenant_id}")
except Exception as e:
self._log_exception_details(e, f'extract_company_display_name for tenant {tenant_id}')
return None
def _log_exception_details(self, exception, context: str = None):
logger.debug(f"Exception in {context if context else ''}: {str(exception)}")
logger.debug(f"Exception type: {type(exception)}")
logger.debug(f"Exception args: {exception.args}")
import traceback
logger.debug(f"Stack trace: {traceback.format_exc()}")
def _check_dns(self, lookup: str) -> bool:
"""Check if a DNS record exists for the given lookup string.
Args:
lookup: The DNS name to check
Returns:
bool: True if DNS record exists, False otherwise
"""
logger.debug(f"Checking DNS record: {lookup}")
try:
answers = dns.resolver.resolve(lookup, 'A')
logger.debug(f"DNS record found for {lookup}. IP addresses: {[str(rdata) for rdata in answers]}")
return True
except dns.resolver.NXDOMAIN:
logger.debug(f"No DNS record found for {lookup}")
return False
except Exception as e:
logger.debug(f"DNS resolution error for {lookup}: {str(e)}")
return False
def check_app_services(self, resource: str) -> Optional[str]:
"""Check for Azure App Services and extract tenant ID."""
try:
lookup = f"{resource}.scm.azurewebsites.net"
if not self._check_dns(lookup):
return None
base_tenant_id = None
scm_tenant_id = None
main_url = f"https://{resource}.azurewebsites.net"
logger.debug(f"Checking main App Service URL: {main_url}")
try:
response = requests.get(main_url, allow_redirects=False, timeout=10)
logger.debug(f"Main App Service response status: {response.status_code}")
logger.debug(f"Main App Service response headers: {dict(response.headers)}")
if response.status_code in [301, 302, 307, 308] and 'Location' in response.headers:
location = response.headers['Location']
logger.debug(f"Found redirect Location header: {location}")
tenant_id = self._extract_tenant_from_oauth_redirect(location)
if self._validate_tenant_id(tenant_id):
self._save_resource(f"{resource}.azurewebsites.net", "AppServices-Base", tenant_id)
logger.info(f"Found App Service base URL tenant ID {tenant_id} for {resource} via OAuth flow")
base_tenant_id = tenant_id
if response.status_code == 401 and 'WWW-Authenticate' in response.headers:
auth_header = response.headers['WWW-Authenticate']
logger.debug(f"Found WWW-Authenticate header: {auth_header}")
if 'Bearer' in auth_header:
tenant_id = self._extract_tenant_from_www_authenticate(auth_header, key='authorization_uri', index=3)
if tenant_id and 'login.microsoftonline.com' in auth_header:
tenant_id = self._extract_tenant_from_oauth_redirect(auth_header)
if self._validate_tenant_id(tenant_id):
self._save_resource(f"{resource}.azurewebsites.net", "AppServices-Base", tenant_id)
logger.info(f"Found App Service base URL tenant ID {tenant_id} for {resource} via Bearer challenge")
base_tenant_id = tenant_id
except requests.exceptions.RequestException as e:
logger.debug(f"Main App Service request error: {str(e)}")
if hasattr(e, 'response') and e.response is not None:
logger.debug(f"Error response status: {e.response.status_code}")
logger.debug(f"Error response headers: {dict(e.response.headers)}")
if 'Location' in e.response.headers:
location = e.response.headers['Location']
tenant_id = self._extract_tenant_from_oauth_redirect(location)
if self._validate_tenant_id(tenant_id):
self._save_resource(f"{resource}.azurewebsites.net", "AppServices-Base", tenant_id)
logger.info(f"Found App Service base URL tenant ID {tenant_id} for {resource} via OAuth error redirect")
base_tenant_id = tenant_id
url = f"https://{resource}.scm.azurewebsites.net/"
logger.debug(f"Checking App Service SCM URL: {url}")
try:
response = requests.head(url, allow_redirects=False, timeout=10)
logger.debug(f"App Service SCM response status: {response.status_code}")
logger.debug(f"App Service SCM response headers: {dict(response.headers)}")
if 'Location' in response.headers:
location = response.headers['Location']
logger.debug(f"Found Location header: {location}")
try:
tenant_id = location.split('/')[3]
logger.debug(f"Extracted potential tenant ID from Location header: {tenant_id}")
if tenant_id and (tenant_id == 'common' or (len(tenant_id) == 36 and tenant_id != self.NULL_TENANT_ID)):
self._save_resource(f"{resource}.scm.azurewebsites.net", "AppServices-SCM", tenant_id)
logger.info(f"Found App Services SCM tenant ID {tenant_id} for {resource}")
scm_tenant_id = tenant_id
except (IndexError, AttributeError) as e:
self._log_exception_details(e, 'extract_tenant_id_from_location_header')
if response.status_code == 401 and 'WWW-Authenticate' in response.headers:
auth_header = response.headers['WWW-Authenticate']
logger.debug(f"Found WWW-Authenticate header: {auth_header}")
if auth_header.startswith('Basic'):
logger.debug("Basic authentication challenge detected - this is an App Service")
self._save_resource(f"{resource}.scm.azurewebsites.net", "AppServices-SCM", "common")
logger.info(f"Found App Service SCM tenant ID 'common' for {resource}")
if not scm_tenant_id:
scm_tenant_id = "common"
except requests.exceptions.RequestException as e:
logger.debug(f"App Service SCM request error for {url}: {str(e)}")
if hasattr(e, 'response') and e.response is not None:
logger.debug(f"Error response status: {e.response.status_code}")
logger.debug(f"Error response headers: {dict(e.response.headers)}")
if 'Location' in e.response.headers:
location = e.response.headers['Location']
logger.debug(f"Found Location header in error response: {location}")
try:
tenant_id = location.split('/')[3]
logger.debug(f"Extracted potential tenant ID from error response Location header: {tenant_id}")
if tenant_id and (tenant_id == 'common' or (len(tenant_id) == 36 and tenant_id != self.NULL_TENANT_ID)):
self._save_resource(f"{resource}.scm.azurewebsites.net", "AppServices-SCM", tenant_id)
logger.info(f"Found App Services SCM tenant ID {tenant_id} for {resource}")
scm_tenant_id = tenant_id
except (IndexError, AttributeError) as e:
self._log_exception_details(e, 'extract_tenant_id_from_error_location_header')
if e.response.status_code == 401 and 'WWW-Authenticate' in e.response.headers:
auth_header = e.response.headers['WWW-Authenticate']
logger.debug(f"Found WWW-Authenticate header in error response: {auth_header}")
if auth_header.startswith('Basic'):
logger.debug("Basic authentication challenge detected in error response - this is an App Service")
self._save_resource(f"{resource}.scm.azurewebsites.net", "AppServices-SCM", "common")
logger.info(f"Found App Service SCM tenant ID 'common' for {resource}")
if not scm_tenant_id:
scm_tenant_id = "common"
except Exception as e:
self._log_exception_details(e, 'check_app_services')
if base_tenant_id and base_tenant_id != 'common':
return base_tenant_id
elif scm_tenant_id and scm_tenant_id != 'common':
return scm_tenant_id
elif base_tenant_id:
return base_tenant_id
else:
return scm_tenant_id
def check_devops(self, resource: str) -> Optional[str]:
"""Check for Azure DevOps and extract tenant ID."""
try:
url = f"https://dev.azure.com/{resource}/_apis/Contribution/HierarchyQuery"
logger.debug(f"Checking DevOps URL: {url}")
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-TFS-FedAuthRedirect': 'Suppress',
'X-TFS-Session': resource
}
data = {
"contributionIds": ["ms.vss-features.my-organizations-data-provider"],
"dataProviderContext": {"properties": {}}
}
response = requests.post(url, headers=headers, json=data, timeout=10, verify=False)
logger.debug(f"Initial response status: {response.status_code}")
logger.debug(f"Response headers: {dict(response.headers)}")
for header in self.DEVOPS_POTENTIAL_HEADERS:
if header in response.headers:
value = response.headers[header]
logger.debug(f"Found header {header}: {value}")
if header == 'X-VSS-ResourceTenant' and value != self.NULL_TENANT_ID:
tenant_id = value
self._save_resource(f"dev.azure.com/{resource}", "DevOps", tenant_id)
logger.info(f"Found DevOps tenant ID {tenant_id} for {resource}")
return tenant_id
elif 'microsoftonline.com' in value:
tenant_id = value.split('/')[-1]
if tenant_id and tenant_id != 'dev.azure.com':
self._save_resource(f"dev.azure.com/{resource}", "DevOps", tenant_id)
logger.info(f"Found DevOps tenant ID {tenant_id} for {resource}")
return tenant_id
elif header == 'X-TFS-FedAuthRedirect' and 'microsoftonline.com' in value:
try:
from urllib.parse import urlparse, parse_qs
parsed = urlparse(value)
params = parse_qs(parsed.fragment.split('#')[0])
if 'ctx' in params:
ctx = params['ctx'][0]
if 'microsoftonline.com' in ctx:
tenant_id = ctx.split('microsoftonline.com/')[1].split('"')[0]
if tenant_id and tenant_id != 'dev.azure.com':
self._save_resource(f"dev.azure.com/{resource}", "DevOps", tenant_id)
logger.info(f"Found DevOps tenant ID {tenant_id} for {resource}")
return tenant_id
except Exception as e:
self._log_exception_details(e, 'devops_redirect_url_parse')
if response.status_code in [401, 403]:
auth_header = response.headers.get('WWW-Authenticate', '')
logger.debug(f"WWW-Authenticate header: {auth_header}")
if 'Bearer' in auth_header:
tenant_id = self._extract_tenant_from_www_authenticate(auth_header, key='authorization_uri', index=-1)
if tenant_id and tenant_id != 'dev.azure.com':
self._save_resource(f"dev.azure.com/{resource}", "DevOps", tenant_id)
logger.info(f"Found DevOps tenant ID {tenant_id} for {resource}")
return tenant_id
url = f"https://{resource}.vssps.visualstudio.com/_apis/Token/SessionToken"
logger.debug(f"Checking VSSPS URL: {url}")
response = requests.get(url, headers=headers, timeout=10, verify=False)
logger.debug(f"VSSPS response status: {response.status_code}")
logger.debug(f"VSSPS response headers: {dict(response.headers)}")
for header in self.DEVOPS_POTENTIAL_HEADERS:
if header in response.headers:
value = response.headers[header]
logger.debug(f"Found header {header}: {value}")
if header == 'X-VSS-ResourceTenant' and value != self.NULL_TENANT_ID:
tenant_id = value
self._save_resource(f"dev.azure.com/{resource}", "DevOps", tenant_id)
logger.info(f"Found DevOps tenant ID {tenant_id} for {resource}")
return tenant_id
elif 'microsoftonline.com' in value:
tenant_id = value.split('/')[-1]
if tenant_id and tenant_id != 'dev.azure.com':
self._save_resource(f"dev.azure.com/{resource}", "DevOps", tenant_id)
logger.info(f"Found DevOps tenant ID {tenant_id} for {resource}")
return tenant_id
except requests.exceptions.RequestException as e:
logger.debug(f"DevOps request failed for {resource}: {str(e)}")
if hasattr(e, 'response') and e.response is not None and hasattr(e.response, 'headers'):
headers = e.response.headers
logger.debug(f"Response headers: {dict(headers)}")
for header in self.DEVOPS_POTENTIAL_HEADERS:
if header in headers:
value = headers[header]
logger.debug(f"Found header {header}: {value}")
if header == 'X-VSS-ResourceTenant' and value != self.NULL_TENANT_ID:
tenant_id = value
self._save_resource(f"dev.azure.com/{resource}", "DevOps", tenant_id)
logger.info(f"Found DevOps tenant ID {tenant_id} for {resource}")
return tenant_id
elif 'microsoftonline.com' in value:
tenant_id = value.split('/')[-1]
if tenant_id and tenant_id != 'dev.azure.com':
self._save_resource(f"dev.azure.com/{resource}", "DevOps", tenant_id)
logger.info(f"Found DevOps tenant ID {tenant_id} for {resource}")
return tenant_id
auth_header = headers.get('WWW-Authenticate', '')
logger.debug(f"WWW-Authenticate header: {auth_header}")
if 'Bearer' in auth_header:
tenant_id = self._extract_tenant_from_www_authenticate(auth_header, key='authorization_uri', index=-1)
if tenant_id and tenant_id != 'dev.azure.com':
self._save_resource(f"dev.azure.com/{resource}", "DevOps", tenant_id)
logger.info(f"Found DevOps tenant ID {tenant_id} for {resource}")
return tenant_id
except Exception as e:
self._log_exception_details(e, 'check_devops')
return None
def check_sharepoint(self, resource: str) -> Optional[str]:
"""Check for SharePoint Online and extract tenant ID."""
try:
lookup = f"{resource}.sharepoint.com"
if not self._check_dns(lookup):
return None
url = f"https://{resource}.sharepoint.com/_vti_bin/client.svc"
headers = {
'Authorization': 'Bearer',
'Accept': 'application/json'
}
try:
response = requests.get(url, headers=headers, timeout=10)
if 'WWW-Authenticate' in response.headers:
auth_header = response.headers['WWW-Authenticate']
if 'Bearer realm="' in auth_header:
try:
tenant_id = auth_header.split('Bearer realm="')[1].split('"')[0]
if self._validate_tenant_id(tenant_id):
self._save_resource(f"{resource}.sharepoint.com", "SharePoint", tenant_id)
logger.info(f"Found SharePoint tenant ID {tenant_id} for {resource}")
return tenant_id
except Exception as e:
self._log_exception_details(e, 'sharepoint_bearer_realm_parse')
except Exception as e:
self._log_exception_details(e, 'sharepoint_client_svc')
url = f"https://{resource}.sharepoint.com/_forms/default.aspx"
try:
response = requests.get(url, timeout=10)
logger.debug(f"Response headers for {resource}: {dict(response.headers)}")
if 'X-MS-CobaltId' in response.headers:
tenant_id = response.headers['X-MS-CobaltId']
if self._validate_tenant_id(tenant_id):
self._save_resource(f"{resource}.sharepoint.com", "SharePoint", tenant_id)
logger.info(f"Found SharePoint tenant ID {tenant_id} for {resource}")
return tenant_id
except Exception as e:
self._log_exception_details(e, 'sharepoint_default_aspx')
except Exception as e:
self._log_exception_details(e, 'check_sharepoint')
return None
def check_key_vault(self, resource: str) -> Optional[str]:
"""Check for Azure Key Vault and extract tenant ID."""
try:
lookup = f"{resource}.vault.azure.net"
if not self._check_dns(lookup):
return None
url = f"https://{resource}.vault.azure.net/keys"
logger.debug(f"Checking Key Vault URL: {url}")
try:
response = requests.head(url, headers={"x-ms-version": "2019-12-12"}, timeout=5, verify=False)
logger.debug(f"Key Vault response status: {response.status_code}")
logger.debug(f"Key Vault response headers: {dict(response.headers)}")
if 'WWW-Authenticate' in response.headers:
auth_header = response.headers['WWW-Authenticate']
tenant_id = self._extract_tenant_from_www_authenticate(auth_header, key='authorization', index=-1)
if self._validate_tenant_id(tenant_id):
self._save_resource(f"{resource}.vault.azure.net", "KeyVault", tenant_id)
logger.info(f"Found Key Vault tenant ID {tenant_id} for {resource}")
return tenant_id
except requests.exceptions.RequestException as e:
if hasattr(e, 'response') and e.response is not None:
logger.debug(f"Key Vault error response status: {e.response.status_code}")
logger.debug(f"Key Vault error response headers: {dict(e.response.headers)}")
if 'WWW-Authenticate' in e.response.headers:
auth_header = e.response.headers['WWW-Authenticate']
tenant_id = self._extract_tenant_from_www_authenticate(auth_header, key='authorization', index=-1)
if self._validate_tenant_id(tenant_id):
self._save_resource(f"{resource}.vault.azure.net", "KeyVault", tenant_id)
logger.info(f"Found Key Vault tenant ID {tenant_id} for {resource}")
return tenant_id
else:
self._log_exception_details(e, 'key_vault_request')
except Exception as e:
self._log_exception_details(e, 'check_key_vault')
return None
def check_storage_account(self, resource: str) -> Optional[str]:
"""Check for Azure Storage Account and extract tenant ID."""
logger.debug(f"Entering check_storage_account for {resource}")
try:
lookup = f"{resource}.blob.core.windows.net"
if not self._check_dns(lookup):
return None
url = f"https://{resource}.blob.core.windows.net/?comp=blobs"
logger.debug(f"Checking Storage Account URL: {url}")
try:
response = requests.get(url, headers={"x-ms-version": "2019-12-12"}, timeout=5, verify=False)
logger.debug(f"Storage Account response status: {response.status_code}")
logger.debug(f"Storage Account response headers: {dict(response.headers)}")
if response.status_code == 401 and 'WWW-Authenticate' in response.headers:
auth_header = response.headers['WWW-Authenticate']
tenant_id = self._extract_tenant_from_www_authenticate(auth_header, key='authorization_uri', index=3)
if self._validate_tenant_id(tenant_id):
self._save_resource(f"{resource}.blob.core.windows.net", "StorageAccount", tenant_id)
logger.info(f"Found Storage Account tenant ID {tenant_id} for {resource}")
return tenant_id
except requests.exceptions.RequestException as e:
if hasattr(e, 'response') and e.response is not None:
logger.debug(f"Storage Account error response status: {e.response.status_code}")
logger.debug(f"Storage Account error response headers: {dict(e.response.headers)}")
if 'WWW-Authenticate' in e.response.headers:
auth_header = e.response.headers['WWW-Authenticate']
tenant_id = self._extract_tenant_from_www_authenticate(auth_header, key='authorization_uri', index=3)
if self._validate_tenant_id(tenant_id):
self._save_resource(f"{resource}.blob.core.windows.net", "StorageAccount", tenant_id)
logger.info(f"Found Storage Account tenant ID {tenant_id} for {resource}")
return tenant_id
else:
# Try alternate endpoint
url = f"https://{resource}.blob.core.windows.net/?restype=service&comp=properties"
logger.debug(f"Checking alternate Storage Account URL: {url}")
try:
response = requests.get(url, headers={"x-ms-version": "2019-12-12"}, timeout=5, verify=False)
logger.debug(f"Storage Account response status: {response.status_code}")
logger.debug(f"Storage Account response headers: {dict(response.headers)}")
if response.status_code == 401 and 'WWW-Authenticate' in response.headers:
auth_header = response.headers['WWW-Authenticate']
tenant_id = self._extract_tenant_from_www_authenticate(auth_header, key='authorization_uri', index=3)
if self._validate_tenant_id(tenant_id):
self._save_resource(f"{resource}.blob.core.windows.net", "StorageAccount", tenant_id)
logger.info(f"Found Storage Account tenant ID {tenant_id} for {resource}")
return tenant_id
except requests.exceptions.RequestException as e2:
if hasattr(e2, 'response') and e2.response is not None and 'WWW-Authenticate' in e2.response.headers:
auth_header = e2.response.headers['WWW-Authenticate']
tenant_id = self._extract_tenant_from_www_authenticate(auth_header, key='authorization_uri', index=3)
if self._validate_tenant_id(tenant_id):
self._save_resource(f"{resource}.blob.core.windows.net", "StorageAccount", tenant_id)
logger.info(f"Found Storage Account tenant ID {tenant_id} for {resource}")
return tenant_id
else:
self._log_exception_details(e, 'storage_account_request')
except Exception as e:
self._log_exception_details(e, 'check_storage_account')
return None
def check_databricks(self, resource: str) -> Optional[str]:
"""Check for Azure Databricks and extract tenant ID."""
try:
lookup = f"{resource}.azuredatabricks.net"
if not self._check_dns(lookup):
return None
url = f"https://{resource}.azuredatabricks.net/aad/auth?hash="
logger.debug(f"Checking Databricks URL: {url}")
try:
response = requests.get(url, allow_redirects=False, timeout=10)
logger.debug(f"Databricks response status: {response.status_code}")
logger.debug(f"Databricks response headers: {dict(response.headers)}")
if 'Location' in response.headers:
location = response.headers['Location']
try:
tenant_id = location.split('/')[3]
if self._validate_tenant_id(tenant_id):
self._save_resource(f"{resource}.azuredatabricks.net", "Databricks", tenant_id)
logger.info(f"Found Databricks tenant ID {tenant_id} for {resource}")
return tenant_id
except Exception as e:
self._log_exception_details(e, 'databricks_location_parse')
except requests.exceptions.RequestException as e:
if hasattr(e, 'response') and e.response is not None:
logger.debug(f"Error response status: {e.response.status_code}")
logger.debug(f"Error response headers: {dict(e.response.headers)}")
if 'Location' in e.response.headers:
location = e.response.headers['Location']
try:
tenant_id = location.split('/')[3]
if self._validate_tenant_id(tenant_id):
self._save_resource(f"{resource}.azuredatabricks.net", "Databricks", tenant_id)
logger.info(f"Found Databricks tenant ID {tenant_id} for {resource}")
return tenant_id
except Exception as e:
self._log_exception_details(e, 'databricks_error_location_parse')
else:
self._log_exception_details(e, 'databricks_request')
except Exception as e:
self._log_exception_details(e, 'check_databricks')
return None
def _save_resource(self, resource_uri: str, resource_type: str, tenant_id: str):
"""Save discovered resource to database."""
# Extract company display name if tenant_id is valid and not 'common'
company_display_name = None
if tenant_id and tenant_id != 'common' and tenant_id != self.NULL_TENANT_ID:
company_display_name = self._extract_company_display_name(tenant_id)
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute('''
INSERT INTO resource_info (resource_uri, resource_type, tenant_id, company_display_name, discovered_at)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(resource_uri) DO UPDATE SET
tenant_id = excluded.tenant_id,
company_display_name = excluded.company_display_name,
discovered_at = ?
''', (resource_uri, resource_type, tenant_id, company_display_name,
datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
conn.commit()
def generate_permutations(self, resources: List[str], permutations_file: str = None) -> List[str]:
"""Generate permutations of resource names using a permutations file.
Args:
resources: List of base resource names
permutations_file: Path to the permutations file (default: None, will use permutations.txt in script directory)
Returns:
List[str]: List of resource names with permutations
"""
# Determine the permutations file path
if not permutations_file or permutations_file == 'default':
permutations_path = os.path.join(os.path.dirname(__file__), "permutations.txt")
else:
permutations_path = permutations_file
if not os.path.exists(permutations_path):
logger.warning(f"Permutations file not found at {permutations_path}. Skipping permutations.")
return resources
try:
with open(permutations_path, 'r') as f:
permutations = [p.strip() for p in f if p.strip()]
# Remove duplicates while preserving order
permutations = list(dict.fromkeys(permutations))
logger.info(f"Loaded {len(permutations)} permutations from {permutations_path}")
generated = []
for resource in resources:
# Add the original resource
generated.append(resource)
# Generate prepend permutations (permutation + resource)
for perm in permutations:
generated.append(f"{perm}{resource}")
generated.append(f"{perm}-{resource}")
# Generate append permutations (resource + permutation)
for perm in permutations:
generated.append(f"{resource}{perm}")
generated.append(f"{resource}-{perm}")
# Remove any duplicates
unique_resources = list(dict.fromkeys(generated))
logger.info(f"Generated {len(unique_resources)} permutations from {len(resources)} base resources")
return unique_resources
except Exception as e:
logger.error(f"Error generating permutations: {str(e)}")
return resources
def process_resources(self, resources: List[str], max_workers: int = 10, use_permutations: str = None, batch_size: int = 1000):
"""Process multiple resources concurrently using ThreadPoolExecutor.
Args:
resources: List of resource names to process
max_workers: Maximum number of concurrent threads (default: 10)
use_permutations: Path to permutations file or 'default' to use permutations.txt (default: None)
batch_size: Number of resources to process in each batch (default: 1000)
"""
logger.debug(f"Processing {len(resources)} resources with {max_workers} workers")
# Generate permutations if requested
if use_permutations:
logger.info(f"Generating permutations of resource names...")
resources = self.generate_permutations(resources, use_permutations)
logger.info(f"Generated {len(resources)} total resources to process")
# Process resources in batches to prevent memory issues
total_resources = len(resources)
processed_count = 0
for i in range(0, total_resources, batch_size):
batch = resources[i:i + batch_size]
batch_num = (i // batch_size) + 1
total_batches = (total_resources + batch_size - 1) // batch_size
logger.info(f"Processing batch {batch_num}/{total_batches} ({len(batch)} resources, {processed_count}/{total_resources} total processed)")
with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
# Submit batch tasks
future_to_resource = {
executor.submit(self.process_resource, resource): resource
for resource in batch
}
# Process completed tasks in this batch
batch_processed = 0
for future in concurrent.futures.as_completed(future_to_resource):
resource = future_to_resource[future]
try:
future.result()
processed_count += 1
batch_processed += 1
# Show progress every 50 resources or at the end of batch
if batch_processed % 50 == 0 or batch_processed == len(batch):
logger.info(f"Batch {batch_num}: {batch_processed}/{len(batch)} completed ({processed_count}/{total_resources} total)")
except Exception as e:
logger.error(f"Error processing resource {resource}: {str(e)}")
logger.debug(f"Exception type: {type(e)}")
logger.debug(f"Exception args: {e.args}")
import traceback
logger.debug(f"Stack trace: {traceback.format_exc()}")
processed_count += 1
batch_processed += 1
# Small delay between batches to prevent overwhelming the system
if i + batch_size < total_resources:
time.sleep(1)
logger.info(f"Completed processing all {total_resources} resources")
def process_resource(self, resource: str):
"""Process a single resource name."""
logger.info(f"Processing resource: {resource}")
# Skip if resource name is too short
if len(resource) < 2:
logger.debug(f"Skipping resource '{resource}' - too short (minimum 2 characters)")
return
# Check services that work with 2+ characters
logger.debug("Checking App Services...")
self.check_app_services(resource)
logger.debug("Checking DevOps...")
self.check_devops(resource)
logger.debug("Checking SharePoint...")
self.check_sharepoint(resource)
# Check services that require 3+ characters
if len(resource) >= 3:
logger.debug("Starting Storage Account check...")
try:
result = self.check_storage_account(resource)
logger.debug(f"Storage Account check completed. Result: {result}")
except Exception as e:
logger.debug(f"Error during Storage Account check: {str(e)}")
logger.debug(f"Exception type: {type(e)}")
logger.debug(f"Exception args: {e.args}")
import traceback
logger.debug(f"Stack trace: {traceback.format_exc()}")
logger.debug("Checking Key Vault...")
self.check_key_vault(resource)
logger.debug("Checking Databricks...")
self.check_databricks(resource)
else:
logger.debug(f"Skipping Key Vault, Storage Account, and Databricks checks - resource name '{resource}' is too short (minimum 3 characters)")
def export_results(self, format: str, tenant_id: Optional[str] = None, run_timestamp: Optional[datetime] = None):
"""Export results to specified format (csv, json, html).
Args:
format: Export format ('csv', 'json', or 'html')
tenant_id: If provided, only export resources with this tenant ID
run_timestamp: If provided, only export resources discovered after this timestamp
"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
query = '''
SELECT resource_uri, resource_type, tenant_id, company_display_name, discovered_at
FROM resource_info
WHERE 1=1
'''
params = []
if tenant_id:
query += ' AND tenant_id = ?'
params.append(tenant_id)
if run_timestamp:
query += ' AND datetime(discovered_at) > datetime(?)'
params.append(run_timestamp.strftime('%Y-%m-%d %H:%M:%S'))
query += ' ORDER BY resource_type, resource_uri'
cursor.execute(query, params)
results = cursor.fetchall()
if not results:
print("\nNo resources to export matching the criteria.")
return
# Always generate a filename with timestamp
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
output_file = f"azure_tenants_export_{timestamp}.{format}"
try:
if format.lower() == 'csv':
self._export_csv(results, output_file)
elif format.lower() == 'json':
self._export_json(results, output_file)
elif format.lower() == 'html':
self._export_html(results, output_file)
else:
print(f"Unsupported export format: {format}")
return
print(f"\nResults exported to: {output_file}")
except Exception as e:
print(f"Error exporting results: {str(e)}")
def _export_csv(self, results: List[tuple], output_file: str):
"""Export results to CSV format."""
with open(output_file, 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(['Resource URI', 'Type', 'Tenant ID', 'Company Display Name', 'Discovered At'])
writer.writerows(results)
def _export_json(self, results: List[tuple], output_file: str):
"""Export results to JSON format."""
data = []
for row in results:
# Decode HTML entities in company display name if present
company_name = row[3] or ""
if company_name:
# Handle double-escaped Unicode sequences first
if '\\u' in company_name:
company_name = company_name.encode('utf-8').decode('unicode_escape')
# Then decode HTML entities
import html
company_name = html.unescape(company_name)
data.append({
'resource_uri': row[0],
'resource_type': row[1],
'tenant_id': row[2],
'company_display_name': company_name,
'discovered_at': row[4]
})
with open(output_file, 'w') as f:
json.dump(data, f, indent=2)
def _export_html(self, results: List[tuple], output_file: str):
"""Export results to HTML format with styled table."""
css = (
'body{background-color:#07142A;color:#F3F1E6;margin:0;padding:20px;font-family:Arial,sans-serif}'
'.container{max-width:1200px;margin:0 auto}'
'.header{display:flex;align-items:center;justify-content:center;margin-bottom:30px;gap:20px}'
'.logo{height:60px;width:auto;border-radius:8px}'
'h1{color:#F56A00;text-align:center;margin:0}'
'.timestamp{color:#71808D;text-align:center;margin-bottom:30px;font-size:0.9em}'
'.search-container{margin-bottom:20px;text-align:center}'
'.search-input{padding:8px 12px;width:300px;border:none;border-radius:4px;background-color:#345367;color:#F3F1E6;font-family:Arial,sans-serif}'
'.search-input::placeholder{color:#71808D}'
'.search-input:focus{outline:none;box-shadow:0 0 0 2px #F56A00}'
'table{width:100%;border-collapse:collapse;background-color:#345367;border-radius:8px;overflow:hidden;box-shadow:0 4px 6px rgba(0,0,0,0.1)}'
'th{background-color:#F3F1E6;color:#07142A;padding:12px;text-align:left;font-weight:bold;cursor:pointer;user-select:none}'
'th:hover{background-color:#F56A00;color:#F3F1E6}'
'th::after{content:"";display:inline-block;width:0;height:0;margin-left:5px;vertical-align:middle;border-left:4px solid transparent;border-right:4px solid transparent}'
'th.asc::after{border-bottom:4px solid #07142A}'
'th.desc::after{border-top:4px solid #07142A}'
'td{padding:12px;border-bottom:1px solid #71808D}'
'tr:last-child td{border-bottom:none}'
'tr:hover{background-color:#2A4252}'
'.resource-type{color:#F56A00;font-weight:bold}'
'.tenant-id{color:#F3F1E6}'
'.company-name{color:#F56A00;font-weight:bold}'
'.no-results{text-align:center;padding:20px;color:#71808D;display:none}'
'@media (max-width:768px){.header{flex-direction:column;gap:10px}.logo{height:40px}table{display:block;overflow-x:auto}}'
)
js = '''
function sortTable(n) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.querySelector("table");
switching = true;
dir = "asc";
// Remove sort indicators from all headers
table.querySelectorAll("th").forEach(th => {
th.classList.remove("asc", "desc");
});
while (switching) {
switching = false;
rows = table.rows;
for (i = 1; i < (rows.length - 1); i++) {
shouldSwitch = false;
x = rows[i].getElementsByTagName("td")[n];
y = rows[i + 1].getElementsByTagName("td")[n];
if (dir == "asc") {
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
}
} else if (dir == "desc") {
if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
shouldSwitch = true;
break;
}
}
}
if (shouldSwitch) {
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
switchcount++;
} else {
if (switchcount == 0 && dir == "asc") {
dir = "desc";
switching = true;
}
}
}
// Add sort indicator to current header
table.getElementsByTagName("th")[n].classList.add(dir);
}
function filterTable() {
var input = document.getElementById("searchInput");
var filter = input.value.toLowerCase();
var table = document.querySelector("table");
var tr = table.getElementsByTagName("tr");
var noResults = document.getElementById("noResults");
var hasResults = false;
for (var i = 1; i < tr.length; i++) {
var td = tr[i].getElementsByTagName("td");
var found = false;
for (var j = 0; j < td.length; j++) {
if (td[j].innerHTML.toLowerCase().indexOf(filter) > -1) {
found = true;
break;
}
}
if (found) {
tr[i].style.display = "";
hasResults = true;
} else {
tr[i].style.display = "none";
}
}
noResults.style.display = hasResults ? "none" : "block";
}
// Add event listeners when the page loads
document.addEventListener("DOMContentLoaded", function() {
// Add click handlers to all headers
document.querySelectorAll("th").forEach((th, index) => {
th.addEventListener("click", () => sortTable(index));
});
// Add input handler for search
document.getElementById("searchInput").addEventListener("input", filterTable);
});
'''
html_template = (
'<!DOCTYPE html>'
'<html lang="en">'
'<head>'
'<meta charset="UTF-8">'