- How to check open ports in Linux using the CLI
- What the hell are a TCP and UDP ports?
- Port numbers
- Check open ports in Linux
- Using netstat to list open ports
- Use ss to list open ports
- Listening ports and applications using lsof command
- nmap command
- The open port doesn’t mean anyone from outside can access those ports
- Conclusion
- Как посмотреть открытые порты в Linux
- Как посмотреть открытые порты linux
- 1. netstat
- 3. lsof
- 4. Nmap
- 5. Zenmap
- Выводы
- Check open ports in Linux | Test firewall rules
- Method-1: Check open ports using nmap
- Understanding different states in nmap
- Method-2: Check list of open ports in Linux using hping3
- Method-3: Test firewall rules
- Summary
- Further Readings
- Related Posts
- 1 thought on “Check open ports in Linux | Test firewall rules”
How to check open ports in Linux using the CLI
I need to list all open ports in Linux cloud server. How do I check open ports in Linux using the CLI? Can you give me the command to check open ports in Linux operating system?
To troubleshoot server problems and to avoid security issue, one needs to find out open TCP and UDP ports. In this tutorial, you will learn the different Linux commands to check open ports in Linux for auditing and securing the server.
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | Yes |
Requirements | Linux command line |
Est. reading time | 5 minutes |
What the hell are a TCP and UDP ports?
A port is nothing but a 16-bit number between 0 to 65535. For example, TCP port number 22 may be forwarded to the OpenSSH server. Therefore, 22 port number is a way to identify the sshd (OpenSSH server) process.
Port numbers
- The Well Known Ports are those from 0 through 1023.
- The Registered Ports are those from 1024 through 49151.
- The Dynamic and Private Ports are those from 49152 through 65535.
A registered port is a network port assigned by the Internet Assigned Numbers Authority (IANA) and stored in /etc/services file. Use the cat command or grep command/egrep command to view port numbers and service mappings:
Display a list of applications and their ports assigned by IANA
Check open ports in Linux
The procedure to monitor and display open ports in Linux is as follows:
- Open a Linux terminal application
- Use ss command to display all open TCP and UDP ports in Linux.
- Another option is to use the netstat command to list all ports in Linux.
- Apart from ss / netstat one can use the lsof command to list open files and ports on Linux based system.
- Finally, one can use nmap command to check TCP and UDP ports too.
Let us see all commands and examples in details.
Using netstat to list open ports
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
- -t : All TCP ports
- -u : All UDP ports
- -l : Display listening server sockets
- -p : Show the PID and name of the program to which each socket belongs
- -n : Don’t resolve names
- | grep LISTEN : Only display open ports by applying grep command filter.
Use ss to list open ports
The ss command is used to dump socket statistics. It allows showing information similar to netstat. It can display more TCP and state information than other tools. The syntax is:
sudo ss -tulpn
Sample outputs:
Listening ports and applications using lsof command
Let us run the following to check open TCP and UDP ports using the lsof command:
sudo lsof -i -P -n | grep LISTEN
Where,
- -i : Look for listing ports
- -P : Inhibits the conversion of port numbers to port names for network files. Inhibiting the conversion may make lsof run a little faster. It is also useful when port name lookup is not working properly.
- -n : Do not use DNS name
- | grep LISTEN : Again only show ports in LISTEN state using the grep command as filter.
nmap command
In addition, to above commands one can use the nmap command which is an open source tool for network exploration and security auditing. We are going to use nmap to find and list open ports in Linux:
$ sudo nmap -sT -O localhost
$ sudo nmap -sU -O 192.168.2.254 ##[ list open UDP ports ]##
$ sudo nmap -sT -O 127.0.0.1 ##[ list open TCP ports ]##
$ sudo nmap -sTU -O 192.168.2.24
Sample outputs:
The open port doesn’t mean anyone from outside can access those ports
So far, you know how to find and list open TCP and UDP ports on Linux. However, those ports can still be blocked by software, cloud, or hardware firewall. Hence, you need to verify that your corporate firewall is not blocking incoming or outgoing access. For instance on Linux server we list or dump firewall rules using the following syntax:
sudo iptables -S
# IPv6
sudo ip6tables -S
Conclusion
In conclusion, finding out open ports is one of the most fundamental duties of a Linux system administrator for security reasons. Therefore, close down all unwanted ports and configure firewall such as UFW and FirewallD to open or block ports as per your requirements. After reading this tutorial, you should have a good understanding of how to check for open ports in Linux. See IANA’s offical list of TCP, UDP and other ports here for more information.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
Как посмотреть открытые порты в Linux
Сетевые порты — это механизм, с помощью которого операционная система определяет какой именно программе необходимо передать сетевой пакет. Здесь можно привести пример с домом. Например, почтальону необходимо доставить посылку. Он доставляет посылку к дому, это IP адрес компьютера. А дальше в самом доме уже должны разобраться в какую квартиру направить эту посылку. Номер квартиры — это уже порт.
Если порт открыт это означает, что какая либо программа, обычно сервис, использует его для связи с другой программой через интернет или в локальной системе. Чтобы посмотреть какие порты открыты в вашей системе Linux можно использовать множество различных утилит. В этой статье мы рассмотрим самые популярные способы посмотреть открытые порты Linux.
Как посмотреть открытые порты linux
1. netstat
Утилита netstat позволяет увидеть открытые в системе порты, а также открытые на данный момент сетевые соединения. Для отображения максимально подробной информации надо использовать опции:
- -l или —listening — посмотреть только прослушиваемые порты;
- -p или —program — показать имя программы и ее PID;
- -t или —tcp — показать tcp порты;
- -u или —udp показать udp порты;
- -n или —numeric показывать ip адреса в числовом виде.
Открытые порты Linux, которые ожидают соединений имеют тип LISTEN, а перед портом отображается IP адрес на котором сервис ожидает подключений. Это может быть определенный IP адрес или */0.0.0.0 что означают любой доступный адрес:
sudo netstat -tulpn
Утилита ss — это современная альтернатива для команды netstat. В отличие от netstat, которая берет информацию из каталога /proc, утилита ss напрямую связывается со специальной подсистемой ядра Linux, поэтому работает быстрее и её данные более точные, если вы хотите выполнить просмотр открытых портов это не имеет большого значения. Опции у неё такие же:
Можно вывести только процессы, работающие на 80-том порту:
sudo ss -tulpn | grep :80
3. lsof
Утилита lsof позволяет посмотреть все открытые в системе соединения, в том числе и сетевые, для этого нужно использовать опцию -i, а чтобы отображались именно порты, а не названия сетевых служб следует использовать опцию -P:
Ещё один пример, смотрим какие процессы работают с портом 80:
sudo lsof -i -P | grep :80
4. Nmap
Программа Nmap — мощный сетевой сканер, разработанный для сканирования и тестирования на проникновение удаленных узлов, но ничего не мешает направить его на локальный компьютер. Утилита позволяет не только посмотреть открытые порты, но и примерно определить какие сервисы их слушают и какие уязвимости у них есть. Программу надо установить:
sudo apt install nmap
Затем можно использовать:
Для простого сканирования можно запускать утилиту без опций. Детальнее о её опциях можно узнать в статье про сканирование сети в Nmap. Эта утилита ещё будет полезна если вы хотите посмотреть какие порты на компьютере доступны из интернета.
Если это публичный сервер, то результат скорее всего не будет отличатся от локального сканирования, но на домашнем компьютере все немного по другому. Первый вариант — используется роутер и в сеть будут видны только порты роутера, еще одним порогом защиты может стать NAT-сервер провайдера. Технология NAT позволяет нескольким пользователям использовать один внешний IP адрес. И так для просмотра открытых внешних портов сначала узнаем внешний ip адрес, для надежности воспользуемся онлайн сервисом:
wget -O — -q eth0.me
Дальше запускаем сканирование:
В результате мы видим, что открыт порт 80 веб-сервера и 22 — порт службы ssh, я их не открывал, эти порты открыты роутером, 80 — для веб-интерфейса, а 22 для может использоваться для обновления прошивки. А еще можно вообще не получить результатов, это будет означать что все порты закрыты, или на сервере установлена система защиты от вторжений IDS. Такая проверка портов может оказаться полезной для того, чтобы понять находится ли ваш компьютер в безопасности и нет ли там лишних открытых портов, доступных всем.
5. Zenmap
Программа Zenmap — это графический интерфейс для nmap. Она не делает ничего нового кроме того, что может делать nmap, просто предоставляет ко всему этому удобный интерфейс. Для её установки выполните:
sudo apt install zenmap
Запустить программу можно из главного меню или командой:
Затем введите адрес localhost в поле Цель и нажмите кнопку Сканирование:
После завершения сканирования утилита вывела список открытых портов Linux.
Выводы
В этой статье мы рассмотрели инструменты, которые вы можете использовать для того чтобы узнать узнать открытые порты linux. Инструментов не так много как для просмотра информации об оперативной памяти или процессоре, но их вполне хватает. А какими программами пользуетесь вы? Напишите в комментариях!
Источник
Check open ports in Linux | Test firewall rules
Table of Contents
Lately I was going through some articles from different search engine to check open ports in Linux. I was quiet surprised with the results as most of these articles in the search results talks about using ss, netstat etc to check if a port is open in Linux.
You have to understand the difference and your requirement.
Do you want to check if a port is open on the destination server or between source and destination server?
Do you want to check if a port is in LISTENING state on the destination server.
As it doesn’t necessarily mean that if a port is not listening then it is not open. A port will be in LISTEN state only when it is in use by some process or else a port can be open and free but since it is not in USE it will not be listed with netstat, lsof, ss commands etc.
So I hope you are clear with your requirement.
In this article I will share the different ways to check open ports or if a port is open on the destination server in Linux.
Method-1: Check open ports using nmap
nmap is an open source tool for network exploration and security auditing. Let’s verify if nmap can successfully give us list of open ports on a Linux server:
Currently I have not added any firewall rules on my destination server:
Now let us check open ports between 35520-35522 on this server using some different client machine with nmap:
We have used -PN to perform TCP SYN/ACK check on the provided list of ports but the output claims that all of these ports are closed. But this is not correct as there is no firewall on server-2 and this setup in in my local LAN so no other firewalls in between these servers.
Now here are the list of listening ports on server-2 :
So if we try to scan these listening ports using nmap:
All of these ports are marked as OPEN. So unless your ports are in use by some process, they will not be marked as OPEN.
Let’s perform some more tests. I will DROP all the incoming requests and only allow certain ports on server-2 using iptables:
List the applied rules
So I have explicitly allowed port 35520 , now let’s perform nmap scan for this port and some others:
Now port 35520 is marked as CLOSED as it is explicitly allowed in iptables but currently is not in use while others are marked as FILTERED as they are blocked in firewall.
Understanding different states in nmap
Though the current version of NMAP is capable of performing many tasks, it initially started out as a port scanner. NMAP has certain ways to detect whether the port on the target system is open or closed. NMAP detects the status of the target port using predefined states as follows:
- Open: The Open state indicates that an application on the target system is actively listening for connections/packets on that port.
- Closed: The Closed state indicates there isn’t any application listening on that port. However, the port state could change to Open in the future.
- Filtered: The Filtered state indicates that either a firewall, a filter, or some kind of network hurdle is blocking the port and hence NMAP isn’t able to determine whether it is open or closed.
- Unfiltered: The Unfiltered state indicates that ports are responding to NMAP probes; however, it isn’t possible to determine whether they are open or closed.
- Open/Filtered: The Open/Filtered state indicates that the port is either filtered or open; however, NMAP isn’t precisely able to determine the state.
- Closed/Filtered: The Closed/Filtered state indicates that the port is either filtered or closed; however, NMAP isn’t precisely able to determine the state.
Method-2: Check list of open ports in Linux using hping3
Another wonderful tool to perform network scan is hping3 in Linux. You may download hping3 using EPEL repo.
We will retain the iptables rule which we applied in the previous example where we had blocked all the ports except 22 and 35520 and perform network scan using hping3:
So based on the above hint, hping3 got a RESET request with ACK on port 35520 which means the port may be in OPEN state while the other ports in the provided range are not responding so they are closed.
If any of the port is in LISTENING state then hping3 will return SYN and ACK flag as shown below:
Method-3: Test firewall rules
Now you may using the tools which I explained above to check open ports but if you wish to test firewall rules then I would recommend using netcat or nc tool. nc can be used to open any port and mark it as listening and then on the client server you can again use nc to send some dummy data to test firewall rule.
Let us retain the above applied iptables rule, so on our server port 35520 is allowed in the firewall. To test this firewall rule, we will enable port 35520 using nc:
So our server is now listening on port 35520, now let’s try to connect to this port using any other client node:
As you can see, nc was able to connect to server-2 using port 35520. Now if you try to send any string from client to server:
Monitor the console on server-1 and you will receive this string:
Similarly let’s try to test firewall rule for any other port which is blocked (we have blocked all the ports except 35520 and 22):
Since port 35521 port is blocked in the firewall, the same will not be accessible from server-1 :
Summary
In this article I shared different methods to perform network scanning to check open ports and test firewall rules in Linux. There are many other tools available which can be used for this purpose. But again I don’t rely on telnet, ss or netstat commands for this purpose as they may not give you accurate data based on your requirement. nmap, hping3 are very vast tools with alot of different options and features which are not covered in this article. I would suggest to go through their man page and explore different options.
Further Readings
Related Posts
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
Thank You for your support!!
1 thought on “Check open ports in Linux | Test firewall rules”
Hi I’m Very interesting to all your tutoes. And i think they can help many people to have a better understanting even me as a beginner in linux.
Источник