TExcelTAD
Home › Computer Networking › Firewalls & ACLs

Firewalls & ACLs

A firewall decides which traffic may pass between networks (or into and out of a host) according to a list of rules. On routers and switches the same idea is called an ACL (Access Control List). Firewalls are the main tool for enforcing "who may talk to what" in a network.

How rules are evaluated

Most firewalls evaluate an ordered rule list top to bottom, and the first matching rule wins. If nothing matches, a default policy applies, which should be deny. A rule matches on fields like:

Field Example
direction / interface inbound on wan0
protocol tcp, udp, icmp
source address 0.0.0.0/0, 10.0.0.0/8
destination address 203.0.113.10/32
destination port 443, 22, 5000-5100
action allow, deny (silently drop), reject (drop and send RST/ICMP)

A rule evaluator

python · try it yourself
import ipaddress
from dataclasses import dataclass

@dataclass
class Rule:
    action: str
    proto: str          # "any", "tcp", "udp", "icmp"
    src: str
    dst: str
    ports: tuple = None # (low, high) or None for any
    comment: str = ""

    def matches(self, proto, src, dst, port):
        if self.proto not in ("any", proto):
            return False
        if ipaddress.ip_address(src) not in ipaddress.ip_network(self.src):
            return False
        if ipaddress.ip_address(dst) not in ipaddress.ip_network(self.dst):
            return False
        if self.ports and not (port is not None and self.ports[0] <= port <= self.ports[1]):
            return False
        return True

RULES = [
    Rule("allow", "tcp", "0.0.0.0/0", "203.0.113.10/32", (443, 443), "public HTTPS"),
    Rule("allow", "tcp", "0.0.0.0/0", "203.0.113.10/32", (80, 80), "HTTP (redirects to HTTPS)"),
    Rule("allow", "tcp", "198.51.100.0/24", "203.0.113.10/32", (22, 22), "SSH from the office only"),
    Rule("deny",  "tcp", "0.0.0.0/0", "203.0.113.10/32", (22, 22), "SSH from anywhere else"),
    Rule("allow", "icmp", "0.0.0.0/0", "0.0.0.0/0", None, "ping and PMTU messages"),
]
DEFAULT = "deny"

def evaluate(proto, src, dst, port=None):
    for number, rule in enumerate(RULES, start=1):
        if rule.matches(proto, src, dst, port):
            return rule.action, f"rule {number} ({rule.comment})"
    return DEFAULT, "default policy"

tests = [("tcp", "8.8.4.4", "203.0.113.10", 443), ("tcp", "198.51.100.7", "203.0.113.10", 22),
         ("tcp", "192.0.2.50", "203.0.113.10", 22), ("udp", "192.0.2.50", "203.0.113.10", 53),
         ("icmp", "192.0.2.50", "203.0.113.10", None), ("tcp", "192.0.2.50", "203.0.113.10", 5432)]
for proto, src, dst, port in tests:
    action, why = evaluate(proto, src, dst, port)
    print(f"{proto:<4} {src:<13} -> {dst}:{port!s:<5} {action.upper():<5} by {why}")
tcp  8.8.4.4       -> 203.0.113.10:443   ALLOW by rule 1 (public HTTPS)
tcp  198.51.100.7  -> 203.0.113.10:22    ALLOW by rule 3 (SSH from the office only)
tcp  192.0.2.50    -> 203.0.113.10:22    DENY  by rule 4 (SSH from anywhere else)
udp  192.0.2.50    -> 203.0.113.10:53    DENY  by default policy
icmp 192.0.2.50    -> 203.0.113.10:None  ALLOW by rule 5 (ping and PMTU messages)
tcp  192.0.2.50    -> 203.0.113.10:5432  DENY  by default policy

Rule order matters

Because the first match wins, a broad rule placed too early shadows the specific rules below it. This is the most common firewall mistake:

python · try it yourself
import ipaddress

def first_match(rules, src, port):
    for action, net, p in rules:
        if ipaddress.ip_address(src) in ipaddress.ip_network(net) and p in (None, port):
            return action
    return "deny"

wrong_order = [("deny", "0.0.0.0/0", 22), ("allow", "198.51.100.0/24", 22)]
right_order = [("allow", "198.51.100.0/24", 22), ("deny", "0.0.0.0/0", 22)]

for name, rules in [("deny first", wrong_order), ("allow first", right_order)]:
    print(f"{name:<12} office SSH: {first_match(rules, '198.51.100.7', 22):<5} "
          f"outsider SSH: {first_match(rules, '192.0.2.50', 22)}")

