VPN linux client – act as a gateway

Your linux VPN client can act as a gateway to networks behind VPN for other local network devices. Let’s say I have a VPN client on Rpi linux machine. I would like to access VPN network from my other computers but I don’t want to install software on each device. In a lot of cases, your home router has a VPN client options, but only for PPTP or OpenVPN, not IPsec.

1. On your VPN client linux machine:

#!/bin/bash

# VPN client traffic forwarding script.

# You can use this to acccess networks behind VPN clients from other local network devices. You basically make a VPN router.
# First you need to establish a VPN connection from this Linux machine. You only need to setup 3 variables
# in the script: main interface, tunnel interface, local network.

# Run the script and set a static route to remote VPN networks in your router, you can now access
# remote VPN networks from other devices in your local network via this machine.

# Main interface
main=ens18

# Tunnel interface
tun=tun0

# Local network
lnetwork=172.16.20.0/24

echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -A FORWARD -o "$tun" -i "$main" -s "$lnetwork" -m conntrack --ctstate NEW -j ACCEPT
iptables -A FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -A POSTROUTING -t nat -j MASQUERADE

# Save iptables to a file
iptables-save > /etc/iptables.save

# Restore iptables
#iptables-restore < /etc/iptables.save

2. Add a new gateway (linux VPN client machine) and a static route to VPN network in your main router:

VPN Linux machine (RPI) local IP is: 172.16.20.83 (our new gateway)
VPN network is: 10.150.60.0/24 (remote VPN network)

Adding gateway on my home router:

Adding static route on my home router:

Now I can access VPN network from any device on my local network, from my desktop PC for example:

The packets in this case are going like this (not 100% correct, just the main idea):

My Desktop PC (172.16.3.2) -> Home router (172.16.3.1) -> Linux Rpi machine (172.16.20.83) -> remote VPN network (10.150.60.0/24) and back.

Leave a Reply

Your email address will not be published. Required fields are marked *