Skip to content

Firewall rules with ufw

AdvancedLesson 47 of 668 min

Read a server’s firewall rules with ufw status, open a port to one address only, and test it from another machine with nc, on a pretend network.

A program listening on a port is only half the story. A firewall decides which connections reach it at all. Servers usually block everything coming in, then allow only what they need: ssh for the admins, 80 and 443 for a website, the database port for the app that uses it. On Ubuntu the firewall is managed with ufw (the "uncomplicated firewall"). The machines here (your laptop, web, db and the router) are pretend ones inside your browser, so nothing you type reaches a real network.

Your laptop is getting a reporting tool that reads the shop's database on db, port 5432. Try it now:

nc -zv db 5432

nc -z just checks whether a port is open. It times out: something drops the connection without an answer, which is what a firewall does.

Reading the rules

The firewall is part of db, so log in there. Its rules need root to read:

sudo ufw status numbered

Each rule says which port (To), what happens (ALLOW, DENY, REJECT), and from where (From). Anything without a rule falls to the default, shown by sudo ufw status verbose: deny (incoming).

Changing them

CommandDoes
sudo ufw allow 22/tcplets anyone reach port 22
sudo ufw allow httpthe same, by service name (80)
sudo ufw allow from 10.0.0.5 to any port 5432lets only 10.0.0.5 reach port 5432
sudo ufw deny 80/tcpdrops connections, so they time out
sudo ufw reject 80/tcprefuses them straight away
sudo ufw delete 3removes rule 3 from the numbered list
sudo ufw enableturns the firewall on

Open a port to as few addresses as you can. A database open to every machine is a database waiting to be found.

Careful:Before sudo ufw enable on a server you reach over ssh, allow port 22 first. Otherwise the firewall locks you out the moment it starts.

Your turn

Let your laptop (10.0.0.5) reach the database on db, port 5432, without opening it to anyone else: (1) on db, look at the firewall rules; (2) allow port 5432 from 10.0.0.5 only; (3) back on your laptop, check with nc -zv db 5432 that the port is open now.

Next