def shadowed(rules):
    for i, (_, net_i, port_i) in enumerate(rules):
        for _, net_j, port_j in rules[i + 1:]:
            if ipaddress.ip_network(net_j).subnet_of(ipaddress.ip_network(net_i)) and port_i in (None, port_j):
                print(f"warning: rule for {net_j} port {port_j} is shadowed by earlier rule {net_i} port {port_i}")

shadowed(wrong_order)
deny first   office SSH: deny  outsider SSH: deny
allow first  office SSH: allow outsider SSH: deny
warning: rule for 198.51.100.0/24 port 22 is shadowed by earlier rule 0.0.0.0/0 port 22

Stateless vs stateful

A stateless filter (a classic router ACL) looks at each packet alone. To let replies back in, you need rules like "allow TCP from any port 443 to my high ports", which also lets in crafted packets. A stateful firewall tracks connections: it allows a reply only if it belongs to a connection started from inside.

python · try it yourself
class StatefulFirewall:
    def __init__(self):
        self.connections = set()

    def outbound(self, src, sport, dst, dport):
        self.connections.add((dst, dport, src, sport))           # remember the expected reply
        return "allow (new connection tracked)"

    def inbound(self, src, sport, dst, dport):
        if (src, sport, dst, dport) in self.connections:
            return "allow (reply to tracked connection)"
        return "drop (unsolicited)"

fw = StatefulFirewall()
print("out ", fw.outbound("10.0.0.5", 51514, "93.184.215.14", 443))
print("in  ", fw.inbound("93.184.215.14", 443, "10.0.0.5", 51514))
print("in  ", fw.inbound("93.184.215.14", 443, "10.0.0.5", 51999))   # wrong port: forged
print("in  ", fw.inbound("192.0.2.66", 443, "10.0.0.5", 51514))      # other host
out  allow (new connection tracked)
in   allow (reply to tracked connection)
in   drop (unsolicited)
in   drop (unsolicited)
Type Looks at Example
Packet filter (stateless ACL) addresses, ports, flags router ACLs, cloud network ACLs
Stateful firewall + connection state iptables/nftables with conntrack, AWS security groups, home routers
Next-generation / application firewall + application, user, content Palo Alto, FortiGate
WAF (Web Application Firewall) HTTP requests (SQL injection, XSS patterns) Cloudflare WAF, ModSecurity
Host firewall traffic of one machine Windows Defender Firewall, ufw, firewalld

Real configurations

Linux nftables (successor of iptables):

text
table inet filter {
  chain input {
    type filter hook input priority 0; policy drop;
    ct state established,related accept
    iif "lo" accept
    ip protocol icmp accept
    tcp dport 443 accept
    ip saddr 198.51.100.0/24 tcp dport 22 accept
  }
}

The same policy with ufw on Ubuntu:

bash
sudo ufw default deny incoming
sudo ufw allow 443/tcp
sudo ufw allow from 198.51.100.0/24 to any port 22 proto tcp
sudo ufw status numbered

Sample output:

text
Status: active

     To                         Action      From
     --                         ------      ----
[ 1] 443/tcp                    ALLOW IN    Anywhere
[ 2] 22/tcp                     ALLOW IN    198.51.100.0/24

A Cisco router ACL uses wildcard masks:

text
access-list 110 permit tcp 198.51.100.0 0.0.0.255 host 203.0.113.10 eq 22
access-list 110 deny   tcp any host 203.0.113.10 eq 22
access-list 110 permit tcp any host 203.0.113.10 eq 443
! every ACL ends with an invisible "deny ip any any"

Tip: Design firewalls as default deny + explicit allows, put specific rules before general ones, comment every rule with its purpose and owner, and review the list regularly: rule sets that only ever grow become impossible to reason about.

Go further: Rule Order, Shadowing and Redundancy has a lab that walks packets through a ruleset and flags rules that can never match.

Test yourself

In a first-match firewall, what happens if the very first rule is 'deny tcp any any port 22'?

  1. Later allow rules for SSH still work
  2. All SSH is blocked, including from allowed networks
  3. The firewall reorders the rules
  4. Only outbound SSH is blocked

What does a stateful firewall track that a stateless filter does not?

  1. MAC addresses
  2. Connections, so replies are allowed only for traffic started from inside
  3. DNS names
  4. User passwords

What should the default policy of an inbound firewall be?

  1. Allow
  2. Deny
  3. Reject only ICMP
  4. Log only