Configure firewall
Published on: 22nd Apr 2014
Updated on: 23th Sep 2022
What is firewall
Firewall is a program that manages the incoming and outgoing traffic.
Why we need it
You may need to block the bad website crawler that causes you to pay money for additional bandwidth usage. Or you may want to block someone from brute force attacking your SSH service.
For any web server, we should open the port that is needed and block the remaining ports.
Here's how you configure it
To speed up the firewall setup, best is to rely on ufw
(uncomplicated firewall) which is a program that handles the low level configuration in iptables
(i.e., the actual firewall).
-
To install
ufw
,sudo apt install ufw
-
To check daemon status
sudo systemctl status ufw
-
To view the rules,
sudo ufw status
OR with the rule number (where you need the number for delete action),
sudo ufw status numbered
-
Update the firewall policies,
sudo ufw allow ssh sudo ufw allow http sudo ufw allow https sudo ufw allow 40000:40100/tcp
NOTES: the last line is to add a port range for FTP (passive port).
-
Finally, to enable the ufw:
sudo ufw enable
-
There is a convenient way to open the port for the given app. To see the app list, run the following command:
sudo ufw app list
-
Then, open the port for Nginx and SSH.
sudo ufw allow 'Nginx Full' sudo ufw allow 'OpenSSH'
-
To block a port,
sudo ufw deny ssh
With iptables
If you want to handle the low level configuration, you will have to use iptables
.
-
To view the rules in the firewall (where
-L
is list all and-n
is skip checking with DNS server):sudo iptables -L -n
-
To block ip address from accessing the server, add a rule to the firewall:
sudo iptables -A INPUT -j DROP -s 192.168.1.200
-
To remove the rule
sudo iptables -D INPUT -j DROP -s 192.168.1.200
NOTE: don't forget to call sudo iptables-persistent save
to save the changes.
-
To save the firewall rules (prevent the rules lost after server restart), run the following commands. If you are using the fail2ban program, try not to install this.
-
Use the add-on
iptables-persistent
utility that helps to save the current settings to file.sudo apt-get install iptables-persistent
-
To save the rules,
sudo /etc/init.d/iptables-persistent save
-
To reload the rules,
sudo /etc/init.d/iptables-persistent reload
-
The rules are stored in,
/etc/iptables/rules.v4
References
-
On how to block IP: http://www.cyberciti.biz/faq/how-do-i-block-an-ip-on-my-linux-server/
-
For more details about
iptables
command: https://help.ubuntu.com/community/IptablesHowTo -
For how to persist the changes in
iptables
: http://askubuntu.com/questions/119393/how-to-save-rules-of-the-iptables
Related posts
Jump to #UBUNTU blog
Author
Lau Hon Wan, software developer.