Setting up a true multi-hop VPN where your traffic goes through multiple distinct VPN servers, with each server potentially being a different provider or location, requires careful configuration. The machine running this script will act as the "middleman" – it connects to the first VPN, and then through that connection, it connects to the second VPN, and so on.
This script will run on a single Linux machine and establish a chain of OpenVPN connections.
How it works:
- Enables IP Forwarding: This is crucial. Your Linux machine needs to be able to forward packets between the VPN tunnels it creates.
- Random OVPN Selection: It randomly picks an
.ovpn file for each hop.
- Chained Connections:
- It starts the first OpenVPN connection.
- Once the first connection is established, it starts the second OpenVPN connection over the first one. This means the second OpenVPN client's traffic will traverse the first VPN tunnel.
- This continues for the specified number of hops.
- NAT (Network Address Translation):
iptables rules are set up to allow traffic to exit from the innermost VPN tunnel to the internet.
- Cleanup: On exit (e.g., Ctrl+C), it kills all OpenVPN processes and cleans up
iptables rules and IP forwarding.
Prerequisites:
- Linux Machine: This script is designed for Linux (Ubuntu, Debian, Fedora, CentOS, etc.).
openvpn installed: sudo apt-get install openvpn (Debian/Ubuntu) or sudo yum install openvpn (CentOS/RHEL).
curl installed: Used to check public IP. sudo apt-get install curl.
jq installed: Used to parse JSON from ipinfo.io. sudo apt-get install jq.
- OVPN Files: A folder containing your
.ovpn configuration files. These files should ideally not contain route-nopull if you want the server to push routes, and should generally be standard client configurations.
Step 1: Create the script file
Save the following content as multihop_vpn.sh:
#!/bin/bash
# Configuration
OVPN_DIR="./ovpn_files" # Directory containing your .ovpn files
NUM_HOPS=2 # Number of VPN hops (e.g., 2 for Client -> VPN1 -> VPN2 -> Internet)
# NOTE: More than 2 hops can significantly increase latency and reduce speed.
# Ensure you have enough *distinct* OVPN files for the number of hops.
LOG_BASE_DIR="/var/log/multihop_vpn" # Base directory for logs
PID_BASE_DIR="/run/multihop_vpn" # Base directory for PIDs
# --- DO NOT EDIT BELOW THIS LINE ---
OVPN_PIDS=()
IP_FORWARDING_ENABLED=0
IPTABLES_RULES_APPLIED=0
LOG_FILE_PREFIX=""
# Function to display error messages and exit
error_exit() {
echo -e "\n\033[31mERROR: $1\033[0m" >&2
cleanup
exit 1
}
# Function to display success messages
success_msg() {
echo -e "\n\033[32mSUCCESS: $1\033[0m"
}
# Function to display informational messages
info_msg() {
echo -e "\n\033[34mINFO: $1\033[0m"
}
# Function to select a random OVPN file
select_random_ovpn() {
local files=($(find "$OVPN_DIR" -name "*.ovpn" -type f))
if [ ${#files[@]} -eq 0 ]; then
error_exit "No .ovpn files found in '$OVPN_DIR'. Please populate the directory."
fi
# Filter out files already used in this session if enough unique files exist
local available_files=()
for file in "${files[@]}"; do
local already_used=0
for used_file in "${USED_OVPN_FILES[@]}"; do
if [[ "$file" == "$used_file" ]]; then
already_used=1
break
fi
done
if [ "$already_used" -eq 0 ]; then
available_files+=("$file")
fi
done
if [ ${#available_files[@]} -eq 0 ]; then
if [ ${#files[@]} -lt $NUM_HOPS ]; then
error_exit "Not enough unique .ovpn files for $NUM_HOPS hops. Found ${#files[@]} but need $NUM_HOPS distinct files for random selection."
else
# All available files have been used, but we need more hops.
# This should ideally not happen if filtering is working, but as a fallback, pick from all again.
info_msg "Ran out of unique OVPN files for random selection. Re-using files."
available_files=("${files[@]}")
fi
fi
local rand_idx=$((RANDOM % ${#available_files[@]}))
echo "${available_files[$rand_idx]}"
}
# Function to get public IP and location
get_public_ip_info() {
local ip_info=$(curl -s "https://ipinfo.io/json")
if [ -z "$ip_info" ]; then
echo "Could not fetch IP information."
return 1
fi
local ip=$(echo "$ip_info" | jq -r '.ip')
local city=$(echo "$ip_info" | jq -r '.city')
local region=$(echo "$ip_info" | jq -r '.region')
local country=$(echo "$ip_info" | jq -r '.country')
local org=$(echo "$ip_info" | jq -r '.org')
echo " Public IP: $ip"
echo " Location: $city, $region, $country"
echo " Provider: $org"
}
# Cleanup function
cleanup() {
echo -e "\n\033[33m--- Cleaning up ---"
# Kill OpenVPN processes
for pid in "${OVPN_PIDS[@]}"; do
if kill "$pid" 2>/dev/null; then
echo " Killed OpenVPN process (PID: $pid)"
else
echo " Could not kill OpenVPN process (PID: $pid), already terminated?"
fi
done
OVPN_PIDS=()
# Disable IP forwarding
if [ "$IP_FORWARDING_ENABLED" -eq 1 ]; then
echo " Disabling IP forwarding..."
sudo sysctl -w net.ipv4.ip_forward=0 >/dev/null 2>&1
sudo sysctl -w net.ipv6.conf.all.forwarding=0 >/dev/null 2>&1
IP_FORWARDING_ENABLED=0
fi
# Remove iptables rules
if [ "$IPTABLES_RULES_APPLIED" -eq 1 ]; then
echo " Removing iptables NAT rules..."
# Note: Order matters for deletion, delete in reverse order of addition
# Delete FORWARD rules first
sudo iptables -D FORWARD -i tun+ -o tun+ -j ACCEPT 2>/dev/null
sudo iptables -D FORWARD -o tun+ -j ACCEPT 2>/dev/null # This rule might be too broad, but useful for general cases
# Delete NAT rule
sudo iptables -t nat -D POSTROUTING -o tun+ -j MASQUERADE 2>/dev/null
IPTABLES_RULES_APPLIED=0
fi
# Clean up logs and pids directories
if [ -n "$LOG_FILE_PREFIX" ]; then
echo " Cleaning up temporary log and pid files..."
rm -f "${LOG_BASE_DIR}/${LOG_FILE_PREFIX}*.log"
rm -f "${PID_BASE_DIR}/${LOG_FILE_PREFIX}*.pid"
fi
rmdir "${LOG_BASE_DIR}" 2>/dev/null || true # Only removes if empty
rmdir "${PID_BASE_DIR}" 2>/dev/null || true # Only removes if empty
echo "--- Cleanup complete ---"
}
# Trap CTRL+C and call cleanup function
trap cleanup SIGINT SIGTERM
# Main script execution
main() {
echo -e "\033[1m--- Multi-Hop OpenVPN Script ---"
echo "Number of hops requested: $NUM_HOPS"
echo "OVPN files directory: $OVPN_DIR"
# Initial check for sudo
if [ "$(id -u)" -ne 0 ]; then
error_exit "This script must be run with sudo. Please run 'sudo ./multihop_vpn.sh'"
fi
# Create log and pid directories
mkdir -p "$LOG_BASE_DIR" || error_exit "Failed to create log directory: $LOG_BASE_DIR"
mkdir -p "$PID_BASE_DIR" || error_exit "Failed to create PID directory: $PID_BASE_DIR"
LOG_FILE_PREFIX="$(date +%Y%m%d%H%M%S)_"
# Get initial public IP
echo -e "\n\033[1mInitial Public IP:\033[0m"
get_public_ip_info || info_msg "Could not determine initial public IP. Continuing..."
# Enable IP forwarding
echo -e "\n\033[1mEnabling IP forwarding...\033[0m"
sudo sysctl -w net.ipv4.ip_forward=1 >/dev/null || error_exit "Failed to enable IPv4 forwarding."
sudo sysctl -w net.ipv6.conf.all.forwarding=1 >/dev/null || error_exit "Failed to enable IPv6 forwarding."
IP_FORWARDING_ENABLED=1
success_msg "IP forwarding enabled."
# Set up basic iptables NAT for all tun interfaces
echo -e "\n\033[1mSetting up iptables NAT rules...\033[0m"
sudo iptables -t nat -A POSTROUTING -o tun+ -j MASQUERADE || error_exit "Failed to set up iptables MASQUERADE rule."
sudo iptables -A FORWARD -i tun+ -o tun+ -j ACCEPT || error_exit "Failed to set up iptables FORWARD rule for tun interfaces."
sudo iptables -A FORWARD -o tun+ -j ACCEPT # Allow outgoing from anywhere to tun
IPTABLES_RULES_APPLIED=1
success_msg "IPTables NAT rules applied for tun+ interfaces."
declare -a USED_OVPN_FILES # To keep track of used files for random selection
for ((i=1; i<=NUM_HOPS; i++)); do
echo -e "\n\033[1m--- Establishing Hop $i of $NUM_HOPS ---\033[0m"
selected_ovpn=$(select_random_ovpn)
if [ -z "$selected_ovpn" ]; then
error_exit "Could not select an OVPN file for hop $i."
fi
USED_OVPN_FILES+=("$selected_ovpn") # Add to used list
LOG_FILE="${LOG_BASE_DIR}/${LOG_FILE_PREFIX}hop_${i}.log"
PID_FILE="${PID_BASE_DIR}/${LOG_FILE_PREFIX}hop_${i}.pid"
echo " Connecting with: $(basename "$selected_ovpn")"
echo " Log file: $LOG_FILE"
echo " PID file: $PID_FILE"
# Start OpenVPN in daemon mode
sudo openvpn --config "$selected_ovpn" \
--daemon \
--writepid "$PID_FILE" \
--log "$LOG_FILE" \
--cd "$OVPN_DIR" \
--script-security 2 \
--up "/bin/true" \
--down "/bin/true" \
--pull-filter ignore "redirect-gateway" \
--pull-filter ignore "dhcp-option" \
--pull-filter ignore "block-outside-dns" \
--remap-usr-set "nobody" \
--remap-grp-set "nogroup" # Security hardening
if [ $? -ne 0 ]; then
error_exit "Failed to start OpenVPN for hop $i. Check log: $LOG_FILE"
fi
# Get PID and store it
current_pid=$(cat "$PID_FILE")
if [ -z "$current_pid" ]; then
error_exit "Failed to retrieve PID for hop $i."
fi
OVPN_PIDS+=("$current_pid")
echo " OpenVPN started (PID: $current_pid). Waiting for connection..."
# Wait for the OpenVPN tunnel to establish
# This is a basic check. A more robust check would parse the log file for "Initialization Sequence Completed"
local max_wait=60
local wait_time=0
local tun_interface_found=0
while [ "$wait_time" -lt "$max_wait" ]; do
if ip a | grep -q "tun"; then
tun_interface_found=1
break
fi
sleep 2
wait_time=$((wait_time + 2))
echo -n "."
done
echo ""
if [ "$tun_interface_found" -eq 0 ]; then
error_exit "OpenVPN tunnel for hop $i did not establish within $max_wait seconds. Check log: $LOG_FILE"
fi
success_msg "Hop $i established successfully."
# Short pause before starting next hop
sleep 5
done
echo -e "\n\033[1m--- All $NUM_HOPS hops established! --- \033[0m"
echo -e "\n\033[1mYour current Public IP:\033[0m"
get_public_ip_info
echo -e "\n\033[33mScript will keep running. Press Ctrl+C to stop VPNs and cleanup.\033[0m"
wait # Keep the script alive until interrupted
}
main "$@"
Step 2: Create the OVPN files directory
mkdir ovpn_files
Step 3: Place your .ovpn files
Copy all your OpenVPN configuration files (e.g., server1.ovpn, server2.ovpn, my_provider_usa.ovpn, etc.) into the ovpn_files directory.
Important Considerations for OVPN files:
redirect-gateway: The script uses --pull-filter ignore "redirect-gateway" to prevent each OpenVPN client from redirecting the system's default gateway. This is crucial because you want the inner VPNs to route through the outer VPNs, not directly to the internet. If you don't ignore it, only the last VPN will effectively route traffic.
- DNS: Similarly,
dhcp-option and block-outside-dns are ignored. This means your system's DNS will be resolved via the outermost active VPN connection.
- Credentials: If your
.ovpn files require a username/password, you'll need to either embed them directly in the .ovpn file (e.g., using auth-user-pass /path/to/credentials.txt) or modify the script to provide them. For security, embedding is usually not recommended.
- Security: The script runs
openvpn as root (due to sudo) and uses --remap-usr-set "nobody" etc., for security hardening, but always be aware of the implications of running sudo commands.
Step 4: Make the script executable
chmod +x multihop_vpn.sh
Step 5: Run the script
sudo ./multihop_vpn.sh
What to expect when running:
- It will ask for your
sudo password.
- It will display your initial public IP.
- It will enable IP forwarding and set up
iptables NAT rules.
- For each hop:
- It will randomly select an
.ovpn file.
- It will start
openvpn in the background (--daemon).
- It will wait for a
tun interface to appear (indicating a successful connection).
- You'll see messages about connecting and the PID of each OpenVPN process.
- Once all hops are established, it will show your final public IP address (which should be the IP of the last VPN server you connected to).
- The script will then wait. Your internet traffic should now be routed through the chained VPNs.
- Press
Ctrl+C to stop the VPNs and clean up the system settings.
Important Notes:
- Latency & Speed: Multi-hopping significantly increases latency and reduces overall internet speed. Each hop adds overhead.
- Reliability: The more hops, the more points of failure. If one VPN server goes down, the entire chain breaks.
- Log Files: Check the log files (e.g.,
/var/log/multihop_vpn/) if you encounter issues. They provide detailed output from OpenVPN.
- Distinct OVPN Files: Ensure you have enough distinct
.ovpn files. The script tries to pick unique files for each hop, but if NUM_HOPS is greater than the number of available files, it will reuse them.
- Security for Credentials: If your OVPN files require a username/password, you should add
--auth-user-pass /path/to/credentials.txt to the openvpn command in the script, where credentials.txt contains your username on the first line and password on the second. Make sure this file is secure (chmod 600).
- Troubleshooting
tun interfaces: If ip a | grep "tun" doesn't show tun interfaces quickly, try increasing the max_wait time in the script. Some VPNs take longer to connect.
This script provides a robust framework for random multi-hop VPN chaining from a single Linux machine.