Skip to content

Instantly share code, notes, and snippets.

@vdusart
Created June 19, 2024 16:06
Show Gist options
  • Save vdusart/66ac323321f69bdde36f89f8de6e0ddf to your computer and use it in GitHub Desktop.
Save vdusart/66ac323321f69bdde36f89f8de6e0ddf to your computer and use it in GitHub Desktop.
Automatically route traffic for specific domains through your VPN with dynamic IP resolution.

WireGuard - Dynamic VPN Routing

Overview

This script is designed to selectively route traffic through a WireGuard VPN based on domain names.

By specifying domain names, this script dynamically resolves their IP addresses and updates routing rules so that only traffic destined for these domains is tunneled through the VPN. This ensures only necessary traffic is routed through it while other traffic remains unaffected.

VPN Configuration

To use this script, your WireGuard configuration file should be set up. Below is an example of what your WireGuard configuration file (wg0.conf) should look like:

[Interface]
PrivateKey = your_private_key
Address = 10.0.0.1/24
DNS = 1.0.0.1

[Peer]
PublicKey = peer_public_key
Endpoint = peer_endpoint:port
AllowedIPs = 0.0.0.0/0
PersistentKeepalive = 25

AllowedIPs = 0.0.0.0/0 - This configuration allows WireGuard to accept all incoming traffic. The actual routing is controlled by the script.

Script

#!/bin/bash

if [ "$EUID" -ne 0 ]
then
    echo "Please run as root."
    exit
fi

# WireGuard Interface
wg_interface="wg0"

# Starting the VPN
wg-quick up ${wg_interface}


# List of all the domains that will go through the VPN
domains=("site1.com" "site2.com")

# DNS Server used for domain name resolution
dns_server="1.0.0.1"

# Default table id used by wg-quick
table_id=51820

# Flush all the existing route from this table
ip route flush table $table_id

# Get the ip address of each domain and add them in the routing table
for domain in "${domains[@]}"; do
    ips=$(dig +short @$dns_server $domain)
    for ip in $ips; do
        ip route add $ip dev $wg_interface table $table_id
    done
done

ip rule add from all lookup $table_id
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment