DEV Community

Naveen Karasu
Naveen Karasu

Posted on

Audit Your VPC: Find Accidentally Public Subnets with Python

Day 5: Find Accidentally Public Subnets

The most common VPC misconfiguration is not a bad security group rule -- it is a subnet using the main route table when it should not be.

Subnets without an explicit route table association inherit the VPC's main route table. If that table has an Internet Gateway route, those subnets are public whether you intended it or not.

Here is a quick AWS CLI audit:

# Get main route table for your VPC
MAIN_RT=$(aws ec2 describe-route-tables \
  --filters Name=vpc-id,Values=vpc-0abc123 \
           Name=association.main,Values=true \
  --query 'RouteTables[0].RouteTableId' --output text)

# Check if main RT has IGW route
aws ec2 describe-route-tables \
  --route-table-ids $MAIN_RT \
  --query 'RouteTables[0].Routes[?GatewayId!=`local`]'

# Find subnets with no explicit RT association
aws ec2 describe-subnets \
  --filters Name=vpc-id,Values=vpc-0abc123 \
  --query 'Subnets[].SubnetId' --output text | tr '\t' '\n' | while read SID; do
  ASSOC=$(aws ec2 describe-route-tables \
    --filters Name=association.subnet-id,Values=$SID \
    --query 'RouteTables[0].RouteTableId' --output text)
  if [ "$ASSOC" = "None" ]; then
    echo "WARNING: $SID uses main route table"
  fi
done
Enter fullscreen mode Exit fullscreen mode

If the main RT has an IGW route AND subnets are unassociated, fix both: remove the IGW route from main, and explicitly associate each subnet.

Tip: In Terraform, always use aws_route_table_association for every subnet. Never rely on the default.

Top comments (0)