Repository navigation
Expand file tree
/
Copy pathaws_resource_auditor.py
More file actions
1399 lines (1220 loc) · 61.5 KB
/
Copy pathaws_resource_auditor.py
File metadata and controls
1399 lines (1220 loc) · 61.5 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
"""
aws_resource_auditor.py
========================
Enumerate resources across every AWS region for one or more profiles found in
an AWS credentials file, and highlight the delta between where a customer
*says* they have resources (--expected-regions) and where resources (or
merely enabled-but-unused regions) actually exist.
This is built for cloud engagement scoping / cleanup work: a customer says
"we only run things in us-east-1 and us-west-2." This script tells you:
* Which other regions actually have resources in them (undocumented
footprint -- a real finding).
* Which regions are enabled but sitting empty (disablement candidates --
reduces attack surface even if nothing is currently there).
* Which regions are disabled entirely (good -- no action needed).
* A full inventory of every resource found, per region, so remediation
(delete it, migrate it, or update the asset list) is easy to action.
WHAT IT SCANS
-------------
For every *enabled* region, the script collects, via explicit, dedicated
API calls (NOT dependent on the tagging API below):
- EC2 instances
- EC2 AMIs (self-owned only)
- EBS volumes
- EC2 snapshots (self-owned only)
- VPCs
- RDS instances (incl. multi-AZ members) and RDS/Aurora clusters
- Lambda functions
- Classic Elastic Load Balancers (ELB)
- Application/Network/Gateway Load Balancers (ELBv2)
- CloudFormation stacks (any status except fully-deleted)
- SNS topics
- SQS queues
- DynamoDB tables
- S3 buckets (global service, bucketed into their actual region)
GLOBAL, not per-region -- collected ONCE per account so the same resource
isn't double/triple/N-times-counted across every enabled region:
- IAM users, roles, groups, and access keys (reported in a distinct
"global (IAM)" row, excluded from the region-scoping/expected-region
math -- IAM isn't a region, so "expected region" findings don't apply
to it, but the inventory and any collector errors are still surfaced)
...plus, as a broad catch-all, everything else the account has that
supports the Resource Groups Tagging API (`resourcegroupstaggingapi:
GetResources`) -- KMS, ECS/EKS, API Gateway, and most other taggable
services. IMPORTANT: this catch-all is a SINGLE permission
(`tag:GetResources`) covering dozens of resource types at once -- if an SCP
or IAM policy blocks it (common with locked-down read-only roles), every
resource type that ISN'T explicitly listed above goes uncollected for that
region, silently, unless you notice the collector-error count. The
explicit collectors above exist specifically so the most commonly-relevant
resource types don't depend on that one permission working.
Results are de-duplicated by ARN, so a resource found by both an explicit
collector and the tagging-API catch-all is only counted once.
Disabled (opt-in-not-enabled) regions are NOT scanned -- calling a service
API in a disabled region simply fails, and a disabled region can't hold
running resources. A disabled region is treated as a *good* outcome.
HANDLING RESTRICTIVE READ-ONLY ROLES
-------------------------------------
Engagement credentials are often a minimal read-only role (e.g. AWS SSO's
AWSReadOnlyAccess) further locked down by a Service Control Policy, so one
or more collectors may get AccessDenied/UnauthorizedOperation in some or
all regions. The script never lets a denied collector fail the whole scan:
- If SOME collectors in a region succeed, the resource count is reported
as a MINIMUM (">=N") and the region's Finding is tagged "[INCOMPLETE:
x/y collectors denied]" -- it will not be silently under-reported.
- If EVERY collector in a region is denied, the count is shown as unknown
("-"), not zero, and the Finding reads "ERROR - could not enumerate".
- By default the raw exceptions (which repeat the caller ARN and SCP ARN
on every line) are NOT printed to STDOUT -- only quantified counts
appear in the region summary table/panel and in
5_collector_errors_<timestamp>.csv. Pass --verbose to print every raw
error as it happens.
REQUIRED IAM PERMISSIONS (read-only)
-------------------------------------
sts:GetCallerIdentity
ec2:DescribeRegions
ec2:DescribeInstances
ec2:DescribeImages
ec2:DescribeVolumes
ec2:DescribeSnapshots
ec2:DescribeVpcs
rds:DescribeDBInstances
rds:DescribeDBClusters
lambda:ListFunctions
elasticloadbalancing:DescribeLoadBalancers
cloudformation:ListStacks
sns:ListTopics
sqs:ListQueues
dynamodb:ListTables
s3:ListAllMyBuckets
s3:GetBucketLocation
iam:ListUsers
iam:ListRoles
iam:ListGroups
iam:ListAccessKeys
tag:GetResources
INSTALL
-------
pip install boto3 alive-progress rich
CONCURRENCY
-----------
Region scans are parallelized across a single shared thread pool covering
EVERY profile being audited at once (default: 8 concurrent region-scans,
tune with --max-workers). This bounds total concurrent AWS API calls at a
flat number regardless of how many accounts/regions are in play, rather
than multiplying a per-account pool by a per-region pool. Every AWS client
is additionally configured with adaptive retries (auto backoff on
Throttling/RequestLimitExceeded), so occasional throttling under
concurrency is absorbed by the SDK rather than showing up as a permissions
error. Account/region discovery (STS + DescribeRegions + S3 listing) stays
sequential per profile -- it's a handful of calls, not the bottleneck.
Pass --max-workers 1 for the old fully-sequential behavior.
USAGE
-----
# Single profile, no expectations set (just inventories everything)
python3 aws_resource_auditor.py --profile customer-prod
# Single profile, flag anything outside these regions as unexpected
python3 aws_resource_auditor.py --profile customer-prod \\
--expected-regions us-east-1,us-west-2
# Every profile in ~/.aws/credentials -- scanned concurrently
python3 aws_resource_auditor.py --all-profiles \\
--expected-regions us-east-1 us-west-2 eu-west-1
# Turn concurrency up (faster, more AWS API pressure) or down/off
python3 aws_resource_auditor.py --all-profiles --max-workers 16
python3 aws_resource_auditor.py --all-profiles --max-workers 1
# Custom credentials file / output location
python3 aws_resource_auditor.py --all-profiles \\
--credentials-file /path/to/credentials \\
--output-dir ./audit_results
OUTPUT
------
Printed to STDOUT (per account):
- Region summary table (resource count per region, unexpected regions
highlighted, collector-error counts called out)
- Findings panel (the "Number of ..." rollup metrics)
- Collector-error details ONLY with --verbose (otherwise a single
quantified line, e.g. "2 region(s), 9 collector error(s) total --
suppressed")
Written to --output-dir (one row per account+region / account+region+type /
resource / collector-error, across ALL scanned accounts):
1_region_summary_<timestamp>.csv
2_resource_type_breakdown_<timestamp>.csv
3_resource_inventory_<timestamp>.csv
4_account_findings_summary_<timestamp>.csv
5_collector_errors_<timestamp>.csv
"""
import argparse
import configparser
import csv
import os
import sys
from collections import Counter, defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from typing import Dict, List, Optional, Set, Tuple
try:
import boto3
from botocore.config import Config
from botocore.exceptions import (
BotoCoreError,
ClientError,
EndpointConnectionError,
NoCredentialsError,
OperationNotPageableError,
ProfileNotFound,
)
except ImportError:
print("ERROR: boto3 is required. Install with: pip install boto3", file=sys.stderr)
sys.exit(1)
# Every AWS client uses adaptive retries -- if concurrent scanning ever does
# trigger throttling (Throttling/RequestLimitExceeded/TooManyRequests), the
# SDK backs off and retries automatically instead of surfacing it as a hard
# failure. This is the main safety net against "getting blocked by AWS";
# --max-workers just controls how much concurrency we offer it in the first
# place.
RETRY_CONFIG = Config(retries={"max_attempts": 10, "mode": "adaptive"})
try:
from alive_progress import alive_bar
except ImportError:
print("ERROR: alive-progress is required. Install with: pip install alive-progress", file=sys.stderr)
sys.exit(1)
try:
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich import box
except ImportError:
print("ERROR: rich is required. Install with: pip install rich", file=sys.stderr)
sys.exit(1)
# --------------------------------------------------------------------------
# Data model
# --------------------------------------------------------------------------
@dataclass
class ResourceRecord:
resource_type: str
resource_id: str
name: str
arn: str
@dataclass
class CollectorError:
"""A single failed API call, with just enough detail to quantify and
troubleshoot restrictive read-only policies (e.g. AWSReadOnlyAccess +
an SCP explicit deny) without dumping the full raw exception to STDOUT
by default."""
region: str
collector: str
code: str # short AWS error code, e.g. AccessDenied, UnauthorizedOperation
scp_denied: bool # True if the error text indicates an SCP explicit deny
message: str # full exception text, shown only with --verbose
@dataclass
class RegionResult:
region: str
enabled: bool
resource_count: Optional[int] = None # None = unknown/error, not "zero"
resources: List[ResourceRecord] = field(default_factory=list)
errors: List[CollectorError] = field(default_factory=list)
collector_total: int = 0 # how many collectors were attempted in this region
expected: Optional[bool] = None # None = user gave no --expected-regions
finding: str = ""
severity: str = "none" # none|good|ok|info|warn|partial|finding|error
is_pseudo_region: bool = False # True for the global IAM inventory row -- not a real AWS region
# --------------------------------------------------------------------------
# Explicit ("core") resource collectors
# --------------------------------------------------------------------------
# Each collector returns a list of ResourceRecord. Every collector is called
# independently and wrapped in try/except by the caller, so one missing
# permission or unsupported service in a given region doesn't blank out the
# whole region's results.
def _paginate(client, op_name: str, result_key: str, **kwargs) -> list:
"""Paginate an AWS API call, falling back to manual NextToken handling
for operations without a registered paginator."""
try:
paginator = client.get_paginator(op_name)
items = []
for page in paginator.paginate(**kwargs):
items.extend(page.get(result_key, []))
return items
except OperationNotPageableError:
method = getattr(client, op_name)
items = []
resp = method(**kwargs)
items.extend(resp.get(result_key, []))
token = resp.get("NextToken")
while token:
resp = method(NextToken=token, **kwargs)
items.extend(resp.get(result_key, []))
token = resp.get("NextToken")
return items
def _classify_error(region: str, collector: str, exc: Exception) -> CollectorError:
"""Turn a raw exception into a short, quantifiable CollectorError --
used to silence noisy STDOUT dumps by default while still surfacing
*how many* and *what kind* of permission gaps exist."""
code = "Error"
if isinstance(exc, ClientError):
code = exc.response.get("Error", {}).get("Code", "ClientError")
msg = str(exc)
scp_denied = "service control policy" in msg.lower()
return CollectorError(region=region, collector=collector, code=code,
scp_denied=scp_denied, message=msg)
def _tag_name(tags) -> str:
if not tags:
return ""
for t in tags:
if t.get("Key") == "Name":
return t.get("Value", "")
return ""
def collect_ec2_instances(session, region, account_id, partition) -> List[ResourceRecord]:
ec2 = session.client("ec2", region_name=region, config=RETRY_CONFIG)
reservations = _paginate(ec2, "describe_instances", "Reservations")
out = []
for r in reservations:
for inst in r.get("Instances", []):
iid = inst["InstanceId"]
out.append(ResourceRecord(
resource_type="ec2:instance",
resource_id=iid,
name=_tag_name(inst.get("Tags")) or inst.get("State", {}).get("Name", ""),
arn=f"arn:{partition}:ec2:{region}:{account_id}:instance/{iid}",
))
return out
def collect_ebs_volumes(session, region, account_id, partition) -> List[ResourceRecord]:
ec2 = session.client("ec2", region_name=region, config=RETRY_CONFIG)
volumes = _paginate(ec2, "describe_volumes", "Volumes")
out = []
for v in volumes:
vid = v["VolumeId"]
out.append(ResourceRecord(
resource_type="ec2:volume",
resource_id=vid,
name=_tag_name(v.get("Tags")),
arn=f"arn:{partition}:ec2:{region}:{account_id}:volume/{vid}",
))
return out
def collect_vpcs(session, region, account_id, partition) -> List[ResourceRecord]:
ec2 = session.client("ec2", region_name=region, config=RETRY_CONFIG)
vpcs = _paginate(ec2, "describe_vpcs", "Vpcs")
out = []
for v in vpcs:
vid = v["VpcId"]
label = _tag_name(v.get("Tags"))
if v.get("IsDefault"):
label = (label + " [default VPC]").strip()
out.append(ResourceRecord(
resource_type="ec2:vpc",
resource_id=vid,
name=label,
arn=f"arn:{partition}:ec2:{region}:{account_id}:vpc/{vid}",
))
return out
def collect_rds_instances(session, region, account_id, partition) -> List[ResourceRecord]:
rds = session.client("rds", region_name=region, config=RETRY_CONFIG)
dbs = _paginate(rds, "describe_db_instances", "DBInstances")
out = []
for db in dbs:
arn = db.get("DBInstanceArn") or f"arn:{partition}:rds:{region}:{account_id}:db:{db['DBInstanceIdentifier']}"
out.append(ResourceRecord(
resource_type="rds:db",
resource_id=db["DBInstanceIdentifier"],
name=db.get("Engine", ""),
arn=arn,
))
return out
def collect_rds_clusters(session, region, account_id, partition) -> List[ResourceRecord]:
rds = session.client("rds", region_name=region, config=RETRY_CONFIG)
clusters = _paginate(rds, "describe_db_clusters", "DBClusters")
out = []
for c in clusters:
arn = c.get("DBClusterArn") or f"arn:{partition}:rds:{region}:{account_id}:cluster:{c['DBClusterIdentifier']}"
out.append(ResourceRecord(
resource_type="rds:cluster",
resource_id=c["DBClusterIdentifier"],
name=c.get("Engine", ""),
arn=arn,
))
return out
def collect_lambda_functions(session, region, account_id, partition) -> List[ResourceRecord]:
lam = session.client("lambda", region_name=region, config=RETRY_CONFIG)
fns = _paginate(lam, "list_functions", "Functions")
out = []
for fn in fns:
arn = fn.get("FunctionArn") or f"arn:{partition}:lambda:{region}:{account_id}:function:{fn['FunctionName']}"
out.append(ResourceRecord(
resource_type="lambda:function",
resource_id=fn["FunctionName"],
name=fn.get("Runtime", ""),
arn=arn,
))
return out
def collect_elb_classic(session, region, account_id, partition) -> List[ResourceRecord]:
elb = session.client("elb", region_name=region, config=RETRY_CONFIG)
lbs = _paginate(elb, "describe_load_balancers", "LoadBalancerDescriptions")
out = []
for lb in lbs:
name = lb["LoadBalancerName"]
out.append(ResourceRecord(
resource_type="elb:classic-load-balancer",
resource_id=name,
name=name,
arn=f"arn:{partition}:elasticloadbalancing:{region}:{account_id}:loadbalancer/{name}",
))
return out
def collect_elbv2(session, region, account_id, partition) -> List[ResourceRecord]:
elbv2 = session.client("elbv2", region_name=region, config=RETRY_CONFIG)
lbs = _paginate(elbv2, "describe_load_balancers", "LoadBalancers")
out = []
for lb in lbs:
arn = lb["LoadBalancerArn"]
out.append(ResourceRecord(
resource_type=f"elbv2:{lb.get('Type', 'load-balancer')}",
resource_id=lb.get("LoadBalancerName", arn),
name=lb.get("DNSName", ""),
arn=arn,
))
return out
# Every status except DELETE_COMPLETE -- a fully-deleted stack isn't a
# resource anymore (AWS just keeps the record around briefly for history).
ACTIVE_STACK_STATUSES = [
"CREATE_IN_PROGRESS", "CREATE_FAILED", "CREATE_COMPLETE",
"ROLLBACK_IN_PROGRESS", "ROLLBACK_FAILED", "ROLLBACK_COMPLETE",
"DELETE_IN_PROGRESS", "DELETE_FAILED",
"UPDATE_IN_PROGRESS", "UPDATE_COMPLETE_CLEANUP_IN_PROGRESS", "UPDATE_COMPLETE",
"UPDATE_FAILED", "UPDATE_ROLLBACK_IN_PROGRESS", "UPDATE_ROLLBACK_FAILED",
"UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS", "UPDATE_ROLLBACK_COMPLETE",
"REVIEW_IN_PROGRESS", "IMPORT_IN_PROGRESS", "IMPORT_COMPLETE",
"IMPORT_ROLLBACK_IN_PROGRESS", "IMPORT_ROLLBACK_FAILED", "IMPORT_ROLLBACK_COMPLETE",
]
def collect_cloudformation_stacks(session, region, account_id, partition) -> List[ResourceRecord]:
cfn = session.client("cloudformation", region_name=region, config=RETRY_CONFIG)
stacks = _paginate(cfn, "list_stacks", "StackSummaries",
StackStatusFilter=ACTIVE_STACK_STATUSES)
out = []
for s in stacks:
name = s["StackName"]
arn = s.get("StackId") or f"arn:{partition}:cloudformation:{region}:{account_id}:stack/{name}"
label = s.get("StackStatus", "")
if s.get("ParentId"):
label = (label + " [nested]").strip()
out.append(ResourceRecord(
resource_type="cloudformation:stack",
resource_id=name,
name=label,
arn=arn,
))
return out
def collect_sns_topics(session, region, account_id, partition) -> List[ResourceRecord]:
sns = session.client("sns", region_name=region, config=RETRY_CONFIG)
topics = _paginate(sns, "list_topics", "Topics")
out = []
for t in topics:
arn = t["TopicArn"]
out.append(ResourceRecord(
resource_type="sns:topic",
resource_id=arn.split(":")[-1],
name="",
arn=arn,
))
return out
def collect_ec2_amis(session, region, account_id, partition) -> List[ResourceRecord]:
"""Self-owned AMIs only -- describe_images() with no owner filter would
return AWS's entire public/marketplace AMI catalog (hundreds of
thousands of images), not this account's resources."""
ec2 = session.client("ec2", region_name=region, config=RETRY_CONFIG)
images = _paginate(ec2, "describe_images", "Images", Owners=["self"])
out = []
for img in images:
iid = img["ImageId"]
out.append(ResourceRecord(
resource_type="ec2:image",
resource_id=iid,
name=img.get("Name", ""),
arn=f"arn:{partition}:ec2:{region}:{account_id}:image/{iid}",
))
return out
def collect_ec2_snapshots(session, region, account_id, partition) -> List[ResourceRecord]:
"""Self-owned snapshots only -- same reasoning as AMIs above: an
unfiltered describe_snapshots() call returns every public snapshot in
the region, not this account's."""
ec2 = session.client("ec2", region_name=region, config=RETRY_CONFIG)
snaps = _paginate(ec2, "describe_snapshots", "Snapshots", OwnerIds=["self"])
out = []
for s in snaps:
sid = s["SnapshotId"]
out.append(ResourceRecord(
resource_type="ec2:snapshot",
resource_id=sid,
name=_tag_name(s.get("Tags")) or s.get("Description", ""),
arn=f"arn:{partition}:ec2:{region}:{account_id}:snapshot/{sid}",
))
return out
def collect_dynamodb_tables(session, region, account_id, partition) -> List[ResourceRecord]:
ddb = session.client("dynamodb", region_name=region, config=RETRY_CONFIG)
names = _paginate(ddb, "list_tables", "TableNames")
return [ResourceRecord(
resource_type="dynamodb:table", resource_id=name, name="",
arn=f"arn:{partition}:dynamodb:{region}:{account_id}:table/{name}",
) for name in names]
def collect_sqs_queues(session, region, account_id, partition) -> List[ResourceRecord]:
sqs = session.client("sqs", region_name=region, config=RETRY_CONFIG)
urls = _paginate(sqs, "list_queues", "QueueUrls")
out = []
for url in urls:
name = url.rstrip("/").split("/")[-1]
out.append(ResourceRecord(
resource_type="sqs:queue", resource_id=name, name="",
arn=f"arn:{partition}:sqs:{region}:{account_id}:{name}",
))
return out
CORE_COLLECTORS = [
("EC2 Instances", collect_ec2_instances),
("EBS Volumes", collect_ebs_volumes),
("EC2 AMIs", collect_ec2_amis),
("EC2 Snapshots", collect_ec2_snapshots),
("VPCs", collect_vpcs),
("RDS Instances", collect_rds_instances),
("RDS Clusters", collect_rds_clusters),
("Lambda Functions", collect_lambda_functions),
("Classic Load Balancers", collect_elb_classic),
("ALB/NLB/GWLB", collect_elbv2),
("CloudFormation Stacks", collect_cloudformation_stacks),
("SNS Topics", collect_sns_topics),
("SQS Queues", collect_sqs_queues),
("DynamoDB Tables", collect_dynamodb_tables),
]
def collect_s3_buckets_by_region(session, account_id, partition) -> Tuple[Dict[str, List[ResourceRecord]], List[CollectorError]]:
"""S3 is a global service -- list every bucket once, then resolve each
bucket's actual region so it can be folded into that region's results."""
errors: List[CollectorError] = []
by_region: Dict[str, List[ResourceRecord]] = defaultdict(list)
try:
s3 = session.client("s3", region_name="us-east-1", config=RETRY_CONFIG)
resp = s3.list_buckets()
except (ClientError, BotoCoreError, EndpointConnectionError) as e:
errors.append(_classify_error("global", "S3 ListBuckets", e))
return by_region, errors
for b in resp.get("Buckets", []):
name = b["Name"]
try:
loc = s3.get_bucket_location(Bucket=name).get("LocationConstraint")
region = loc or "us-east-1"
if region == "EU":
region = "eu-west-1"
except (ClientError, BotoCoreError, EndpointConnectionError) as e:
errors.append(_classify_error("global", f"S3 GetBucketLocation ({name})", e))
region = "unknown"
by_region[region].append(ResourceRecord(
resource_type="s3:bucket",
resource_id=name,
name="",
arn=f"arn:{partition}:s3:::{name}",
))
return by_region, errors
def collect_iam_users(session, account_id, partition) -> List[ResourceRecord]:
iam = session.client("iam", region_name="us-east-1", config=RETRY_CONFIG)
users = _paginate(iam, "list_users", "Users")
return [ResourceRecord(resource_type="iam:user", resource_id=u["UserName"], name="",
arn=u["Arn"]) for u in users]
def collect_iam_roles(session, account_id, partition) -> List[ResourceRecord]:
iam = session.client("iam", region_name="us-east-1", config=RETRY_CONFIG)
roles = _paginate(iam, "list_roles", "Roles")
out = []
for r in roles:
label = "service-linked" if r.get("Path", "").startswith("/aws-service-role/") else ""
out.append(ResourceRecord(resource_type="iam:role", resource_id=r["RoleName"],
name=label, arn=r["Arn"]))
return out
def collect_iam_groups(session, account_id, partition) -> List[ResourceRecord]:
iam = session.client("iam", region_name="us-east-1", config=RETRY_CONFIG)
groups = _paginate(iam, "list_groups", "Groups")
return [ResourceRecord(resource_type="iam:group", resource_id=g["GroupName"], name="",
arn=g["Arn"]) for g in groups]
def collect_iam_access_keys(session, account_id, partition) -> List[ResourceRecord]:
"""Independently re-lists users (rather than sharing collect_iam_users's
result) so this collector fails/succeeds on its own -- consistent with
every other collector never depending on another collector's state."""
iam = session.client("iam", region_name="us-east-1", config=RETRY_CONFIG)
users = _paginate(iam, "list_users", "Users")
out = []
for u in users:
user_name = u["UserName"]
keys = _paginate(iam, "list_access_keys", "AccessKeyMetadata", UserName=user_name)
for k in keys:
key_id = k["AccessKeyId"]
created = k.get("CreateDate")
created_str = created.strftime("%Y-%m-%d") if hasattr(created, "strftime") else ""
out.append(ResourceRecord(
resource_type="iam:access-key", resource_id=key_id,
name=f"{k.get('Status', '')}, user={user_name}, created={created_str}",
arn=f"arn:{partition}:iam::{account_id}:user/{user_name}/access-key/{key_id}",
))
return out
IAM_COLLECTORS = [
("IAM Users", collect_iam_users),
("IAM Roles", collect_iam_roles),
("IAM Groups", collect_iam_groups),
("IAM Access Keys", collect_iam_access_keys),
]
def collect_tagged_resources(session, region, account_id, partition) -> List[ResourceRecord]:
"""Catch-all via the Resource Groups Tagging API -- covers most
services not explicitly collected above (KMS, ECS/EKS, API Gateway,
etc.)."""
client = session.client("resourcegroupstaggingapi", region_name=region, config=RETRY_CONFIG)
items = _paginate(client, "get_resources", "ResourceTagMappingList", ResourcesPerPage=100)
out = []
for item in items:
arn = item["ResourceARN"]
rtype, rid = _type_and_id_from_arn(arn)
out.append(ResourceRecord(
resource_type=rtype,
resource_id=rid,
name=_tag_name(item.get("Tags")),
arn=arn,
))
return out
def _type_and_id_from_arn(arn: str) -> Tuple[str, str]:
"""Best-effort parse of an ARN's resource type and resource id, handling
both 'service:region:account:type/id' and 'service:region:account:type:id'
ARN shapes."""
parts = arn.split(":", 5)
if len(parts) < 6:
return "unknown", arn
service = parts[2]
resource_part = parts[5]
if "/" in resource_part:
rtype, rid = resource_part.split("/", 1)
elif ":" in resource_part:
rtype, rid = resource_part.split(":", 1)
else:
rtype, rid = resource_part, resource_part
return f"{service}:{rtype}", rid
# --------------------------------------------------------------------------
# Per-region scan orchestration
# --------------------------------------------------------------------------
def _run_collectors(collectors, error_region_label: str, fn_args: tuple,
extra_records=None) -> Tuple[List[ResourceRecord], List[CollectorError], bool]:
"""Runs a list of (label, fn) collectors against the same args, merging
results de-duplicated by ARN and tracking per-collector failures without
letting any single denied/broken collector take down the others. Shared
by scan_region() (regional collectors) and IAM collection (global,
once per account)."""
seen_arns: Set[str] = set()
records: List[ResourceRecord] = []
errors: List[CollectorError] = []
any_success = False
def add(rec: ResourceRecord):
if rec.arn not in seen_arns:
seen_arns.add(rec.arn)
records.append(rec)
for label, fn in collectors:
try:
for rec in fn(*fn_args):
add(rec)
any_success = True
except (ClientError, BotoCoreError, EndpointConnectionError) as e:
errors.append(_classify_error(error_region_label, label, e))
except Exception as e: # defensive -- never let one collector kill the scan
errors.append(_classify_error(error_region_label, label, e))
for rec in (extra_records or []):
add(rec)
any_success = True
return records, errors, any_success
def scan_region(session, account_id, partition, region, extra_records=None,
skip_tagging_api=False) -> Tuple[List[ResourceRecord], List[CollectorError], bool, int]:
collector_total = len(CORE_COLLECTORS) + (0 if skip_tagging_api else 1)
collectors = list(CORE_COLLECTORS)
if not skip_tagging_api:
collectors = collectors + [("Resource Groups Tagging API", collect_tagged_resources)]
records, errors, any_success = _run_collectors(
collectors, region, (session, region, account_id, partition), extra_records=extra_records,
)
return records, errors, any_success, collector_total
def collect_iam_resources(session, account_id, partition) -> Tuple[List[ResourceRecord], List[CollectorError], bool]:
"""IAM is a fully global service -- collected ONCE per account here,
never inside the per-region loop, so the same role/user/group ARN
doesn't get counted once per enabled region."""
return _run_collectors(IAM_COLLECTORS, "global", (session, account_id, partition))
def get_account_identity(session, bootstrap_region) -> Tuple[str, str]:
sts = session.client("sts", region_name=bootstrap_region, config=RETRY_CONFIG)
identity = sts.get_caller_identity()
arn = identity["Arn"]
partition = arn.split(":")[1]
return identity["Account"], partition
def get_all_regions(session, bootstrap_region) -> List[Tuple[str, bool]]:
"""Returns [(region_name, enabled), ...]. A disabled (opt-in-not-enabled)
region is a GOOD thing -- it can't hold running resources."""
ec2 = session.client("ec2", region_name=bootstrap_region, config=RETRY_CONFIG)
resp = ec2.describe_regions(AllRegions=True)
out = []
for r in resp["Regions"]:
enabled = r["OptInStatus"] in ("opt-in-not-required", "opted-in")
out.append((r["RegionName"], enabled))
return sorted(out, key=lambda x: x[0])
# --------------------------------------------------------------------------
# Findings classification
# --------------------------------------------------------------------------
def classify(region_result: RegionResult, expected_regions: Optional[Set[str]]):
r = region_result
if r.is_pseudo_region:
# IAM is global, not region-scoped -- "expected region" logic simply
# doesn't apply to it. Report it as inventory, not a region finding.
r.expected = None
if r.resource_count is None:
r.finding = (f"Global IAM inventory - could not enumerate "
f"({len(r.errors)}/{r.collector_total} collectors denied)")
r.severity = "error"
else:
r.finding = "Global IAM inventory (account-wide, not region-scoped)"
r.severity = "info"
if r.errors:
r.finding += (f" [INCOMPLETE: {len(r.errors)}/{r.collector_total} "
f"collectors denied -- count is a MINIMUM]")
r.severity = "partial"
return
if not r.enabled:
r.expected = None
r.finding = "Disabled (good)"
r.severity = "good"
return
# Whether this region is on the documented/expected list is knowable
# regardless of whether we could enumerate what's inside it -- an
# enabled region outside the expected footprint is itself a finding,
# even when permissions block us from confirming what's running there.
r.expected = (r.region in expected_regions) if expected_regions is not None else None
if r.resource_count is None:
# Every collector was denied -- resources are UNKNOWN, not zero.
if expected_regions is None:
r.finding = (f"ERROR - could not enumerate "
f"({len(r.errors)}/{r.collector_total} collectors denied -- check permissions)")
r.severity = "error"
elif r.expected:
r.finding = (f"Expected region, but resource status UNKNOWN "
f"({len(r.errors)}/{r.collector_total} collectors denied -- check permissions)")
r.severity = "error"
else:
r.finding = (f"FINDING - enabled region NOT expected; resource status UNCONFIRMED "
f"({len(r.errors)}/{r.collector_total} collectors denied) -- a region with "
f"no expected resources should not be enabled at all; MANUAL REVIEW REQUIRED")
r.severity = "finding_unconfirmed"
return
if expected_regions is None:
r.finding = "In use" if r.resource_count > 0 else "Enabled, no resources found"
r.severity = "info" if r.resource_count > 0 else "none"
else:
if r.expected and r.resource_count > 0:
r.finding = "OK - expected region, in use"
r.severity = "ok"
elif r.expected and r.resource_count == 0:
r.finding = "Expected region, but NO resources found"
r.severity = "info"
elif not r.expected and r.resource_count > 0:
r.finding = "FINDING - unexpected resources present"
r.severity = "finding"
else: # not expected, zero resources (fully or partially confirmed)
r.finding = "FINDING - enabled region not expected, unused (disablement candidate)"
r.severity = "warn"
# Some collectors succeeded (so resource_count is real) but others were
# denied -- the count is a MINIMUM, not a confirmed total. Flag this
# quantitatively rather than silently under-reporting.
if r.errors:
r.finding += (f" [INCOMPLETE: {len(r.errors)}/{r.collector_total} collectors denied "
f"-- count is a MINIMUM]")
if r.severity in ("good", "ok", "info", "none"):
r.severity = "partial"
# --------------------------------------------------------------------------
# Account-level rollup metrics
# --------------------------------------------------------------------------
def compute_account_metrics(region_results: List[RegionResult], expected_regions: Optional[Set[str]]) -> dict:
m = Counter()
real_regions = [r for r in region_results if not r.is_pseudo_region]
m["total_regions_checked"] = len(real_regions)
for r in real_regions:
if not r.enabled:
m["disabled_regions"] += 1
continue
m["enabled_regions"] += 1
if r.resource_count is None:
m["regions_with_errors"] += 1
m["total_collector_errors"] += len(r.errors)
else:
if r.resource_count > 0:
m["enabled_regions_with_resources"] += 1
else:
m["enabled_regions_without_resources"] += 1
if r.errors:
m["regions_with_partial_data"] += 1
m["total_collector_errors"] += len(r.errors)
if expected_regions is None:
continue
if r.expected:
if r.resource_count is None:
m["expected_regions_unknown"] += 1
elif r.resource_count > 0:
m["expected_regions_with_resources"] += 1
else:
m["expected_regions_without_resources"] += 1
else:
# An enabled region outside the expected footprint is a FINDING
# on its own -- always counted here, even when we couldn't
# enumerate what (if anything) is running in it.
m["enabled_regions_not_expected"] += 1
if r.resource_count is not None and r.resource_count > 0:
m["unexpected_regions_with_resources"] += 1 # KEY FINDING -- confirmed
elif r.resource_count == 0 and not r.errors:
m["unused_enabled_regions_not_expected"] += 1 # KEY FINDING -- confirmed unused
else:
# resource_count is None, or 0-but-only-a-floor (some
# collectors denied) -- we genuinely don't know if it's
# empty. Still a finding: it shouldn't be enabled at all.
m["unexpected_regions_unconfirmed"] += 1 # KEY FINDING -- inconclusive
# IAM is global, not region-scoped -- reported separately from the
# region tallies above rather than folded into them.
for r in region_results:
if r.is_pseudo_region:
m["iam_resource_count"] = r.resource_count if r.resource_count is not None else 0
m["iam_data_unknown"] = 1 if r.resource_count is None else 0
m["iam_collector_errors"] = len(r.errors)
return m
# --------------------------------------------------------------------------
# CLI
# --------------------------------------------------------------------------
def split_regions(values: List[str]) -> Set[str]:
out = set()
for v in values:
for piece in v.split(","):
piece = piece.strip().lower()
if piece:
out.add(piece)
return out
def parse_args():
p = argparse.ArgumentParser(
description="Enumerate AWS resources across every region for one or more profiles, "
"and flag regions used outside a documented/expected footprint.",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=__doc__,
)
profile_group = p.add_mutually_exclusive_group(required=True)
profile_group.add_argument("--profile", help="Scan only this profile from the credentials file.")
profile_group.add_argument("--all-profiles", action="store_true",
help="Scan every profile found in the credentials file.")
p.add_argument("--expected-regions", nargs="+", default=None, metavar="REGION",
help="Region(s) the customer expects to have resources in. "
"Comma- and/or space-separated, e.g. "
"--expected-regions us-east-1,us-west-2 or "
"--expected-regions us-east-1 us-west-2. "
"If omitted, the report is purely informational (nothing is "
"flagged as 'unexpected', but usage is still shown).")
p.add_argument("--credentials-file", default="~/.aws/credentials",
help="Path to the AWS credentials file (default: ~/.aws/credentials).")
p.add_argument("--regions", nargs="+", default=None, metavar="REGION",
help="Restrict the scan to these regions instead of every region in the "
"partition (comma- and/or space-separated). Mostly useful for testing.")
p.add_argument("--bootstrap-region", default="us-east-1",
help="Region used to call STS/EC2 DescribeRegions to discover the account "
"and region list (default: us-east-1). Use a GovCloud/China region "
"here if auditing a profile in one of those partitions.")
p.add_argument("--output-dir", default=None,
help="Directory to write CSV output to (default: "
"./aws_resource_audit_<timestamp>).")
p.add_argument("--no-tagging-api", action="store_true",
help="Skip the Resource Groups Tagging API catch-all collector "
"(only the explicitly-coded resource types will be counted). "
"Use this if the account lacks tag:GetResources permission.")
p.add_argument("--no-color", action="store_true", help="Disable colored/highlighted STDOUT output.")
p.add_argument("--verbose", "-v", action="store_true",
help="Print the full raw error for every failed collector call (permission "
"denials, SCP explicit denies, etc.) as it happens. Without this flag, "
"those errors are silenced on STDOUT and instead surfaced as quantified "
"counts in the region summary table/CSV and in "
"5_collector_errors_<timestamp>.csv.")
p.add_argument("--max-workers", type=int, default=8, metavar="N",
help="Max region-scans to run concurrently, pooled across every profile "
"being audited (default: 8). Each worker still calls the ~15 collectors "
"for its region one at a time, so this bounds total concurrent AWS API "
"calls, not multiplies against region/profile counts. Every client also "
"retries with adaptive backoff on throttling, so raising this is safe to "
"try if scans still feel slow; lower it if you actually get throttled. "
"Use --max-workers 1 to scan strictly sequentially (old behavior).")
return p.parse_args()
def resolve_profiles(args) -> List[str]:
cred_path = Path(os.path.expanduser(args.credentials_file))
if not cred_path.exists():
print(f"ERROR: credentials file not found: {cred_path}", file=sys.stderr)
sys.exit(1)
parser = configparser.ConfigParser()
parser.read(cred_path)
available = list(parser.sections())
# configparser hides a literal [default] section behind DEFAULTSECT handling
# in some edge cases; the AWS CLI also treats "default" as a valid profile name.
if "default" not in available and parser.defaults():
available.insert(0, "default")
if not available:
print(f"ERROR: no profiles found in {cred_path}", file=sys.stderr)
sys.exit(1)
if args.all_profiles:
return available
if args.profile not in available:
print(f"ERROR: profile '{args.profile}' not found in {cred_path}.\n"
f"Available profiles: {', '.join(available)}", file=sys.stderr)
sys.exit(1)
return [args.profile]
# --------------------------------------------------------------------------
# STDOUT rendering
# --------------------------------------------------------------------------
SEVERITY_STYLE = {
"good": "dim green",