Logicalwebhost Cheatsheet

Linux & Open Source Cheatsheets & Howto's

Skip to: Content | Sidebar | Footer

Linux router

How to build a linux router using a server with two interfaces. This means eth0 connects to the internet or a DHCP router, and eth1 connects to a switch and the rest of your LAN network and routes all their traffic out to the internet over eth0. You can implement your own firewall, or do other stuff if you want like turning your router into a file share to put your stuff on it so other computers in your house can get to it.

# The external WAN interface (eth0)
allow-hotplug eth0
iface eth0 inet dhcp
 
# The internal LAN interface (eth1)
allow-hotplug eth1
iface eth1 inet static
   address 192.168.0.1
   netmask 255.255.255.0
   network 192.168.0.0
   broadcast 192.168.0.255

This means all your LAN computers will be 192.168.0.something. Now you make the router modify traffic with dnsmasq:

apt-get install dnsmasq
vi /etc/dnsmasq.conf
  interface=eth1
  listen-address=127.0.0.1
  domain=what.ever.com
  dhcp-range=192.168.0.100,192.168.0.110,12h
vi /etc/sysctl.conf
net.ipv4.ip_forward=1

Now tell your firewall how to handle packets:

vi /etc/iptables.rules
  *nat
  -A PREROUTING -i eth0 -p tcp -m tcp --dport 50000 -j DNAT --to-destination 192.168.0.3:50000
  -A POSTROUTING -o eth0 -j MASQUERADE
  COMMIT
 
  *filter
  -A INPUT -i lo -j ACCEPT
  -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
  -A INPUT -i eth0 -p tcp -m tcp --dport 222 -j ACCEPT
  -A INPUT -i eth0 -j DROP
  -A FORWARD -i eth0 -p tcp -m tcp --dport 50000 -m state --state NEW -j ACCEPT
  COMMIT

Now make those rules active by doing:

iptables-restore < /etc/iptables.rules
 now make sure those rules are loaded when it brings up the interface on boot
vi /etc/network/interfaces (add next line under iface lo)
pre-up iptables-restore < /etc/iptables.rules

Now reboot and see if it works.

Props to http://blog.noviantech.com/2010/12/22/debian-router-gateway-in-15-minutes/

tunnel traffic over openvpn tunnel

copy a valid client.conf into the /etc/openvpn directory, then do:

vi /etc/iptables-rules
:%s/eth0/tun0/g

It will start up when you restart the computer, you can also manually test the openvpn client later by doing:

cd /etc/openvpn
openvpn --configure client.conf

Now when you restart, it will attempt to route all traffic on eth1 to the tun0 you just created, which is the virtual network 10.8.0.1 which is really the VPN tunnel, so it looks like all your traffic is coming out at the other end of the VPN tunnel. If you want to check, go to another computer on a switch connected to eth1 and visit:

http://ipof.me