Skip to content
Tutorials Center
My learning

Topics

Lesson 79 of 95 ยท System Administration

Firewalls: ufw, iptables and nftables

Understand the Linux firewall: chains and rules, default policies, stateful tracking, ufw commands, iptables and nftables examples and how to avoid locking yourself out.

A server that is connected to the internet receives unwanted traffic within minutes: scans for open SSH ports, probes for old databases, attempts to find forgotten admin panels. A firewall decides which network packets may reach your machine, which may leave it and which are thrown away. On Linux the firewall is built into the kernel (the netfilter framework), and you control it with front-end tools: ufw (simple), iptables (the classic) and nftables (the modern replacement). They are three ways to write rules for the same engine.

Changing real firewall rules requires root and a network stack we do not have in this sandbox, so the commands below are read-only. What you can run are models in Bash: a rule engine that evaluates packets against an ordered ruleset, a stateful connection tracker, and a small translator from an easy policy format into real nft and iptables commands. Writing the engine yourself is the quickest way to understand why rule order and default policies matter so much.

How a packet travels

Packets pass through fixed checkpoints called hooks. At each hook the kernel runs the rules of the chains attached to it. For a firewall on a normal server three chains matter most:

flowchart LR
    NET["Packet arrives"] --> PRE["prerouting"]
    PRE --> RT{"Routing<br/>decision"}
    RT -- "for this host" --> IN["INPUT chain"]
    IN --> APP["Local process"]
    APP --> OUT["OUTPUT chain"]
    RT -- "for another host" --> FWD["FORWARD chain"]
    FWD --> POST["postrouting"]
    OUT --> POST
    POST --> OUTNET["Packet leaves"]

INPUT filters traffic to this machine, OUTPUT filters traffic it creates, FORWARD filters traffic it routes for others. NAT happens in prerouting and postrouting.

Terminology you need:

  • A rule has a match (protocol, port, source address, interface, connection state) and a target or verdict: ACCEPT, DROP (silently discard) or REJECT (discard and tell the sender).
  • A chain is an ordered list of rules. Rules are checked from top to bottom and the first match wins.
  • The chain's policy is the verdict when no rule matches. A safe server uses DROP for INPUT.
  • A table groups chains: filter (accept or drop), nat (address translation), mangle (packet changes).

Modelling a rule chain

Here is a small packet filter. A rule is action protocol port source; any is a wildcard and sources can be addresses or CIDR networks such as 10.0.0.0/8. To match a network, the engine converts the address to a 32-bit number and compares the leading bits, which is exactly what the kernel does.

Bash A first-match-wins packet filter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Look at Ruleset A first: only the office network reaches SSH, the web is open to everybody, and anything not named (MySQL, DNS) falls through to the policy and is dropped. Rulesets B and C show the most common mistake in firewall work. The same two rules, in a different order, give opposite results, because the first matching rule decides. Put narrow exceptions before broad permissions. With iptables, -A appends at the end, while -I inserts at the top; mixing them up produces exactly this bug.

Stateful filtering

Opening port 22 inbound is not enough on its own to let your server download an update. The server sends a request to a mirror (outbound), and the reply is an inbound packet from a random high port. Writing rules for every possible reply is impossible, so the kernel keeps a connection tracking table (conntrack). The standard rule is "accept packets that belong to a connection we already allowed" (ESTABLISHED,RELATED), placed near the top of INPUT. Then you only open the ports where new connections should be accepted.

Bash Why ESTABLISHED,RELATED matters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The same tracking is why an ESTABLISHED rule belongs near the top: it is cheap, and it keeps existing sessions alive even while you edit the rules for new ones.

ufw: the simple front end

ufw (Uncomplicated Firewall) is the default on Ubuntu. It writes iptables or nftables rules for you from short commands. All read-only:

CONSOLE
$ sudo ufw status verbose
$ sudo ufw default deny incoming
$ sudo ufw default allow outgoing
$ sudo ufw allow 22/tcp                         # keep SSH working BEFORE enabling
$ sudo ufw allow 80,443/tcp
$ sudo ufw allow from 10.0.0.0/8 to any port 5432 proto tcp
$ sudo ufw limit ssh                            # rate-limit repeated SSH connection attempts
$ sudo ufw enable
$ sudo ufw status numbered
$ sudo ufw delete 3                             # remove rule number 3
$ sudo ufw deny from 203.0.113.0/24
$ sudo ufw logging on

ufw remembers its rules across reboots; ufw reload re-applies them. Rules added after enable take effect immediately. Application profiles (ufw app list, ufw allow "Nginx Full") save you from remembering port numbers. Note that ufw checks rules in the order of the list too.

iptables: the classic

iptables (with ip6tables for IPv6) works directly on chains. The options you use constantly: -A append, -I insert (at a position), -D delete, -L -n -v --line-numbers list, -P set a policy, -F flush, -p protocol, --dport destination port, -s source, -i interface, -j target. A sensible baseline for a web server:

CONSOLE
$ sudo iptables -A INPUT -i lo -j ACCEPT
$ sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
$ sudo iptables -A INPUT -p tcp -s 10.0.0.0/8 --dport 22 -j ACCEPT
$ sudo iptables -A INPUT -p tcp -m multiport --dports 80,443 -j ACCEPT
$ sudo iptables -A INPUT -p icmp --icmp-type echo-request -m limit --limit 5/second -j ACCEPT
$ sudo iptables -P INPUT DROP          # only now: the default becomes DROP
$ sudo iptables -L INPUT -n -v --line-numbers

Order is deliberate: first allow what must work, set -P INPUT DROP last. If you set the DROP policy first (or run iptables -F while the policy is DROP) you cut your own SSH session. Rules live in memory: they vanish at reboot unless you save them with iptables-save > /etc/iptables/rules.v4 (the iptables-persistent or netfilter-persistent package loads it at boot) and restore them with iptables-restore < file. Inspect the rules in script-friendly form with iptables -S.

nftables: the modern replacement

nftables replaces iptables, ip6tables, arptables and ebtables with one tool, nft, and one syntax. Rules live in tables of a family (inet covers IPv4 and IPv6), chains hook into the kernel, and sets let a single rule match many addresses or ports. Debian, Fedora and RHEL use nftables underneath; on many systems the iptables command is a compatibility layer that creates nftables rules. A complete ruleset file, /etc/nftables.conf, equal to the baseline above:

TEXT
#!/usr/sbin/nft -f
flush ruleset

table inet filter {
  set admin_nets {
    type ipv4_addr
    flags interval
    elements = { 10.0.0.0/8, 192.168.1.0/24 }
  }

  chain input {
    type filter hook input priority 0; policy drop;
    iif lo accept
    ct state established,related accept
    ct state invalid drop
    ip protocol icmp accept
    ip6 nexthdr ipv6-icmp accept
    tcp dport 22 ip saddr @admin_nets accept
    tcp dport { 80, 443 } accept
    limit rate 5/minute log prefix "input-drop: "
  }

  chain forward {
    type filter hook forward priority 0; policy drop;
  }

  chain output {
    type filter hook output priority 0; policy accept;
  }
}
CONSOLE
$ sudo nft -c -f /etc/nftables.conf          # -c checks the syntax without applying
$ sudo nft -f /etc/nftables.conf             # load it
$ sudo nft list ruleset
$ sudo nft -a list chain inet filter input   # -a shows handles
$ sudo nft delete rule inet filter input handle 9
$ sudo systemctl enable --now nftables       # load at boot

Compare it with iptables: one tcp dport { 80, 443 } replaces multiport, the set @admin_nets can be updated without touching rules, and IPv4 plus IPv6 share one table. Changes are applied atomically, so loading a file never leaves a half-configured firewall.

firewalld and iptables in daily use

firewalld (Fedora, RHEL, Rocky, Alma) manages rules through zones. A zone is a trust level for a set of interfaces or source addresses: public allows only what you open, trusted allows everything, drop silently discards everything. Services are named bundles of ports (ssh, http, https). Changes made without --permanent last until reload or reboot; with it they are stored but need --reload to apply.

CONSOLE
$ sudo firewall-cmd --state                                 # running?
$ sudo firewall-cmd --get-active-zones
$ sudo firewall-cmd --zone=public --add-service=http        # open now (runtime only)
$ sudo firewall-cmd --zone=public --add-service=https --permanent
$ sudo firewall-cmd --zone=public --add-port=8080/tcp --permanent
$ sudo firewall-cmd --zone=public --add-interface=eth0 --permanent
$ sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="203.0.113.7" port port="22" protocol="tcp" accept'
$ sudo firewall-cmd --reload
$ sudo firewall-cmd --list-all                              # everything in the default zone

Typical mistakes: applying a rule to the wrong zone (the interface is in public, the rule went to home), forgetting --permanent or --reload, and over-blocking, such as dropping everything before allowing your own SSH session.

iptables organises rules into tables (filter for allow and block, nat for address translation, mangle for packet changes, raw for connection-tracking exemptions) and chains (INPUT, OUTPUT, FORWARD, plus PREROUTING and POSTROUTING in nat). A rule is -A chain (append) or -I chain (insert at the top), a match (-s source address, -p tcp protocol, --dport 22 destination port, -i eth0 input interface) and a target (-j ACCEPT, DROP or REJECT). You can create your own chains with -N name and delete rules with -D.

CONSOLE
$ sudo iptables -L -n -v --line-numbers          # rules with packet and byte counters and line numbers
$ sudo iptables -A INPUT -p tcp --dport 22 -s 203.0.113.0/24 -j ACCEPT
$ sudo iptables -I INPUT 1 -i lo -j ACCEPT       # insert as rule 1
$ sudo iptables -A INPUT -j DROP                 # the last rule: drop all the rest
$ sudo iptables -D INPUT 3                       # delete rule number 3
$ sudo iptables -N LOGDROP                       # a user-defined chain
$ sudo iptables -F && sudo iptables -X           # flush all rules, delete user chains (careful on remote hosts)

Rules set this way vanish at reboot: save them with iptables-save > /etc/iptables/rules.v4 (the iptables-persistent package restores them). Traffic shaping, which limits bandwidth rather than blocking it, is not done by iptables: that is tc (traffic control).

Translating a simple policy

Many administrators keep a short human policy and generate the real rules. This translator reads lines such as allow tcp 22 from 10.0.0.0/8 and prints both nft and iptables commands. It only prints; nothing is applied:

Bash From a plain policy to nft and iptables commands

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Safe defaults and avoiding lockout

Rules for a typical server, in order of importance:

  1. Default deny incoming, allow outgoing (add outbound filtering only if you need it).
  2. Accept the loopback interface and established/related connections.
  3. Allow SSH only from the networks that need it, and consider a non-default setup such as a VPN or bastion host. See SSH, scp and Working Remotely.
  4. Open only the service ports you run (80, 443, ...). Check what listens with ss -tulpn (Network Troubleshooting).
  5. Allow ICMP (at least echo-request and the errors needed by path MTU discovery); blocking all ICMP breaks things in surprising ways, and IPv6 depends on it.
  6. Rate-limit and log the rest, but never log every dropped packet at full rate: it can fill the disk.
  7. Treat IPv6 as equal to IPv4. A firewall that protects only IPv4 leaves the other door open.

To avoid cutting yourself off while editing remote rules:

  • Keep a second SSH session open while you test; existing sessions survive because of the ESTABLISHED rule.
  • Schedule an automatic undo before changing anything, and cancel it when you are happy: echo 'ufw disable' | sudo at now + 5 minutes, then atrm the job. See Scheduling with cron, at and systemd Timers.
  • Use a syntax check (nft -c -f) and iptables-apply (which asks you to confirm within a timeout and otherwise rolls back).
  • Keep console or cloud-provider access in case you do lock yourself out.

Other things worth knowing:

  • Docker publishes container ports by writing its own iptables rules that run before ufw's, so ufw deny 8080 does not hide a container published with -p 8080:80. Bind to localhost (-p 127.0.0.1:8080:80) or manage the DOCKER-USER chain.
  • Cloud security groups are a firewall outside your VM. Use them as the first layer and the host firewall as the second.
  • firewalld (default on RHEL/Fedora) uses zones such as public and trusted and commands like firewall-cmd --add-service=http --permanent.
  • A firewall is one layer. It does not replace updates, strong authentication, least-privilege users (see Users, Groups and sudo) or monitoring.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A chain contains ACCEPT tcp 80 any followed by DROP tcp 80 203.0.113.0/24. What happens to HTTP packets from 203.0.113.9?

    Rules are evaluated top to bottom and the first match decides. The broad ACCEPT matches first, so the DROP rule is never reached. Put specific exceptions before general rules.
  2. 2. Why is -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT almost always one of the first INPUT rules?

    Connection tracking recognises packets that belong to flows already allowed, so you only write rules for new inbound connections.
  3. 3. What is the difference between DROP and REJECT?

    DROP makes the sender wait for a timeout; REJECT answers immediately with an ICMP error or TCP reset, which is friendlier on a trusted network but tells scanners the host exists.
  4. 4. You are connected over SSH and run iptables -P INPUT DROP on a fresh machine that has no other rules. What most likely happens?

    With no ESTABLISHED rule, even replies on your existing SSH connection fall to the DROP policy. Add the accept rules first and set the policy last.
  5. 5. Which statement about nftables is true?

    nftables unifies the old tools. The inet family handles both IP versions, sets make rules shorter, and nft -f file loads a whole ruleset atomically.

Summary

  • Linux filters packets in the kernel (netfilter). Rules sit in chains attached to hooks: INPUT for traffic to the host, OUTPUT for traffic it sends, FORWARD for routed traffic.
  • Rules are checked top to bottom and the first match wins; the chain policy applies when nothing matches. Use a default of deny for incoming traffic.
  • Accept loopback and ESTABLISHED,RELATED first, then open only the ports and networks you need.
  • ufw is the easiest tool (ufw allow 22/tcp, ufw enable); iptables edits chains directly and must be saved to persist; nftables (nft -f /etc/nftables.conf) is the modern syntax with sets and atomic loading.
  • Cover IPv6, allow needed ICMP, and remember that Docker and cloud networks add their own rules.
  • Avoid lockouts: allow SSH before enabling, keep a second session, and schedule an automatic rollback.

Next: Network Troubleshooting: ip, ss, tcpdump, nmap, dig