~/notes/2026|09|05
iptables from Scratch: Part 2 | Writing a Policy
Part 1 covered tables, chains and targets. Now we write a real policy — the kind that makes a fresh VPS stop being an open door. The philosophy in one line: deny by default, then open exactly what you use.
Set the default to no
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPTOUTPUT stays open so your box can reach updates and DNS. Everything inbound now dies unless a rule says otherwise. If you run this over SSH, your next command had better be the SSH rule.
Allow the conversation, not the knock
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -i lo -j ACCEPTThe first rule is the one that makes a stateful firewall usable: replies to connections you started are allowed, without opening any port. The second keeps loopback working — half of localhost debugging is a firewall that forgot this line.
Then open the doors you actually use
iptables -A INPUT -p tcp --dport 22 -j ACCEPT # ssh
iptables -A INPUT -p tcp --dport 80 -j ACCEPT # http
iptables -A INPUT -p tcp --dport 443 -j ACCEPT # httpsEvery extra port is surface area. When a service is temporary, remove its rule when you remove the service — a firewall full of forgotten allowances is a firewall that lied to you.
Test like the internet is watching
iptables -L -n -v # what is actually loaded
iptables -Z # zero the counters, wait a day, re-checkCounter columns tell you which rules ever matched. A rule with zero hits after a week is either protecting nothing or wrong. Also test from outside, not from the box: local traffic takes a different path and will not tell you what the internet sees.
Make it survive the reboot
apt install iptables-persistent
netfilter-persistent saveA firewall that vanishes on reboot is a firewall you will forget you had — until the day it matters. Save the ruleset, and re-save it every time you change it.
That is a complete, boring, working policy. Part 3 takes the same policy and turns it into NAT, port forwarding and the rules that let one public IP serve several machines.