How to PROPERLY Open Port in RHEL/CentOS Linux


Written by - Deepak Prasad

In the ever-evolving landscape of network administration, understanding how to manage and configure systems is paramount. One of the fundamental tasks that administrators often find themselves handling is port management. Specifically, when working with CentOS, a popular choice for web servers and enterprise environments, knowing how to "CentOS open port" is a crucial skill. Ports serve as communication endpoints, enabling software applications to communicate over networks. Opening a port in CentOS allows specific software or services to communicate freely, facilitating necessary functions like web hosting, file transfers, or database queries. However, it's not just about opening a port; it's about striking the right balance between functionality and security.

In this article, we will delve deep into the intricacies of opening a port in CentOS, ensuring that you have a thorough understanding of the process and the considerations involved.

 

Identifying the Current Port Status

Before making changes to your system, especially when it comes to networking and security configurations, it's pivotal to first understand the current status. Being aware of which ports are already open and the firewall rules in place is essential in maintaining the system's security and ensuring no conflicts arise when implementing new rules or services.

 

Tools to Check Open Ports

netstat:

Short for 'network statistics', netstat is a command-line tool that provides information about network connections, routing tables, interface statistics, masquerade connections, and more. When used with certain flags, it can display a list of open ports and the services running on them.

To list all the open ports, you can use:

$ netstat -tuln
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN     
tcp6       0      0 :::80                   :::*                    LISTEN

This shows that the system has SSH (port 22) and HTTP (port 80) services listening.

 

lsof:

The lsof command, meaning 'list open files', can be employed in the context of networking to identify which process is using a certain port. It's versatile and can provide a lot of information about files opened by processes, including network sockets.

To list processes that are using network ports:

$ lsof -i
COMMAND  PID   USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
sshd    1234  root    3u  IPv4  12345      0t0  TCP *:ssh (LISTEN)
httpd   5678  httpd   4u  IPv6  67890      0t0  TCP *:http (LISTEN)

This indicates sshd is using port 22 and httpd is using port 80.

 

ss:

Standing for 'socket statistics', ss is a utility to investigate sockets. It's a modern replacement for netstat, offering faster and more detailed insights into the system's network activity.

$ ss -tuln
State     Recv-Q Send-Q   Local Address:Port      Peer Address:Port 
LISTEN    0      128     0.0.0.0:22               0.0.0.0:*              
LISTEN    0      128     [::]:80                  [::]:*

 

nmap:

To check the list of existing ports which are open we will use nmap to check port status:

