Ip tables is a firewall installed on Linux machines that is used to block internet traffic in IPv4 security.
Setting Up Ports
We start by identifying the ports to open:
- Port 22 which is the SSH port and is used to connect to the VPS remotely
- Port 80 and 443 (SSL port) used for web traffic.
- Port 25 (regular SMTP) port 465 (secure SMTP) for sending email.
- Port 110 (POP3) and port 995 (secure POP3 port) for receiving emails.
- IMAP ports; 143 for IMAP and 993 for IMAP over SSL.
Block common attacks
Due to some virtual machines coming with empty configurations meaning that all traffic is allowed; we start by erasing all firewall rules
Then we block null packets.
iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP
Next we reject a syn-flood attack
iptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP
We then remove another common pattern: XMAS packets
iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP
Open up selected ports
We start by adding some services, the first is a localhost interface:
iptables -A INPUT -i lo -j ACCEPT
then we all web server traffic:
iptables -A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp -m tcp --dport 443 -j ACCEPT
Next are SMTP servers (only if required):
iptables -A INPUT -p tcp -m tcp –dport 25 -j ACCEPT
iptables -A INPUT -p tcp -m tcp –dport 465 -j ACCEPT
We then allow the users to read email on their server:
iptables -A INPUT -p tcp -m tcp --dport 110 -j ACCEPT
[iptables -A INPUT -p tcp -m tcp --dport 995 -j ACCEPT
Finally, we allow the IMAP mail protocol:
iptables -A INPUT -p tcp -m tcp --dport 143 -j ACCEPT
iptables -A INPUT -p tcp -m tcp --dport 993 -j ACCEPT
Limiting SSH access via IP Tables
To be able to access your web server remotely, we should allow SSH traffic by
iptables -A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
This allows tcp traffic to port 22.
For safety to the network, you can allow traffic to come to the SSH port from only one IP address by the following rule
iptables -A INPUT -p tcp -s YOUR_IP_ADDRESS -m tcp --dport 22 -j ACCEPT
Replace your IP address with that one.
Add a rule allowing the use of outgoing connections to allow things such as software updates
iptables -I INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
After that, we then block everything else and allow all outgoing connections and with that we will have set up the firewall
iptables -P OUTPUT ACCEPT
iptables -P INPUT DROP
Save the configuration
To save our IP tables firewall configuration:
iptables-save | sudo tee /etc/sysconfig/iptables
The iptables configuration file on CentOS is located at /etc/sysconfig/iptables.
We can restart the firewall to see if it is working by running
service iptables restart