Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-sonnet-4-20250514-thinking-32k· AnthropicHugging Face LMArena Human Preference 140K

how to do multihop vpn using openvpn on linux. Create a script that automatically adds…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Amazon Novaamazon.nova-pro-v1:0’s answer.
  1. User

    how to do multihop vpn using openvpn on linux. Create a script that automatically adds route

  2. Claude Assistant

    Here's how to set up a multihop VPN with OpenVPN on Linux, along with an automated routing script.

    Concept Overview

    A multihop VPN chains two VPN connections: Your device → VPN1 → VPN2 → Internet. This provides additional privacy by obscuring your traffic path.

    Basic Setup

    You'll need two OpenVPN configuration files and proper routing. Here's the approach:

    1. Connect to the first VPN server
    2. Route the second VPN connection through the first VPN tunnel
    3. Route all other traffic through the second VPN

    Automated Multihop Script

    #!/bin/bash
    
    # multihop-vpn.sh - Automated multihop VPN setup script
    
    set -e
    
    # Configuration
    VPN1_CONFIG="/path/to/first-server.ovpn"
    VPN2_CONFIG="/path/to/second-server.ovpn"
    VPN1_INTERFACE="tun0"
    VPN2_INTERFACE="tun1"
    
    # Colors for output
    RED='\033[0;31m'
    GREEN='\033[0;32m'
    YELLOW='\033[1;33m'
    NC='\033[0m'
    
    log() {
        echo -e "${GREEN}[$(date '+%H:%M:%S')]${NC} $1"
    }
    
    error() {
        echo -e "${RED}[ERROR]${NC} $1" >&2
    }
    
    warn() {
        echo -e "${YELLOW}[WARNING]${NC} $1"
    }
    
    # Check if running as root
    check_root() {
        if [[ $EUID -ne 0 ]]; then
            error "This script must be run as root"
            exit 1
        fi
    }
    
    # Store original routing table
    store_original_routes() {
        log "Storing original routing table..."
        ip route show > /tmp/original_routes.txt
        echo "$(ip route | grep default)" > /tmp/original_default_route.txt
    }
    
    # Restore original routing
    restore_routes() {
        log "Restoring original routes..."
        
        # Kill OpenVPN processes
        pkill -f "openvpn.*$VPN1_CONFIG" 2>/dev/null || true
        pkill -f "openvpn.*$VPN2_CONFIG" 2>/dev/null || true
        
        # Wait for interfaces to go down
        sleep 2
        
        # Restore original default route
        if [[ -f /tmp/original_default_route.txt ]]; then
            while read -r route; do
                [[ -n "$route" ]] && ip route add $route 2>/dev/null || true
            done < /tmp/original_default_route.txt
        fi
        
        # Flush and restore routes
        ip route flush table main 2>/dev/null || true
        if [[ -f /tmp/original_routes.txt ]]; then
            while read -r route; do
                [[ -n "$route" ]] && ip route add $route 2>/dev/null || true
            done < /tmp/original_routes.txt
        fi
        
        # Clean up temp files
        rm -f /tmp/original_routes.txt /tmp/original_default_route.txt
        
        log "Routes restored"
    }
    
    # Get VPN server IPs from config files
    get_vpn_servers() {
        VPN1_SERVER=$(grep -E '^remote ' "$VPN1_CONFIG" | head -1 | awk '{print $2}')
        VPN2_SERVER=$(grep -E '^remote ' "$VPN2_CONFIG" | head -1 | awk '{print $2}')
        
        if [[ -z "$VPN1_SERVER" || -z "$VPN2_SERVER" ]]; then
            error "Could not extract server IPs from config files"
            exit 1
        fi
        
        log "VPN1 Server: $VPN1_SERVER"
        log "VPN2 Server: $VPN2_SERVER"
    }
    
    # Start first VPN connection
    start_vpn1() {
        log "Starting first VPN connection..."
        
        # Get original default route
        ORIGINAL_GW=$(ip route | grep default | head -1 | awk '{print $3}')
        ORIGINAL_DEV=$(ip route | grep default | head -1 | awk '{print $5}')
        
        # Add route for VPN1 server through original gateway
        ip route add "$VPN1_SERVER/32" via "$ORIGINAL_GW" dev "$ORIGINAL_DEV"
        
        # Start VPN1 in background
        openvpn --config "$VPN1_CONFIG" --daemon --writepid /var/run/openvpn-vpn1.pid
        
        # Wait for interface to come up
        local timeout=30
        while [[ $timeout -gt 0 ]]; do
            if ip link show "$VPN1_INTERFACE" &>/dev/null; then
                log "VPN1 interface $VPN1_INTERFACE is up"
                break
            fi
            sleep 1
            ((timeout--))
        done
        
        if [[ $timeout -eq 0 ]]; then
            error "VPN1 interface failed to come up"
            exit 1
        fi
        
        # Get VPN1 gateway
        sleep 2
        VPN1_GW=$(ip route | grep "$VPN1_INTERFACE" | grep -E '^default|^0\.0\.0\.0' | awk '{print $3}' | head -1)
        if [[ -z "$VPN1_GW" ]]; then
            VPN1_GW=$(ip route | grep "$VPN1_INTERFACE" | head -1 | awk '{print $1}' | cut -d'/' -f1)
        fi
        
        log "VPN1 gateway: $VPN1_GW"
    }
    
    # Start second VPN connection
    start_vpn2() {
        log "Starting second VPN connection..."
        
        # Add route for VPN2 server through VPN1
        ip route add "$VPN2_SERVER/32" via "$VPN1_GW" dev "$VPN1_INTERFACE"
        
        # Modify VPN2 config to use specific interface
        local temp_config="/tmp/vpn2_temp.ovpn"
        cp "$VPN2_CONFIG" "$temp_config"
        
        # Ensure VPN2 uses tun1
        if ! grep -q "^dev " "$temp_config"; then
            echo "dev $VPN2_INTERFACE" >> "$temp_config"
        else
            sed -i "s/^dev .*/dev $VPN2_INTERFACE/" "$temp_config"
        fi
        
        # Start VPN2
        openvpn --config "$temp_config" --daemon --writepid /var/run/openvpn-vpn2.pid
        
        # Wait for interface to come up
        local timeout=30
        while [[ $timeout -gt 0 ]]; do
            if ip link show "$VPN2_INTERFACE" &>/dev/null; then
                log "VPN2 interface $VPN2_INTERFACE is up"
                break
            fi
            sleep 1
            ((timeout--))
        done
        
        if [[ $timeout -eq 0 ]]; then
            error "VPN2 interface failed to come up"
            cleanup
            exit 1
        fi
        
        # Clean up temp config
        rm -f "$temp_config"
    }
    
    # Setup final routing
    setup_routing() {
        log "Setting up multihop routing..."
        
        # Remove any default routes that might conflict
        ip route del default 2>/dev/null || true
        
        # Set default route through VPN2
        VPN2_GW=$(ip route | grep "$VPN2_INTERFACE" | head -1 | awk '{print $3}')
        if [[ -z "$VPN2_GW" ]]; then
            # Try to get gateway from interface IP
            VPN2_GW=$(ip addr show "$VPN2_INTERFACE" | grep 'inet ' | awk '{print $4}' | cut -d'/' -f1)
        fi
        
        if [[ -n "$VPN2_GW" ]]; then
            ip route add default via "$VPN2_GW" dev "$VPN2_INTERFACE"
            log "Default route set through VPN2: $VPN2_GW"
        else
            warn "Could not determine VPN2 gateway, using interface directly"
            ip route add default dev "$VPN2_INTERFACE"
        fi
        
        # Ensure DNS goes through the tunnel
        if [[ -f /etc/resolv.conf.bak ]]; then
            cp /etc/resolv.conf.bak /etc/resolv.conf
        else
            cp /etc/resolv.conf /etc/resolv.conf.bak
        fi
        
        echo "nameserver 8.8.8.8" > /etc/resolv.conf
        echo "nameserver 8.8.4.4" >> /etc/resolv.conf
    }
    
    # Test connectivity
    test_connection() {
        log "Testing multihop connection..."
        
        if curl -s --max-time 10 httpbin.org/ip > /tmp/ip_test.txt; then
            local exit_ip=$(cat /tmp/ip_test.txt | grep -o '"origin": "[^"]*' | cut -d'"' -f4)
            log "Multihop VPN is working! Exit IP: $exit_ip"
            rm -f /tmp/ip_test.txt
        else
            warn "Connection test failed, but VPN might still be working"
        fi
    }
    
    # Cleanup function
    cleanup() {
        log "Cleaning up..."
        restore_routes
        
        # Restore DNS
        if [[ -f /etc/resolv.conf.bak ]]; then
            mv /etc/resolv.conf.bak /etc/resolv.conf
        fi
        
        # Remove PID files
        rm -f /var/run/openvpn-vpn1.pid /var/run/openvpn-vpn2.pid
    }
    
    # Signal handlers
    trap cleanup EXIT
    trap cleanup SIGINT
    trap cleanup SIGTERM
    
    # Main execution
    main() {
        check_root
        
        case "${1:-start}" in
            "start")
                log "Starting multihop VPN setup..."
                store_original_routes
                get_vpn_servers
                start_vpn1
                sleep 5
                start_vpn2
                sleep 5
                setup_routing
                test_connection
                log "Multihop VPN setup complete!"
                log "Press Ctrl+C to stop and restore original routing"
                
                # Keep script running
                while true; do
                    sleep 10
                done
                ;;
            "stop")
                log "Stopping multihop VPN..."
                cleanup
                log "Multihop VPN stopped"
                ;;
            "status")
                echo "VPN1 Status:"
                if pgrep -f "openvpn.*$VPN1_CONFIG" > /dev/null; then
                    echo "  Running (PID: $(pgrep -f "openvpn.*$VPN1_CONFIG"))"
                else
                    echo "  Stopped"
                fi
                
                echo "VPN2 Status:"
                if pgrep -f "openvpn.*$VPN2_CONFIG" > /dev/null; then
                    echo "  Running (PID: $(pgrep -f "openvpn.*$VPN2_CONFIG"))"
                else
                    echo "  Stopped"
                fi
                ;;
            *)
                echo "Usage: $0 {start|stop|status}"
                echo "  start  - Start multihop VPN"
                echo "  stop   - Stop multihop VPN and restore routes"
                echo "  status - Show VPN status"
                exit 1
                ;;
        esac
    }
    
    # Run main function
    main "$@"
    

    Usage

    1. Make the script executable:
    chmod +x multihop-vpn.sh
    
    1. Edit the script configuration:
    # Update these paths in the script
    VPN1_CONFIG="/path/to/your/first-server.ovpn"
    VPN2_CONFIG="/path/to/your/second-server.ovpn"
    
    1. Run the script:
    # Start multihop VPN
    sudo ./multihop-vpn.sh start
    
    # Check status
    sudo ./multihop-vpn.sh status
    
    # Stop and restore original routing
    sudo ./multihop-vpn.sh stop
    

    Important Considerations

    Security Notes:

    • Use different VPN providers for each hop to maximize privacy
    • Ensure both VPN configs use different tunnel interfaces (tun0, tun1)
    • The script stores and restores your original routing table

    Performance:

    • Multihop adds latency and reduces bandwidth
    • Monitor connection stability for both hops

    DNS:

    • The script sets public DNS servers to prevent leaks
    • Consider using DNS servers provided by your VPN providers

    Troubleshooting:

    • Check that both OpenVPN configs work individually first
    • Verify firewall settings don't block the connections
    • Monitor logs: journalctl -f -u openvpn@*

    The script handles route management automatically and includes cleanup on exit, making multihop VPN setup much more manageable.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.