daemonl

In case you were wondering...

iptables

(update: If you are in the situation I was in, just use AWS network rules. Much harder to muck up)

Being the only tech for a company means taking care of all of it. So, I had to learn iptables - it's not as hard as I thought it would be.

Two major pieces of advice before setting up firewalls:

  1. Use a script to set it all up, so you can run it a few times to get it right, and you can run it on multiple servers.

  2. If you are remotely logged in to the server - try to access it some other way, if you can't, then definitely re-read number 1 and test it on another server you do have access to.

There seems to be a lack of sample iptables codes out there - so here's part of mine. It's particularly closed off - drops everything except, including outgoing. I had to manually add DNS entries (/etc/named) and firewall exceptions for the apt-get repositories and other services I use.

There are many other ways it could be done, this is more of a demonstration for those who learn by reading code.

iptables -F resets the whole thing

-P is policy - the default, so for this setup the default is to DROP unless something else says to ACCEPT it.

eth0 is the first ethernet card, lo is loopback - check 'ifconfig' to see your adaptors.

#!/bin/bash  

iptables -F  
iptables -P INPUT DROP  
iptables -P OUTPUT DROP  
iptables -P FORWARD DROP  

iptables -A INPUT -i eth0 -p TCP -m state --state ESTABLISHED,RELATED -j ACCEPT  
iptables -A INPUT -i eth0 -p TCP --dport 80 -m state --state NEW -j ACCEPT  
iptables -A INPUT -i eth0 -p TCP --dport 443 -m state --state NEW -j ACCEPT  
iptables -A INPUT -i eth0 -p TCP --dport 22 -m state --state NEW -j ACCEPT  
iptables -A INPUT -i lo -j ACCEPT  
iptables -A INPUT -m limit --limit 15/minute -j LOG --log-level 7 --log-prefix "Dropped by firewall: "  

iptables -A OUTPUT -o eth0 -p TCP --sport 22 -m state --state ESTABLISHED -j ACCEPT  
iptables -A OUTPUT -o eth0 -p TCP --sport 80 -m state --state ESTABLISHED -j ACCEPT  
iptables -A OUTPUT -o eth0 -p TCP --sport 443 -m state --state ESTABLISHED -j ACCEPT  

iptables -A OUTPUT -o eth0 -p TCP -d mirror.ubuntu.com --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT  
iptables -A OUTPUT -o eth0 -p TCP -d db.local.clamav.net --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT  
iptables -A OUTPUT -o eth0 -p TCP -d db.local.clamav.net --dport 443 -m state --state NEW,ESTABLISHED -j ACCEPT