How to Validate AWS Security Group Ingress Rules in Python

Validates AWS security group ingress rules (protocol, port ranges, CIDR, description) and returns a list of errors or OK.

Easy Python 3.9+ Aug 9, 2026 Cloud + Python 11 views 0 copies

Python code

51 lines
Python 3.9+
from dataclasses import dataclass
from typing import List, Optional

@dataclass
class SecurityGroupRule:
    protocol: str
    port_range: tuple
    cidr: str
    description: str = ""

def validate_ingress_rule(rule: SecurityGroupRule) -> List[str]:
    """Validate a security group ingress rule against common AWS patterns."""
    errors = []
    
    # Validate protocol
    valid_protocols = {"tcp", "udp", "icmp", "-1"}
    if rule.protocol not in valid_protocols:
        errors.append(f"Invalid protocol: {rule.protocol}")
    
    # Validate port range (0-65535)
    if not (-1 <= rule.port_range[0] <= 65535 and -1 <= rule.port_range[1] <= 65535):
        errors.append(f"Invalid port range: {rule.port_range}")
    elif rule.port_range[0] > rule.port_range[1]:
        errors.append(f"Port range start > end: {rule.port_range}")
    
    # Validate CIDR format
    import re
    if not re.match(r"^(\d{1,3}\.){3}\d{1,3}/\d{1,2}$", rule.cidr):
        errors.append(f"Invalid CIDR: {rule.cidr}")
    elif rule.cidr == "0.0.0.0/0":
        errors.append("Open to all IPs — security risk unless intentional")
    
    # Description length check
    if len(rule.description) > 255:
        errors.append("Description exceeds 255 chars")
    
    return errors if errors else ["OK"]

if __name__ == "__main__":
    # Mock rules to validate
    test_rules = [
        SecurityGroupRule("tcp", (22, 22), "0.0.0.0/0", "SSH access"),
        SecurityGroupRule("udp", (53, 53), "192.168.1.0/24", "DNS"),
        SecurityGroupRule("h2", (8080, 8080), "10.0.0.5/32", "Web"),
        SecurityGroupRule("tcp", (10000, 200), "invalid-cidr", "Broken rule"),
        SecurityGroupRule("-1", (-1, -1), "10.0.0.0/8", "All traffic"),
    ]
    
    for rule in test_rules:
        result = validate_ingress_rule(rule)
        print(f"Rule ({rule.protocol}, {rule.port_range}, {rule.cidr}) → {result}")

Output

stdout
Rule (tcp, (22, 22), 0.0.0.0/0) → ['Open to all IPs — security risk unless intentional']
Rule (udp, (53, 53), 192.168.1.0/24) → ['OK']
Rule (h2, (8080, 8080), 10.0.0.5/32) → ['Invalid protocol: h2']
Rule (tcp, (10000, 200), invalid-cidr) → ['Port range start > end: (10000, 200)', 'Invalid CIDR: invalid-cidr']
Rule (-1, (-1, -1), 10.0.0.0/8) → ['OK']

How it works

This validator uses a dataclass (SecurityGroupRule) to model the rule fields and a function that returns a list of error strings. The protocol check uses a set for O(1) lookup against AWS-supported values. Port range validation ensures both endpoints are in the valid 0-65535 range and that start <= end. CIDR validation uses a regex to catch malformed IPv4 CIDR blocks and flags an overly permissive 0.0.0.0/0. The description check enforces the 255-character limit. The pattern returns ['OK'] when no errors are found, making it easy to integrate into CI/CD checks or policy validation scripts.

Common mistakes

  • Forgetting to handle the all-traffic protocol '-1' which uses -1 for both ports
  • Using a regex that only checks for digits without verifying octet ranges (e.g., 999.1.1.0/24)
  • Not returning early on fatal errors, causing multiple overlapping messages
  • Hard-coding port ranges as a list instead of a tuple, which can lead to accidental mutation

Variations

  1. Use `ipaddress.ip_network` from the standard library to validate CIDR notation more robustly than regex.
  2. Define the validator as a class method or use a Pydantic model for more complex validation logic.

Real-world use cases

  • Pre-deployment checks in Terraform or CloudFormation tooling to flag insecure security group rules before they're applied.
  • Audit scripts that scan existing AWS security groups and report violations against your organization's allowlist policies.
  • Reusable validation function inside a serverless function that processes security group change events and sends alerts.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Cloud + Python

Related tutorials and quizzes for this topic.