How to deny all incoming ports except FTP port 20 and 21 on Ubuntu 18.04 Bionic Beaver Linux

Objective

The objective is to enable UFW firewall, deny all incoming ports however only allow FTP port 20 and 21 on Ubuntu 18.04 Bionic Beaver Linux

Operating System and Software Versions

  • Operating System: – Ubuntu 18.04 Bionic Beaver

Requirements

Privileged access to your Ubuntu 18.04 Bionic Beaver will be required.

Difficulty

EASY

Conventions

  • # – requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command
  • $ – requires given linux commands to be executed as a regular non-privileged user

Instructions

Check the current firewall status

Check your firewall status. By default the UFW firewall will be disabled.

$ sudo ufw status
Status: inactive

Keep the firewall disabled to allow possible SSH connections or enable it by:

$ sudo ufw enable

Block all incoming traffic

First, we can block all incoming traffic using the following linux command:

$ sudo ufw default deny incoming
Default incoming policy changed to 'deny'
(be sure to update your rules accordingly)


Allow FTP ports 20,21 incoming traffic

The following linux command will allow both TCP incoming 20 and 21 ports from any source:

$ sudo ufw allow from any to any port 20,21 proto tcp
Rule added
Rule added (v6)

To allow only specific IP address eg. 10.1.1.231 execute:

$ sudo ufw allow from 10.1.1.231 to any port 20,21 proto tcp

The above command will allow an incoming traffic only from 10.1.1.231 IP address. Alternatively, the next command example will allow only 10.1.1.0/8 subnet to connect to TCP ports 20 and 21:

$ sudo ufw allow from 10.1.1.0/8 to any port 20,21 proto tcp

Enable Firewall

$ sudo ufw enable
Command may disrupt existing ssh connections. Proceed with operation (y|n)? y
Firewall is active and enabled on system startup

Check status

$ sudo ufw status verbose
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
New profiles: skip

To                         Action      From
--                         ------      ----
20,21/tcp                  ALLOW IN    Anywhere                  
20,21/tcp                  ALLOW IN    10.1.1.231                
20,21/tcp                  ALLOW IN    10.0.0.0/8                
20,21/tcp (v6)             ALLOW IN    Anywhere (v6)