cloud security

Performing AWS Account Enumeration with ScoutSuite

Perform comprehensive security posture assessment of AWS accounts using ScoutSuite to enumerate resources, identify misconfigurations, and generate actionable security reports.

awscloud-securitycspmenumerationmisconfigurationnccgroupscoutsuitesecurity-audit
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

Overview

ScoutSuite is an open-source multi-cloud security auditing tool developed by NCC Group that enables comprehensive security posture assessment of AWS environments. It queries AWS APIs to gather configuration data across all services, stores results locally, and generates interactive HTML reports highlighting high-risk areas. ScoutSuite is agentless and works by analyzing how cloud resources are configured, accessed, and monitored.

When to Use

  • When conducting security assessments that involve performing aws account enumeration with scout suite
  • When following incident response procedures for related security events
  • When performing scheduled security testing or auditing activities
  • When validating security controls through hands-on testing

Prerequisites

  • Python 3.6+ installed
  • AWS CLI configured with appropriate IAM credentials
  • Read-only IAM permissions across target AWS services (SecurityAudit managed policy recommended)
  • pip package manager for ScoutSuite installation
  • Network access to AWS API endpoints

Installation and Setup

Install ScoutSuite

pip install scoutsuite

Verify installation

scout --version

Configure AWS credentials

aws configure
# Or use environment variables:
export AWS_ACCESS_KEY_ID=<your-key>
export AWS_SECRET_ACCESS_KEY=<your-secret>
export AWS_DEFAULT_REGION=us-east-1

Required IAM Policy

Attach the AWS managed policy SecurityAudit and ViewOnlyAccess to the IAM user or role running ScoutSuite. For comprehensive scanning, a custom policy may be needed:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "acm:Describe*",
        "acm:List*",
        "cloudformation:Describe*",
        "cloudformation:Get*",
        "cloudformation:List*",
        "cloudtrail:Describe*",
        "cloudtrail:Get*",
        "cloudtrail:List*",
        "cloudwatch:Describe*",
        "cloudwatch:Get*",
        "cloudwatch:List*",
        "config:Describe*",
        "config:Get*",
        "config:List*",
        "dynamodb:Describe*",
        "dynamodb:List*",
        "ec2:Describe*",
        "ec2:Get*",
        "elasticloadbalancing:Describe*",
        "iam:Generate*",
        "iam:Get*",
        "iam:List*",
        "iam:Simulate*",
        "kms:Describe*",
        "kms:Get*",
        "kms:List*",
        "lambda:Get*",
        "lambda:List*",
        "logs:Describe*",
        "logs:Get*",
        "rds:Describe*",
        "rds:List*",
        "redshift:Describe*",
        "route53:Get*",
        "route53:List*",
        "s3:Get*",
        "s3:List*",
        "ses:Get*",
        "ses:List*",
        "sns:Get*",
        "sns:List*",
        "sqs:Get*",
        "sqs:List*",
        "ssm:Describe*",
        "ssm:Get*",
        "ssm:List*"
      ],
      "Resource": "*"
    }
  ]
}

Running ScoutSuite

Full AWS scan

scout aws

Scan specific services only

scout aws --services s3 iam ec2 rds

Scan specific regions

scout aws --regions us-east-1 us-west-2 eu-west-1

Use an assumed role for cross-account scanning

scout aws --profile target-account-profile

Exclude specific services from scan

scout aws --skip iam ec2

Specify output directory

scout aws --report-dir /tmp/scoutsuite-reports/

Report Analysis

ScoutSuite generates an interactive HTML report stored locally. The report includes:

  1. Dashboard: Overview of findings by severity (danger, warning, good)
  2. Service-level findings: Grouped by AWS service (IAM, S3, EC2, RDS, etc.)
  3. Rule-based checks: Each finding maps to a security best practice rule
  4. Resource inventory: Complete listing of enumerated resources

Key areas to review in the report

Service Critical Checks
IAM Root account MFA, password policy, unused credentials, overprivileged policies
S3 Public buckets, unencrypted buckets, versioning disabled, logging disabled
EC2 Security groups with 0.0.0.0/0, unencrypted EBS volumes, public IPs
RDS Public accessibility, unencrypted databases, backup retention
CloudTrail Logging disabled, log file validation, multi-region disabled
Lambda Public access, environment variable secrets, VPC configuration

Interpreting Findings

Severity Levels

  • Danger (Red): Critical security issues requiring immediate remediation (e.g., S3 buckets with public write access)
  • Warning (Orange): Moderate risk findings that should be addressed (e.g., unused IAM access keys)
  • Good (Green): Security best practices that are properly configured

Common High-Risk Findings

  1. IAM root account without MFA: The AWS root account has no multi-factor authentication enabled
  2. S3 bucket policy allows public access: Bucket policies with Principal set to "*"
  3. Security group allows unrestricted SSH: Inbound rule allowing 0.0.0.0/0 on port 22
  4. CloudTrail not enabled in all regions: Audit logging gaps allow unmonitored API activity
  5. RDS instance publicly accessible: Database endpoints reachable from the internet

Remediation Workflow

  1. Run ScoutSuite scan to establish baseline
  2. Export findings and prioritize by severity
  3. Create remediation tickets for danger and warning findings
  4. Implement fixes (update security groups, enable encryption, restrict access)
  5. Re-run ScoutSuite to verify remediation
  6. Schedule regular scans (weekly or after infrastructure changes)

Integration with CI/CD

# Run ScoutSuite in CI/CD pipeline and fail on danger findings
scout aws --services s3 iam ec2 --no-browser --report-dir ./scout-report/
 
# Parse results programmatically
python -c "
import json
with open('./scout-report/scoutsuite-results/scoutsuite_results.json') as f:
    results = json.load(f)
    for service in results.get('services', {}):
        findings = results['services'][service].get('findings', {})
        for finding_id, finding in findings.items():
            if finding.get('flagged_items', 0) > 0 and finding.get('level') == 'danger':
                print(f'CRITICAL: {finding_id} - {finding.get(\"description\", \"\")}')
"

Multi-Cloud Capability

ScoutSuite supports multiple cloud providers using the same framework:

# Azure
scout azure --cli
 
# GCP
scout gcp --user-account
 
# AWS with specific profile
scout aws --profile production

References

Source materials

References and resources

Everything below is rendered for inspection. Script files are read-only and never run.

References 3

api-reference.md5.0 KB

API Reference: AWS Account Enumeration with Scout Suite

Libraries Used

Library Purpose
subprocess Execute Scout Suite CLI scans
json Parse Scout Suite JSON report output
boto3 AWS SDK for supplementary API calls
os Read AWS credentials from environment

Installation

pip install scoutsuite boto3
 
# Or from source
git clone https://github.com/nccgroup/ScoutSuite
cd ScoutSuite
pip install -r requirements.txt
python scout.py --help

Authentication

Scout Suite uses standard AWS credential chain:

import os
 
# Option 1: Environment variables
os.environ["AWS_ACCESS_KEY_ID"] = "AKIA..."
os.environ["AWS_SECRET_ACCESS_KEY"] = "..."
os.environ["AWS_DEFAULT_REGION"] = "us-east-1"
 
# Option 2: AWS CLI profile
# scout aws --profile my-profile
 
# Option 3: IAM Role (EC2 instance profile / ECS task role)
# Automatically detected by boto3

CLI Reference

Full AWS Account Scan

scout aws --report-dir ./scout-report

Scan Specific Services

scout aws --services iam s3 ec2 rds lambda --report-dir ./scout-report

Scan Specific Regions

scout aws --regions us-east-1 us-west-2 eu-west-1 --report-dir ./scout-report

Use Named Profile

scout aws --profile production-readonly --report-dir ./scout-report

Key CLI Flags

