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
| Action | The other side sees |
|---|---|
allow | gets in |
deny | nothing — the packet is dropped, it waits until it times out |
reject | "connection refused" at once |
limit | gets 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.