Categories
Uncategorized

Multiple default gateways on Linux

Suppose you have a Linux machine doing IP forwarding (net.ipv4.ip_forward=1).

Depending on the incoming traffic, you might want to forward the packets to different gateways.

With just one gateway, you can simply add (or replace) the default gateway:
ip route add default via x.x.x.x

If you want to set a default gateway for a specific (incoming) IP range, you can add a custom routing table, using iproute2:

  • echo 200 custom >> /etc/iproute2/rt_tables
  • ip rule add from 10.1.2.0/24 table custom
  • ip route add default via y.y.y.y table custom
  • ip route flush cache

Categories
Linux

A gateway to forward all traffic to a remote VPN server

Suppose you’ve setup a VM and configured it as a site-to-site VPN with OpenVPN, using iroute and staticclients. You are using this VM as a default gateway for other VMs and now want to forward all traffic from the VMs not through the default gateway‘s adapter, but through the VPN tunnel.

Why would you want to do this? One use-case might be because you want your VMs to have the same originating IP address as the VPN server.

To get started, make sure you add these commands in a terminal on your default gateway:

  • ip route add ip-address-of-vpn-server/32 via default-gateway-ip dev enp0s5 (providing enp0s5 is your current adapter)
  • ip route del default
  • ip route add default via 192.168.159.14 dev tun0 (providing 192.168.159.14 is the private IP you got from your VPN)

The commands above will make sure your gateway can still reach the VPN server. Once the default route is deleted, we add a new default route that goes through the tunnel.

On the other side of the tunnel, on your VPN server, you will need to add these commands:

  • iptables -I FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
  • iptables -I FORWARD -i tun0 -o eth0 -s 192.168.159.0/24 -m conntrack --ctstate NEW -j ACCEPT
  • iptables -t nat -I POSTROUTING -s 192.168.159.0/24 -o eth0 -j MASQUERADE
  • iptables -t nat -I POSTROUTING -o tun0 -j MASQUERADE
  • iptables -I FORWARD -i eth0 -o tun0 -j ACCEPT
  • iptables -I FORWARD -i tun0 -o eth0 -j ACCEPT
  • iptables -I FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT

Now the VMs will be able to connect through the VPN tunnel and use the VPN server as default gateway.