Flag Description
--provider Cloud provider: aws, azure, gcp
--profile AWS CLI named profile
--regions Specific AWS regions to scan
--services Specific services to audit
--report-dir Output directory for HTML report
--no-browser Don't open report in browser
--max-workers Number of parallel API threads
--result-format Output format: json, csv
--exceptions Path to exceptions file (known acceptable findings)
--ruleset Custom ruleset file for scoring

Python Integration

Run Scout Suite and Parse Results

import subprocess
import json
from pathlib import Path
 
def run_scout(services=None, regions=None, profile=None, report_dir="/tmp/scout"):
    cmd = ["scout", "aws", "--report-dir", report_dir, "--no-browser"]
    if services:
        cmd.extend(["--services"] + services)
    if regions:
        cmd.extend(["--regions"] + regions)
    if profile:
        cmd.extend(["--profile", profile])
 
    result = subprocess.run(cmd, capture_output=True, text=True, timeout=1800)
    if result.returncode != 0:
        raise RuntimeError(f"Scout Suite failed: {result.stderr}")
 
    # Parse the JSON results
    report_path = Path(report_dir) / "scoutsuite-results" / "scoutsuite_results.json"
    if report_path.exists():
        with open(report_path) as f:
            return json.load(f)
    return None

Extract High-Risk Findings

def extract_findings(report, min_severity="warning"):
    severity_order = {"danger": 3, "warning": 2, "info": 1}
    min_level = severity_order.get(min_severity, 1)
    findings = []
 
    for service_name, service_data in report.get("services", {}).items():
        for rule_name, rule_data in service_data.get("findings", {}).items():
            level = severity_order.get(rule_data.get("level", "info"), 0)
            if level >= min_level:
                findings.append({
                    "service": service_name,
                    "rule": rule_name,
                    "severity": rule_data.get("level"),
                    "description": rule_data.get("description"),
                    "flagged_items": rule_data.get("flagged_items", 0),
                    "checked_items": rule_data.get("checked_items", 0),
                })
    return sorted(findings, key=lambda x: severity_order.get(x["severity"], 0), reverse=True)

Common Findings Categories

Service Common Findings
IAM Root account MFA, access key rotation, overly permissive policies
S3 Public buckets, missing encryption, no versioning
EC2 Security groups with 0.0.0.0/0, unencrypted EBS, public IPs
RDS Public access, no encryption at rest, no multi-AZ
Lambda Overly permissive roles, environment variable secrets
CloudTrail Logging disabled, no log file validation
VPC Default VPC in use, missing flow logs

Output Format

{
  "provider_code": "aws",
  "account_id": "123456789012",
  "last_run": {
    "time": "2025-01-15T10:30:00Z",
    "ruleset_name": "default",
    "run_parameters": {"services": ["iam", "s3", "ec2"]}
  },
  "services": {
    "iam": {
      "findings": {
        "iam-root-account-no-mfa": {
          "level": "danger",
          "description": "Root account does not have MFA enabled",
          "flagged_items": 1,
          "checked_items": 1
        }
      }
    },
    "s3": {
      "findings": {
        "s3-bucket-no-default-encryption": {
          "level": "warning",
          "description": "S3 bucket does not have default encryption",
          "flagged_items": 3,
          "checked_items": 15
        }
      }
    }
  }
}
standards.md1.9 KB

Standards and References - AWS Account Enumeration with ScoutSuite

Industry Standards

CIS AWS Foundations Benchmark v3.0

  • Section 1: Identity and Access Management
  • Section 2: Logging
  • Section 3: Monitoring
  • Section 4: Networking
  • Section 5: Storage

AWS Well-Architected Framework - Security Pillar

  • SEC 1: Securely operate your workload
  • SEC 2: Manage identities for people and machines
  • SEC 3: Manage permissions for people and machines
  • SEC 6: Protect compute resources
  • SEC 8: Protect data at rest
  • SEC 9: Protect data in transit

NIST 800-53 Mapped Controls

  • AC-2: Account Management
  • AU-2: Audit Events
  • AU-6: Audit Review, Analysis, and Reporting
  • CM-6: Configuration Settings
  • SC-7: Boundary Protection

