First install iptables with this command
sudo yum install iptables-services
Now start iptables
sudo service iptables start
Use the below command to flush any existing rules that might be there
sudo iptables -F
Now add rules one by one by executing the following commands
Block null packets
sudo iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP
Reject is a syn-flood attack
sudo iptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP
XMAS packets
sudo iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP
Allow localhost traffic
sudo iptables -A INPUT -i lo -j ACCEPT
Allow http port 80
sudo iptables -A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
Allow https port 443
sudo iptables -A INPUT -p tcp -m tcp --dport 443 -j ACCEPT
Allow SMTP
sudo iptables -A INPUT -p tcp -m tcp --dport 25 -j ACCEPT sudo iptables -A INPUT -p tcp -m tcp --dport 465 -j ACCEPT
Allow POP3
sudo iptables -A INPUT -p tcp -m tcp --dport 110 -j ACCEPT sudo iptables -A INPUT -p tcp -m tcp --dport 995 -j ACCEPT
Allow IMAP
sudo iptables -A INPUT -p tcp -m tcp --dport 143 -j ACCEPT sudo iptables -A INPUT -p tcp -m tcp --dport 993 -j ACCEPT
Allow SSH
sudo iptables -A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
Caution: You could potentially loose ssh access to your server if you are not careful with this. If you have changed the SSH port number and are not using the default port 22 to login then replace 22 with the appropriate port number.
Allow established outgoing connections to receive incoming replies.
sudo iptables -I INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
Now allow all outgoing connections and block all the incoming connections except the ones we have explicitly allowed in the above rules.
sudo iptables -P OUTPUT ACCEPT sudo iptables -P INPUT DROP
Now save the firewall rules
sudo iptables-save | sudo tee /etc/sysconfig/iptables
or
sudo iptables-save > /etc/sysconfig/iptables
Enable
sudo systemctl enable iptables
Now restart iptables
sudo service iptables restart
or
sudo systemctl restart iptables
Useful command:
List iptables firewall rules
sudo iptables -S
sudo iptables -L -n