How to close open ports on Linux

A few weeks ago, I received the following email from one of my server providers:

Recent network security audits have detected some issues on your instances.  Please review the following reports and help us to ensure the security of our network:

The issue was due to a potentially vulnerable port which was left open on my server. Fortunately enough, I was given the command to block the offensive port. However, I like to conduct research on commands before I simply use them on one of my live servers. Let’s take a look at how to first locate listening ports on your server.

Note – we will be running commands as sudo. You will need to have super user privileges to run these commands, so make sure you have the appropriate permissions.

Locate listening port(s)

To locate listening ports, we can use the ss command. Through the ss command, we can view socket statistics and it’s quite faster than its deprecated counterpart (netstat). Open your Terminal or sign into your server, then type the following command:

sudo ss -tulwn | grep LISTEN

Once entered, the command will dump all listening ports.

Picture of listening ports.

There are not many ports on the machine, but the output could potentially be longer depending on your server’s configuration. Once you have found the offending port, it’s now time to disable it.

Close an open port

For the following example, we’ll be using the ufw command (Uncomplicated Firewall) to block the port. The command should be available on most, if not all, Linux distributions. However, if the command is not available then you can use iptables to block the port.

Let’s say you are running a web server, and you only want traffic coming through ports 80 and 443, HTTP and HTTPS respectively. Well, we can block port 8080. To block the port, simply type the command:

sudo ufw deny 8080

Press enter, and the port will be blocked. Simple enough, right? Well, if you ever need to re-open a port you can simply type the command:

sudo ufw allow 8080

I hope you enjoyed the article, and found it to be of use.