UFW (Uncomplicated Firewall) is a friendly front end to the Linux packet filter. The idea is simple: block everything coming in, then allow only the services you actually run.
Warning: Always allow SSH before you run ufw enable. If you lock yourself out anyway, open the browser console from Open Control Panel on your service page and run sudo ufw disable.
1. Install UFW
Ubuntu includes it. On Debian install it first:
sudo apt install -y ufw2. Set the defaults
sudo ufw default deny incoming
sudo ufw default allow outgoing3. Allow SSH
sudo ufw allow OpenSSHIf SSH runs on another port, allow that port instead, for example sudo ufw allow 2222/tcp. To slow down password-guessing bots you can use limit instead of allow. It blocks an address that opens 6 or more connections in 30 seconds:
sudo ufw limit OpenSSH4. Switch it on and check
sudo ufw enable
sudo ufw status verboseBefore you close your session, open a new SSH connection to prove you can still get in.
Open more ports when you need them
sudo ufw allow 80,443/tcp # website (HTTP and HTTPS)
sudo ufw allow 'Nginx Full' # same, using the Nginx profile
sudo ufw app list # profiles installed packages provideAllow a port from one address only, for example a database used by your office IP:
sudo ufw allow from 198.51.100.7 to any port 3306 proto tcpRemove a rule
List rules with numbers, then delete by number:
sudo ufw status numbered
sudo ufw delete 3Numbers shift after each delete, so list them again before deleting another.
IPv6
Check that /etc/default/ufw contains IPV6=yes (the default). UFW then applies every rule to IPv6 too, so a port you did not open is closed on both.
Docker users, read this
Ports published with Docker (-p 8080:80) are handled by Docker's own rules and are reachable even if UFW does not allow them. Publish to 127.0.0.1 only (-p 127.0.0.1:8080:80) and put Nginx in front. See Install Docker and Docker Compose.
Troubleshooting
- A service is unreachable: check
sudo ufw statuslists its port, and that the service listens on the public address:sudo ss -tlnp. - Blocked traffic:
sudo ufw logging on, then watchsudo journalctl -k -f | grep UFW. - Start over:
sudo ufw resetremoves every rule and disables UFW. Allow SSH again before re-enabling.
