Rules, chains, and policy
A firewall holds rules in chains. A chain is a list that packets are checked against at one point in their journey, such as traffic coming into the machine or traffic leaving it. Each rule names a condition, such as a destination port, and an action, such as accept or drop. Rules are checked from top to bottom, and the first match decides the packet.
Every chain also has a default policy, which applies when no rule matches. A policy of drop with explicit accept rules for the services you want is an allowlist, which is the safer default. A policy of accept with explicit drop rules is a blocklist, which is easier to start with and easier to get wrong.
An allowlist in plain terms
An allowlist states which traffic is permitted and denies everything else. For a server that serves web and secure shell traffic, the list is short: port 443 for HTTPS and port 22 for ssh. Everything else is dropped by default, so a service that you forgot about is not reachable.
| Rule | Meaning |
|---|---|
| accept tcp port 22 | Allow ssh connections in |
| accept tcp port 443 | Allow HTTPS connections in |
| policy drop | Drop every other packet that reaches the end of the chain |
Reading order matters
A rule that drops traffic from one address placed above a rule that accepts everything from a network will drop that address first. The position of each rule is part of its meaning. When a filter misbehaves, read the rules in order and find the first one that matches the packet in question, because that is the one that acted.
Stateful filtering
Modern firewalls track connections. A rule can accept replies to connections that the machine started, which means outgoing requests get their answers without an explicit rule for each reply. Stateful tracking is the reason a typical home firewall lets you browse while blocking unsolicited incoming traffic.
The tools on Linux
On Linux, rules are installed with nftables or the older iptables command, both of which need root privileges to change anything. Reading rules also needs privileges on most systems. The lab image has neither tool, so this unit uses a shell script to model an allowlist and to show the first-match behavior.
Firewall rules change what the kernel accepts. A mistake can lock you out of a remote machine, so test rules on a console or in a virtual machine first.
Hands-on: model the allowlist
The lab asks you to write a script that returns ACCEPT for ports 22 and 443 and DROP for everything else, then to run it over several ports and save the results. The case statement is the same first-match logic that a firewall chain uses.
for p in 22 80 443; do case $p in 22|443) echo "$p ACCEPT";; *) echo "$p DROP";; esac; doneThe output lists 22 ACCEPT, 80 DROP, and 443 ACCEPT, in the order of the loop.