Locating and blocking unwanted open ports in Linux should be a task every network admin knows how to do.
So you’re a network administrator and you have a number of Linux machines in your data center. You’ve found some odd traffic bouncing about your network and your curiosity is piqued. Is it possible that traffic is making use of an open port on a machine? If so, where’s the port and how do you close it?
On those Linux machines, the task is actually pretty simple. I want to show you how to locate an open port and close it. I’ll be demonstrating on Ubuntu Server 18.04, although the process will be similar on many distributions—the only difference being how you close the port.
SEE: Windows 10 security: A guide for business leaders (TechRepublic Premium)
What you’ll need
In order to make this work, all you’ll need is a running instance of Ubuntu Server and a user account with sudo privileges.
How to locate a listening port
Fortunately, you don’t have to install any software to make this work. Why? Because we’ll be using the ss command (as netstat has been deprecated) to view the listening ports on your server. This will be done completely from the command line, so either log into your server or use secure shell for access. Once you’re at the bash prompt, issue the command:
sudo ss -tulwn | grep LISTEN
The options are as follows:
- -t Show only TCP sockets on Linux
- -u Display only UDP sockets on Linux
- -l Show listening sockets (for example, TCP port 22 is opened by SSHD server)
- -p List process name that opened sockets
- -n Don’t resolve service names
The output (Figure A) will list out only the listening ports.
As you can see, there are only a handful of listening ports on this machine (53, 22, 631, 445, 3306, 11211, 80, 8080). That’s a pretty slim listing of ports.
If you’re unsure of what port maps to what service, you can always find out in the /etc/services file. Read that file with the command:
You should see a listing of every port available to Linux (Figure B).
How to close a port
Say you are hosting a web server on the machine but you don’t want port 8080 listening. Instead, you only want traffic going through ports 80 (HTTP) and 443 (HTTPS). To close port 8080, we’ll use the ufw (Uncomplicated FireWall) command like so:
sudo ufw deny 8080
You should see the rules have been updated and the port is now blocked. If you find blocking this port to cause problems with a service or application, you can re-open it with the command:
sudo ufw allow 8080
And that’s all there is to locating and closing a listening port on Ubuntu Server 18.04. This process should work on most distributions, the only caveat will be how you block a port as not every distribution uses ufw. If your distribution of choice uses a different command for blocking ports (such as sudo iptables -A INPUT -p tcp –destination-port 80 -j DROP), make sure you know how to take care of this task on your servers.