Opening and Closing Ports in CentOS 6 and 7 using IPtables

Setting up a good firewall is an essential step in ensuring the security of your system. IPtables is the default firewall used on CentOS.

It is a command-line utility that uses policy chains to allow or block traffic. When a connection tries to establish itself on a CentOS system, IPtables looks for a rule in its list to match it to. If it doesn’t find one, it resorts to the default action.

Types of Chains

IPtables uses three types of chains, input, output and forward

Input chain is used to control the behaviour of incoming connections for example SSH

Output chain is used for outgoing connections for example ping

Forward chain is used for incoming connections that are not really being delivered locally.

A lot of protocols however require two way communication e.g SSH and ping and as such both chains need to be allowed.

To list the current firewall rules, the command below is issued

iptables
-L

This command lists all the firewall rules currently loaded into IPtables.

To open and close a port is CentOS 6, the commands below are executed

Opening a port

iptables -I INPUT -p tcp -m tcp --dport 9042 -j ACCEPT
service iptables save
Closing a port

iptables -I INPUT -p tcp -m tcp --dport 9042 -j REJECT
service iptables save

To open and close a port in CentOS 7, the commands below are used.

Opening a Port

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

Closing a port

firewall-cmd --zone=public --remove-port=9042/tcp
firewall-cmd --runtime-to-permanent 
firewall-cmd --reload

Leave a Reply

Your email address will not be published. Required fields are marked *