How to set up Linux UFW?

December 16, 2022
Linux

How to use IPv6 with UFW? (optional)

If IPv6 is enabled on your Ubuntu server, UFW must be configured to support IPv6 in order to manage firewall rules not only for IPv4 but also for IPv6. To do this, open the UFW configuration with nano or your favorite editor.

sudo nano /etc/default/ufw
Then make sure that the value of IPv6 is=yes.

How to set up standard policies?

Set to default settings:

sudo ufw default deny incoming 
sudo ufw default allow outgoing

How to allow SSH connections?

Must be set before activation, otherwise SSH access is not possible:

sudo ufw allow ssh

ufw knew what allow ssh means (Prot 22) otherwise the command also works:

sudo ufw allow 22

or whichever port you have configured for SSH.

How to activate UFW?

sudo ufw enable

Y and Enter to continue

#show status of ufw and the rules 
sudo ufw status verbose

then reboot the system, check with the above command that port 22 (SSH) is allowed if you are in an SSH session.
22/tcp ALLOW IN Anywhere

#reboot system 
sudo reboot

How to allow other connections with UFW?

Examples:

#Specific IP addresses 
sudo ufw allow from 203.0.113.4
sudo ufw allow from 203.0.113.4 to any port 22

#Subnets
sudo ufw allow from 203.0.113.0/24
sudo ufw allow from 203.0.113.0/24 to any port 22
#sudo ufw allow from 203.0.113.0/24 to any port 22 ip addr

Output Excerpt
2: eth0: BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state
. . .
3: eth1: BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN group default

#If server has a public network interface called eth0, you could allow HTTP traffic (port 80) to it
sudo ufw allow in on eth0 to any port 80
sudo ufw allow in on eth1 to any port 3306 #MySQL-Databaseserver

How to reject connections?

#deny HTTP connections 
sudo ufw deny http
#deny all connections from (IP)
sudo ufw deny from 203.0.113.4

How to delete UFW rules

If rule numbers have been used:

#List of firewall rules with number 
sudo ufw status numbered

#delete by number e.g. rule 2
sudo ufw delete 2

According to actual rule:

#rule named "allow http"
sudo ufw delete allow http

#or instead of http (allow 80)
sudo ufw delete allow 80

How to check UFW status and rules?

sudo ufw status verbose

How to enable or reset UFW?

#disable ufw all configured settings are no longer enabled 
sudo ufw disable

#reset all rules and you can start from scratch
sudo ufw reset



Get to know UFW better through this project