#!/bin/bash # wirecon-mtu-probe.sh — find the largest payload that survives PMTUD toward # the WG peer's public endpoint, then print the recommended WG MTU # (payload - 80 bytes of WG/UDP/IPv4 overhead). # # Usage: wirecon-mtu-probe.sh [] # If is omitted, reads the Endpoint from /etc/wireguard/wg0.conf. set -euo pipefail CONF="${WIRECON_CONF:-/etc/wirecon/wirecon.conf}" # shellcheck source=/dev/null [[ -r "$CONF" ]] && source "$CONF" : "${MTU_MIN:=1200}" : "${MTU_MAX:=1420}" target="${1:-}" if [[ -z "$target" ]]; then # extract Endpoint host from wg0.conf target=$(awk -F'= *' '/^Endpoint/ {gsub(/:[0-9]+$/,"",$2); print $2; exit}' /etc/wireguard/wg0.conf 2>/dev/null || true) fi if [[ -z "$target" ]]; then echo "usage: $0 " >&2 exit 2 fi echo "probing PMTU toward $target (range $MTU_MIN..$MTU_MAX)" >&2 # ICMP payload = mtu - 28 (IP+ICMP headers) probe_ok() { local mtu=$1 local payload=$((mtu - 28)) ping -M do -s "$payload" -c 1 -W 2 -n "$target" >/dev/null 2>&1 } lo=$MTU_MIN hi=$MTU_MAX best=0 if ! probe_ok "$lo"; then echo "FAIL: even $lo does not pass DF — path is broken or host unreachable" >&2 exit 1 fi best=$lo while [[ $lo -le $hi ]]; do mid=$(( (lo + hi) / 2 )) if probe_ok "$mid"; then best=$mid lo=$(( mid + 1 )) else hi=$(( mid - 1 )) fi done # WireGuard-over-IPv4-over-UDP overhead: 20 (IPv4) + 8 (UDP) + 32 (WG) = 60. # Round down to 80 for safety margin (covers IPv6, extra hops). wg_mtu=$(( best - 80 )) echo "path MTU: $best" echo "recommended WG MTU: $wg_mtu" echo echo "apply on both peers:" echo " sed -i 's/^MTU = .*/MTU = ${wg_mtu}/' /etc/wireguard/wg0.conf" echo " rc-service wg-quick.wg0 restart"