ScoutSuite Rule Mappings

IAM Rules

Rule ID Description CIS Benchmark
iam-root-account-no-mfa Root account MFA not enabled 1.5
iam-user-no-mfa IAM user without MFA 1.10
iam-password-policy-no-uppercase Weak password policy 1.5
iam-unused-access-key Access key unused > 90 days 1.12
iam-inline-policy Inline policies attached to users 1.16

S3 Rules

Rule ID Description CIS Benchmark
s3-bucket-public-access Bucket allows public access 2.1.5
s3-bucket-no-logging Server access logging disabled 2.1.3
s3-bucket-no-versioning Versioning not enabled N/A
s3-bucket-no-encryption Default encryption not set 2.1.1

EC2 Rules

Rule ID Description CIS Benchmark
ec2-security-group-opens-all-ports Security group allows all traffic 5.2
ec2-instance-with-public-ip Instance has public IP N/A
ec2-ebs-volume-not-encrypted EBS volume unencrypted 2.2.1

Compliance Framework Coverage

  • SOC 2 Type II
  • PCI DSS v4.0
  • HIPAA Security Rule
  • ISO 27001:2022
  • GDPR (data protection controls)
workflows.md2.4 KB

Workflows - AWS Account Enumeration with ScoutSuite

Standard Security Assessment Workflow

1. Preparation Phase
   ├── Define scope (accounts, regions, services)
   ├── Create read-only IAM role with SecurityAudit policy
   ├── Install and configure ScoutSuite
   └── Verify credentials and connectivity
 
2. Enumeration Phase
   ├── Run ScoutSuite against target AWS account
   ├── Monitor scan progress and address API errors
   ├── Collect results from all specified regions
   └── Generate HTML report
 
3. Analysis Phase
   ├── Review dashboard for severity distribution
   ├── Prioritize danger-level findings
   ├── Map findings to CIS Benchmarks
   ├── Identify patterns across services
   └── Document false positives
 
4. Reporting Phase
   ├── Create executive summary of findings
   ├── Detail remediation steps per finding
   ├── Assign priority and ownership
   └── Establish remediation timeline
 
5. Remediation Phase
   ├── Implement fixes per priority order
   ├── Re-scan to validate remediation
   ├── Update documentation
   └── Schedule recurring assessments

Multi-Account Assessment Workflow

1. Setup Organization Scanning
   ├── Create cross-account IAM roles in each target account
   ├── Configure trust relationships to auditor account
   └── Prepare account list and scanning schedule
 
2. Execute Scans
   ├── Iterate through accounts using assume-role
   ├── Run ScoutSuite per account
   ├── Aggregate results into central location
   └── Generate per-account and aggregate reports
 
3. Consolidate Findings
   ├── Merge findings across accounts
   ├── Identify organization-wide patterns
   ├── Compare accounts against baseline
   └── Produce organization security scorecard

CI/CD Integration Workflow

1. Pipeline Trigger
   ├── Infrastructure change detected (Terraform/CloudFormation)
   └── Scheduled nightly scan
 
2. Automated Scan
   ├── Run ScoutSuite with targeted service scope
   ├── Parse JSON results programmatically
   └── Evaluate against security baseline
 
3. Gate Decision
   ├── Danger findings → Block deployment, alert security team
   ├── Warning findings → Proceed with notification
   └── No findings → Continue pipeline

Scripts 2

agent.py9.1 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""ScoutSuite AWS account enumeration and security audit agent.

