Skip to content

Instantly share code, notes, and snippets.

@sw00
Last active July 9, 2019 20:52
Show Gist options
  • Save sw00/9f0d7e4da259de325674eb5bfeea5f28 to your computer and use it in GitHub Desktop.
Save sw00/9f0d7e4da259de325674eb5bfeea5f28 to your computer and use it in GitHub Desktop.
Bash script to configure routes so that host can still serve traffic over its public IP interface while VPN is on.
#!/bin/bash
set -xe
calculate_subnet() {
IP=$1
PREFIX=$2
{ IFS=. read -r i1 i2 i3 i4; } <<< $IP
{ IFS=. read -r xx m1 m2 m3 m4; } <<< $(for a in $(seq 1 32); do if [ $(((a - 1) % 8)) -eq 0 ]; then echo -n .; fi; if [ $a -le $PREFIX ]; then echo -n 1; else echo -n 0; fi; done)
printf "%d.%d.%d.%d\n" "$((i1 & (2#$m1)))" "$((i2 & (2#$m2)))" "$((i3 & (2#$m3)))" "$((i4 & (2#$m4)))"
IFS=\
}
FULL_PUBLIC_ADDRESS=$(ip addr | grep -E 'inet(.*)global' | awk '{ print $2 }')
PUBLIC_IP=$(echo $FULL_PUBLIC_ADDRESS | cut -d/ -f1)
IP_PREFIX=$(echo $FULL_PUBLIC_ADDRESS | cut -d/ -f2)
PUBLIC_SUBNET=$(calculate_subnet $PUBLIC_IP $IP_PREFIX)
ADAPTOR=$(ip addr | grep -E 'inet(.*)global' | awk '{print $NF}')
DEFAULT_GATEWAY=$(ip route | grep default | grep -oE 'default via ([0-9.]{1,3}{4})' | cut -d\ -f3)
# Create routing table for packets from public IP
ip rule add table 128 from $PUBLIC_IP
# Route response packets over default adaptor (instead of vpn)
ip route add table 128 to "$PUBLIC_SUBNET/$IP_PREFIX" dev $ADAPTOR
# Set default gateway to current default
ip route add table 128 default via $DEFAULT_GATEWAY
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment