Masquerading how-to for GNU/Linux

Prerequisites

  • dnsmasq
  • iptables

Those softwares should be available in your distribution's repositories. For Debian (or Debian-based distribution) install for example with:

    aptitude install dnsmasq iptables

Dnmasq configuration

We'll use dnsmasq as DNS proxy and DHCP server. Will configure it so that it handles DHCP and DNS request on any interface with an IP adress in the 192.168.40.0/24 subnet.

In /etc/dnsmasq/dnsmasq.conf add the following line:

dhcp-range=192.168.40.50,192.168.40.200,12h

Enable masquerading

Let's suppose you're connected to the internet via wan and you want to share it on lan.

  1. Enable packet forwarding

    echo 1 > /proc/sys/net/ipv4/ip_forward
    
  2. Enable masquerading of packet forwarded to wan

    iptables -t nat -A POSTROUTING -o wan -j MASQUERADE
    
  3. Setup the lan interface

    ip link set dev lan up
    ip addr add 192.168.40.1/24 dev lan
    
  4. Start dnsmasq

    If you are using sysvinit execute invoke-rc.d dnsmasq start.

    If you are using systemd execute systemctl start dnsmasq.

Disable masquerading

It is sufficient to remove the ip address on the interface sharing the connection:

ip addr del 192.168.40.1/24 dev lan

To clean things up you may also:

  1. Disable packet forwarding

    echo 0 > /proc/sys/net/ipv4/ip_forward
    
  2. Disable masquerading of packet forwarded to wan

    iptables -t nat -D POSTROUTING -o wan -j MASQUERADE
    
  3. Bring lan down

    ip link set dev eth0 down
    
  4. Stop dnsmasq

    If you are using sysvinit execute invoke-rc.d dnsmasq stop.

    If you are using systemd execute systemctl stop dnsmasq.