Previously posted on blog.labrat.info on February 2, 2011
After posting about how to make a simple firewall on a BSD system I’ve been asked to do the same for Linux. In Linux the command you’ll want to look at is iptables.
Here’s the script I use to get a basic web server protected:
#!/bin/bash # Flush all chains /sbin/iptables --flush # Allow unlimited traffic on the loopback interface /sbin/iptables -A INPUT -i lo -j ACCEPT /sbin/iptables -A OUTPUT -o lo -j ACCEPT # Set default policies are set to Drop /sbin/iptables --policy INPUT DROP /sbin/iptables --policy OUTPUT DROP /sbin/iptables --policy FORWARD DROP # Previously initiated and accepted exchanges bypass rule checking # Allow unlimited outbound traffic /sbin/iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT /sbin/iptables -A OUTPUT -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT # Allow incoming (tcp) SSH traffic /sbin/iptables -A INPUT -p tcp --dport ssh -m state --state NEW -j ACCEPT # Allow incoming (udp) DHCP /sbin/iptables -A INPUT -p udp --dport bootpc -j ACCEPT # Allow incoming (tcp) WWW request /sbin/iptables -A INPUT -p tcp --dport www -m state --state NEW -j ACCEPT # Drop all other traffic /sbin/iptables -A INPUT -j DROP
We can go by this line by line.
- Line 4 flushes all previous IPTable rules to we can make sure we have a clean slate to start.
- Lines 7 – 8 disable any filtering on the loopback device. You’ll most likely use this to make connections inside of the machine which are assumed to be secure.
- Lines 11 – 13 set the default policy to be “Drop”. This means that if a connection doesn’t match any of the rules that we are going to create, it will be dropped. Basically, nothing can connect unless we explicitly punch a hole.
- Lines 17 – 18 are just for performance. If a connection has already been established it’s not worth checking again to see if it should be filtered or not.
- Line 21 is the first rule. We are letting SSH connections make it though the firewall so they can connect to the SSH server running on the machine.
- Line 24 is a hole in the firewall in case the machine is using DHCP to setup it’s network. If the machine has a static IP, this rule is not necessary and can be removed/commented out.
- Line 27 punches another hole though the firewall so traffic can get to the webserver on port 80.
- Line 30 makes sure that if no rule was satisfied the connection will be dropped.
For example if you want to open a port for Tomcat on the default port (8080) the line would look something like this:
# Allow incoming (tcp) traffic to Tomcat on port 8080 sbin/iptables -A INPUT -p tcp --dport 8080 -m state --state NEW -j ACCEPT