I have been trying to put together a basic server iptables script that will work for most sites just running a basic webserver using HTTP(S) and SSH (ports 80, 443, & 22). After all, most VPS only need these starting ports rules and can add mail or game ports later as need.
So far I have the following ruleset and I was wondering if anyone knows of a better script or any improvements that could be added.
*filter # Allows all loopback (lo0) traffic and drop all traffic to 127/8 that doesn't use lo0 -A INPUT -i lo -j ACCEPT -A INPUT ! -i lo -d 127.0.0.0/8 -j REJECT # Accepts all established inbound connections -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT # Allows all outbound traffic # You can modify this to only allow certain traffic -A OUTPUT -j ACCEPT # Allows HTTP and HTTPS connections from anywhere (the normal ports for websites) -A INPUT -p tcp --dport 80 -j ACCEPT -A INPUT -p tcp --dport 443 -j ACCEPT # Allows SSH connections (only 4 attempts by an IP every 3 minutes, drop the rest) -A INPUT -p tcp -m tcp --dport 22 -m state --state NEW -m recent --set --name DEFAULT --rsource -A INPUT -p tcp -m tcp --dport 22 -m state --state NEW -m recent --update --seconds 180 --hitcount 4 --name DEFAULT --rsource -j DROP -A INPUT -p tcp -m state --state NEW --dport 22 -j ACCEPT # Allow ping -A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT # log iptables denied calls -A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7 # Reject all other inbound - default deny unless explicitly allowed policy -A INPUT -j REJECT -A FORWARD -j REJECT COMMIT
iptables is one of the most important parts of securing your box (also see fail2ban) and yet there are many people like myself that have trouble understanding everything that goes into making a secure basic firewall for our servers.
What is the most secure way to only open the basic ports needed for a webserver?
Update: cyberciti.biz has another iptables script that looks pretty good.
Also, rather than using Denyhosts or fail2ban you could use iptables itself to block bad repeated attempts at SSH.
modprobeis not installed (or there is any other error before you open up port 22), you'll lock yourself out of the server.