Skip to content

Instantly share code, notes, and snippets.

@vincascm
Created May 25, 2024 03:23
Show Gist options
  • Select an option

  • Save vincascm/8582fe95f144767095cc552f652ad683 to your computer and use it in GitHub Desktop.

Select an option

Save vincascm/8582fe95f144767095cc552f652ad683 to your computer and use it in GitHub Desktop.
A watchdog for running the Phantun client and WireGuard in OpenWrt
#!/bin/sh
# SPDX-License-Identifier: GPL-2.0
#
WAIT_DURATION=300
. /lib/functions.sh
check_peer_activity() {
local cfg=$1
local iface=$2
local disabled
local public_key
local endpoint_host
local endpoint_port
local persistent_keepalive
local last_handshake
local idle_seconds
config_get_bool disabled "${cfg}" "disabled" 0
config_get public_key "${cfg}" "public_key"
config_get endpoint_host "${cfg}" "endpoint_host"
config_get endpoint_port "${cfg}" "endpoint_port"
if [ "${disabled}" -eq 1 ]; then
# skip disabled peers
return 0
fi
# re-resolve endpoint hostname 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 300 ] && return 0;
/etc/init.d/phantun restart
}
while true; do
# 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" " ")
config_load network
for iface in $wg_ifaces; do
config_foreach check_peer_activity "wireguard_${iface}" "${iface}"
done
sleep $WAIT_DURATION
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment