-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcollect.py
More file actions
1586 lines (1354 loc) · 60.4 KB
/
collect.py
File metadata and controls
1586 lines (1354 loc) · 60.4 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
"""
CCA CloudShell - Unified Cloud Collector
Simple entry point for collecting cloud resources.
Auto-detects available cloud credentials and runs appropriate collectors.
Usage:
# Auto-detect mode (recommended)
python collect.py
# Direct cloud selection
python collect.py --cloud aws
python collect.py --cloud azure
python collect.py --cloud gcp
python collect.py --cloud m365
# Interactive setup wizard
python collect.py --setup
# Skip permission check (if you know credentials are valid)
python collect.py --cloud aws --skip-check
# Pass additional arguments to the collector
python collect.py --cloud aws -- --org-role CCARole --regions us-east-1
"""
import argparse
import importlib.util
import os
import sys
from typing import Any, Dict, List, Optional, Tuple
# ANSI colors for terminal output
class Colors:
HEADER = '\033[95m'
BLUE = '\033[94m'
CYAN = '\033[96m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BOLD = '\033[1m'
END = '\033[0m'
def color(text: str, c: str) -> str:
"""Apply color if terminal supports it."""
if sys.stdout.isatty():
return f"{c}{text}{Colors.END}"
return text
def print_banner():
"""Print welcome banner."""
banner = """
╔═══════════════════════════════════════════════════════════════╗
║ CCA CloudShell Collector ║
║ Cloud Resource Assessment & Protection Audit ║
╚═══════════════════════════════════════════════════════════════╝
"""
print(color(banner, Colors.CYAN))
def print_cloud_menu():
"""Print cloud selection menu."""
print(color("\nSelect a cloud platform to collect from:\n", Colors.BOLD))
print(f" {color('1', Colors.GREEN)}) AWS - Amazon Web Services")
print(f" {color('2', Colors.GREEN)}) Azure - Microsoft Azure")
print(f" {color('3', Colors.GREEN)}) GCP - Google Cloud Platform")
print(f" {color('4', Colors.GREEN)}) M365 - Microsoft 365 (SharePoint, OneDrive, Teams)")
print()
print(color(" Large Organizations:", Colors.BOLD))
print(f" {color('5', Colors.GREEN)}) AWS Org - AWS Organization (parallel + SSO refresh)")
print()
print(f" {color('q', Colors.RED)}) Quit")
print()
def prompt_aws_org_options() -> Optional[Dict[str, Any]]:
"""Prompt for AWS Organization collection options."""
print(color("\n=== AWS Organization Collection Setup ===\n", Colors.BOLD))
# Get org role name
print("Enter the IAM role name deployed to member accounts.")
print("(This role should have CCA read permissions and trust the management account)")
print()
try:
org_role = input(color("Role name [CCARole]: ", Colors.CYAN)).strip()
if not org_role:
org_role = "CCARole"
# External ID (security best practice)
print()
print("External ID adds security to cross-account role assumption.")
print("Leave blank if your roles don't require an external ID.")
print()
external_id = input(color("External ID (or Enter to skip): ", Colors.CYAN)).strip()
# Regions filter
print()
print("By default, all enabled regions are collected.")
print("Specify regions to limit scope (e.g., us-east-1,us-west-2).")
print()
regions = input(color("Regions to collect (Enter for all): ", Colors.CYAN)).strip()
# Parallel accounts
print()
print("Parallel workers speed up collection by running multiple accounts simultaneously.")
print("Auto-tunes to 4 for 50+ accounts, 8 for 100+ accounts if not specified.")
print()
parallel_input = input(color("Parallel account workers (Enter for auto, or 1-16) [auto]: ", Colors.CYAN)).strip()
parallel_accounts = None
if parallel_input:
try:
parallel_accounts = int(parallel_input)
if parallel_accounts < 1 or parallel_accounts > 16:
print(color("Invalid value, using auto-tune", Colors.YELLOW))
parallel_accounts = None
except ValueError:
print(color("Invalid value, using auto-tune", Colors.YELLOW))
# Parallel regions
print()
print("Parallel region collection speeds up each account (4-8 recommended).")
print()
parallel_regions_input = input(color("Parallel regions (Enter for default 4, or 1-16): ", Colors.CYAN)).strip()
parallel_regions = None
if parallel_regions_input:
try:
parallel_regions = int(parallel_regions_input)
if parallel_regions < 1 or parallel_regions > 16:
print(color("Invalid value, using default", Colors.YELLOW))
parallel_regions = None
except ValueError:
print(color("Invalid value, using default", Colors.YELLOW))
# SSO refresh
print()
print("SSO credentials typically expire after 1 hour.")
print("Enable auto-refresh to keep credentials valid during long collections.")
print()
sso_input = input(color("Enable SSO auto-refresh? [Y/n]: ", Colors.CYAN)).strip().lower()
sso_refresh = sso_input != 'n'
# Change rate collection
print()
print("Change rate data helps the sizing tool estimate backup requirements.")
print("Queries CloudWatch metrics (adds ~30s per account).")
print()
change_rate_input = input(color("Collect data change rates? [Y/n]: ", Colors.CYAN)).strip().lower()
include_change_rate = change_rate_input != 'n'
# Include resource IDs
print()
print("Resource IDs/ARNs are redacted by default for privacy.")
print("Include them for compliance or detailed inventory needs.")
print()
resource_ids_input = input(color("Include full resource IDs? [y/N]: ", Colors.CYAN)).strip().lower()
include_resource_ids = resource_ids_input in ('y', 'yes')
# Output directory
print()
output = input(color("Output directory [./output]: ", Colors.CYAN)).strip()
if not output:
output = "./output"
# Cost collection
print()
print("Data protection cost collection analyzes AWS Backup, EBS snapshot,")
print("and other backup-related costs from AWS Cost Explorer.")
print()
cost_input = input(color("Also collect data protection costs? [Y/n]: ", Colors.CYAN)).strip().lower()
collect_costs = cost_input != 'n'
cost_opts = {}
if collect_costs:
cost_opts['org_costs'] = True
return {
'org_role': org_role,
'external_id': external_id if external_id else None,
'regions': regions if regions else None,
'parallel_accounts': parallel_accounts,
'parallel_regions': parallel_regions,
'sso_refresh': sso_refresh,
'include_change_rate': include_change_rate,
'include_resource_ids': include_resource_ids,
'output': output,
'collect_costs': collect_costs,
'cost_opts': cost_opts
}
except (KeyboardInterrupt, EOFError):
print()
return None
def prompt_aws_options() -> Optional[Dict[str, Any]]:
"""Prompt for AWS collection options including cost collection."""
print(color("\n=== AWS Collection Options ===\n", Colors.BOLD))
try:
# Regions filter
print("By default, all enabled regions are collected.")
print("Specify regions to limit scope (e.g., us-east-1,us-west-2).")
print()
regions = input(color("Regions to collect (Enter for all): ", Colors.CYAN)).strip()
# Change rate collection
print()
print("Change rate data helps the sizing tool estimate backup requirements.")
print("Queries CloudWatch metrics (adds collection time).")
print()
change_rate_input = input(color("Collect data change rates? [Y/n]: ", Colors.CYAN)).strip().lower()
include_change_rate = change_rate_input != 'n'
# Include resource IDs
print()
print("Resource IDs/ARNs are redacted by default for privacy.")
print("Include them for compliance or detailed inventory needs.")
print()
resource_ids_input = input(color("Include full resource IDs? [y/N]: ", Colors.CYAN)).strip().lower()
include_resource_ids = resource_ids_input in ('y', 'yes')
# Output directory
print()
output = input(color("Output directory [./output]: ", Colors.CYAN)).strip()
if not output:
output = "./output"
# Cost collection
print()
print("Data protection cost collection analyzes AWS Backup, EBS snapshot,")
print("and other backup-related costs from AWS Cost Explorer.")
print()
cost_input = input(color("Also collect data protection costs? [Y/n]: ", Colors.CYAN)).strip().lower()
collect_costs = cost_input != 'n'
cost_opts = {}
if collect_costs:
print()
print("For AWS Organizations, costs can be broken down by member account.")
org_input = input(color("Break down costs by linked account (org)? [y/N]: ", Colors.CYAN)).strip().lower()
cost_opts['org_costs'] = org_input in ('y', 'yes')
return {
'regions': regions if regions else None,
'include_change_rate': include_change_rate,
'include_resource_ids': include_resource_ids,
'output': output,
'collect_costs': collect_costs,
'cost_opts': cost_opts
}
except (KeyboardInterrupt, EOFError):
print()
return None
def prompt_azure_options() -> Optional[Dict[str, Any]]:
"""Prompt for Azure collection options including cost collection."""
print(color("\n=== Azure Collection Options ===\n", Colors.BOLD))
try:
# Subscription filter
print("By default, all accessible subscriptions are collected.")
print("Specify a subscription ID to limit scope.")
print()
subscription_id = input(color("Subscription ID (Enter for all): ", Colors.CYAN)).strip()
# Regions filter
print()
print("By default, all regions are collected.")
print("Specify regions to limit scope (e.g., eastus,westus2).")
print()
regions = input(color("Regions to collect (Enter for all): ", Colors.CYAN)).strip()
# Change rate collection
print()
print("Change rate data helps the sizing tool estimate backup requirements.")
print("Queries Azure Monitor metrics (adds collection time).")
print()
change_rate_input = input(color("Collect data change rates? [Y/n]: ", Colors.CYAN)).strip().lower()
include_change_rate = change_rate_input != 'n'
# Include resource IDs
print()
print("Resource IDs are redacted by default for privacy.")
print("Include them for compliance or detailed inventory needs.")
print()
resource_ids_input = input(color("Include full resource IDs? [y/N]: ", Colors.CYAN)).strip().lower()
include_resource_ids = resource_ids_input in ('y', 'yes')
# Output directory
print()
output = input(color("Output directory [./output]: ", Colors.CYAN)).strip()
if not output:
output = "./output"
# Cost collection
print()
print("Data protection cost collection analyzes Azure Backup vault costs,")
print("managed disk snapshots, and recovery services from Cost Management.")
print()
cost_input = input(color("Also collect data protection costs? [Y/n]: ", Colors.CYAN)).strip().lower()
collect_costs = cost_input != 'n'
cost_opts = {}
if collect_costs:
# Use same subscription if specified, otherwise auto-detect
cost_opts['subscription_id'] = subscription_id if subscription_id else None
return {
'subscription_id': subscription_id if subscription_id else None,
'regions': regions if regions else None,
'include_change_rate': include_change_rate,
'include_resource_ids': include_resource_ids,
'output': output,
'collect_costs': collect_costs,
'cost_opts': cost_opts
}
except (KeyboardInterrupt, EOFError):
print()
return None
def prompt_gcp_options() -> Optional[Dict[str, Any]]:
"""Prompt for GCP collection options including cost collection."""
print(color("\n=== GCP Collection Options ===\n", Colors.BOLD))
try:
# Project scope
print("By default, collects from the current project only.")
print("Choose 'all' to collect from all accessible projects.")
print()
project_input = input(color("Project scope - specific ID, 'all', or Enter for current: ", Colors.CYAN)).strip().lower()
all_projects = project_input == 'all'
project = None if (all_projects or not project_input) else project_input
# Regions filter
print()
print("By default, all regions are collected.")
print("Specify regions to limit scope (e.g., us-central1,us-east1).")
print()
regions = input(color("Regions to collect (Enter for all): ", Colors.CYAN)).strip()
# Change rate collection
print()
print("Change rate data helps the sizing tool estimate backup requirements.")
print("Queries Cloud Monitoring metrics (adds collection time).")
print()
change_rate_input = input(color("Collect data change rates? [Y/n]: ", Colors.CYAN)).strip().lower()
include_change_rate = change_rate_input != 'n'
# Include resource IDs
print()
print("Resource IDs are redacted by default for privacy.")
print("Include them for compliance or detailed inventory needs.")
print()
resource_ids_input = input(color("Include full resource IDs? [y/N]: ", Colors.CYAN)).strip().lower()
include_resource_ids = resource_ids_input in ('y', 'yes')
# Output directory
print()
output = input(color("Output directory [./output]: ", Colors.CYAN)).strip()
if not output:
output = "./output"
# Cost collection
print()
print("Data protection cost collection requires BigQuery billing export.")
print("See: https://cloud.google.com/billing/docs/how-to/export-data-bigquery")
print()
cost_input = input(color("Also collect data protection costs? [Y/n]: ", Colors.CYAN)).strip().lower()
collect_costs = cost_input != 'n'
cost_opts = {}
if collect_costs:
print()
cost_project = input(color("GCP project ID with billing export: ", Colors.CYAN)).strip()
if not cost_project:
print(color("Project ID is required for cost collection.", Colors.YELLOW))
collect_costs = False
else:
cost_opts['project'] = cost_project
billing_table = input(color("BigQuery billing table (project.dataset.table): ", Colors.CYAN)).strip()
if not billing_table:
print(color("Billing table is required for cost collection.", Colors.YELLOW))
collect_costs = False
else:
cost_opts['billing_table'] = billing_table
return {
'project': project,
'all_projects': all_projects,
'regions': regions if regions else None,
'include_change_rate': include_change_rate,
'include_resource_ids': include_resource_ids,
'output': output,
'collect_costs': collect_costs,
'cost_opts': cost_opts
}
except (KeyboardInterrupt, EOFError):
print()
return None
def prompt_m365_options() -> Optional[Dict[str, Any]]:
"""Prompt for M365 collection options."""
print(color("\n=== Microsoft 365 Collection Options ===\n", Colors.BOLD))
try:
# Workload selection
print("Select which M365 workloads to collect:")
print("(All are collected by default)")
print()
sp_input = input(color("Collect SharePoint sites? [Y/n]: ", Colors.CYAN)).strip().lower()
skip_sharepoint = sp_input == 'n'
od_input = input(color("Collect OneDrive accounts? [Y/n]: ", Colors.CYAN)).strip().lower()
skip_onedrive = od_input == 'n'
ex_input = input(color("Collect Exchange mailboxes? [Y/n]: ", Colors.CYAN)).strip().lower()
skip_exchange = ex_input == 'n'
teams_input = input(color("Collect Teams? [Y/n]: ", Colors.CYAN)).strip().lower()
skip_teams = teams_input == 'n'
# Entra ID (Azure AD)
print()
print("Entra ID (Azure AD) collection includes users and groups.")
print("Useful for identity protection assessment.")
print()
entra_input = input(color("Include Entra ID users and groups? [y/N]: ", Colors.CYAN)).strip().lower()
include_entra = entra_input in ('y', 'yes')
# Output directory
print()
output = input(color("Output directory [./output]: ", Colors.CYAN)).strip()
if not output:
output = "./output"
return {
'skip_sharepoint': skip_sharepoint,
'skip_onedrive': skip_onedrive,
'skip_exchange': skip_exchange,
'skip_teams': skip_teams,
'include_entra': include_entra,
'output': output,
}
except (KeyboardInterrupt, EOFError):
print()
return None
def get_cloud_choice() -> Optional[str]:
"""Get cloud choice from user input."""
choices = {
'1': 'aws',
'2': 'azure',
'3': 'gcp',
'4': 'm365',
'5': 'aws-org',
'aws': 'aws',
'azure': 'azure',
'gcp': 'gcp',
'm365': 'm365',
'aws-org': 'aws-org',
}
while True:
try:
choice = input(color("Enter choice (1-5 or cloud name): ", Colors.CYAN)).strip().lower()
if choice in ('q', 'quit', 'exit'):
return None
if choice in choices:
return choices[choice]
print(color("Invalid choice. Please enter 1-5 or a cloud name.", Colors.YELLOW))
except (KeyboardInterrupt, EOFError):
print()
return None
# =============================================================================
# Permission Verification
# =============================================================================
def check_aws_permissions() -> Tuple[bool, str, List[str]]:
"""
Verify AWS credentials and basic permissions.
Returns: (success, message, details)
"""
details = []
try:
import boto3
from botocore.exceptions import ClientError, NoCredentialsError
except ImportError:
return False, "boto3 not installed", ["Run: pip install boto3"]
# Check credentials
try:
sts = boto3.client('sts')
identity = sts.get_caller_identity()
account_id = identity['Account']
arn = identity['Arn']
details.append(f"Account: {account_id}")
details.append(f"Identity: {arn}")
except NoCredentialsError:
return False, "No AWS credentials found", [
"Configure credentials via:",
" - AWS CloudShell (recommended)",
" - aws configure",
" - Environment variables (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)",
" - IAM role (EC2 instance profile)"
]
except ClientError as e:
return False, f"Credential error: {e}", []
# Check basic read permissions
try:
ec2 = boto3.client('ec2') # type: ignore[call-overload]
regions = ec2.describe_regions()
details.append(f"Regions: {len(regions.get('Regions', []))} enabled")
except ClientError as e:
code = e.response.get('Error', {}).get('Code', '')
if code in ('UnauthorizedOperation', 'AccessDenied'):
return False, "Missing ec2:DescribeRegions permission", [
"Add ReadOnlyAccess policy or see docs/PERMISSIONS.md"
]
details.append(f"Region check: {e}")
# Quick check for S3 access
try:
s3 = boto3.client('s3') # type: ignore[call-overload]
s3.list_buckets()
details.append("S3: ✓ ListBuckets")
except ClientError as e:
code = e.response.get('Error', {}).get('Code', '')
if code in ('AccessDenied',):
details.append("S3: ✗ No s3:ListAllMyBuckets")
# Check for Organizations access (optional)
try:
org = boto3.client('organizations') # type: ignore[call-overload]
org.describe_organization()
details.append("Org: ✓ Organizations access (multi-account ready)")
except ClientError:
details.append("Org: – Single account mode (no Organizations access)")
except Exception:
pass
return True, "AWS credentials verified", details
def check_azure_permissions() -> Tuple[bool, str, List[str]]:
"""
Verify Azure credentials and basic permissions.
Returns: (success, message, details)
"""
details = []
try:
from azure.identity import DefaultAzureCredential
from azure.mgmt.subscription import SubscriptionClient
except ImportError:
return False, "Azure SDK not installed", [
"Run: pip install azure-identity azure-mgmt-subscription"
]
try:
credential = DefaultAzureCredential()
# Get token to verify credentials work
credential.get_token("https://management.azure.com/.default")
details.append("Auth: DefaultAzureCredential")
except Exception as e:
return False, f"Azure authentication failed: {e}", [
"Configure credentials via:",
" - Azure Cloud Shell (recommended)",
" - az login",
" - Service principal environment variables",
" - Managed identity"
]
# List subscriptions
try:
sub_client = SubscriptionClient(credential)
subs = list(sub_client.subscriptions.list())
if subs:
details.append(f"Subs: {len(subs)} accessible")
for sub in subs[:3]:
sub_id = sub.subscription_id or 'unknown'
details.append(f" - {sub.display_name} ({sub_id[:8]}...)")
if len(subs) > 3:
details.append(f" ... and {len(subs) - 3} more")
else:
return False, "No subscriptions accessible", [
"Ensure your account has Reader access to at least one subscription"
]
except Exception as e:
return False, f"Failed to list subscriptions: {e}", []
return True, "Azure credentials verified", details
def check_gcp_permissions() -> Tuple[bool, str, List[str]]:
"""
Verify GCP credentials and basic permissions.
Returns: (success, message, details)
"""
details = []
try:
import google.auth
from google.cloud import resourcemanager_v3
except ImportError:
return False, "GCP SDK not installed", [
"Run: pip install google-auth google-cloud-resource-manager"
]
try:
credentials, project = google.auth.default()
if project:
details.append(f"Project: {project}")
else:
details.append("Project: (not set, will scan all accessible)")
except Exception as e:
return False, f"GCP authentication failed: {e}", [
"Configure credentials via:",
" - Google Cloud Shell (recommended)",
" - gcloud auth application-default login",
" - Service account key file (GOOGLE_APPLICATION_CREDENTIALS)"
]
# Try to list projects
try:
client = resourcemanager_v3.ProjectsClient()
projects = list(client.search_projects(query=""))
if projects:
details.append(f"Projects: {len(projects)} accessible")
for proj in projects[:3]:
details.append(f" - {proj.display_name} ({proj.project_id})")
if len(projects) > 3:
details.append(f" ... and {len(projects) - 3} more")
else:
details.append("Projects: None found (may need resourcemanager.projects.get)")
except Exception as e:
# If resourcemanager_v3 isn't available, try simpler check
details.append(f"Projects: Could not list ({e})")
return True, "GCP credentials verified", details
def check_m365_permissions() -> Tuple[bool, str, List[str]]:
"""
Verify M365 credentials and basic permissions.
Prefers App Registration credentials if available.
Falls back to Azure CLI / DefaultAzureCredential.
Errors if partial App Registration credentials are set.
Returns: (success, message, details)
"""
details = []
# Check for App Registration environment variables
tenant_id = os.environ.get('MS365_TENANT_ID')
client_id = os.environ.get('MS365_CLIENT_ID')
client_secret = os.environ.get('MS365_CLIENT_SECRET')
ms365_vars = {
'MS365_TENANT_ID': tenant_id,
'MS365_CLIENT_ID': client_id,
'MS365_CLIENT_SECRET': client_secret
}
set_vars = [k for k, v in ms365_vars.items() if v]
missing_vars = [k for k, v in ms365_vars.items() if not v]
# Error on partial credentials - user started setup but didn't finish
if set_vars and missing_vars:
return False, "Partial App Registration credentials detected", [
f"You have set: {', '.join(set_vars)}",
f"But missing: {', '.join(missing_vars)}",
"",
"Please set ALL three environment variables:",
" export MS365_TENANT_ID='your-tenant-id'",
" export MS365_CLIENT_ID='your-client-id'",
" export MS365_CLIENT_SECRET='your-client-secret'",
"",
"Or unset all of them to use Azure CLI authentication:",
" unset MS365_TENANT_ID MS365_CLIENT_ID MS365_CLIENT_SECRET",
" az login"
]
# Try to import required libraries
try:
from azure.identity import ClientSecretCredential, DefaultAzureCredential
from msgraph.graph_service_client import GraphServiceClient # noqa: F401
except ImportError:
return False, "msgraph SDK not installed", [
"Run: pip install msgraph-sdk azure-identity"
]
# Use App Registration if all credentials are set (preferred)
if all([tenant_id, client_id, client_secret]):
details.append("Method: App Registration (preferred)")
details.append(f"Tenant: {tenant_id}")
details.append(f"Client: {client_id[:8]}...")
try:
credential = ClientSecretCredential(
tenant_id=tenant_id,
client_id=client_id,
client_secret=client_secret
)
# Try to get a token for Graph API
token = credential.get_token("https://graph.microsoft.com/.default")
if token:
details.append("Auth: ✓ Token acquired")
return True, "M365 App Registration verified", details
except Exception as e:
return False, f"App Registration authentication failed: {e}", [
"Check that:",
" - Tenant ID, Client ID, and Client Secret are correct",
" - The App Registration has the required API permissions",
" - Admin consent has been granted for the permissions"
]
# Fall back to DefaultAzureCredential (Azure CLI, Managed Identity, etc.)
details.append("Method: Azure CLI / DefaultAzureCredential")
details.append(" (Set MS365_* env vars to use App Registration instead)")
try:
# Skip managed identity on non-Azure machines to avoid timeout
is_azure = os.environ.get('ACC_TERM_ID') or os.path.exists(os.path.expanduser('~/clouddrive'))
credential = DefaultAzureCredential(
exclude_managed_identity_credential=not is_azure
)
# Try to get a token for Graph API
token = credential.get_token("https://graph.microsoft.com/.default")
if token:
details.append("Auth: ✓ Token acquired via Azure CLI")
details.append("")
details.append("⚠ Note: For production use, App Registration is recommended.")
details.append(" See docs/collectors/m365.md for setup instructions.")
return True, "M365 credentials verified (Azure CLI)", details
except Exception as e:
return False, f"Azure CLI authentication failed: {e}", [
"No valid credentials found. Options:",
"",
"Option 1: App Registration (recommended for production)",
" export MS365_TENANT_ID='your-tenant-id'",
" export MS365_CLIENT_ID='your-client-id'",
" export MS365_CLIENT_SECRET='your-client-secret'",
"",
"Option 2: Azure CLI (for development/testing)",
" az login",
"",
"See docs/collectors/m365.md for detailed setup instructions."
]
return False, "No M365 credentials found", details
def check_change_rate_requirements(cloud: str) -> Tuple[bool, str]:
"""
Check if the required monitoring package is installed for change rate collection.
Returns: (success, error_message)
"""
if cloud in ('aws', 'aws-org'):
# AWS uses boto3 CloudWatch which is part of core boto3 - always available
return True, ""
elif cloud == 'azure':
try:
from azure.mgmt.monitor import MonitorManagementClient # noqa: F401
return True, ""
except ImportError:
return False, (
"Change rate collection requires azure-mgmt-monitor.\n"
"Install it with: pip install azure-mgmt-monitor\n"
"Or use --skip-change-rate to skip change rate collection."
)
elif cloud == 'gcp':
try:
from google.cloud import monitoring_v3 # noqa: F401
return True, ""
except ImportError:
return False, (
"Change rate collection requires google-cloud-monitoring.\n"
"Install it with: pip install google-cloud-monitoring\n"
"Or use --skip-change-rate to skip change rate collection."
)
# M365 doesn't have change rate collection
return True, ""
# =============================================================================
# Cloud Auto-Detection
# =============================================================================
def detect_aws() -> bool:
"""Check if AWS credentials are available."""
# Check environment variables
if os.environ.get('AWS_ACCESS_KEY_ID') or os.environ.get('AWS_SESSION_TOKEN'):
return True
# Check for CloudShell
if os.environ.get('AWS_EXECUTION_ENV'):
return True
# Check for credentials file
aws_creds = os.path.expanduser('~/.aws/credentials')
if os.path.exists(aws_creds):
return True
# Check for config file with SSO
aws_config = os.path.expanduser('~/.aws/config')
if os.path.exists(aws_config):
return True
return False
def detect_azure() -> bool:
"""Check if Azure credentials are available."""
# Check environment variables
if os.environ.get('AZURE_CLIENT_ID') or os.environ.get('AZURE_SUBSCRIPTION_ID'):
return True
# Check for Cloud Shell
if os.environ.get('ACC_TERM_ID') or os.path.exists(os.path.expanduser('~/clouddrive')):
return True
# Check for Azure CLI logged in
azure_config = os.path.expanduser('~/.azure/azureProfile.json')
if os.path.exists(azure_config):
return True
return False
def detect_gcp() -> bool:
"""Check if GCP credentials are available."""
# Check environment variables
if os.environ.get('GOOGLE_APPLICATION_CREDENTIALS'):
return True
if os.environ.get('GOOGLE_CLOUD_PROJECT') or os.environ.get('GCLOUD_PROJECT'):
return True
# Check for Cloud Shell
if os.environ.get('CLOUD_SHELL') == 'true' or os.environ.get('DEVSHELL_GCLOUD_CONFIG'):
return True
# Check for gcloud config
gcloud_config = os.path.expanduser('~/.config/gcloud/credentials.db')
if os.path.exists(gcloud_config):
return True
# Check for application default credentials
adc = os.path.expanduser('~/.config/gcloud/application_default_credentials.json')
if os.path.exists(adc):
return True
return False
def detect_m365() -> bool:
"""Check if M365 credentials are available.
Detects both App Registration credentials (preferred) and Azure CLI.
Returns True if either authentication method is available.
"""
# Check for App Registration credentials (preferred method)
tenant_id = os.environ.get('MS365_TENANT_ID')
client_id = os.environ.get('MS365_CLIENT_ID')
client_secret = os.environ.get('MS365_CLIENT_SECRET')
if all([tenant_id, client_id, client_secret]):
return True
# Check for Azure CLI / DefaultAzureCredential
# This includes: Azure CLI login, Managed Identity, env vars
azure_config = os.path.expanduser('~/.azure/azureProfile.json')
if os.path.exists(azure_config):
return True
# Check for Azure Cloud Shell
if os.environ.get('ACC_TERM_ID') or os.path.exists(os.path.expanduser('~/clouddrive')):
return True
# Check for AZURE_ env vars (service principal)
if os.environ.get('AZURE_CLIENT_ID') and os.environ.get('AZURE_TENANT_ID'):
return True
return False
def auto_detect_clouds() -> List[str]:
"""Detect which clouds have credentials configured."""
detected = []
detectors = [
('aws', detect_aws),
('azure', detect_azure),
('gcp', detect_gcp),
('m365', detect_m365),
]
for cloud, detector in detectors:
try:
if detector():
detected.append(cloud)
except Exception:
pass # Ignore detection errors
return detected
def verify_permissions(cloud: str) -> bool:
"""Run permission check for specified cloud."""
print(color(f"\n{'─'*60}", Colors.CYAN))
print(color(f" Checking {cloud.upper()} permissions...", Colors.BOLD))
print(color(f"{'─'*60}\n", Colors.CYAN))
checkers = {
'aws': check_aws_permissions,
'azure': check_azure_permissions,
'gcp': check_gcp_permissions,
'm365': check_m365_permissions,
}
checker = checkers.get(cloud)
if not checker:
print(color(f"Unknown cloud: {cloud}", Colors.RED))
return False
try:
success, message, details = checker()
except Exception as e:
print(color(f" ✗ Permission check failed: {e}", Colors.RED))
print(color("\n This could indicate missing credentials or SDK issues.", Colors.YELLOW))
return False
if success:
print(color(f" ✓ {message}", Colors.GREEN))
else:
print(color(f" ✗ {message}", Colors.RED))
if details:
print()
for line in details:
if line.startswith(" "):
print(color(f" {line}", Colors.CYAN if success else Colors.YELLOW))
else:
print(color(f" {line}", Colors.CYAN if success else Colors.YELLOW))
print()
return success
# =============================================================================
# Collection Execution
# =============================================================================
def _run_module(module_path: str, argv: List[str]) -> int:
"""Load a collector module and call its main(), returning the exit code."""
spec = importlib.util.spec_from_file_location("_collector", module_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module) # type: ignore[union-attr]
saved_argv = sys.argv
sys.argv = argv
try:
module.main()
return 0
except SystemExit as e:
return e.code if isinstance(e.code, int) else (0 if e.code is None else 1)
except KeyboardInterrupt:
return 130
finally:
sys.argv = saved_argv
def run_collector(cloud: str, extra_args: List[str]) -> int:
"""
Run the appropriate collector script.
Returns the exit code from the collector.
"""
collectors = {
'aws': 'aws_collect.py',
'azure': 'azure_collect.py',
'gcp': 'gcp_collect.py',
'm365': 'm365_collect.py',
}
collector = collectors.get(cloud)
if not collector:
print(color(f"Unknown cloud: {cloud}", Colors.RED))
return 1
script_dir = os.path.dirname(os.path.abspath(__file__))
collector_path = os.path.realpath(os.path.join(script_dir, collector))
if not collector_path.startswith(os.path.realpath(script_dir) + os.sep):
print(color(f"Collector path outside expected directory: {collector_path}", Colors.RED))
return 1
if not os.path.exists(collector_path):
print(color(f"Collector not found: {collector_path}", Colors.RED))
return 1
print(color(f"\n{'─'*60}", Colors.CYAN))
print(color(f" Starting {cloud.upper()} collection...", Colors.BOLD))
print(color(f"{'─'*60}\n", Colors.CYAN))
if extra_args: