Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 37 Β· Networking and Firewalls

Firewalls with nftables, ufw and firewalld

Learn how the Linux packet filter works and how to manage it with nftables, ufw and firewalld: default-deny policy, stateful rules, NAT, and safe remote changes.

A firewall decides which packets may reach your server and which may leave it. On Linux the filtering happens inside the kernel (the netfilter framework). You never talk to the kernel directly: you use a front end, and which one depends on your distribution. This lesson explains the common model, shows the three front ends you will meet (nftables, ufw and firewalld) and gives you a safe procedure for changing rules on a machine you reach over SSH.

The site cannot run a kernel firewall, so every command here is read-only. The runnable examples are Python stand-ins that model rule evaluation, so you can see why rule order, the default policy and connection tracking matter.

The model: chains, rules and policy

Packets traverse hooks in the kernel. nftables groups rules into chains attached to hooks:

  • input: packets addressed to this machine.
  • output: packets this machine sends.
  • forward: packets the machine routes between interfaces (only relevant for routers, gateways and container hosts).
  • prerouting / postrouting: used for NAT.

Each chain has a policy (accept or drop) for packets that match no rule, and an ordered list of rules. The first matching rule with a verdict (accept, drop, reject) wins. The recommended base is default deny on input: drop everything, then allow exactly what the server offers.

Two details every firewall needs:

  1. Connection tracking. Allow packets belonging to an established connection (ct state established,related accept). Without it, replies to your own outgoing requests would be dropped.
  2. Loopback. Always accept iif lo, or local services talking to each other break in strange ways.
flowchart LR
    P["packet arrives"] --> C{"established<br/>or related?"}
    C -- yes --> A["accept"]
    C -- no --> R{"matches an<br/>allow rule?"}
    R -- yes --> A
    R -- no --> D["policy: drop"]

A typical input chain: reply traffic first, then explicit allows, then the default policy.

nftables

nftables replaced iptables as the kernel's modern packet-filter interface; Debian, Ubuntu, RHEL and Fedora all ship it, and the old iptables command is often a compatibility wrapper (iptables-nft). A complete, small server ruleset:

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

table inet filter {
    chain input {
        type filter hook input priority 0; policy drop;

        ct state established,related accept
        ct state invalid drop
        iif "lo" accept

        ip protocol icmp accept
        ip6 nexthdr icmpv6 accept

        tcp dport 22 ct state new limit rate 10/minute accept
        tcp dport { 80, 443 } accept
    }
    chain forward {
        type filter hook forward priority 0; policy drop;
    }
    chain output {
        type filter hook output priority 0; policy accept;
    }
}

inet applies to both IPv4 and IPv6, so you write the rules once. Working with it:

Terminal
sudo nft list ruleset                 # show what is loaded now
sudo nft -c -f /etc/nftables.conf     # syntax check only
sudo nft -f /etc/nftables.conf        # load the file
sudo systemctl enable --now nftables  # load at boot (RHEL/Debian service)
sudo nft add rule inet filter input tcp dport 8080 accept

Rules added with nft add live only in memory. Persist them in /etc/nftables.conf (Debian and Ubuntu) or /etc/sysconfig/nftables.conf (RHEL family).

Python Evaluate a packet against an input chain

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 input()), it gets the next line from this box.

Notice the last packet: it targets port 22, but the invalid rule comes first, so it is dropped. Rule order is part of the logic.

ufw: the simple front end (Ubuntu, Debian)

ufw ("uncomplicated firewall") generates netfilter rules from short commands. It is the right tool for a single web server.

Terminal
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow OpenSSH              # or: sudo ufw allow 22/tcp
sudo ufw allow 80,443/tcp
sudo ufw allow from 203.0.113.0/24 to any port 5432 proto tcp
sudo ufw limit ssh                  # rate-limit new SSH connections
sudo ufw enable
sudo ufw status numbered
sudo ufw delete 3

