Chapter 3 · 3.4
A firewall with ufw (or nftables)
On the WebOké network, all incoming traffic to your VPS is allowed. You decide what gets in yourself, with a firewall on your server. That way you only allow what you need, such as SSH and your website.
Please note: Open SSH before you turn on the firewall. If you don't, you'll lock yourself out. If it happens anyway, turn off the firewall via the console (see Locked out: you can no longer reach your server).
ufw on Debian and Ubuntu
ufw is a simple layer on top of the Linux firewall. It's already there on Ubuntu; on Debian you install it:
anna@web1:~$ sudo apt install ufw
anna@web1:~$ sudo ufw allow OpenSSH
anna@web1:~$ sudo ufw allow 80,443/tcp
anna@web1:~$ sudo ufw enable
Command may disrupt existing ssh connections. Proceed with operation (y|n)? y
Firewall is active and enabled on system startup
anna@web1:~$ sudo ufw status verbose
Status: active
Default: deny (incoming), allow (outgoing), disabled (routed)
To Action From
-- ------ ----
22/tcp (OpenSSH) ALLOW IN Anywhere
80,443/tcp ALLOW IN Anywhere
22/tcp (OpenSSH (v6)) ALLOW IN Anywhere (v6)
80,443/tcp (v6) ALLOW IN Anywhere (v6)
Anything you don't allow is denied. The rules automatically apply to IPv6 too. You only need ports 80 and 443 for a website (chapter 5). If you use Caddy with HTTP/3, also open sudo ufw allow 443/udp.
Useful ufw commands
| Command | What does it do? |
|---|---|
sudo ufw status numbered | Show the rules with a number |
sudo ufw delete 3 | Remove rule 3 |
sudo ufw allow from 198.51.100.7 to any port 22 proto tcp | Open a port for one IP address only |
sudo ufw limit OpenSSH | Temporarily deny an address that starts 6 or more connections within 30 seconds |
sudo ufw disable | Turn off the firewall (for example via the console if you're locked out) |
Without ufw: nftables
On Debian, nftables is the firewall under the bonnet. If you don't want ufw, write the rules yourself in /etc/nftables.conf. A small basic setup for IPv4 and IPv6 together:
#!/usr/sbin/nft -f
flush ruleset
table inet filter {
chain input {
type filter hook input priority filter; policy drop;
ct state established,related accept
iif "lo" accept
meta l4proto { icmp, ipv6-icmp } accept
tcp dport { 22, 80, 443 } accept
}
}
anna@web1:~$ sudo nft -c -f /etc/nftables.conf
anna@web1:~$ sudo systemctl enable --now nftables
Use nft -c to check the file first. Use either ufw or nftables, not both at the same time.
On AlmaLinux and Rocky Linux firewalld is already installed: sudo firewall-cmd --permanent --add-service=http --add-service=https and sudo firewall-cmd --reload. SSH is open there by default.
Tip: Do you use Docker? Ports you publish with Docker bypass ufw. So read Docker and the firewall: publishing ports safely.
