OpenWRT dynamic IP watchdog

Aleksandr V. Piskunov aleksandr.v.piskunov at
Sat Jun 16 11:27:12 CEST 2018

I'm using OpenWRT routers to connect several networks (most behind
NAT) to the main one, with a public but dynamic IP. In order to keep
WireGuard connections alive in case of sudden endpoint IP change, some
kind of monitoring is required, so I adapted
script to the specifics of OpenWRT networking system.
Tested it for a few weeks with a several IP changes, server downtimes,
etc.. seems to be working just fine.

If any OpenWRT wireguard package maintainers are reading this, please
review and consider for pushing to the wireguard-tools(?) package.

# to be called from cron every 1..2 minutes
. /lib/

check_peer_activity() {
  local cfg=$1
  local iface=$2
  local public_key
  local endpoint_host
  local endpoint_port
  local persistent_keepalive
  local last_handshake
  local idle_seconds

  config_get public_key "${cfg}" "public_key"
  config_get endpoint_host "${cfg}" "endpoint_host"
  config_get endpoint_port "${cfg}" "endpoint_port"
  config_get persistent_keepalive "${cfg}" "persistent_keepalive"

  # only process peers with endpoints and keepalive set
  [ -z ${endpoint_host} ] && return 0;
  [ -z ${persistent_keepalive} ] && return 0;

  # resolve endpoint and reconnect if not responding for too long
  last_handshake=`wg show ${iface} latest-handshakes | grep
${public_key} | awk '{print $2}'`
  [ -z ${last_handshake} ] && return 0;
  idle_seconds=$((`date +%s`-${last_handshake}))
  [ ${idle_seconds} -lt 150 ] && return 0;
  logger -t "wireguard_monitor" "${iface} endpoint
${endpoint_host}:${endpoint_port} is not responding for
${idle_seconds} seconds, trying to reconnect"
  wg set ${iface} peer ${public_key} endpoint

# query ubus for all active wireguard interfaces
wg_ifaces=`ubus -S call network.interface dump | jsonfilter -e
'@.interface[@.up=true]' | jsonfilter -a -e
'@[@.proto="wireguard"].interface' | tr "\n" " "`

# check every peer in every active wireguard interface
config_load network
for iface in $wg_ifaces; do
  config_foreach check_peer_activity "wireguard_${iface}" "${iface}"

More information about the WireGuard mailing list