Wraps the ScoutSuite CLI to perform comprehensive AWS security audits,
parses the generated JSON results, and produces a structured findings
report covering IAM, S3, EC2, RDS, Lambda, and other AWS services.
"""
import argparse
import json
import os
import subprocess
import sys
from datetime import datetime, timezone


def find_scoutsuite_binary():
    """Locate the scout CLI binary."""
    custom_path = os.environ.get("SCOUTSUITE_PATH")
    if custom_path and os.path.isfile(custom_path):
        return custom_path
    for name in ["scout", "scout.exe"]:
        for directory in os.environ.get("PATH", "").split(os.pathsep):
            full_path = os.path.join(directory, name)
            if os.path.isfile(full_path):
                return full_path
    return None


def run_scoutsuite(scout_bin, profile=None, services=None, regions=None,
                   result_dir=None, max_workers=None, no_browser=True):
    """Execute ScoutSuite AWS scan."""
    if scout_bin:
        cmd = [scout_bin, "aws"]
    else:
        cmd = [sys.executable, "-m", "ScoutSuite", "aws"]

    if profile:
        cmd.extend(["--profile", profile])
    if services:
        cmd.extend(["--services"] + services)
    if regions:
        cmd.extend(["--regions"] + regions)
    if result_dir:
        cmd.extend(["--report-dir", result_dir])
    if max_workers:
        cmd.extend(["--max-workers", str(max_workers)])
    if no_browser:
        cmd.append("--no-browser")

    print(f"[*] Running: {' '.join(cmd)}")
    result = subprocess.run(
        cmd,
        capture_output=True,
        text=True,
        timeout=1800,
    )
    if result.returncode != 0:
        print(f"[!] ScoutSuite exited with code {result.returncode}", file=sys.stderr)
        if result.stderr:
            print(f"    stderr: {result.stderr[:500]}", file=sys.stderr)
    return result.returncode, result.stdout, result.stderr


def find_latest_results(result_dir=None):
    """Find the most recent ScoutSuite results JSON file."""
    import glob as _glob
    if result_dir:
        search_dirs = [result_dir]
    else:
        search_dirs = [
            os.path.expanduser("~/.local/share/scoutsuite-report"),
            "scoutsuite-report",
            os.path.join(os.getcwd(), "scoutsuite-report"),
        ]
    for base_dir in search_dirs:
        pattern = os.path.join(base_dir, "scoutsuite-results", "scoutsuite_results_*.js")
        matches = _glob.glob(pattern)
        if not matches:
            pattern = os.path.join(base_dir, "**", "scoutsuite_results_*.js")
            matches = _glob.glob(pattern, recursive=True)
        if matches:
            return max(matches, key=os.path.getmtime)
    return None


def parse_results(results_file):
    """Parse ScoutSuite results JavaScript file into Python dict."""
    print(f"[*] Parsing results from {results_file}")
    with open(results_file, "r", encoding="utf-8") as f:
        content = f.read()
    json_start = content.find("{")
    if json_start == -1:
        print("[!] Could not find JSON data in results file", file=sys.stderr)
        return None
    json_data = content[json_start:].rstrip().rstrip(";")
    return json.loads(json_data)


def extract_findings(results):
    """Extract security findings from ScoutSuite results."""
    findings = []
    services = results.get("services", {})
    severity_map = {"danger": "CRITICAL", "warning": "HIGH", "info": "INFO"}

    for service_name, service_data in services.items():
        rules = service_data.get("findings", {})
        for rule_id, rule_data in rules.items():
            flagged = rule_data.get("flagged_items", 0)
            if flagged == 0:
                continue
            level = rule_data.get("level", "warning")
            findings.append({
                "service": service_name,
                "rule_id": rule_id,
                "description": rule_data.get("description", ""),
                "severity": severity_map.get(level, "MEDIUM"),
                "level": level,
                "flagged_items": flagged,
                "checked_items": rule_data.get("checked_items", 0),
                "rationale": rule_data.get("rationale", ""),
                "remediation": rule_data.get("remediation", ""),
                "references": rule_data.get("references", []),
                "compliance": rule_data.get("compliance", []),
            })

    severity_order = {"CRITICAL": 0, "HIGH": 1, "MEDIUM": 2, "INFO": 3}
    findings.sort(key=lambda f: (severity_order.get(f["severity"], 9), -f["flagged_items"]))
    return findings


def extract_account_info(results):
    """Extract AWS account metadata from results."""
    last_run = results.get("last_run", {})
    return {
        "account_id": results.get("account_id", "unknown"),
        "partition": results.get("partition", "aws"),
        "run_time": last_run.get("time", ""),
        "version": last_run.get("version", ""),
        "ruleset": last_run.get("ruleset_name", "default"),
        "services_scanned": list(results.get("services", {}).keys()),
    }


def format_summary(account_info, findings):
    """Print a human-readable summary."""
    print(f"\n{'='*60}")
    print(f"  ScoutSuite AWS Security Audit Report")
    print(f"{'='*60}")
    print(f"  Account     : {account_info['account_id']}")
    print(f"  Partition   : {account_info['partition']}")
    print(f"  Scan Time   : {account_info['run_time']}")
    print(f"  Services    : {', '.join(account_info['services_scanned'])}")
    print(f"  Failing Rules: {len(findings)}")

    severity_counts = {}
    for f in findings:
        sev = f["severity"]
        severity_counts[sev] = severity_counts.get(sev, 0) + 1

    print(f"\n  Severity Breakdown:")
    for sev in ["CRITICAL", "HIGH", "MEDIUM", "INFO"]:
        count = severity_counts.get(sev, 0)
        if count > 0:
            print(f"    {sev:10s}: {count}")

    by_service = {}
    for f in findings:
        by_service.setdefault(f["service"], []).append(f)

    print(f"\n  Findings by Service:")
    for svc, items in sorted(by_service.items(), key=lambda x: -len(x[1])):
        danger = sum(1 for i in items if i["severity"] == "CRITICAL")
        warn = sum(1 for i in items if i["severity"] == "HIGH")
        print(f"    {svc:20s}: {len(items)} findings ({danger} critical, {warn} high)")

    print(f"\n  Top Critical/High Findings:")
    for f in findings[:15]:
        if f["severity"] in ("CRITICAL", "HIGH"):
            print(f"    [{f['severity']:8s}] {f['service']:12s} | "
                  f"{f['description'][:60]} ({f['flagged_items']} items)")

    return severity_counts


def main():
    parser = argparse.ArgumentParser(
        description="ScoutSuite AWS security audit agent"
    )
    parser.add_argument("--profile", help="AWS CLI profile name")
    parser.add_argument("--services", nargs="+",
                        help="Specific services to audit (e.g., iam s3 ec2 rds)")
    parser.add_argument("--regions", nargs="+",
                        help="Specific regions to audit")
    parser.add_argument("--result-dir", help="Directory for ScoutSuite report output")
    parser.add_argument("--results-file",
                        help="Parse existing results file instead of running scan")
    parser.add_argument("--max-workers", type=int, default=10,
                        help="Max concurrent API workers (default: 10)")
    parser.add_argument("--output", "-o", help="Output JSON report path")
    parser.add_argument("--verbose", "-v", action="store_true")
    args = parser.parse_args()

    if args.results_file:
        results_file = args.results_file
    else:
        scout_bin = find_scoutsuite_binary()
        returncode, stdout, stderr = run_scoutsuite(
            scout_bin, args.profile, args.services, args.regions,
            args.result_dir, args.max_workers
        )
        if returncode != 0:
            print("[!] ScoutSuite scan failed", file=sys.stderr)
            sys.exit(1)
        results_file = find_latest_results(args.result_dir)

    if not results_file or not os.path.isfile(results_file):
        print("[!] Could not find ScoutSuite results file", file=sys.stderr)
        sys.exit(1)

    results = parse_results(results_file)
    if not results:
        sys.exit(1)

    account_info = extract_account_info(results)
    findings = extract_findings(results)
    severity_counts = format_summary(account_info, findings)

    report = {
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "tool": "ScoutSuite",
        "account": account_info,
        "severity_counts": severity_counts,
        "total_findings": len(findings),
        "findings": findings,
        "risk_level": (
            "CRITICAL" if severity_counts.get("CRITICAL", 0) > 0
            else "HIGH" if severity_counts.get("HIGH", 0) > 0
            else "MEDIUM" if len(findings) > 0
            else "LOW"
        ),
    }

    if args.output:
        with open(args.output, "w") as f:
            json.dump(report, f, indent=2)
        print(f"\n[+] Report saved to {args.output}")
    elif args.verbose:
        print(json.dumps(report, indent=2))


if __name__ == "__main__":
    main()
process.py8.1 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""
ScoutSuite AWS Security Assessment Automation Script

Automates ScoutSuite scanning, parses results, and generates
summary reports for AWS security posture assessment.
"""

