Skip to main content
Glama
annaescalada

AWS Security Group Auditor

by annaescalada
README.md
# AWS Security Group Auditor

Audits AWS Security Groups for dangerous configurations. Detects publicly exposed critical ports (SSH, RDP, databases) and provides remediation commands.

## Features

- Automated detection of dangerous rules (0.0.0.0/0 on critical ports)
- Optional AI analysis via Claude
- Markdown reports with remediation commands
- MCP server for Claude Desktop integration
- Risk prioritization (Critical, High, Medium)

## Detection Rules

- Port 22 (SSH) open to Internet
- Port 3389 (RDP) open to Internet
- Database ports (3306, 5432, 27017) exposed
- Protocol -1 (all traffic) open to 0.0.0.0/0
- Administrative and internal services publicly exposed

## Requirements

- Python 3.10+
- AWS credentials (via AWS CLI or environment variables)
- Anthropic API key (optional, for AI analysis only)

## Installation

```bash
# Clone or download repository
cd sg-auditor

# Create virtual environment with Python 3.10+
python3.11 -m venv venv
source venv/bin/activate

# Install dependencies
pip install -r requirements.txt
```

### AWS Configuration

**Option 1: AWS CLI (recommended)**
```bash
aws configure
```

**Option 2: Environment variables**
```bash
export AWS_ACCESS_KEY_ID="your_key"
export AWS_SECRET_ACCESS_KEY="your_secret"
export AWS_DEFAULT_REGION="us-east-1"
```

### Optional: Claude AI Analysis

Create `.env` file for AI-powered analysis:
```env
ANTHROPIC_API_KEY=sk-ant-xxx
```

Get your API key at [console.anthropic.com](https://console.anthropic.com/)

## Usage

### CLI

```bash
# Audit default region
python audit.py

# Audit specific region
python audit.py --region us-west-2

# Skip AI analysis
python audit.py --no-ai

# Custom output directory
python audit.py --output-dir /path/to/reports
```

Exit codes: 0 (clean), 1 (high severity), 2 (critical severity)

### MCP Server (Claude Desktop Integration)

Configure in `~/Library/Application Support/Claude/claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "security-group-auditor": {
      "command": "/path/to/sg-auditor/venv/bin/python",
      "args": ["/path/to/sg-auditor/src/mcp_server.py"]
    }
  }
}
```

Restart Claude Desktop. Available tools:
- `scan_security_groups` - Scan all Security Groups in a region
- `analyze_specific_group` - Analyze specific Security Group by ID
- `get_risk_summary` - Get risk information

### Python Library

```python
from src.audit_core import run_audit

result = run_audit(region='us-east-1')
print(f"Findings: {result['summary']['total_findings']}")
```

## Architecture

```
sg-auditor/
├── audit.py                 # CLI entry point
├── requirements.txt         # Python dependencies
├── src/
│   ├── audit_core.py       # Core audit logic (shared)
│   ├── sg_collector.py     # AWS Security Group collector (boto3)
│   ├── rule_analyzer.py    # Dangerous rule detector
│   ├── ai_agent.py         # Optional AI analysis (CLI only)
│   ├── mcp_server.py       # MCP server (Claude Desktop)
│   └── report_generator.py # Markdown report generator
└── reports/                # Generated audit reports
```

**Design:**
- `audit_core.py` contains shared logic used by both CLI and MCP server
- `ai_agent.py` is only used by CLI tool (MCP returns raw findings for Claude to analyze)
- `mcp_server.py` exposes tools via Model Context Protocol for AI agents

## AWS Permissions

Required IAM permissions (read-only):

```json
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": [
      "ec2:DescribeSecurityGroups",
      "ec2:DescribeRegions"
    ],
    "Resource": "*"
  }]
}
```

The auditor never modifies AWS resources.

## Advanced Usage

### CI/CD Integration

```bash
python audit.py --region us-east-1 --no-ai
if [ $? -eq 2 ]; then
    echo "CRITICAL findings - blocking deployment"
    exit 1
fi
```

### Multi-Region Audit

```bash
for region in us-east-1 us-west-2 eu-west-1; do
    python audit.py --region $region
done
```

### AWS Organizations

Use assumed roles in `src/sg_collector.py`:

```python
sts = boto3.client('sts')
assumed_role = sts.assume_role(
    RoleArn='arn:aws:iam::ACCOUNT_ID:role/SecurityAuditor',
    RoleSessionName='SecurityAudit'
)
credentials = assumed_role['Credentials']
self.ec2_client = boto3.client(
    'ec2',
    aws_access_key_id=credentials['AccessKeyId'],
    aws_secret_access_key=credentials['SecretAccessKey'],
    aws_session_token=credentials['SessionToken']
)
```

## Customization

### Custom Ports

Edit `src/rule_analyzer.py` to add custom ports:

```python
CRITICAL_PORTS = {
    22: "SSH",
    3389: "RDP",
    8080: "Custom Application",
}
```

## Cost

Claude AI analysis (optional):
- ~5,000 tokens per audit (~$0.10 USD)
- Use `--no-ai` flag to skip AI analysis

## Resources

- [boto3 Documentation](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html)
- [Anthropic API](https://docs.anthropic.com/)
- [AWS Security Groups Best Practices](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html)
- [Model Context Protocol](https://modelcontextprotocol.io/)

## License

MIT