On CentOS and other Red Hat variants, iptables often comes with some pre-configured rules, check the current iptable rules using the following command.
sudo iptables -L
Firewalls can commonly be configured in one of two ways, either set the default rule to accept and then block any unwanted traffic with specific rules, or by using the rules to define allowed traffic and blocking everything else. The latter is often the recommended approach, as it allows pre-emptively blocking traffic, rather than having to reactively reject connections that should not be attempting to access your cloud server.
Next, allow traffic to a specific port to enable SSH connections with the following.
iptables -A INPUT -p tcp -s IP_address2 --dport 22 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
After adding all the allowed rules you require, change the input policy to drop.
sudo iptables -P INPUT DROP
The same policy rules can be defined to other chains as well by entering the chain name and selecting either DROP or ACCEPT.
Now if you were to restart your cloud server all of these iptables configurations would be wiped. To prevent this, save the rules to a file.
sudo iptables-save > /etc/sysconfig/iptables
You can then simply restore the saved rules by reading the file you saved.
# Overwrite the current rules sudo iptables-restore < /etc/sysconfig/iptables # Add the new rules keeping the current ones sudo iptables-restore -n < /etc/sysconfig/iptables
To automate the restore at reboot CentOS offers a system service by the same name, iptables. However, it does not come in the default configuration and needs to be installed manually.
sudo yum install iptables-services
Once installed, start and enable the service.
sudo systemctl start iptables sudo systemctl enable iptables
Afterwards, you can simply save the current rules using the following command.
sudo service iptables save
These are just a few simple commands you can use with iptables, which is capable of much more. Read on to check on some of the other options available for more advanced control over iptable rules.