<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
---
name: automating-firewall-rule-audits
description: >-
  Automate firewall rule auditing across iptables, nftables, AWS Security
  Groups, and Azure NSGs. Covers rule extraction, overly permissive rule
  detection, shadow rule identification, unused rule cleanup, and compliance
  reporting against least-privilege principles.
domain: cybersecurity
subdomain: automation-scripting
tags:
  - firewall-audit
  - iptables
  - nftables
  - security-groups
  - nsg
  - least-privilege
  - network-security
version: "1.0"
author: defconxt
license: AGPL-3.0
metadata:
  mitre-attack: ["T1562.004"]
---

# Automating Firewall Rule Audits

## Overview

Firewall rulesets accumulate technical debt over time: overly permissive
rules, shadowed entries, and orphaned references. This skill covers building
automated auditors that parse rulesets from multiple sources, flag violations
of least-privilege, identify shadow rules, and generate remediation reports.

Mode: `[MODE: BLUE]` — Defensive network security with compliance focus.

## Prerequisites

| Requirement | Details |
|---|---|
| Python 3.10+ with `boto3` (for AWS), `azure-mgmt-network` (for Azure) | Required |
| Root/sudo for local iptables/nftables inspection | Required |
| Cloud API credentials for Security Group / NSG auditing | Required |

## Key Concepts

### iptables Rule Parser

```python
import subprocess
import re

def parse_iptables() -> list[dict]:
    """Parse iptables rules into structured format."""
    result = subprocess.run(
        ["iptables", "-L", "-n", "-v", "--line-numbers"],
        capture_output=True, text=True, timeout=10,
    )
    rules = []
    current_chain = ""
    for line in result.stdout.splitlines():
        if line.startswith("Chain"):
            current_chain = line.split()[1]
        match = re.match(
            r"^\s*(\d+)\s+(\d+[KMG]?)\s+(\d+[KMG]?)\s+(\S+)\s+(\S+)\s+"
            r"(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s*(.*)",
            line,
        )
        if match:
            rules.append({
                "chain": current_chain,
                "num": int(match.group(1)),
                "packets": match.group(2),
                "bytes": match.group(3),
                "target": match.group(4),
                "protocol": match.group(5),
                "source": match.group(8),
                "destination": match.group(9),
                "options": match.group(10).strip(),
            })
    return rules
```

### Overly Permissive Rule Detection

```python
def find_permissive_rules(rules: list[dict]) -> list[dict]:
    """Flag rules that allow too-broad access."""
    findings = []
    for rule in rules:
        issues = []
        if rule["source"] == "0.0.0.0/0" and rule["target"] == "ACCEPT":
            issues.append("source_any")
        if rule["destination"] == "0.0.0.0/0" and rule["target"] == "ACCEPT":
            issues.append("destination_any")
        if rule["protocol"] == "all" and rule["target"] == "ACCEPT":
            issues.append("protocol_any")
        if issues:
            findings.append({**rule, "issues": issues, "severity": "high"})
    return findings
```

### AWS Security Group Audit

```python
def audit_security_groups(region: str = "us-east-1") -> list[dict]:
    """Audit AWS Security Groups for overly permissive rules."""
    import boto3
    ec2 = boto3.client("ec2", region_name=region)
    sgs = ec2.describe_security_groups()["SecurityGroups"]
    findings = []
    for sg in sgs:
        for rule in sg.get("IpPermissions", []):
            for ip_range in rule.get("IpRanges", []):
                if ip_range.get("CidrIp") == "0.0.0.0/0":
                    findings.append({
                        "sg_id": sg["GroupId"],
                        "sg_name": sg["GroupName"],
                        "port": rule.get("FromPort", "all"),
                        "protocol": rule.get("IpProtocol", "all"),
                        "cidr": "0.0.0.0/0",
                        "severity": "critical" if rule.get("FromPort") in (22, 3389) else "high",
                    })
    return findings
```

## Workflow

### Step 1: Audit Local Firewall Rules

```bash
node scripts/agent.js --action audit-local
```

### Step 2: Find Overly Permissive Rules

```bash
node scripts/agent.js --action find-permissive
```

### Step 3: Audit AWS Security Groups

```bash
node scripts/agent.js --action audit-aws --region us-east-1
```

## Verification

- [ ] iptables parser extracts all chains and rules with counters
- [ ] Permissive rule detector flags 0.0.0.0/0 sources and protocol=all
- [ ] AWS SG audit identifies public-facing SSH/RDP rules
- [ ] Shadow rule detection identifies unreachable rules
- [ ] Exit code 0 on compliant, 1 on findings, 2 on error

## References

- [CIS Control 9 — Network Monitoring and Defense](https://www.cisecurity.org/controls)
- [AWS Security Group Best Practices](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-security-groups.html)
- [NIST SP 800-41 Rev. 1 — Firewall Guidelines](https://csrc.nist.gov/publications/detail/sp/800-41/rev-1/final)
- [MITRE ATT&CK T1562.004 — Disable or Modify System Firewall](https://attack.mitre.org/techniques/T1562/004/)
