How To Set Up a Firewall with UFW on Ubuntu 20.04


UFW is installed by default on Ubuntu, so you don’t need to install this.

Setting Up Default Policies

To set the default UFW incoming policy to deny, run:
sudo ufw default deny incoming

root@tutorialspots3:~# sudo ufw default deny incoming
Default incoming policy changed to 'deny'
(be sure to update your rules accordingly)

To set the default UFW outgoing policy to allow, run:
sudo ufw default allow outgoing

root@tutorialspots3:~# sudo ufw default allow outgoing
Default outgoing policy changed to 'allow'
(be sure to update your rules accordingly)

Allowing SSH Connections

Method 1: sudo ufw allow OpenSSH
Method 2: sudo ufw allow ssh
Method 3: sudo ufw allow 22

root@tutorialspots3:~# sudo ufw allow ssh
Rules updated
Rules updated (v6)

Enabling UFW
sudo ufw enable

root@tutorialspots3:~# sudo ufw enable
Command may disrupt existing ssh connections. Proceed with operation (y|n)? y
Firewall is active and enabled on system startup

Allowing Other Connections

Example:
sudo ufw allow http
sudo ufw allow https

root@tutorialspots3:~# sudo ufw allow http
Rule added
Rule added (v6)
root@tutorialspots3:~# sudo ufw allow https
Rule added
Rule added (v6)

Specific Port Ranges

sudo ufw allow 7000:8000/tcp

Specific IP Addresses, CIDR

sudo ufw allow from 5.111.22.33
sudo ufw allow from 5.111.22.33/24

Specific Port and IP Address
sudo ufw allow from 5.111.0.0/16 to any port 27017

root@tutorialspots3:~# sudo ufw allow from 5.111.22.33/16 to any port 27017
Rule added

Connections to a Specific Network Interface
sudo ufw allow in on eth0 to any port 80

Denying Connections
Similar to allowing connections
sudo ufw deny from 5.111.22.33

Deleting Rules

Deleting a UFW Rule By Number

To see number use this command:
sudo ufw status numbered

Delete by number:
sudo ufw delete 1

Deleting a UFW Rule By Name

sudo ufw delete allow http

Checking UFW Status and Rules

sudo ufw status verbose

Disabling or Resetting UFW

sudo ufw disable
sudo ufw reset

1 Comment

Leave a Reply