Skip to content

Instantly share code, notes, and snippets.

@oddmario
Last active September 28, 2024 09:08
Show Gist options
  • Save oddmario/9090d929360ebef09e4cce690dbd7a66 to your computer and use it in GitHub Desktop.
Save oddmario/9090d929360ebef09e4cce690dbd7a66 to your computer and use it in GitHub Desktop.
Stop routing all traffic through OpenVPN and use it on-demand using the tunnel interface name instead

Stop routing all traffic through OpenVPN and use it on-demand using the tunnel interface name instead

#!/bin/bash

# https://serverfault.com/questions/978701/setting-up-openvpn-as-an-interface-rather-than-routing-all-traffic-from-paid-vpn
# https://serverfault.com/questions/992624/vpn-client-doesnt-have-internet-connection

OVPN_TUN_INTERFACE_NAME="tun0"

# Get the IP address assigned to $OVPN_TUN_INTERFACE_NAME
TUN_IP=$(ip -4 addr show $OVPN_TUN_INTERFACE_NAME | grep -oP '(?<=inet\s)\d+(\.\d+){3}')

# Add the routing table entry if it doesn't exist
if ! grep -q "1000 vpn" /etc/iproute2/rt_tables; then
  echo "1000 vpn" >> /etc/iproute2/rt_tables
fi

# Delete any already existing rules that end with 'lookup vpn'
for rule in $(ip rule show | grep 'lookup vpn' | awk '{print $1}' | sed 's/://'); do
    ip rule del pref $rule
done

# Delete any already existing routes in the vpn table
ip route flush table vpn

ip route add default via $TUN_IP dev $OVPN_TUN_INTERFACE_NAME table vpn
ip rule add from $TUN_IP/32 lookup vpn

Requirements in the client config file

route-nopull
pull-filter ignore redirect-gateway

This is necessary to stop OpenVPN from setting up the routes on its own.

Bonus: additional tuning parameters for your config

#sndbuf 1024000
#rcvbuf 1024000
txqueuelen 99999
#tun-mtu 1420
comp-lzo no
push "comp-lzo no"

Example

curl --interface tun0 https://icanhazip.com
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment