Debian as router

From RHS Wiki
Jump to navigation Jump to search

Make a debian box router[edit]

Enable routing[edit]

Temporal

sudo sysctl -w net.ipv4.ip_forward=1 # 

Permanent

sudo nano /etc/sysctl.conf
   net.ipv4.ip_forward = 1

Create NAT rule at IPTABLES[edit]

sudo iptables -t nat -A POSTROUTING -s 15.17.170.215/32 -o tun0 -j MASQUERADE

List iptables NAT rules[edit]

sudo iptables -t nat -L -n -v 

Delete NAT rule[edit]

  • List the rules with line numbers
sudo iptables -t nat -v -L POSTROUTING -n --line-number
Chain POSTROUTING (policy ACCEPT 241 packets, 23342 bytes)
num   pkts bytes target     prot opt in     out     source               destination         
1        2   168 MASQUERADE  all  --  *      tun0    15.17.170.215        0.0.0.0/0           
2      250 15024 MASQUERADE  all  --  *      tun0    15.17.164.7          0.0.0.0/0           
3    16409 1098K MASQUERADE  all  --  *      tun0    15.17.165.42         0.0.0.0/0
  • If you want to delete the rule: 3 16409 1098K MASQUERADE all -- * tun0 15.17.165.42 0.0.0.0/0
sudo iptables -t nat -D POSTROUTING 3

Add route to linux[edit]

ip route add 10.0.192.0/18 via 15.17.160.217 dev eth0


With SystemD[edit]

Start Script[edit]

#!/bin/bash
Ariel=15.17.170.200
Arrow=15.17.169.59
Carabanchel=15.17.170.206
Marito=15.17.160.181
CarlosDuque=15.17.170.138
Mapper=15.17.163.102

sudo sysctl -w net.ipv4.ip_forward=1

function clear_nat {
    for i in $( sudo iptables -t nat -L -n -v --line-numbers | grep ^[0-9] | awk '{ print $1 }' )
        do sudo iptables -t nat -D POSTROUTING 1
    done
}

function add_nat {
    sudo iptables -t nat -A POSTROUTING -s ${1}/32 -d 10.0.192.0/18 -o tun0 -j MASQUERADE
}

function add_wlan_nat { 
    sudo iptables -t nat -A POSTROUTING -s ${1}/32 -o wlan0 -j MASQUERADE
}

clear_nat
add_nat ${Ariel}
add_nat ${Carabanchel}
add_nat ${Arrow}
add_nat ${CarlosDuque}
add_nat ${Marito}
add_nat ${Mapper}
add_wlan_nat ${Carabanchel}

sudo iptables -t nat --line-numbers -L -n -v

Stop Script[edit]

#!/bin/bash
sudo sysctl -w net.ipv4.ip_forward=0

function clear_nat {
    for i in $( sudo iptables -t nat -L -n -v --line-numbers | grep ^[0-9] | awk '{ print $1 }' )
        do sudo iptables -t nat -D POSTROUTING 1
    done
}

function add_nat {
    sudo iptables -t nat -A POSTROUTING -s ${1}/32 -o tun0 -j MASQUERADE
}

clear_nat
sudo iptables -t nat --line-numbers -L -n -v

Multiple routes for one source[edit]

  • The more specific rule must go first
sudo iptables -t nat -A POSTROUTING -s 15.17.170.206 -d 10.0.192.0/18 -o tun0 -j MASQUERADE
sudo iptables -t nat -A POSTROUTING -s 15.17.170.206 -o wlan0 -j MASQUERADE