Andrew Mercer
on this page

What it is

ufw is a small front end for iptables/nftables that ships with Ubuntu and is packaged on Debian. It is aimed at single-host firewalls: a default policy plus a short list of allow rules. For NAT gateways and routers reach for iptables, nftables, or firewalld instead.

References: Wikipedia, Debian wiki.

Install and enable

sudo apt-get install -y ufw

Allow SSH before you enable the firewall on a remote machine, or you will lock yourself out:

sudo ufw allow ssh
sudo ufw enable
sudo ufw status verbose

Default policy

sudo ufw default deny incoming
sudo ufw default allow outgoing

Allowing traffic

sudo ufw allow ssh                     # by service name (/etc/services)
sudo ufw allow 8080/tcp                # by port and protocol
sudo ufw allow from 192.168.0.0/24 proto tcp to any port 22   # ssh from one subnet only

A successful ufw status verbose looks like:

Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)

To                         Action      From
--                         ------      ----
22/tcp                     ALLOW IN    Anywhere
22/tcp (v6)                ALLOW IN    Anywhere (v6)

Each rule appears twice, once for IPv4 and once for IPv6.

Deleting rules

sudo ufw status numbered
sudo ufw delete 2

The numbers shift after every delete, so re-run status numbered before deleting another. You can also delete by rule text: sudo ufw delete allow 8080/tcp.

Cheat sheet

ufw status verbose
ufw allow <port>/<proto>
ufw allow from <cidr> to any port <port>
ufw status numbered && ufw delete <n>
ufw disable