import json
import subprocess
import sys
import os
from datetime import datetime
from pathlib import Path
from collections import defaultdict


def run_scoutsuite_scan(
    services=None,
    regions=None,
    profile=None,
    report_dir=None
):
    """Execute ScoutSuite scan against AWS account."""
    cmd = ["scout", "aws", "--no-browser"]

    if services:
        cmd.extend(["--services"] + services)
    if regions:
        cmd.extend(["--regions"] + regions)
    if profile:
        cmd.extend(["--profile", profile])
    if report_dir:
        cmd.extend(["--report-dir", report_dir])

    print(f"[*] Running ScoutSuite scan: {' '.join(cmd)}")
    result = subprocess.run(cmd, capture_output=True, text=True)

    if result.returncode != 0:
        print(f"[!] ScoutSuite scan failed: {result.stderr}")
        return False

    print("[+] ScoutSuite scan completed successfully")
    return True


def parse_scoutsuite_results(report_dir):
    """Parse ScoutSuite JSON results and extract findings."""
    results_file = Path(report_dir) / "scoutsuite-results" / "scoutsuite_results.json"

    if not results_file.exists():
        # Try alternative path structure
        for path in Path(report_dir).rglob("scoutsuite_results*.json"):
            results_file = path
            break

    if not results_file.exists():
        print(f"[!] Results file not found in {report_dir}")
        return None

    with open(results_file, "r") as f:
        return json.load(f)


