iptables -F
First, we start with blocking null packets.
iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP
The next pattern to reject is a syn-flood attack.
iptables -A INPUT -p tcp ! --syn -m state --state NEW -j DROP
Now we move on to one more common pattern: XMAS packets, also a recon packet.
iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP
Now we can start adding selected services to our firewall filter. The first such thing is a localhost interface:
iptables -A INPUT -i lo -j ACCEPT
Now we can allow 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
We should also allow SSH traffic, so we can connect to the VPS remotely. The simple way to do it would be with this command:
iptables -A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
Now, you can create the firewall rule to only allow traffic to SSH port if it comes from one source: your IP address:
iptables -A INPUT -p tcp -s YOUR_IP_ADDRESS -m tcp --dport 22 -j ACCEPT
Right now, we need to add one more rule that will allow us to use outgoing connections (ie. ping from VPS or run software updates);
iptables -I INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
It will allow any established outgoing connections to receive replies from the VPS on the other side of that connection. When we have it all set up, we will block everything else, and allow all outgoing connections.
iptables -P OUTPUT ACCEPT
iptables -P INPUT DROP
Now that we have all the configuration in, we can list the rules to see if anything is missing.
iptables -L -n
The -n switch here is because we need only ip addresses, not domain names. Ie. if there is an IP in the rules like this: 69.55.48.33: the firewall would go look it up and see that it was a digitalocean.com IP. We don't need that, just the address itself. Now we can finally save our firewall configuration:
iptables-save | sudo tee /etc/sysconfig/iptables
The iptables configuration file on CentOS is located at /etc/sysconfig/iptables. The above command saved the rules we created into that file. Just to make sure everything works, we can restart the firewall:
service iptables restart