Securus Journal 43.65°N, 79.38°W

iptables: building rules that make sense

How iptables passes packets through tables and chains, a default-deny baseline built from scratch, and the ordering mistakes that make good rules do nothing.

Contents

Four firewalls in under a decade

Linux has rewritten its firewall more often than most parts of the kernel. The first, ipfw, was borrowed from BSD. Linux 2.0 replaced it with ipfwadm, and 2.2 with ipchains. In 1998 Rusty Russell started the netfilter project to do the job properly, as a set of hooks in the kernel’s network stack with a stateful packet filter on top, and its command-line tool, iptables, arrived with Linux 2.4 in January 2001. Russell wrote the project’s early guides himself, in a breezy voice, under the series title “Rusty’s Remarkably Unreliable Guides.”

iptables has also outlived the arrival of its replacement. nftables entered the kernel in version 3.13, in 2014, and on most current distributions the iptables command is in fact iptables-nft, which accepts the old syntax and writes nftables rules underneath. The syntax survives because so many scripts and so much documentation depend on it.

iptables has a reputation for being arcane. The reputation is partly deserved: the syntax is terse, and the documentation assumes the reader already knows what chains, tables and targets are. The underlying model is logical once it is internalized, though, and the visibility it gives over network traffic is worth the learning curve.

This is a walkthrough of how to approach iptables, and the ruleset used here as a baseline on personal systems.


The mental model

iptables filters packets in the kernel by passing them through a series of chains in specific tables. For most firewall purposes only the filter table matters, and within it three chains:

  • INPUT: traffic destined for the local machine
  • OUTPUT: traffic originating from the local machine
  • FORWARD: traffic passing through (router or gateway use)

Within a chain, rules are checked from the top down, and the first rule whose match fits and whose target is final (ACCEPT, DROP, REJECT) decides the packet. Order is everything. A packet that matches no rule gets the chain’s default policy, and the two meaningful policies are ACCEPT and DROP.

A sane starting point: default DROP on INPUT, default ACCEPT on OUTPUT.


A working baseline

# Flush existing rules
iptables -F
iptables -X

# Default policies
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

# Allow established and related connections (return traffic)
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

# Allow loopback
iptables -A INPUT -i lo -j ACCEPT

# Allow SSH (adjust port if you've changed it)
iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# Allow HTTP and HTTPS if hosting anything
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# Allow ICMP (ping), optional but useful
iptables -A INPUT -p icmp -j ACCEPT

# Drop everything else (covered by default policy, but explicit is clear)
iptables -A INPUT -j DROP

The ESTABLISHED,RELATED rule is the one that makes default-deny livable. Without it, DROP on INPUT would block all return traffic, including the replies to connections the machine itself opened, which would break nearly everything. It is also why the rule comes first: most packets on a busy host belong to connections already established, and they are decided at the first rule checked.

Run this as a script, not line by line over SSH. Typed one command at a time, the session dies at iptables -P INPUT DROP, because the rule that would let its packets back in has not been added yet. The iptables-apply tool goes further: it loads a saved ruleset and rolls it back automatically unless the change is confirmed within a timeout.

These rules cover IPv4 only. IPv6 has its own table, managed with ip6tables, and a host with an IPv6 address and no ip6tables rules is wide open on that side whatever the IPv4 rules say. The IPv6 version of the baseline needs one change beyond the command name: ICMPv6 must be allowed, because IPv6 uses it to find neighbours on the local network.


Logging before dropping

Before the final DROP, a LOG rule shows what is being blocked:

iptables -A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables-drop: " --log-level 4
iptables -A INPUT -j DROP

These two lines replace the explicit DROP at the end of the baseline; they do not follow it. Appended after a rule that drops everything, the LOG rule would never see a packet. The --limit keeps a port scan from flooding the log. The output appears in /var/log/kern.log, or in journalctl -k on systems that keep kernel messages in the journal. Watching it for a while gives a clear picture of what is actually hitting the machine.


Rate limiting SSH

SSH brute force is a constant reality, even on non-standard ports. iptables can rate-limit connection attempts:

iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 4 -j DROP

This drops any source IP that makes more than 3 new SSH connection attempts within 60 seconds. Crude, but effective. Fail2Ban is more sophisticated, but this works in the kernel with no daemon required.

The order trap applies again. These two rules must sit above the rule that accepts port 22, because a new connection that has already been accepted never reaches them. In the baseline script, put them directly before the SSH line. (-m state --state NEW is the older spelling of -m conntrack --ctstate NEW; both work.)


Persistence

iptables rules do not survive a reboot by default. To make them persistent:

# Debian/Ubuntu
sudo apt install iptables-persistent
sudo netfilter-persistent save

# Fedora/RHEL, with the iptables-services package and firewalld stopped and disabled:
sudo sh -c 'iptables-save > /etc/sysconfig/iptables'
sudo systemctl enable iptables

On Fedora and RHEL, firewalld is the default firewall and drives nftables directly, so saved iptables rules and firewalld should not both be in charge. The sh -c wrapper matters: in sudo iptables-save > file, the redirection is done by the unprivileged shell before sudo runs, and it fails with “Permission denied.” The IPv6 rules are saved the same way, with ip6tables-save into /etc/sysconfig/ip6tables.

Alternatively, write the rules into a shell script and call it from a systemd unit at boot. That makes the ruleset self-documenting and easy to keep under version control.


Security relevance

In the CompTIA Security+ outline (SY0-701), network-layer filtering is a mitigation under Domain 2, Threats, Vulnerabilities, and Mitigations: a direct control against unauthorized access that reduces exposure to scanning and brute-force attempts. Firewall rules, access lists, ports and protocols appear by name under Domain 4, Security Operations. Understanding why rules are ordered as they are, and what a default policy means, informs better network architecture.


What the habits are

Writing a bad ruleset that blocks everything important is just as easy as writing a good one. The habits that prevent it are few. Start with an explicit default policy. Allow established connections before anything else. Remember that order decides, so a rule below a final ACCEPT or DROP for the same traffic is dead. Test changes carefully, above all on remote systems, and log what you drop.

Once the model clicks, iptables becomes one of the more satisfying tools to work with. The kernel does exactly what it was told, and every accepted or rejected packet can be traced to the line that decided it. Russell’s guides called themselves unreliable. The packet filter they described has been anything but.

Tools used: iptables, iptables-save, iptables-restore, conntrack, netfilter-persistent.

Sources

  • Russell, Rusty. Linux 2.4 Packet Filtering HOWTO. Netfilter project, 2002.
  • Netfilter project. iptables(8), iptables-extensions(8) and iptables-apply(8) manual pages.
  • Red Hat. Configuring firewalls and packet filters, RHEL documentation.
  • CompTIA. Security+ (SY0-701) Exam Objectives.