Setting up a multi-hop VPN using OpenVPN on Linux involves configuring multiple OpenVPN instances to route traffic through several VPN servers. Below is a step-by-step guide to achieve this, along with a script to automatically add routes.
Step 1: Install OpenVPN
First, ensure OpenVPN is installed on your Linux system. You can install it using your package manager. For example, on Ubuntu/Debian:
sudo apt update
sudo apt install openvpn
Step 2: Configure OpenVPN
You need to configure multiple OpenVPN instances. Let's assume you have two VPN servers: vpn1.example.com and vpn2.example.com.
Create Configuration Files
Create configuration files for each VPN server. For example:
/etc/openvpn/client1.conf
client
dev tun
proto udp
remote vpn1.example.com 1194
resolv-retry infinite
nobind
persist-key
persist-tun
ca ca.crt
cert client1.crt
key client1.key
remote-cert-tls server
cipher AES-256-CBC
comp-lzo
verb 3
/etc/openvpn/client2.conf
client
dev tun
proto udp
remote vpn2.example.com 1194
resolv-retry infinite
nobind
persist-key
persist-tun
ca ca.crt
cert client2.crt
key client2.key
remote-cert-tls server
cipher AES-256-CBC
comp-lzo
verb 3
Step 3: Create a Script to Automatically Add Routes
Create a script to automatically add routes after the VPN connections are established. This script will be called by the OpenVPN client configuration.
/usr/local/bin/add-routes.sh
#!/bin/bash
# Define the routes to add
ROUTE1="10.8.0.0/24"
ROUTE2="10.9.0.0/24"
# Add routes
sudo ip route add $ROUTE1 dev tun0
sudo ip route add $ROUTE2 dev tun1
# Log the routes added
echo "Routes added: $ROUTE1 via tun0, $ROUTE2 via tun1" >> /var/log/openvpn/routes.log
Make the script executable:
sudo chmod +x /usr/local/bin/add-routes.sh
Step 4: Modify OpenVPN Configuration to Call the Script
Modify the OpenVPN client configuration files to call the script after the VPN connection is established.
/etc/openvpn/client1.conf
client
dev tun
proto udp
remote vpn1.example.com 1194
resolv-retry infinite
nobind
persist-key
persist-tun
ca ca.crt
cert client1.crt
key client1.key
remote-cert-tls server
cipher AES-256-CBC
comp-lzo
verb 3
script-security 2
up /usr/local/bin/add-routes.sh
/etc/openvpn/client2.conf
client
dev tun
proto udp
remote vpn2.example.com 1194
resolv-retry infinite
nobind
persist-key
persist-tun
ca ca.crt
cert client2.crt
key client2.key
remote-cert-tls server
cipher AES-256-CBC
comp-lzo
verb 3
script-security 2
up /usr/local/bin/add-routes.sh
Step 5: Start the OpenVPN Clients
Start the OpenVPN clients to establish the connections and add the routes.
sudo openvpn --config /etc/openvpn/client1.conf &
sudo openvpn --config /etc/openvpn/client2.conf &
Step 6: Verify the Routes
Check the routes to ensure they have been added correctly.
ip route show
This setup will establish a multi-hop VPN connection and automatically add the necessary routes using the script. Adjust the routes and configuration files as needed for your specific use case.