def extract_findings(results):
    """Extract and categorize findings from ScoutSuite results."""
    findings_summary = {
        "danger": [],
        "warning": [],
        "good": []
    }
    service_summary = defaultdict(lambda: {"danger": 0, "warning": 0, "good": 0})

    services = results.get("services", {})
    for service_name, service_data in services.items():
        findings = service_data.get("findings", {})
        for finding_id, finding in findings.items():
            level = finding.get("level", "warning")
            flagged = finding.get("flagged_items", 0)
            total = finding.get("checked_items", 0)
            description = finding.get("description", "No description")
            rationale = finding.get("rationale", "")

            entry = {
                "id": finding_id,
                "service": service_name,
                "description": description,
                "rationale": rationale,
                "flagged_items": flagged,
                "checked_items": total,
                "level": level
            }

            if flagged > 0:
                if level == "danger":
                    findings_summary["danger"].append(entry)
                    service_summary[service_name]["danger"] += flagged
                elif level == "warning":
                    findings_summary["warning"].append(entry)
                    service_summary[service_name]["warning"] += flagged
            else:
                findings_summary["good"].append(entry)
                service_summary[service_name]["good"] += 1

    return findings_summary, dict(service_summary)


def generate_report(findings_summary, service_summary, output_file=None):
    """Generate a text-based summary report."""
    report_lines = []
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    report_lines.append("=" * 70)
    report_lines.append("ScoutSuite AWS Security Assessment Report")
    report_lines.append(f"Generated: {timestamp}")
    report_lines.append("=" * 70)

    # Executive summary
    danger_count = len(findings_summary["danger"])
    warning_count = len(findings_summary["warning"])
    good_count = len(findings_summary["good"])

    report_lines.append(f"\n## Executive Summary")
    report_lines.append(f"  Critical Findings : {danger_count}")
    report_lines.append(f"  Warning Findings  : {warning_count}")
    report_lines.append(f"  Passing Checks    : {good_count}")

    # Service breakdown
    report_lines.append(f"\n## Service Breakdown")
    report_lines.append(f"{'Service':<20} {'Danger':<10} {'Warning':<10} {'Good':<10}")
    report_lines.append("-" * 50)
    for service, counts in sorted(service_summary.items()):
        report_lines.append(
            f"{service:<20} {counts['danger']:<10} {counts['warning']:<10} {counts['good']:<10}"
        )

    # Critical findings detail
    if findings_summary["danger"]:
        report_lines.append(f"\n## Critical Findings (Requires Immediate Action)")
        report_lines.append("-" * 50)
        for finding in sorted(findings_summary["danger"], key=lambda x: x["flagged_items"], reverse=True):
            report_lines.append(f"\n  [{finding['service'].upper()}] {finding['id']}")
            report_lines.append(f"  Description: {finding['description']}")
            report_lines.append(f"  Flagged Items: {finding['flagged_items']}/{finding['checked_items']}")
            if finding["rationale"]:
                report_lines.append(f"  Rationale: {finding['rationale']}")

    # Warning findings
    if findings_summary["warning"]:
        report_lines.append(f"\n## Warning Findings")
        report_lines.append("-" * 50)
        for finding in sorted(findings_summary["warning"], key=lambda x: x["flagged_items"], reverse=True)[:20]:
            report_lines.append(f"\n  [{finding['service'].upper()}] {finding['id']}")
            report_lines.append(f"  Description: {finding['description']}")
            report_lines.append(f"  Flagged Items: {finding['flagged_items']}/{finding['checked_items']}")

    report = "\n".join(report_lines)

    if output_file:
        with open(output_file, "w") as f:
            f.write(report)
        print(f"[+] Report saved to {output_file}")
    else:
        print(report)

    return report


