Server setup: Setting up a firewall

A firewall is a basic filter that can provide an efficient protection to your server by only allowing the traffic in and out as the rules of the firewall allows it. Setting up a firewall on a Ubuntu Linux server does not need to be complicated - in fact the one used in this example is called “uncomplicated firewall”.

To get the firewall up and running make sure it’s installed through the package manager. Login and switch to a root shell, then install the firewall with this command:

apt-get install ufw

If everything goes okay, the firewall is installed but not configured nor enabled.

Firewall Configuration

I find the easiest way to mange the firewall is through a little script in the root home directory. The beginning script could look something like this:

#!/bin/sh
ufw reset
ufw allow from 127.0.0.1
#ufw allow ssh
ufw enable
ufw status

Line 2 resets any existing configuration rules in the firewall.

In line 3 you should change the 127.0.0.1 to you own fixed IP address if you have one (you really ought to). This line will allow any traffic from you ip-number into the server (assuming there is something able to receive it naturally).

If you haven’t a fixed IP number line 3 should be removed and line 4 used instead. It allows SSH connections from any outside IP-number to knock on the door - then well rely on the SSH daemon (and the configuration of this) to reject any unwanted visitors knocking on the server.

Line 5 enables the firewall and line 6 prints a list of the current status and configuration of the firewall.

Depending on what you are using your server to do, you’ll probably need a few more lines in the firewall script. If you’re running a webserver, you should at least add a line (just above the “ufw enable” line) allowing web traffic to pass through the server:

utf enable www

Are you using https on you’re webserver? - then you need to allow that too:

utf enable www

The simple enable lines above are suitable for “publicly accessible services”. If you’re running something the whole world should be able to use, UFW allows for that too. The Community documentation on UFW over at the Ubuntu site is quite helpful.