Linux: routing traffic between two networks with iptables

Ok, so this is a strange network setup, but I`m trying to get the internets from one network to another.

headless server ((((( wireless router (other network)-----internet
       |
       |
router (my network) ))))) wireless computers
   |   |   |
wired computers

So, basically, I have a headless Linux box that I want to setup as a router between my network (eth0) and the other network (wlan0). I should be able to configure everything else, but I`m not very experienced with iptables.

I`ve done the same thing before between two wired networks, but I never wrote down the rules.


Actually, you don't really need iptables for basic routing - iptables helps you with filtering and NAT (and other things too).

You can activate packet forwarding with:

sysctl -w net.ipv4.conf.all.forwarding=1

Add net.ipv4.conf.all.forwarding=1 to /etc/sysctl.conf to make the setting stick.

In case you are filtering on the server (you can check this with iptables -nvL - if the FORWARD chain has policy ACCEPT you're not filtering), you need to add rules to allow the packets to be forwarded between networks:

iptables -I FORWARD -i eth0 -o wlan0 -s wi.red.net.work/24 -d wire.less.net.work/24 -j ACCEPT
iptables -I FORWARD -i wlan0 -o eth0 -s wire.less.net.work/24 -d wi.red.net.work/24 -j ACCEPT

If you aren't filtering but want to (you should too, by the way - see @Red Tux's comment, it's good practice to filter by default and allow only the minimum) add the previous rules plus this one:

iptables -P FORWARD DROP

This changes the policy so all packets not matching any rules are discarded.

Also, if you're going for real security, you should probably filter on the INPUT chain as well. This chain processes requests coming to your router with a destination IP that matches one of its own - that is, incoming connections (for example SSH). A sensible default would be:

iptables -I INPUT -i eth0 -s allowed.admin.ip.here -p tcp --dport 22 -j ACCEPT
iptables -I INPUT -i lo -j ACCEPT
iptables -P INPUT DROP # make sure you've put your IP on the first rule before running this 
                       # or you'll lock you out of the server

This allows SSH only from a designed host in the wired network (take note of the warning), allows all traffic on the loopback interface (required by some software) and discards all the rest.

As you can see you can allow only some ports through using -p tcp|udp --dport N. You should consider doing this on the FORWARD chain too for increased security.