def check_compliance_gate(findings_summary, max_danger=0, max_warning=10):
    """Check if findings meet compliance gate thresholds for CI/CD."""
    danger_count = len(findings_summary["danger"])
    warning_count = len(findings_summary["warning"])

    passed = True

    if danger_count > max_danger:
        print(f"[FAIL] {danger_count} critical findings exceed threshold of {max_danger}")
        passed = False
    else:
        print(f"[PASS] Critical findings ({danger_count}) within threshold ({max_danger})")

    if warning_count > max_warning:
        print(f"[WARN] {warning_count} warning findings exceed threshold of {max_warning}")

    return passed


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(description="ScoutSuite AWS Security Assessment")
    parser.add_argument("--scan", action="store_true", help="Run ScoutSuite scan")
    parser.add_argument("--parse", type=str, help="Parse existing ScoutSuite results directory")
    parser.add_argument("--services", nargs="+", default=None, help="AWS services to scan")
    parser.add_argument("--regions", nargs="+", default=None, help="AWS regions to scan")
    parser.add_argument("--profile", type=str, default=None, help="AWS profile name")
    parser.add_argument("--report-dir", type=str, default="./scoutsuite-report", help="Report output directory")
    parser.add_argument("--output", type=str, default=None, help="Output file for summary report")
    parser.add_argument("--gate", action="store_true", help="Run compliance gate check")
    parser.add_argument("--max-danger", type=int, default=0, help="Max allowed danger findings")

    args = parser.parse_args()

    if args.scan:
        success = run_scoutsuite_scan(
            services=args.services,
            regions=args.regions,
            profile=args.profile,
            report_dir=args.report_dir
        )
        if not success:
            sys.exit(1)

    report_dir = args.parse or args.report_dir
    results = parse_scoutsuite_results(report_dir)

    if results:
        findings_summary, service_summary = extract_findings(results)
        generate_report(findings_summary, service_summary, args.output)

        if args.gate:
            passed = check_compliance_gate(findings_summary, max_danger=args.max_danger)
            sys.exit(0 if passed else 1)

Assets 1

template.mdtext/markdown · 2.0 KB
Keep exploring