Build a wall (a friendly one)
Nobody gets in without an invitation. Not even you, if you're careless.
A server with no firewall is a house with every door unlocked. ufw (the uncomplicated firewall) lets you close them all, then open exactly the ones you need, in about five commands.
🧰 What you need
- An Ubuntu or Debian machine
- A way in that isn't SSH, just in case (a keyboard and screen, or your VM's console)
Let's build it
See what's listening
sudo ss -tulpnEvery line is an open door: a program listening on a port. You'll probably see SSH on port 22.
Install ufw and set the defaults
sudo apt install -y ufw
sudo ufw default deny incoming
sudo ufw default allow outgoingOpen the SSH door FIRST
sudo ufw allow OpenSSHDo this before turning the firewall on. Seriously. (See "Break it" below for why.)
Switch it on
sudo ufw enable
sudo ufw status verboseTest from another computer
nc -zv your-server-ip 22
nc -zv your-server-ip 330622 answers; 3306 (or any port you didn't open) doesn't.
✅ How you know it worked
sudo ufw status lists only the ports you opened, and a port test from another machine only gets through those.
💥 Break it on purpose
From the machine's own keyboard or console (not over SSH!):
sudo ufw delete allow OpenSSHNow try to SSH in from another computer. Locked out. This happens to real engineers on real servers, which is exactly why you open SSH before enabling a firewall. Let yourself back in with sudo ufw allow OpenSSH.
🧠 What's really going on
ufw is a friendly front end for the Linux kernel's own packet filter (nftables). "Default deny incoming" drops every new connection unless a rule allows it, while replies to connections you started still get through, because the firewall remembers them. That's why your server can still browse the web while nobody can connect to it uninvited.
← Back to all Linux labs · Stuck? Email me