Enabling the firewall will help you protect your dedicated server from unwanted connections to private services that you may want to disable from the public internet.
By default the firewall in Ubuntu is disabled. In this article we’ll explain how to use uncomplicated firewall (ufw) to configure iptables, which you may use this guide on other distributions if ufw is installed.
1. Gain root access within the console/SSH by executing ‘sudo su’
2. Add a rule to allow SSH so we don’t disconnected by executing ‘ufw allow [sshportnumberhere]/tcp’
You also may add other services such as http with ‘ufw allow 80/tcp’
3. Enable the firewall by executing ‘ufw enable’
To allow udp ports, replace tcp with udp. For example: ‘ufw allow portnumberhere/udp’
If you need open a range of ports you can execute ‘ufw allow 100:200/tcp’ to allow connects from port 100 to port 200.
– You may replace ‘tcp’ with ‘udp’ if you need to open udp ports.
If you need to deny a specific IP, execute ‘ufw deny from ipaddresshere’
-You can deny an entire subnet/block by executing ‘ufw deny from ipaddress/subnetprefix’
Removing a rule in the firewall is a very simple task.
1. Execute ‘ufw status numbered’ and look for the rule you’d like to remove.
2. Execute ‘ufw delete rulenumberhere’ to remove the rule.
We suggest if you’re using this command, also remove the IPv6 rules by following steps 2 and 3. Each time you delete a rule, the numbering changes.
==============
Advanced settings
==============
You can specify an IP or IP subnet to only have access to a specific port. For this example: SSH.
1. We need to add the rule to allow the IP to connect port 22 and ignore all others by executing ‘ufw allow from theipyouwanttopasshere to any port 22 proto tcp’
You can change ‘tcp’ to ‘udp’ if you need to open an udp port.
2. Remove any other rule that allows port 22 to all connections by executing ‘ufw status numbered’
3. Remove the rule by executing ‘ufw delete rulenumberhere’
We suggest if you’re using this command, also remove the IPv6 rules by following steps 2 and 3. Each time you delete a rule, the numbering changes.
Also please keep in mind that when you apply this rule, if you’re not in the IP or in the IP subnet specified, you will get disconnected.