Setting up firewall with UFW on linux
One of first defenses of your server is firewall. Firewall was often solved with complex and mysterious tools in the past.
Today we can use tool called UFW.
Before we begin
Make sure you have UFW installed. Ubuntu should have it right after installation. In case it's not installed, you can use following command:
sudo apt-get install ufw
Firewall status
Let's get status of our firewall.
sudo ufw status
It will probably tell you that it's inactive right now.
When UFW is active, the output will be a list of current rules.
Using IPv6 with UFW
In case your VPS uses IPv6, make sure UFW has IPv6 enabled.
File: /etc/default/ufw
IPV6=yes
Save and close the file.
Restart fiewall using:
sudo ufw disable
sudo ufw enable
UFW will be setting up rules for both IPv4 and IPv6, when it's needed now.
Basic settings
One of the things that makes setting up a firewall easier is to specify basic rules for allowing and denying connections. The basic setting for UFW is to reject all incoming connections (outside world cannot access your server) and allow all outgoing connections (any application on your server has access to the outside world).
We can achieve this using:
sudo ufw default deny incoming
sudo ufw default allow outgoing
Alternatively, it's possible to disable all outgoing connections and then define only which applications should have access to the outside world.
sudo ufw default deny outgoing
Allowing connections
We can allow connections for certain services and ports, for example: to enable SSH we can use:
sudo ufw allow ssh
In this case, "ssh" corresponds to:
sudo ufw allow 22/tcp
This command allows conections on port 22 for TCP protocol.
In case SSH runs on another port, we can enable the port in firewall.
More useful services:
sudo ufw allow www orsudo ufw allow 80/tcp
sudo ufw allow ftpor
sudo ufw allow 21/tcp
Ranges
We can allow traffic for range of ports for specified protocol.
For example: range form 500 to 1000:
sudo ufw allow 500:1000/tcp
IP addresses
We can allow connections for certain IP addresses:
sudo ufw allow from 172.16.x.x
Denying connection
Now we're going to have a look at how to deny a connection:
sudo ufw deny 80/tcp
This command will deny traffic on port 80.
Deleting rules
We have 2 options to delete a rule:
sudo ufw delete allow ssh
or
sudo ufw status numbered
sudo ufw delete (cislo)
Enabling firewall
We can turn UFW on, when we have it ready.
In case you're connecting over SSH, make sure the SSH port (default 22) is alllowed.
sudo ufw enable
We can check UFW status and active rules with:
sudo ufw status
Disabling UFW:
sudo ufw disable
Reset
In case you need to reset UFW to default settings, you can use:
sudo ufw reset
We're done :)