# nmap localhost
Starting Nmap 7.70 ( https://nmap.org ) at 2020-03-22 12:08 IST
Nmap scan report for localhost (127.0.0.1)
Host is up (0.000024s latency).
Other addresses for localhost (not scanned): ::1
Not shown: 998 closed ports
PORT STATE SERVICE
22/tcp open ssh
111/tcp open rpcbind
Nmap done: 1 IP address (1 host up) scanned in 1.71 seconds

Currently we see only two ports are open on my CentOS 8 node.

 

Evaluating Firewall Rules

Once you've identified the open ports, it's equally crucial to understand the existing firewall rules. Firewalls act as gatekeepers, controlling incoming and outgoing network traffic based on predetermined security policies.

 

List active rules:

Depending on the firewall solution you're using (e.g., iptables, firewalld, ufw), there are specific commands to list the active rules. By examining these rules, you can determine which ports are allowed, which are blocked, and any other specific conditions or exceptions that have been set.

iptables: For this example, let's consider iptables:

sudo iptables -L -v -n

firewalld is the default firewall management tool for Red Hat-based distributions like CentOS and Fedora.

sudo firewall-cmd --get-active-zones
sudo firewall-cmd --list-all --zone=public

The output indicates that for the public zone, services like ssh, dhcpv6-client, and http are allowed. Additionally, custom ports 8080 and 8443 are also open.

ufw is the default firewall tool for Ubuntu and other Debian-based distributions.

sudo ufw status verbose

 

Check for default policies:

Firewalls can have default policies, like denying all incoming traffic unless explicitly allowed. Knowing these defaults will give you a backdrop against which specific rules operate.

With firewalld, zones are used to define the behavior of incoming and outgoing traffic. The default zone can be checked using:

firewall-cmd --get-default-zone

To check the policies for the public zone:

firewall-cmd --list-all --zone=public

 

Analyze rule hierarchy:

Sometimes, the order of firewall rules matters. A rule set early in the list might override a subsequent rule. It's vital to understand this hierarchy when diagnosing issues or planning changes.

With ufw, rules are processed in the order they are defined, from top to bottom. If a packet matches a rule, it will be processed accordingly, and no further rules will be checked.

For example, if you have:

To                         Action      From
--                         ------      ----
22/tcp                     DENY        Anywhere
22/tcp                     ALLOW       192.168.1.0/24

Even though you've allowed SSH (port 22) traffic from the 192.168.1.0/24 subnet, the earlier rule denies all SSH traffic, so the second rule will never be applied. It's essential to ensure that more specific rules are defined before general ones to avoid such conflicts.

 

Opening Ports at Firewall Level

Using firewalld

firewalld is a dynamic firewall daemon that manages firewall rules with the concept of zones. It's typically found in Red Hat-based distributions, including CentOS and Fedora. With firewalld, administrators can manage rules without needing to restart the firewall, and it provides an easy-to-use interface for managing complex firewall setups.

# Open a port (Example: 8080 TCP)
firewall-cmd --zone=public --add-port=8080/tcp --permanent

# Reload the firewall to apply the changes
firewall-cmd --reload

# Verify that the port has been opened
firewall-cmd --list-ports

 

Using ufw

ufw, short for Uncomplicated Firewall, is designed to be an easy-to-use interface for the more complex iptables. It's the default firewall configuration tool for Ubuntu. ufw provides a user-friendly way to manage netfilter, the underlying packet filtering subsystem in Linux.

# Open a port (Example: 8080 TCP)
sudo ufw allow 8080/tcp

# Enable the firewall (if not already enabled)
sudo ufw enable

# Verify that the port has been opened
sudo ufw status

 

Using iptables

iptables is a detailed packet filtering framework in Linux. It's the tool behind most of the Linux firewall solutions and offers extensive capabilities to define packet filtering rules. While powerful, it's often considered more complex than solutions like ufw or firewalld.

# Open a port (Example: 8080 TCP)
sudo iptables -A INPUT -p tcp --dport 8080 -j ACCEPT

# Save the configuration for persistence (this might vary depending on your distro/setup)
sudo service iptables save

# Verify that the port has been opened
sudo iptables -L -v -n

 

Testing the Opened Port

Once you've opened a port, it's imperative to test it to ensure that the configurations are correctly set, and the desired services are accessible through that port. Let's dive into how you can perform such tests:

 

Using telnet

telnet is a client-server protocol that provides a bidirectional interactive text-oriented communication facility. While its primary purpose isn't for port testing, it can be used to check the accessibility of a port.

Now telnet may not be installed in all Linux distributions, you can install it manually:

# Install telnet (Debian-based)
sudo apt update
sudo apt install telnet

# Install telnet (Red Hat-based)
sudo yum install telnet      # CentOS 6 and older versions
sudo dnf install telnet      # CentOS 7 and newer versions, Fedora

# Install telnet (openSUSE)
sudo zypper install telnet


# Install telnet (Arch Linux)
sudo pacman -S inetutils

Here is a sample command syntax to check port connectivity

# Test connectivity to a specific port (Example: 8080)
telnet [hostname or IP] 8080

If the port is open and reachable, you might see a successful connection message; otherwise, you'll encounter a connection timeout or refusal.

By default telnet will not exit the session once it is connected, so to exit telnet, you can use the following procedure:

  1. Press Ctrl + ] (Control key followed by the right square bracket). This will take you to the telnet command prompt.
  2. At the telnet command prompt, simply type quit and then press Enter.

Alternatively use the echo command in conjunction with telnet and pipe it through, forcing an immediate disconnection once connected. 

echo "quit" | telnet [hostname or IP] [port]

