Connect to random wireguard server

Hope someone can help me settle this once and for all. I would like to move away from openvpn to wireguard for the obvious reasons. The thing holding me back is that I can't figure it out! I would like to connect to random wireguard servers, each having different settings.

This is easily possible with the function remote-random explained here.

Wireguard does not have the same function, so there are few workarounds as explained here:
https://forum.openwrt.org/t/how-to-choose-a-random-wireguard-server/14750/30

  1. Using dnsmasq
  2. Using axillary file:
cat << "EOF" > servers.conf
gb2,185.16.85.130,gEor1tjIW4DmKfF24A8j8Ongw7B9pnhZ2n09xR5mH1o=
gb4,141.98.252.130,IJJe0TQtuQOyemL4IZn6oHEsMKSPqOuLfD5HoAWEPTY=
EOF

cat << "EOF" > wg_rand.sh
#!/bin/sh
WGINTERFACE="${1:-mullvad}"
WGPEER="${2:-wireguard_mullvad}"
FILE="servers.conf"
IN=$(sed -n "$(awk 'END {srand(); r=rand()*NR; if (r<NR)
{sub(/\..*/,"",r); r++;}; print r}' $FILE)p" $FILE)
IFS="," read -r DESCRIPTION HOST PUBKEY << EOF2
${IN}
EOF2
uci set network.@"$WGPEER"[0].description="${DESCRIPTION}"
uci set network.@"$WGPEER"[0].endpoint_host="${HOST}"
uci set network.@"$WGPEER"[0].public_key="${PUBKEY}"
/etc/init.d/network reload
ifup "${WGINTERFACE}"
EOF

I would like to use axillary file. However I have two issues:

  1. The problem with the method used above is that the script randomizes just "description", "endpoint_host" and "public_key". However I need the script to randomize more than that. For each server, I have the following values which need to change for the next server in the list:
    "PrivateKey", "Address", "DNS", "PublicKey", "PresharedKey", "AllowedIPs", "Endpoint", "PersistentKeepalive".

  2. I spent many hours trying to get a sense of the script, how to add it and how to add it under cron jobs. As you can read, I am not good at writing scripts. I read the whole thread many times in the past, but can't figure it out. Do I need to setup a wireguard interface first before the script can randomize the values? Or does it create an interface with the values in "servervs.conf"? As you see, I need a simple guide to be able to set this up.

So in summary, I need to connect to a random wireguard server each time the router reboots and change the above values in the wireguard interface to values needed for another server.

Can anyone help me with that?
Thank you in advance

Why not connect to all wg endpoints by default and randomly set route allowed ips for just one of them?

2 Likes

Following @stangri excellent suggestion, create all peers but on startup randomly enable one and leave the others disabled

2 Likes

Or, probably even better, distribute the traffic among all tunnels.

1 Like