audit-labs/audit-tools

A collection of scripts, queries, and other goodies you can use in an audit. audit automation compliance evidence scripts

tui/aws_runner.py

v1.1.0
audit-tools/tui/aws_runner.py history · blame · raw

150 lines · 4493 bytes

  1"""
  2Drive the AWS audit collectors from the TUI.
  3
  4Reuses the collectors and CSV reporter under ``applications/aws`` unchanged.
  5Mirrors the other runners: a ``CHECKS`` registry plus ``run_audit`` that writes
  6the same package ``applications/aws/audit.py`` produces and reports progress
  7through a callback.
  8
  9AWS collectors take a single config dict (a boto3 session plus region/account);
 10there is no per-item cache, so every check is called as ``fn(cfg)``.
 11"""
 12
 13import os
 14import sys
 15from collections.abc import Iterable
 16from dataclasses import dataclass
 17from datetime import date
 18
 19from tui.common import Check, ProgressCallback, ProgressEvent
 20
 21_REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 22if _REPO_ROOT not in sys.path:
 23    sys.path.insert(0, _REPO_ROOT)
 24
 25from applications.aws.collectors import (
 26    api,
 27    iam,
 28    monitoring,
 29    s3,
 30    security_groups,
 31    sso,
 32)
 33from applications.aws.reporters import csv_reporter
 34
 35# --- Check registry ---------------------------------------------------------
 36
 37CHECKS: list[Check] = [
 38    Check("iam_users", "IAM users", iam.iam_users, "iam_users.csv"),
 39    Check(
 40        "password_policy",
 41        "Password policy",
 42        iam.password_policy,
 43        "password_policy.csv",
 44    ),
 45    Check(
 46        "account_security",
 47        "Account security (root MFA)",
 48        iam.account_security,
 49        "account_security.csv",
 50    ),
 51    Check(
 52        "s3_public_access",
 53        "S3 public access",
 54        s3.s3_public_access,
 55        "s3_public_access.csv",
 56    ),
 57    Check(
 58        "security_groups",
 59        "Open security groups",
 60        security_groups.security_groups,
 61        "open_security_groups.csv",
 62        note="scans all regions",
 63    ),
 64    Check("cloudtrail", "CloudTrail", monitoring.cloudtrail, "cloudtrail.csv"),
 65    Check(
 66        "config_recorders",
 67        "AWS Config recorders",
 68        monitoring.config_recorders,
 69        "config_recorders.csv",
 70        note="scans all regions",
 71    ),
 72    Check(
 73        "sso_assignments",
 74        "SSO assignments",
 75        sso.sso_assignments,
 76        "sso_assignments.csv",
 77        note="requires Identity Center + Organizations",
 78    ),
 79]
 80
 81DEFAULT_SELECTION = [c.key for c in CHECKS if c.key != "sso_assignments"]
 82
 83
 84# --- Output helper ----------------------------------------------------------
 85
 86
 87def default_output_dir(out: str, profile: str) -> str:
 88    """Match the folder naming used by applications/aws/audit.py."""
 89    subject = profile or "default"
 90    return os.path.join(out, f"aws_audit_{subject}_{date.today().isoformat()}")
 91
 92
 93@dataclass(frozen=True)
 94class AwsTarget:
 95    """The AWS profile, region, and account to audit."""
 96
 97    profile: str
 98    region: str
 99    account: str
100
101
102# --- Runner -----------------------------------------------------------------
103
104
105def run_audit(
106    target: AwsTarget,
107    *,
108    output_dir: str,
109    selected_keys: Iterable[str],
110    on_event: ProgressCallback,
111) -> list[tuple[str, int]]:
112    """
113    Run the selected checks and write the audit package to ``output_dir``.
114
115    A collector that raises is reported as an error and recorded with a count
116    of 0, so one bad check never aborts the whole run. If the AWS session itself
117    can't be built (e.g. an unknown profile), that is reported and the run ends
118    cleanly.
119    """
120    profile, region, account = target.profile, target.region, target.account
121    subject = profile or "default"
122    selected = set(selected_keys)
123    checks = [c for c in CHECKS if c.key in selected]
124
125    try:
126        cfg = api.build_cfg(profile, region, account)
127    except Exception as e:
128        on_event(ProgressEvent("error", "AWS session", message=str(e)))
129        csv_reporter.write_summary(output_dir, subject, [])
130        on_event(ProgressEvent("summary", output_dir, count=0))
131        return []
132
133    sections: list[tuple[str, int]] = []
134    for c in checks:
135        on_event(ProgressEvent("start", c.label))
136        try:
137            rows = c.fn(cfg)
138        except Exception as e:
139            on_event(ProgressEvent("error", c.label, message=str(e)))
140            sections.append((c.label, 0))
141            continue
142
143        csv_reporter.write(output_dir, c.filename, rows)
144        sections.append((c.label, len(rows)))
145        on_event(ProgressEvent("done", c.label, count=len(rows)))
146
147    csv_reporter.write_summary(output_dir, subject, sections)
148    total = sum(n for _, n in sections)
149    on_event(ProgressEvent("summary", output_dir, count=total))
150    return sections