Guides / Linux servers

Set up a server firewall with ufw, firewalld or nftables

beginnerUpdated 26 Nov 20261176 words

A host firewall drops traffic to every port you did not open on purpose. It is the second line of defence: the first is that internal services listen on 127.0.0.1 only (see auditing listening ports). When an update or a configuration change puts a database back on a public address, the firewall still keeps it closed.

ufw, firewalld and nftables all program the same netfilter code in the kernel. Pick the one that comes with your distribution and use only that one: ufw on Ubuntu (and Debian if you like it), firewalld on RHEL, Rocky and Alma, plain nftables on Debian and Alpine.

Before you start

  • Allow SSH before you turn on a default-deny policy, and keep the current SSH session open.
  • Know how to reach the console of the server through the hosting provider, in case you lock yourself out.
  • Many providers also offer a network firewall outside the server (security groups, cloud firewalls). It is a good addition, and it is configured in the web panel of the provider, not on the server.
  • On a Docker host, read Docker bypasses ufw as well: ports published by Docker do not pass through the input rules shown here.

Ubuntu and Debian: ufw

sudo apt install ufw
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow OpenSSH
sudo ufw allow 80,443/tcp
sudo ufw enable
sudo ufw status verbose

OpenSSH is an application profile that opens port 22/tcp; sudo ufw app list shows the profiles installed packages bring. If SSH runs on another port, allow that port instead (sudo ufw allow 2222/tcp).

ufw applies each rule to IPv4 and IPv6 when IPV6=yes is set in /etc/default/ufw, which is the default.

Useful commands:

sudo ufw status numbered     # rules with numbers
sudo ufw delete 3            # delete rule number 3
sudo ufw limit 22/tcp        # deny an address that opens 6 or more connections in 30 seconds
sudo ufw allow from 198.51.100.7 to any port 5432 proto tcp

ufw checks rules in order and the first match wins. Put specific rules before general ones; ufw insert 1 ... places a rule at the top.

RHEL, Rocky Linux and AlmaLinux: firewalld

firewalld is installed and active on standard installations. Each network interface belongs to a zone; the default zone public allows ssh, dhcpv6-client and cockpit.

sudo systemctl enable --now firewalld
sudo firewall-cmd --get-active-zones
sudo firewall-cmd --permanent --add-service=http --add-service=https
sudo firewall-cmd --permanent --remove-service=cockpit    # if you do not use Cockpit
sudo firewall-cmd --reload
sudo firewall-cmd --list-all

--permanent writes the configuration to disk; --reload applies it. Without --permanent, a change is active at once but gone after the next reload or reboot. For a port without a service name: sudo firewall-cmd --permanent --add-port=8443/tcp.

Any distribution: plain nftables

On current releases, the rules of ufw (through iptables-nft) and of firewalld end up as nftables rules in the kernel. A plain nftables ruleset in one file is easy to read and works the same on every distribution.

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

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

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

        meta l4proto icmp accept
        meta l4proto ipv6-icmp accept

        tcp dport 22 accept
        tcp dport { 80, 443 } accept
    }
    chain forward {
        type filter hook forward priority filter; policy drop;
    }
    chain output {
        type filter hook output priority filter; policy accept;
    }
}

The inet family covers IPv4 and IPv6 in one table. ICMP stays open, because IPv6 does not work without it and path MTU discovery needs it for IPv4.

Where the file goes and how it loads at boot:

Distribution File Enable at boot
Debian /etc/nftables.conf sudo systemctl enable nftables
RHEL, Rocky, Alma (without firewalld) /etc/sysconfig/nftables.conf sudo systemctl disable --now firewalld && sudo systemctl enable nftables
Alpine /etc/nftables.nft and /etc/nftables.d/*.nft rc-update add nftables

Check the syntax before loading (with the path of your distribution):

sudo nft -c -f /etc/nftables.conf

Alpine ships /etc/nftables.nft with a default-deny input chain that allows loopback, replies and ICMP, but not SSH. Starting the nftables service with that file alone cuts SSH. The file includes /etc/nftables.d/*.nft at the end, so add your ports there instead of editing it:

# /etc/nftables.d/50-services.nft
table inet filter {
    chain input {
        tcp dport 22 accept comment "SSH"
        tcp dport { 80, 443 } accept comment "Web"
    }
}

The rules are appended to the input chain defined in /etc/nftables.nft. Check with nft -c -f /etc/nftables.nft, and start the service with rc-service nftables start (with the undo below).

Apply it with an automatic undo

A wrong rule can cut your SSH session. Save the current rules, schedule their return in two minutes, then load the new file. If you are still connected, cancel the undo.

sudo nft list ruleset | sudo tee /root/nft-before.nft >/dev/null
sudo systemd-run --on-active=120 --unit=nft-undo /bin/sh -c 'nft flush ruleset; nft -f /root/nft-before.nft'
sudo nft -f /etc/nftables.conf
# open a new SSH connection to test, then:
sudo systemctl stop nft-undo.timer

Alpine does not use systemd. Start the undo with nohup, so that it survives a dropped session, and stop it after the test:

nohup sh -c 'sleep 120; nft flush ruleset; nft -f /root/nft-before.nft' >/dev/null 2>&1 &
echo $! > /root/nft-undo.pid
nft -f /etc/nftables.nft
# open a new SSH connection to test, then:
kill "$(cat /root/nft-undo.pid)"

On a Docker host, do not flush everything

flush ruleset removes all rules, including the ones Docker created for container networking. On a Docker host, replace that line so the file only replaces its own table:

table inet filter
delete table inet filter
table inet filter {
    # chains as above
}

The first line creates the table if it is missing, so that the delete works on the first load too. In a test, this file loaded twice in a row and left another table in place. If the undo above ran on a Docker host, restart Docker (sudo systemctl restart docker) so that it writes its rules again.

Check the firewall

sudo ufw status verbose          # ufw
sudo firewall-cmd --list-all     # firewalld
sudo nft list ruleset            # nftables, and the result of the other two

Then test from another machine. nc -vz 203.0.113.10 5432 should time out for a closed port and connect for an open one. Test IPv6 as well when the server has an IPv6 address.

Patchbrief checks every day whether a firewall is loaded and lists the services that listen on public addresses.

Sources

Check your servers every day

The agent of Patchbrief reports the packages and settings of a server once a day; the digest names what to fix first.

Start free