The last step in securing our server is to install a firewall. The idea behind a firewall is that every exposed port is a potential security vulnerability. Therefore, we want to expose as few ports as possible.
All Linux distributions come with a firewall called iptables, which, by default, allows all traffic to pass through. Configuring iptables by hand can be challenging as the format is not the most intuitive. For example, an inactive iptables configuration looks like this:
$ sudo iptables -L -n -v
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
To help system administrators to manage the iptables firewall more easily, the Ubuntu distribution comes with a command-line program called ufw (short for uncomplicated firewall), which we will use here.
ufw is inactive by default, but before we enable it, let's add some rules for it to enforce:
hobnob@hobnob:$ sudo ufw status
Status: inactive
The only port we need to expose right now is the one for SSH, which is port 22. We can do this by adding individual ports directly:
hobnob@hobnob:$ sudo ufw allow 22
However, there's an easier way: services may register their profiles with ufw, allowing ufw to manage their ports by name. You can view a list of registered applications by running ufw app list:
hobnob@hobnob:$ sudo ufw app list
Available applications:
OpenSSH
Therefore, instead of specifying port 22, we can specify the name of the application instead:
hobnob@hobnob:$ sudo ufw allow OpenSSH
Rules updated
Rules updated (v6)
Now the rules are in place, we can enable ufw:
hobnob@hobnob:$ sudo ufw enable
Command may disrupt existing ssh connections. Proceed with operation (y|n)? y
Firewall is active and enabled on system startup
Now, when we check again, only the OpenSSH port (22) is opened:
hobnob@hobnob:$ sudo ufw status
Status: active
To Action From
-- ------ ----
OpenSSH ALLOW Anywhere
OpenSSH (v6) ALLOW Anywhere (v6)