TExcelTAD
Home › AWS Cloud › Security Groups vs NACLs

Security Groups vs NACLs

A VPC has two layers of firewall:

  • Security groups act on network interfaces (instances, load balancers, databases).
  • Network ACLs (NACLs) act on subnets.
Security group Network ACL
Applies to Network interfaces (resources) Subnets
Rules Allow only Allow and deny
State Stateful: replies are allowed automatically Stateless: replies need their own rule
Evaluation All rules together (any allow matches) In rule number order, first match wins
Default Deny all inbound, allow all outbound Default NACL allows everything
Can reference Other security groups Only CIDR ranges

Security groups

bash
aws ec2 create-security-group --group-name web-sg --description "web servers" --vpc-id vpc-0abc1234def567890
aws ec2 authorize-security-group-ingress --group-id sg-0web1111111111111 \
    --protocol tcp --port 80 --source-group sg-0alb2222222222222
aws ec2 authorize-security-group-ingress --group-id sg-0db33333333333333 \
    --protocol tcp --port 5432 --source-group sg-0web1111111111111

Referencing a security group instead of an IP range is a powerful pattern: "the database accepts port 5432 from anything in web-sg", no matter how many web servers Auto Scaling launches or which IPs they get.

python · try it yourself
import ipaddress

security_groups = {
    "alb-sg": [("tcp", 443, "0.0.0.0/0")],
    "web-sg": [("tcp", 80, "sg:alb-sg")],
    "db-sg":  [("tcp", 5432, "sg:web-sg")],
}
members = {"alb-1": "alb-sg", "web-1": "web-sg", "web-2": "web-sg", "db-1": "db-sg"}
ips = {"alb-1": "10.20.0.10", "web-1": "10.20.32.4", "web-2": "10.20.33.8", "db-1": "10.20.64.5"}

def allowed(dst, src, port, src_ip=None):
    for proto, p, source in security_groups[members[dst]]:
        if p != port:
            continue
        if source.startswith("sg:") and src in members and members[src] == source[3:]:
            return True
        if not source.startswith("sg:") and ipaddress.ip_address(src_ip or ips.get(src)) in ipaddress.ip_network(source):
            return True
    return False

tests = [("alb-1", "internet", 443, "203.0.113.50"), ("web-1", "alb-1", 80, None),
         ("web-1", "internet", 80, "203.0.113.50"), ("db-1", "web-2", 5432, None),
         ("db-1", "alb-1", 5432, None)]
for dst, src, port, src_ip in tests:
    print(f"{src:>8} -> {dst}:{port:<5} {'ALLOW' if allowed(dst, src, port, src_ip) else 'deny'}")
internet -> alb-1:443   ALLOW
   alb-1 -> web-1:80    ALLOW
internet -> web-1:80    deny
   web-2 -> db-1:5432  ALLOW
   alb-1 -> db-1:5432  deny

Each tier only accepts traffic from the tier in front of it. The database is unreachable from the internet and even from the load balancer.

Network ACLs

NACL rules are numbered and evaluated from the lowest number; the first matching rule decides. The final * rule denies everything else. Because NACLs are stateless, you must also allow the return traffic, which goes to the client's ephemeral port (1024–65535).

python · try it yourself
import ipaddress

inbound = [   # (rule number, protocol, port range, source CIDR, action)
    (100, "tcp", (443, 443), "0.0.0.0/0", "allow"),
    (110, "tcp", (22, 22), "198.51.100.0/24", "allow"),
    (120, "tcp", (1024, 65535), "0.0.0.0/0", "allow"),   # replies to outbound connections
    (90,  "tcp", (0, 65535), "203.0.113.66/32", "deny"),  # a blocked attacker
]

def evaluate(rules, port, source):
    for number, proto, (lo, hi), cidr, action in sorted(rules):
        if lo <= port <= hi and ipaddress.ip_address(source) in ipaddress.ip_network(cidr):
            return f"{action.upper()} (rule {number})"
    return "DENY (rule *)"

for port, src in [(443, "192.0.2.10"), (443, "203.0.113.66"), (22, "192.0.2.10"),
                  (22, "198.51.100.25"), (3306, "192.0.2.10"), (51000, "192.0.2.10")]:
    print(f"port {port:<5} from {src:<14} {evaluate(inbound, port, src)}")
port 443   from 192.0.2.10     ALLOW (rule 100)
port 443   from 203.0.113.66   DENY (rule 90)
port 22    from 192.0.2.10     DENY (rule *)
port 22    from 198.51.100.25  ALLOW (rule 110)
port 3306  from 192.0.2.10     ALLOW (rule 120)
port 51000 from 192.0.2.10     ALLOW (rule 120)

Rule 90 is checked before rule 100, so the attacker's address is denied even on port 443. Blocking one IP like this is something security groups cannot do, because they have no deny rules. Notice also that port 3306 gets in through rule 120: the wide ephemeral-port rule needed for replies opens every high port inbound. NACLs are a coarse tool, which is why the fine-grained filtering belongs in security groups.

Stateful vs stateless

python · try it yourself
def round_trip(firewall_stateful, outbound_rules_allow_ephemeral):
    # A client on the internet connects to port 443 on a server; the reply leaves on port 51000.
    inbound_ok = True                                # assume 443 is allowed inbound
    if firewall_stateful:
        reply_ok = True                              # the connection is tracked
    else:
        reply_ok = outbound_rules_allow_ephemeral    # needs an explicit outbound rule
    return "works" if inbound_ok and reply_ok else "request arrives, reply is dropped"

print("security group              :", round_trip(True, False))
print("NACL without outbound 1024+ :", round_trip(False, False))
print("NACL with outbound 1024+    :", round_trip(False, True))
security group              : works
NACL without outbound 1024+ : request arrives, reply is dropped
NACL with outbound 1024+    : works

Tip: Most designs keep NACLs at their default (allow all) and do the real filtering with security groups. Use NACLs for coarse subnet-wide guard rails and explicit denies.

Test yourself

Which firewall is stateful?

  1. Network ACL
  2. Security group
  3. Both
  4. Neither

You must block one malicious IP address for a whole subnet. What do you use?

  1. A security group deny rule
  2. A NACL deny rule
  3. A route table entry
  4. An IAM policy

NACL rules 100 (allow 443 from anywhere) and 90 (deny all from 203.0.113.66) exist. A request from 203.0.113.66 to port 443 is ...

  1. Allowed by rule 100
  2. Denied by rule 90
  3. Allowed, allow beats deny
  4. Dropped by the security group