Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I would like to block everything EXCEPT SSH/FTP/HTTP/POSTFIX and MySQL.

With "everything" I mean all the other ports, block pings etc etc.

share|improve this question

migrated from May 9 '11 at 11:13

This question came from our site for professional and enthusiast programmers.

I'm guessing you mean incoming connections (the INPUT chain), and not forwarded ones (as in a router). Also I take postfix means just SMTP (25).

iptables -P INPUT ACCEPT
iptables -F INPUT

for port in 21 22 25 80 3306
  iptables -A INPUT -p tcp --dport $port -j ACCEPT

iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -i lo -j ACCEPT
iptables -P INPUT DROP

Test your FTP connection in particular, you may need to enable ip_conntrack_ftp for it to work correctly without modifying the client settings.

share|improve this answer
you can also chain them onto one line if you wish: iptables -I INPUT -p tcp -m multiport --mport 21,22,25,80,3306 -j ACCEPT – Squeeb May 9 '11 at 11:34
+1 You could probably do with a iptables -F INPUT otherwise you may be building on any pre-existing INPUT rules which the OP may not want. – Iain May 9 '11 at 11:35
@Iain - you're right, thanks! @Squeeb - you're right too, thanks for the pointer - I prefer the for loop though if there aren't many rules around as it enables you to get per-port statistics easily on iptables -nvL. Do you know if there's a way to get that using multiport? – Eduardo Ivanec May 9 '11 at 11:45
If you are on a Redhat-based machine, run service iptables save after the above steps to make the rules persistent (survive reboot etc.) – jmtd May 9 '11 at 13:39
I'd also suggest replacing the last line with iptables -A INPUT -j DROP or even iptables -A INPUT -j REJECT --reject-with icmp-host-prohibited instead of -P DROP. In practice, setting the INPUT chain default policy to "DROP" is a sure-fire way to lock yourself out of the machine if you flush the rules by accident (easy to do when experimenting and setting up your firewall -- including if you run iptables -F as suggested earlier :)) – jmtd May 9 '11 at 13:41

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.