By echoing "quit" into the telnet command, as soon as a connection is made, the quit command is issued to telnet, which then terminates the session.

Alternatively, if you have the timeout command available:

timeout 5 telnet [hostname or IP] [port]

In the above command, timeout 5 ensures that the telnet command runs for a maximum of 5 seconds before being terminated. Adjust the time (5 in this case) as needed based on your requirements.

 

Using nc (netcat)

netcat is a versatile networking tool, often dubbed the "Swiss army knife" of networking. It can be used for just about anything under the sun involving TCP, UDP, or UNIX-domain sockets.

netcat may not be installed by default, so you may need to install it manually:

# Install netcat (nc) on Debian-based
sudo apt install netcat

# Install netcat (nc) on Red Hat-based
sudo yum install nc          # CentOS 6 and older versions
sudo dnf install nmap-ncat   # CentOS 7 and newer versions, Fedora

# Install netcat (nc) on OpenSUSE
sudo zypper install netcat

# Install netcat (nc) on Arch Linux
sudo pacman -S gnu-netcat

Here is a sample command syntax to check connectivity using nc command

# Test connectivity to a specific port (Example: 8080)
nc -zv [hostname or IP] 8080

The -z flag makes netcat scan for listening daemons without sending any data to them, while -v enables verbose mode. A successful connection will yield a success message, and a failure will result in a timeout or refusal.

The -w option in nc (netcat) is used to set a timeout for establishing a connection or reading from a connection. When you use -w2, it will specify a 2-second timeout.

nc -w2 -zv [hostname or IP] [port]

This will attempt to connect to the specified hostname or IP on the given port. If nc can't establish the connection within 2 seconds, it will time out. If it successfully connects, it will immediately close the connection due to the -z flag (which instructs nc to only scan for listening daemons without actually sending any data).

 

Using bash's Built-in TCP Functionality

Bash, starting from version 2.04, comes with a little-known feature that allows users to make TCP or UDP connections using special file descriptors /dev/tcp/host/port for TCP and /dev/udp/host/port for UDP.

For Example:

$ timeout 4 bash -c "</dev/tcp/100.73.162.2/8075"
$ echo $?
0

The command </dev/tcp/100.73.162.2/8075 attempts to open a connection to IP address 100.73.162.2 on port 8075. If the connection succeeds, it essentially does nothing and moves on. If the connection fails, Bash will return an error.

Wrapping the command with timeout 4 bash -c ensures that the command will only attempt the connection for a maximum of 4 seconds, preventing long hangs if the port isn't responding.

After running the command, you check the exit status with echo $?.  If you get a return code 0 then it indicates the port is open and accessible. If you get a different non-zero return code, it can indicate other types of errors.

 

Troubleshooting Common Issues

Troubleshooting network-related issues, especially when dealing with ports, often involves a multi-faceted approach. Here are some insights into the common challenges you highlighted:

 

1. Port is Still Not Accessible

When a port is not accessible, it might be due to several reasons:

  • Firewall Rules: The most common reason is that firewall rules might be blocking access. Double-check your rules, and ensure that you have allowed traffic on the desired port.

  • Service Not Running: The application or service meant to listen on the port might not be running. Use tools like netstat or ss to see if any service is actively listening on the port.

  • Network Configuration: If you're trying to access a port on a different machine, network configurations such as NAT, port forwarding, or even ISP restrictions can come into play. Ensure that all network configurations are correctly set up to allow traffic on the required port.

 

2. Conflict with Other Services or Rules

Conflicting rules or services can interfere with the desired functionality:

  • Port Already in Use: If another service is already running on the desired port, you'll face a binding issue. Ensure the port is free before trying to start a new service on it. Tools like lsof and netstat can help you identify which process is using a particular port.

  • Overlapping Firewall Rules: Some firewalls process rules in a top-down manner. If a deny rule appears before an allow rule for a specific port, the deny rule will take precedence. Ensure that your allow rules are not being inadvertently overridden by prior conflicting rules.

  • Service-Specific Configurations: Some services might bind to a specific IP address (like 127.0.0.1) instead of all available ones (0.0.0.0). Ensure that the service configuration allows external connections if required.

 