Add the SSH rule before ufw enable, or you lock yourself out of a remote machine. ufw status verbose prints the default policies; /etc/ufw/ holds the stored rules. Note that Docker publishes container ports through its own netfilter rules, which can bypass ufw's deny policy; check what is actually reachable from outside (see Reducing the Attack Surface).

firewalld: zones (RHEL, Fedora, Rocky, Alma)

firewalld assigns each network interface to a zone (public, internal, trusted, dmz, ...). A zone is a set of allowed services and ports. Changes can be runtime (immediate, temporary) or permanent (stored, applied on reload).

Terminal
sudo firewall-cmd --state
sudo firewall-cmd --get-active-zones
sudo firewall-cmd --zone=public --list-all
sudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --permanent --zone=public --add-port=8080/tcp
sudo firewall-cmd --permanent --zone=internal --add-source=10.0.0.0/8
sudo firewall-cmd --reload

A frequent mistake is adding a rule without --permanent and losing it at the next reload or reboot, or adding it with --permanent and forgetting --reload, then wondering why it has no effect. Use --runtime-to-permanent after you have tested a runtime change.

NAT and forwarding

A server acting as a gateway rewrites addresses. Masquerade (source NAT) lets private hosts reach the internet through this machine's public address; DNAT (port forwarding) sends incoming traffic on a port to another host.

TEXT
table ip nat {
    chain postrouting {
        type nat hook postrouting priority 100;
        oifname "ens3" masquerade
    }
    chain prerouting {
        type nat hook prerouting priority -100;
        tcp dport 8443 dnat to 10.0.0.20:443
    }
}

Forwarding also needs the kernel switch net.ipv4.ip_forward=1 (sudo sysctl -w net.ipv4.ip_forward=1, persisted in /etc/sysctl.d/99-forward.conf) and a permissive enough forward chain.

Changing a firewall safely over SSH

  1. Keep a second SSH session open while you test.
  2. Add the allow rule for SSH first, then change the policy.
  3. Test syntax before loading (nft -c -f).
  4. Schedule a rollback: sudo sh -c 'sleep 300 && nft flush ruleset' &, and cancel it once you confirm access. (With a default-deny setup flushing the ruleset opens the machine; it is a temporary escape hatch, not a state to keep.)
  5. Verify from outside with a scanner or nc -vz host port, because what is "open" is what an outsider sees, not what the config file says.
Python Lockout check before enabling a firewall

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 input()), it gets the next line from this box.

Firewall front ends

nftables The kernel interface. Full control.
ufw Short commands. Ubuntu, Debian.
firewalld Zones and services. RHEL family.

Use only one front end at a time.

1 / 2

Check your understanding

Quick check Β· 4 questions

of 4 answered You scored / 4 Β· perfect!

  1. 1. Why does a default-deny input chain need a rule for established and related connections?

    Connection tracking lets reply packets through without opening ports for every outgoing request.
  2. 2. You run sudo firewall-cmd --add-service=https (no --permanent) and reboot. What happens?

    Runtime rules are lost on reload or reboot; use --permanent or --runtime-to-permanent.
  3. 3. What is the main risk of running ufw enable on a remote server before adding any rules?

    ufw denies incoming connections by default, so allow SSH first.
  4. 4. Which nftables chain sees packets the machine routes between two interfaces?

    forward handles routed traffic; input is for packets destined to the host itself.

Summary

  • netfilter runs in the kernel; nftables, ufw and firewalld are front ends. Use one at a time.
  • Build a default-deny input policy, accept established traffic and loopback, then allow only needed ports.
  • Rule order matters: the first matching verdict wins.
  • firewalld separates runtime from permanent configuration; nft add rules are also memory-only until saved.
  • NAT and forwarding need both rules and net.ipv4.ip_forward.
  • Change remote firewalls with a second session, a syntax check and a rollback plan, and verify from outside.

Next: Remote Access with SSH