Linux runs the world and we all know it. It is the backbone of most servers and network devices. Whitelisting or opening a port in Linux is a common and essential task, since it allows other applications to communicate with the service. There are many ways to do it and let us discuss some of the methods to open port in Linux.
Using iptables
One of the most traditional and widely acceptable methods to manage ports in Linux is via the iptables. Iptables is a user-space utility program that allows a sys admins to configure the IP packet filter rules of the Linux kernel firewall, implemented as different Netfilter modules.
To open a port using iptables, you can use the following command
sudo iptables -A INPUT -p tcp --dport PORT_NUMBER -j ACCEPT
Replace PORT_NUMBER
with the actual port you want to open. This command appends a rule to the INPUT chain, allowing incoming TCP traffic on the specified port.
To make the changes persistent across reboots, you need to save the iptables rules
sudo service iptables save
sudo service iptables restart
UFW (Uncomplicated Firewall)
UFW is a user-friendly interface for managing iptables, making it easier for users who are not comfortable with complexities of the iptable syntaxes. It comes pre-installed in many Linux distributions as well.
To open a port using UFW, you can use the following command
sudo ufw allow PORT_NUMBER
This command allows incoming traffic on the specified port. To enable UFW, if it’s not already enabled
sudo ufw enable
Firewalld
Firewalld is a dynamic firewall manager available in many modern Linux distributions. It provides a more flexible and easy-to-use interface compared to traditional iptables.
To open a port using firewalld, use the following commands
sudo firewall-cmd --zone=public --add-port=PORT_NUMBER/tcp --permanent
sudo firewall-cmd --reload
These commands add a permanent rule to open the specified TCP port and reload the firewall configuration.
Editing iptables Configuration Files:
For those who prefer manual configuration, iptables rules can be added directly to the configuration files. The main configuration file is typically located at /etc/sysconfig/iptables
or /etc/iptables/rules.v4
.
Manually open a port by adding a rule to the configuration file
-A INPUT -p tcp --dport PORT_NUMBER -j ACCEPT
Save the file and restart iptables to apply the changes.
Using Netcat (nc)
Netcat is a versatile networking utility that can be used to open ports for various purposes, such as testing and debugging. To open a port using Netcat:
nc -l -p PORT_NUMBER
This command listens on the specified port for incoming connections. Note that Netcat will not persistently open the port; it’s suitable for temporary testing.
Conclusion
In a nutshell, use the method that you choose to fit. But always keep in mind that security is the primary thing and make sure not to run programs in default port and open them to the world like the ssh server. Since these are prone to exploits.