Saturday, June 6, 2009

linux as router

Back in the days in our student house we used an old pentium II machine to share our internet access. Hardware routers were much more expensive those days.

A simple script to make a NAT router (replace INTERNET= and LOCALNET= if you have other devices).
Place the script in /etc/network/if-up.d/ (at least with debian) and call it natrouter.sh. Make sure you chmod +x natrouter.sh.

#!/bin/sh

INTERNET=eth0
LOCALNET=eth1

PATH=/usr/sbin:/sbin:/bin:/usr/bin

# delete all existing rules
iptables -F
iptables -t nat -F
iptables -t mangle -F
iptables -X

# Always accept traffic on individual interfaces
iptables -A INPUT -i lo,$INTERNET,$LOCALNET -j ACCEPT

# Allow established connections back to the LAN
iptables -A FORWARD -i $INTERNET -o $LOCALNET -m state --state ESTABLISHED,RELATED -j ACCEPT

# Allow outgoing connections from the LAN to INTERNET
iptables -A FORWARD -i $LOCALNET -o $INTERNET -j ACCEPT

# Masquerade
iptables -t nat -A POSTROUTING -o $INTERNET -j MASQUERADE

# Don't forward from the outside to the inside
iptables -A FORWARD -i $INTERNET -o $LOCALNET -j REJECT

# Enable routing
echo 1 > /proc/sys/net/ipv4/ip_forward