How to deny all incoming ports except HTTP port 80 and HTTPS port 443 on Ubuntu 18.04 Bionic Beaver Linux

Objective

The objective is to enable UFW firewall, deny all incoming ports however only allow HTTP port 80 and HTTPS port 443 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.

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

Other Versions of this Tutorial

Ubuntu 20.04 (Focal Fossa)

Instructions

Check a current firewall status

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

$ sudo ufw status
Status: inactive

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 HTTP/HTTPS incoming traffic

UFW offers three possible profiles to allow/deny traffic to the Apache web server:

  • Apache – Port 80
  • Apache Full – Ports 80,443
  • Apache Secure – Port 443

and Nginx webserver:

  • Nginx HTTP – Port 80
  • Nginx Full – Ports 80,443
  • Nginx HTTPS – Port 443

Using the above profile names we can allow an incoming traffic to suit any scenario. For example to allow both ports 80,443 on for Apache execute:

$ sudo ufw allow in "Apache Full"
Rule added
Rule added (v6)

Alternatively, to allow only port 443 on Nginx server execute:

$ sudo ufw allow in "Nginx HTTPS"

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
--                         ------      ----               
80,443/tcp (Apache Full)   ALLOW IN    Anywhere                             
80,443/tcp (Apache Full (v6)) ALLOW IN    Anywhere (v6)

Appendix

Error:

$ sudo ufw allow in "Apache Full"
ERROR: Could not find a profile matching 'Apache Full'

You do not have Apache webserver installed on your system yet. To install Apache webserver execute:

$ sudo apt install apache2