0126f699bb433e75bdc2ebb62b8a27a56769ba01
2 # SPDX-License-Identifier: GPL-2.0
4 # Copyright (C) 2018 Aleksandr V. Piskunov <aleksandr.v.piskunov@gmail.com>.
5 # Copyright (C) 2015-2018 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
7 # This watchdog script tries to re-resolve hostnames for inactive WireGuard peers.
8 # Use it for peers with a frequently changing dynamic IP.
9 # persistent_keepalive must be set, recommended value is 25 seconds.
11 # Run this script from cron every minute:
12 # echo '* * * * * /usr/bin/wireguard_watchdog' >> /etc/crontabs/root
17 check_peer_activity
() {
24 local persistent_keepalive
28 config_get_bool disabled
"${cfg}" "disabled" 0
29 config_get public_key
"${cfg}" "public_key"
30 config_get endpoint_host
"${cfg}" "endpoint_host"
31 config_get endpoint_port
"${cfg}" "endpoint_port"
33 if [ "${disabled}" -eq 1 ]; then
38 persistent_keepalive
=$
(wg show
${iface} persistent-keepalive | grep ${public_key} | awk '{print $2}')
40 # only process peers with endpoints and keepalive set
41 [ -z ${endpoint_host} ] && return 0;
42 [ -z ${persistent_keepalive} -o ${persistent_keepalive} = "off" ] && return 0;
45 # check taken from packages/net/ddns-scripts/files/dynamic_dns_functions.sh
46 local IPV4_REGEX="[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}"
47 local IPV6_REGEX="\(\([0-9A-Fa-f]\{1,4\}:\)\{1,\}\)\(\([0-9A-Fa-f]\{1,4\}\)\{0,1\}\)\(\(:[0-9A-Fa-f]\{1,4\}\)\{1,\}\)"
48 local IPV4=$(echo ${endpoint_host} | grep -m 1 -o "$IPV4_REGEX$") # do not detect ip in 0.0.0.0.example.com
49 local IPV6=$(echo ${endpoint_host} | grep -m 1 -o "$IPV6_REGEX")
50 [ -n "${IPV4}" -o -n "${IPV6}" ] && return 0;
52 # re-resolve endpoint hostname if not responding for too long
53 last_handshake=$(wg show ${iface} latest-handshakes | grep ${public_key} | awk '{print $2}')
54 [ -z ${last_handshake} ] && return 0;
55 idle_seconds
=$
(($
(date +%s
)-${last_handshake}))
56 [ ${idle_seconds} -lt 150 ] && return 0;
57 logger
-t "wireguard_monitor" "${iface} endpoint ${endpoint_host}:${endpoint_port} is not responding for ${idle_seconds} seconds, trying to re-resolve hostname"
58 wg
set ${iface} peer ${public_key} endpoint "${endpoint_host}:${endpoint_port}"
61 # query ubus for all active wireguard interfaces
62 wg_ifaces=$(ubus -S call network.interface dump | jsonfilter -e '@.interface[@.up=true]' | jsonfilter -a -e '@[@.proto="wireguard
"].interface' | tr "\n" " ")
64 # check every peer in every active wireguard interface
66 for iface in $wg_ifaces; do
67 config_foreach check_peer_activity "wireguard_
${iface}" "${iface}"