Intermediate · 12 min · practise every command in the built-in terminal

ufw — Precise Rules

"Port 22 for everyone" is a start. Real servers say who: SSH only from the office, the website for everyone, one troublemaker for no one.

From an address or a network

sudo ufw allow from 192.168.1.0/24 to any port 22 proto tcp
sudo ufw delete allow OpenSSH          # the rule for everyone goes
sudo ufw status
To                         Action      From
--                         ------      ----
22/tcp                     ALLOW       192.168.1.0/24

192.168.1.0/24 is the whole network 192.168.1.0 – 192.168.1.255 (your own address, 192.168.1.42 — see who). A single address works too: from 203.0.113.5.

Order matters

ufw reads the rules top down, and the first one that fits wins. A deny added at the end comes too late if an allow above already let the connection in. insert puts a rule where you want it:

sudo ufw insert 1 deny from 203.0.113.7    # before everything else
sudo ufw status numbered

deny, reject, limit

ActionThe other side sees
allowgets in
denynothing — the packet is dropped, it waits until it times out
reject"connection refused" at once
limitgets in — unless it connects 6 times in 30 seconds: then it's blocked

limit is made for SSH: password-guessing bots connect over and over, people don't.

sudo ufw limit from 192.168.1.0/24 to any port 22 proto tcp   # the same rule, now with a limit

Defaults and logging

sudo ufw default deny incoming     # what isn't allowed stays out (the default)
sudo ufw default allow outgoing    # the server may connect anywhere (the default)
sudo ufw logging on                # low, medium, high — or off

The whole set, as commands

sudo ufw show added
Added user rules (see 'ufw status' for running firewall):
ufw deny from 203.0.113.7
ufw limit from 192.168.1.0/24 to any port 22 proto tcp

Handy for documentation — or to set up the next server the same way. Start over with sudo ufw reset.

💡 Before you close a door, make sure you have another one: an allowed SSH rule for your own address, or the hosting company's web console.

Practice tasks

  1. Allow SSH from your office network 192.168.1.0/24
  2. Remove the rule that lets everyone reach SSH
  3. Block 203.0.113.7 completely — as the very first rule
  4. Turn the office's SSH rule into a limit rule
  5. Show all your rules as ufw commands
  6. Check the defaults: deny what comes in, allow what goes out

Commands in this lesson

Firewall (ufw)