audit-labs/audit-tools
A collection of scripts, queries, and other goodies you can use in an audit.
clone: git clone https://gitbay.org/audit-labs/audit-tools.git
v1.0.0: applications/aws/collectors/api.py · raw
1"""Shared AWS session helpers.
2
3Authentication uses the standard boto3 credential chain (environment variables,
4shared config/credentials files, SSO profiles, instance roles). No access keys
5are ever passed in or stored by this tool.
6"""
7
8import boto3
9
10
11def build_cfg(profile="", region="", account=""):
12 """Build the config dict the collectors expect.
13
14 ``profile`` and ``region`` are optional; when empty, boto3's default
15 resolution applies. ``account`` is an optional account name used only by the
16 SSO assignments collector.
17 """
18 kwargs = {}
19 if profile:
20 kwargs["profile_name"] = profile
21 if region:
22 kwargs["region_name"] = region
23 session = boto3.Session(**kwargs)
24 return {
25 "session": session,
26 "profile": profile,
27 "region": region,
28 "account": account,
29 }
30
31
32def account_id(cfg):
33 """Return the AWS account ID for the active credentials, or '' on failure."""
34 try:
35 return cfg["session"].client("sts").get_caller_identity()["Account"]
36 except Exception:
37 return ""
38
39
40def enabled_regions(cfg):
41 """Return the region names enabled for the account (for region-scoped checks)."""
42 ec2 = cfg["session"].client("ec2", region_name=cfg.get("region") or "us-east-1")
43 return [r["RegionName"] for r in ec2.describe_regions().get("Regions", [])]