- Easy steps to open a port in Linux RHEL/CentOS 7/8
- Check port status
- Check list of listening ports
- Open a port for some service
- firewalld open port
- Use nc or ncat to open a port in Linux
- Use nc or ncat to open a port and transfer files
- Related Posts
- 3 thoughts on “Easy steps to open a port in Linux RHEL/CentOS 7/8”
- How To Ubuntu Linux Firewall Open Port Command
- Ubuntu Linux firewall open port command
- How do I see the current status of my firewall?
- How do I open tcp port # 22?
- How do I open tcp port # 80 and 443?
- How do I open tcp and udp port # 53?
- Advanced examples for opening TCP and UDP ports
- Denying/blocking port access
- How to delete ufw rules
- Conclusion
- Simple stateful firewall
- Contents
- Prerequisites
- Firewall for a single machine
- Creating necessary chains
- The FORWARD chain
- The OUTPUT chain
- The INPUT chain
- Resulting iptables.rules file
- The TCP and UDP chains
- Opening ports to incoming connections
- Port knocking
- Protection against spoofing attacks
- «Hide» your computer
- Block ping request
- Tricking port scanners
- Protection against other attacks
- Bruteforce attacks
- Saving the rules
- Resulting ip6tables.rules file
- Setting up a NAT gateway
- Setting up the filter table
- Creating necessary chains
- Setting up the FORWARD chain
- Setting up the fw-interfaces and fw-open chains
- Setting up the nat table
- Setting up the POSTROUTING chain
- Setting up the PREROUTING chain
- Saving the rules
Easy steps to open a port in Linux RHEL/CentOS 7/8
Table of Contents
In this article I will share examples to check port status and open a port in Linux. This article was written while using CentOS 8, so it is safe to say that it also fully covers CentOS/RHEL 7/8, Fedora, Oracle Enterprise Linux and generally the whole Red Hat family of operating systems and possibly Novell’s SLES and OpenSUSE.
Before we jump into the examples to open a port in Linux, we must understand the requirement clearly. The very basic question which comes to my mind
- Do you need to open a port for a service? Such as a custom port 5555 for apache service?
- Do you mean the port is already listening but blocked by firewall so you want to open a port in firewall?
- Open a port for custom temporary task such as transfer and receive files using this port and then close the port.
We will cover all these scenarios in this article
Check port status
To check the list of existing ports which are open we will use nmap to check port status:
Currently we see only two ports are open on my CentOS 8 node.
Check list of listening ports
We will use netstat to list the TCP ports which are in listening state. The total number of ports are higher compared to the nmap output.
Open a port for some service
If this is your requirement then you are looking for the wrong question. Basically it is other way round i.e. a service will open a port. For example when you start SSHD service, by default it will start port 22 and not the other way round i.e. if you open port 22, it will not automatically start SSHD service.
Let us observe this in example, we know that port 22 is open on my CentOS 8 node. If I stop the sshd service
You can see that port 22 is not open anymore.
You must use respective service’s configuration file to change the default port. Once done you can restart the service and that should automatically open the respective port on your Linux node.
This covers the first scenario.
firewalld open port
It is also possible that your ports are disabled in firewall. If your port is not listed in nmap then it is most likely blocked by firewall.
We will use firewalld to open a port as this is the most used interface today in RHEL/CentOS 7 and 8. Determine which zone the system’s network interfaces are in. In the following example, the eth0 and eth1 interface is in the ‘public’ zone:
To permanently firewalld open port in a zone use the —add-port option. The example below permanently opens TCP port 1234 in the ‘public‘ zone. Note that permanent changes do not take effect until the firewalld service is reloaded.
Once firewalld open port, next use netstat to check port status:
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.
Use nc or ncat to open a port in Linux
Let us verify this theory Use nc or ncat to open a port in Linux nc or ncat is delivered as part of nmap-ncat rpm in RHEL/CentOS which you can install using yum or dnf. Use —listen with —port to open a port using nc command. In the below example we open port 1234
Open another terminal of this server and check port status
As you see port 1234 is listening for both IPv4 and IPv6. To only use IPv4 use -4 with the above command
Next on another terminal you can check port status for port 1234
Use nc or ncat to open a port and transfer files
We can also use nc to transfer file from one host to another host. Here I will transfer my » inputfile » from centos-8 to rhel-8 On the client we will open a random port, here we will use 9899. I have enabled verbose so you can see more details on the screen
Next to start the transfer, use the below command
If you face any issues you can check the firewall between your server and client. It is possible that the respective port is blocked and you must use firewalld open port
Lastly I hope the steps from the article to open a port and check port status on Linux was helpful. So, let me know your suggestions and feedback using the comment section.
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!!
3 thoughts on “Easy steps to open a port in Linux RHEL/CentOS 7/8”
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:
Thanks for this!
Hi
I did below steps and reloaded firewall but still when I do netstat -ntlp port 1234 not showing open
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.
Источник
How To Ubuntu Linux Firewall Open Port Command
Ubuntu Linux firewall open port command
The program is for managing a Linux firewall is ufw. It aims to provide an easy to use interface for the user/sysadmins and developers. For example:
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | Yes |
Requirements | ufw command on Ubuntu/Debian Linux |
Est. reading time | 3 minutes |
- You can open/close ports with ufw allow command.
- Block an IPv4/IPv6 address.
- Delete existing firewall rules.
- Turn on or off firewall logs.
- And more.
Let us see some examples of ufw firewall to open port on Ubuntu server.
How do I see the current status of my firewall?
Type the following command:
sudo ufw status verbose
Sample outputs:
Fig.01: Check the status of UFW on a Ubuntu Linux
How do I open tcp port # 22?
To allow incoming tcp packets on port 22, enter:
sudo ufw allow 22/tcp
Verify it:
sudo ufw status verbose
How do I open tcp port # 80 and 443?
The service specific syntax is as follows to open http and https service ports:
sudo ufw allow http
sudo ufw allow https
OR
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
How do I open tcp and udp port # 53?
To allow incoming tcp and udp packet on port 53, enter:
sudo ufw allow 53
Verify it:
sudo ufw status verbose
Advanced examples for opening TCP and UDP ports
To allow IP address 192.168.1.10 access to port 22 for all protocols
sudo ufw allow from 192.168.1.10 to any port 22
Open port 74.86.26.69:443 (SSL 443 nginx/apache/lighttpd server) for all, enter:
sudo ufw allow from any to 74.86.26.69 port 443 proto tcp
To allows subnet 192.168.1.0/24 to Sabma services, enter:
ufw allow from 192.168.1.0/24 to any app Samba
You can find service info as follows:
sudo ufw app list
Sample outputs:
To get information on Squid profile/app, run:
ufw app info Squid
Sample outputs:
Denying/blocking port access
We can add deny rule as follows to block all access to port 25:
sudo ufw deny 25
sudo ufw deny 25/tcp comment ‘Block access to smptd by default’
- 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 ➔
How to delete ufw rules
We can list firewall rules using the following syntax on Ubuntu Linux:
sudo ufw status
sudo ufw numbered
Once we found firewall rule number delete by that number:
sudo ufw delete
sudo ufw delete 5
Another option is to type:
ufw delete deny 25/tcp comment ‘Block access to smptd by default’
Conclusion
In this page, you learned how to open TCP and UDP ports using UFW which is a default firewall management tool on Ubuntu Linux. See ufw command man page for more info and all other my tutorials below:
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
Simple stateful firewall
This page explains how to set up a stateful firewall using iptables. It also explains what the rules mean and why they are needed. For simplicity, it is split into two major sections. The first section deals with a firewall for a single machine, the second sets up a NAT gateway in addition to the firewall from the first section.
Contents
Prerequisites
First, install the userland utilities iptables or verify that they are already installed.
This article assumes that there are currently no iptables rules set. To check the current ruleset and verify that there are currently no rules run the following:
If there are rules, you may be able to reset the rules by loading a default rule set:
Firewall for a single machine
Creating necessary chains
For this basic setup, we will create two user-defined chains that we will use to open up ports in the firewall.
The chains can of course have arbitrary names. We pick these just to match the protocols we want handle with them in the later rules, which are specified with the protocol options, e.g. -p tcp , always.
The FORWARD chain
If you want to set up your machine as a NAT gateway, please look at #Setting up a NAT gateway. For a single machine, however, we simply set the policy of the FORWARD chain to DROP and move on:
The OUTPUT chain
The OUTPUT chain can be a powerful tool for filtering outbound traffic, especially for servers and other devices which do not run web browsers or peer-to-peer tools that need to connect to arbitrary destinations on the internet. However, properly setting up an OUTPUT chain requires information about the intended use of the system. A secure set of rules for a desktop system, laptop system, cloud server and home/on-prem server would all be very different.
In this simple example, we will allow all outbound traffic by setting the default policy for the OUTPUT chain to ACCEPT. This is less secure, but is highly compatible with many systems.
The INPUT chain
Similar to the previous chains, we set the default policy for the INPUT chain to DROP in case something somehow slips by our rules. Dropping all traffic and specifying what is allowed is the best way to make a secure firewall.
Every packet that is received by any network interface will pass the INPUT chain first, if it is destined for this machine. In this chain, we make sure that only the packets that we want are accepted.
The first rule added to the INPUT chain will allow traffic that belongs to established connections, or new valid traffic that is related to these connections such as ICMP errors, or echo replies (the packets a host returns when pinged). ICMP stands for Internet Control Message Protocol. Some ICMP messages are very important and help to manage congestion and MTU, and are accepted by this rule:
The connection state ESTABLISHED implies that either another rule previously allowed the initial ( —ctstate NEW ) connection attempt or the connection was already active (for example an active remote SSH connection).
The second rule will accept all traffic from the «loopback» (lo) interface, which is necessary for many applications and services.
The third rule will drop all traffic with an «INVALID» state match. Traffic can fall into four «state» categories: NEW, ESTABLISHED, RELATED or INVALID and this is what makes this a «stateful» firewall rather than a less secure «stateless» one. States are tracked using the «nf_conntrack_*» kernel modules which are loaded automatically by the kernel as you add rules.
The next rule will accept all new incoming ICMP echo requests, also known as pings. Only the first packet will count as NEW, the others will be handled by the RELATED, ESTABLISHED rule. Since the computer is not a router, no other ICMP traffic with state NEW needs to be allowed.
Now we attach the TCP and UDP chains to the INPUT chain to handle all new incoming connections. Once a connection is accepted by either TCP or UDP chain, it is handled by the RELATED/ESTABLISHED traffic rule. The TCP and UDP chains will either accept new incoming connections, or politely reject them. New TCP connections must be started with SYN packets.
We reject TCP connections with TCP RESET packets and UDP streams with ICMP port unreachable messages if the ports are not opened. This imitates default Linux behavior (RFC compliant), and it allows the sender to quickly close the connection and clean up.
For other protocols, we add a final rule to the INPUT chain to reject all remaining incoming traffic with icmp protocol unreachable messages. This imitates Linux’s default behavior.
Resulting iptables.rules file
Example of iptables.rules file after running all the commands from above:
This file can be generated and saved with:
and can be used to continue with the following sections. If you are setting up the firewall remotely via SSH, append the following rule to allow new SSH connections before continuing (adjust port as required):
The TCP and UDP chains
The TCP and UDP chains contain rules for accepting new incoming TCP connections and UDP streams to specific ports.
Opening ports to incoming connections
To accept incoming TCP connections on port 80 for a web server:
To accept incoming TCP connections on port 443 for a web server (HTTPS):
To allow remote SSH connections (on port 22):
To accept incoming TCP/UDP requests for a DNS server (port 53):
See iptables(8) for more advanced rules, like matching multiple ports.
Port knocking
Port knocking is a method to externally open ports that, by default, the firewall keeps closed. It works by requiring connection attempts to a series of predefined closed ports. When the correct sequence of port «knocks» (connection attempts) is received, the firewall opens certain port(s) to allow a connection. See Port knocking for more information.
Protection against spoofing attacks
Blocking reserved local addresses incoming from the internet or local network is normally done through setting rp_filter (Reverse Path Filter) in sysctl to 1. To do so, add the following line to your /etc/sysctl.d/90-firewall.conf file (see sysctl for details) to enable source address verification which is built into Linux kernel itself. The verification by the kernel will handle spoofing better than individual iptables rules for each case.
This can be done with netfilter instead if statistics (and better logging) are desired:
For niche setups where asynchronous routing is used, the rp_filter=2 sysctl option needs to be used instead. Passing the —loose switch to the rpfilter module will accomplish the same thing with netfilter.
«Hide» your computer
If you are running a desktop machine, it might be a good idea to block some incoming requests.
Block ping request
A ‘Ping’ request is an ICMP packet sent to the destination address to ensure connectivity between the devices. If your network works well, you can safely block all ping requests. It is important to note that this does not actually hide your computer — any packet sent to you is rejected, so you will still show up in a simple nmap «ping scan» of an IP range.
This is rudimentary «protection» and makes life difficult when debugging issues in the future. This should only be done for educational purposes.
To block echo requests, add the following line to your /etc/sysctl.d/90-firewall.conf file (see sysctl for details):
More information is in the iptables man page, or reading the docs and examples on the webpage http://www.snowman.net/projects/ipt_recent/
Tricking port scanners
Port scans are used by attackers to identify open ports on your computer. This allows them to identify and fingerprint your running services and possibly launch exploits against them.
The INVALID state rule will take care of every type of port scan except UDP, ACK and SYN scans (-sU, -sA and -sS in nmap respectively).
ACK scans are not used to identify open ports, but to identify ports filtered by a firewall. Due to the SYN check for all TCP connections with the state NEW, every single packet sent by an ACK scan will be correctly rejected by a TCP RESET packet. Some firewalls drop these packets instead, and this allows an attacker to map out the firewall rules.
The recent module can be used to trick the remaining two types of port scans. The recent module is used to add hosts to a «recent» list which can be used to fingerprint and stop certain types of attacks. Current recent lists can be viewed in /proc/net/xt_recent/ .
SYN scans
In a SYN scan, the port scanner sends a SYN (synchronization) packet to every port to initiate a TCP connection. Closed ports return a TCP RESET packet, or get dropped by a strict firewall, while open ports return a SYN ACK packet.
The recent module can be used to keep track of hosts with rejected connection attempts and return a TCP RESET for any SYN packet they send to open ports as if the port was closed. If an open port is the first to be scanned, a SYN ACK will still be returned, so running applications such as ssh on non-standard ports is required for this to work consistently.
First, insert a rule at the top of the TCP chain. This rule responds with a TCP RESET to any host that got onto the TCP-PORTSCAN list in the past sixty seconds. The —update switch causes the recent list to be updated, meaning the 60 second counter is reset.
Next, the rule for rejecting TCP packets need to be modified to add hosts with rejected packets to the TCP-PORTSCAN list.
UDP scans
UDP port scans are similar to TCP SYN scans except that UDP is a «connectionless» protocol. There are no handshakes or acknowledgements. Instead, the scanner sends UDP packets to each UDP port. Closed ports should return ICMP port unreachable messages, and open ports do not return a response. Since UDP is not a «reliable» protocol, the scanner has no way of knowing if packets were lost, and has to do multiple checks for each port that does not return a response.
The Linux kernel sends out ICMP port unreachable messages very slowly, so a full UDP scan against a Linux machine would take over 10 hours. However, common ports could still be identified, so applying the same countermeasures against UDP scans as SYN scans is a good idea.
First, add a rule to reject packets from hosts on the UDP-PORTSCAN list to the top of the UDP chain.
Next, modify the reject packets rule for UDP:
Restore the Final Rule
If either or both of the portscanning tricks above were used, the final default rule is no longer the last rule in the INPUT chain. It needs to be the last rule, or it would intercept the trick port scanner rules you just added, rendering them useless. Simply delete (-D) the rule, then add it again using append (-A), which will place it at the end of the chain.
Protection against other attacks
See the sysctl#TCP/IP stack hardening for relevant kernel parameters.
Bruteforce attacks
Unfortunately, bruteforce attacks on services accessible via an external IP address are common. One reason for this is that the attacks are easy to perform with the many tools available. Fortunately, there are a number of ways to protect the services against them. One is the use of appropriate iptables rules which activate and blacklist an IP after a set number of packets attempt to initiate a connection. Another is the use of specialised daemons that monitor the logfiles for failed attempts and blacklist accordingly.
Two packages that ban IPs after too many password failures are Fail2ban or, for sshd in particular, Sshguard. These two applications update iptables rules to reject temporarily or permanently future connections from attackers.
The following rules give an example configuration to mitigate SSH bruteforce attacks using iptables .
Most of the rules should be self-explanatory: the first one allows for a maximum of three connection packets in ten seconds and drops further attempts from this IP. The next rule adds a quirk by allowing a maximum of four hits in 30 minutes. This is done because some bruteforce attacks are actually performed slow and not in a burst of attempts. The rules employ a number of additional options. To read more about them, check the original reference for this example in compilefailure.blogspot.com. The LOG_AND_DROP chain is used for logging dropped connections.
The above rules can be used to protect any service, though the SSH daemon is probably the most often required one.
In terms of order, one must ensure that -A INPUT -p tcp —dport ssh -m conntrack —ctstate NEW -j IN_SSH is at the right position in the iptables sequence: it should come before the TCP chain is attached to INPUT in order to catch new SSH connections first. If all the previous steps of this wiki have been completed, the following positioning works:
If you do not use IPv6, you can consider disabling it, otherwise follow these steps to enable the IPv6 firewall rules.
Copy the IPv4 rules used in this example as a base, and change any IPs from IPv4 format to IPv6 format:
A few of the rules in this example have to be adapted for use with IPv6. The ICMP protocol has been updated in IPv6, replacing the ICMP protocol for use with IPv4. Hence, the reject error return codes —reject-with icmp-port-unreachable and —reject-with icmp-proto-unreachable have to be converted to ICMPv6 codes.
The available ICMPv6 error codes are listed in RFC 4443, which specifies that connection attempts blocked by a firewall rule should use —reject-with icmp6-adm-prohibited . Doing so will basically inform the remote system that the connection was rejected by a firewall, rather than a listening service.
If it is preferred not to explicitly inform about the existence of a firewall filter, the packet may also be rejected without the message:
The above will reject with the default return error of —reject-with icmp6-port-unreachable . You should note though, that identifying a firewall is a basic feature of port scanning applications and most will identify it regardless.
This article or section needs expansion.
In the next step make sure the protocol and extension are changed to be IPv6 appropriate for the rule regarding all new incoming ICMP echo requests (pings):
Netfilter conntrack does not appear to track ICMPv6 Neighbor Discovery Protocol (the IPv6 equivalent of ARP), so we need to allow ICMPv6 traffic regardless of state for all directly attached subnets. The following should be inserted after dropping —ctstate INVALID , but before any other DROP or REJECT targets, along with a corresponding line for each directly attached subnet:
If you want to enable DHCPv6, you need to accept incoming connections on UDP port 546:
Since there is no kernel reverse path filter for IPv6, you may want to enable one in ip6tables with the following:
Saving the rules
The rule sets are now finished and should be saved to a file so that they can be loaded on every boot.
Save the IPv4 and IPv6 rules with these commands:
Resulting ip6tables.rules file
Example of ip6tables.rules file after running all the commands from above:
Then enable and start iptables.service and the ip6tables.service . Check the status of the services to make sure the rules are loaded correctly.
Setting up a NAT gateway
This section of the guide deals with NAT gateways. It is assumed that you already read the first part of the guide and set up the INPUT, OUTPUT, TCP and UDP chains like described above. All rules so far have been created in the filter table. In this section, we will also have to use the nat table.
Setting up the filter table
Creating necessary chains
In our setup, we will create two new chains in the filter table, fw-interfaces and fw-open, using the following commands:
Setting up the FORWARD chain
Setting up the FORWARD chain is similar to the INPUT chain in the first section.
Now we set up a rule with the conntrack match, identical to the one in the INPUT chain:
The next step is to enable forwarding for trusted interfaces and to make all packets pass the fw-open chain.
The remaining packets are denied with an ICMP message:
Setting up the fw-interfaces and fw-open chains
The meaning of the fw-interfaces and fw-open chains is explained later, when we deal with the POSTROUTING and PREROUTING chains in the nat table, respectively.
Setting up the nat table
All over this section, we assume that the outgoing interface (the one with the public internet IP) is ppp0. Keep in mind that you have to change the name in all following rules if your outgoing interface has another name.
Setting up the POSTROUTING chain
Now, we have to define who is allowed to connect to the internet. Let us assume we have the subnet 192.168.0.0/24 (which means all addresses that are of the form 192.168.0.*) on eth0. We first need to accept the machines on this interface in the FORWARD table, that is why we created the fw-interfaces chain above:
Now, we have to alter all outgoing packets so that they have our public IP address as the source address, instead of the local LAN address. To do this, we use the MASQUERADE target:
Do not forget the -o ppp0 parameter above. If you omit it, your network will be screwed up.
Let us assume we have another subnet, 10.3.0.0/16 (which means all addresses 10.3.*.*), on the interface eth1. We add the same rules as above again:
The last step is to enable packet forwarding (if it is not already enabled).
Machines from these subnets can now use your new NAT machine as their gateway. Note that you may want to set up a DNS and DHCP server like dnsmasq or a combination of BIND and dhcpd to simplify network settings DNS resolution on the client machines. This is not the topic of this guide.
Setting up the PREROUTING chain
Sometimes, we want to change the address of an incoming packet from the gateway to a LAN machine. To do this, we use the fw-open chain defined above, as well as the PREROUTING chain in the nat table in the following two simple examples.
First, we want to change all incoming SSH packets (port 22) to the ssh server of the machine 192.168.0.5:
The second example will show you how to change packets to a different port than the incoming port. We want to change any incoming connection on port 8000 to our web server on 192.168.0.6, port 80:
The same setup also works with udp packets.
Saving the rules
This assumes that you have followed the steps above to enable the iptables systemd service.
Источник