3. Addressing Connectivity Issues

General connectivity issues might not be limited to a specific port:

  • Ping the Host: A simple ping command can help you determine if there's basic connectivity between two machines. If you can't ping the host, there are broader network issues at play.

  • Traceroute: The traceroute or tracert (Windows) command can help identify where the connection is breaking down if the target host is several hops away.

  • Network Tools: Tools like mtr (a combination of ping and traceroute) provide real-time diagnostics about the network connection.

  • Check Physical Connections: While it might sound trivial, ensuring that all cables are correctly connected, switches are powered on, and Wi-Fi connections are stable can save a lot of headaches.

  • Logs: Always check logs of the application, service, or firewall in question. They often provide specific details about what's going wrong.

 

Closing or Deleting Rules

Managing open ports is essential for maintaining a secure and optimized system. At times, it's necessary to close ports or delete firewall rules to prevent unwanted access or enhance system security.

 

iptables:

To delete a rule allowing traffic on a specific port:

# For TCP
sudo iptables -D INPUT -p tcp --dport [PORT_NUMBER] -j ACCEPT

# For UDP
sudo iptables -D INPUT -p udp --dport [PORT_NUMBER] -j ACCEPT

Save the updated rules:

# For Debian/Ubuntu
sudo iptables-save > /etc/iptables/rules.v4

# For Red Hat/CentOS (using iptables-services)
sudo service iptables save

 

firewalld:

To remove a port:

sudo firewall-cmd --permanent --remove-port=[PORT_NUMBER]/tcp  # For TCP
sudo firewall-cmd --permanent --remove-port=[PORT_NUMBER]/udp  # For UDP

Reload firewalld to apply changes:

sudo firewall-cmd --reload

 

ufw (Uncomplicated Firewall):

To deny or delete a rule for a specific port:

sudo ufw delete allow [PORT_NUMBER]/tcp # For TCP
sudo ufw delete allow [PORT_NUMBER]/udp # For UDP

 

Summary

Managing network ports effectively is crucial for system security and optimization. While the necessity to open ports arises from applications requiring network communication, it's equally important to know when and how to close them. The primary reasons to close a port include security concerns, system optimization, compliance with standards, and troubleshooting endeavors. When working with CentOS, a popular Linux distribution, tools like iptables, firewalld, and ufw provide comprehensive control over port management. While opening a port in CentOS caters to application needs, it's crucial to be aware of the potential risks and monitor them regularly. Deleting or modifying firewall rules should be done judiciously to prevent unwanted exposure or system conflicts. In essence, the balance between functionality and security is vital when managing open ports in CentOS.

 

References

Open firewall port on CentOS 7

 

Deepak Prasad

He is the founder of GoLinuxCloud and brings over a decade of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive experience, he excels in various domains, from development to DevOps, Networking, and Security, ensuring robust and efficient solutions for diverse projects. You can reach out to him on his LinkedIn profile or join on Facebook page.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

5 thoughts on “How to PROPERLY Open Port in RHEL/CentOS Linux”

  1. A very thorough and helpful post. I was trying to allow ssh on a secondary port and could not get it to work using the usual advice (w/CentOS8.)
    The recommendation you provided to add the port using the firewall-cmd was the missing ingredient:

    firewall-cmd --zone=public --add-port=22/tcp --permanent
    firewall-cmd --reload

    Thanks for this!

    Reply
  2. Hi
    I did below steps and reloaded firewall but still when I do netstat -ntlp port 1234 not showing open

    [root@centos-8 ~]# firewall-cmd --zone=public --add-port=1234/tcp --permanent
    success
    [root@centos-8 ~]# firewall-cmd --reload
    success

    Thanks
    Al

    Reply
    • I did explained this part in the article

      We still don’t see port 1234 here. This is because currently port 1234 is not bind to any service. So our port is OPEN but NOT LISTENING. As soon as a request or service tries to use port 1234, we will get this in LISTEN state.

      Reply
    • I assume you are asking about nc command. By default nc will close the connection after current connection is completed. To keep it active use -k along with -l

      Reply

Leave a Comment