Tighten firewall rules to least privilege
A rule open to 0.0.0.0/0 is a standing invitation. Least privilege means every allow names a
specific source, port, and direction — and every rule you keep has a proven consumer.
Procedure
- Dump the current rules with their sources and ports:
For Linux hosts:aws ec2 describe-security-groups --group-ids "$SG" \ --query 'SecurityGroups[].IpPermissions[].[IpProtocol,FromPort,ToPort,IpRanges[].CidrIp]' --output jsonsudo iptables -Sorsudo nft list ruleset. - Flag every overly broad rule — ingress from
0.0.0.0/0,-A INPUT ... -j ACCEPTwith no match:aws ec2 describe-security-groups --group-ids "$SG" \ --query 'SecurityGroups[].IpPermissions[?contains(IpRanges[].CidrIp, `0.0.0.0/0`)]' - For each broad rule, identify the real consumer before changing it:
No observed traffic over a representative window is evidence a rule may be removable — not proof.# AWS VPC flow logs: which sources actually hit this port aws logs filter-log-events --log-group-name /aws/vpc/flowlogs \ --filter-pattern '{ $.dstport = 5432 }' --query 'events[].message' | head - Narrow public ingress to the actual CIDR of the client (office range, CDN egress range, partner IP):
aws ec2 revoke-security-group-ingress --group-id "$SG" --protocol tcp --port 5432 --cidr 0.0.0.0/0 aws ec2 authorize-security-group-ingress --group-id "$SG" --protocol tcp --port 5432 --cidr 203.0.113.0/24 - Reference another security group as the source instead of a CIDR when the caller is known:
aws ec2 authorize-security-group-ingress --group-id "$SG" --protocol tcp --port 5432 \ --source-group sg-0app123 - Keep explicit deny at the end (NACL) or default-deny (security groups are allow-only) and document each remaining rule with a tag or comment naming the owner.
- Re-test the flows the rule serves before removing a temporary exception.
Pitfalls
- Removing a "temporary"
0.0.0.0/0rule during business hours cuts users who never got migrated. - Security groups are allow-only and stateful; a network ACL is stateless, so narrowing one direction breaks return traffic.
- A CIDR of
10.0.0.0/8is not least privilege — it is every private host in every peered VPC. - VPC flow logs sample and can lag; absence of traffic in a log is weak evidence, not certainty.
- Hardcoding a dynamic IP (home office) into a rule guarantees a future outage when the IP changes.
- Opening a wide port range (
0-65535) "to be safe" is worse than a single wrong port. - Rule changes are not transactional; a revoke-then-authorize gap drops in-flight connections.
Verification
aws ec2 describe-security-groups --group-ids "$SG" \
--query 'SecurityGroups[].IpPermissions[].IpRanges[].CidrIp' | grep '0.0.0.0/0'
# expect no output for the tightened port
Pass means the previously public port no longer lists 0.0.0.0/0 and the real consumer still
connects. Report: "port 5432 narrowed 0.0.0.0/0 → 203.0.113.0/24; app connectivity verified."