Skip to content

Ubuntu — UFW Firewall

UFW (Uncomplicated Firewall) is the default firewall tool on Ubuntu. It wraps iptables with a simpler interface. This guide covers a complete baseline setup for a typical server.

Pre-requisites

  • Ubuntu 20.04 or later
  • sudo access
  • Active SSH session — read the SSH warning below before enabling UFW

Defaults

UFW ships inactive. The sensible defaults for a server:

sudo ufw default deny incoming
sudo ufw default allow outgoing

Allow SSH before enabling

Always add your SSH rule before running ufw enable. Enabling UFW without an SSH rule on a remote server locks you out immediately.


Common Allow Rules

By service name

UFW knows common services by name:

sudo ufw allow ssh
sudo ufw allow http
sudo ufw allow https

By port number

sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

Port range

sudo ufw allow 8000:8100/tcp

From a specific IP

sudo ufw allow from 203.0.113.10
sudo ufw allow from 203.0.113.10 to any port 22

From a subnet

sudo ufw allow from 192.168.1.0/24
sudo ufw allow from 192.168.1.0/24 to any port 22

Deny Rules

deny silently drops packets. reject drops them and sends back an error (faster timeout for the sender):

sudo ufw deny 8080/tcp
sudo ufw reject from 203.0.113.50
sudo ufw deny out 25

Rate Limiting

Built-in rate limiting blocks IPs that make 6+ connections within 30 seconds. Essential for SSH:

sudo ufw limit ssh

Use this instead of allow ssh on any public-facing server.


Enable / Disable

sudo ufw enable
sudo ufw disable
sudo ufw reset

Check Status

sudo ufw status verbose
sudo ufw status numbered

Example output:

Status: active

     To                         Action      From
     --                         ------      ----
[ 1] 22/tcp                     LIMIT IN    Anywhere
[ 2] 80/tcp                     ALLOW IN    Anywhere
[ 3] 443/tcp                    ALLOW IN    Anywhere

Delete Rules

By rule number (get numbers from sudo ufw status numbered):

sudo ufw delete 3

By rule definition:

sudo ufw delete allow 80/tcp
sudo ufw delete allow https

Baseline Setup — Typical Web Server

The minimum ruleset for a server running SSH, HTTP, and HTTPS:

sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw limit ssh
sudo ufw allow http
sudo ufw allow https
sudo ufw enable
sudo ufw status verbose

Outbound SMTP

If the server should not send email directly (most servers), block outbound port 25 to prevent abuse if the system is ever compromised:

sudo ufw deny out 25