From 080219c09a23bb84b883ffcb66984caece22fcff Mon Sep 17 00:00:00 2001 From: Niels Mokkenstorm Date: Thu, 19 Nov 2026 13:23:21 +0100 Subject: [PATCH] feat: delete host routes left on a gateway from a previous network --- README.md | 12 +++++ macos/stale-routes/install | 55 ++++++++++++++++++++++ macos/stale-routes/stale-routes | 65 ++++++++++++++++++++++++++ tests/test_stale_routes.py | 83 +++++++++++++++++++++++++++++++++ 4 files changed, 215 insertions(+) create mode 100755 macos/stale-routes/install create mode 100755 macos/stale-routes/stale-routes create mode 100644 tests/test_stale_routes.py diff --git a/README.md b/README.md index 6b34f0a..c0ebb5e 100644 --- a/README.md +++ b/README.md @@ -147,3 +147,15 @@ train run demo # stops on fail/needs-user; rerun to resume train watch # curses table; q quits, exits 0 on completion train ls ``` + +## Stale host routes + +A VPN or filter client pins per-destination host routes to the gateway of the network it saw them on and +leaves them behind on a network change, so those addresses (Slack, more than once) fail locally. A root job +deletes static host routes whose gateway is no longer on-link on the route's interface, on every network +change and every 5 minutes, and logs each removal to `/var/log/stale-routes.log`. + +```sh +sudo macos/stale-routes/install # --remove to uninstall +STALE_ROUTES_DRY=1 macos/stale-routes/stale-routes # show what it would delete +``` diff --git a/macos/stale-routes/install b/macos/stale-routes/install new file mode 100755 index 0000000..2717a0e --- /dev/null +++ b/macos/stale-routes/install @@ -0,0 +1,55 @@ +#!/bin/bash +# Install the stale host route cleanup: a root-owned script and one launchd job. +# +# sudo macos/stale-routes/install install or update +# sudo macos/stale-routes/install --remove unload and delete the job and its log +# +# The job runs on every network configuration change and every 5 minutes, and logs what it +# removes to /var/log/stale-routes.log. + +set -euo pipefail + +[[ "$(id -u)" == 0 ]] || { echo "run with sudo" >&2; exit 77; } + +src="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +bin=/usr/local/libexec/stale-routes +label=dev.mokkenstorm.stale-routes +target="/Library/LaunchDaemons/$label.plist" +log=/var/log/stale-routes.log + +launchctl bootout "system/$label" 2>/dev/null || true + +if [[ "${1:-}" == --remove ]]; then + rm -f "$target" "$bin" "$log" + echo "removed" + exit 0 +fi + +install -d -o root -g wheel -m 755 /usr/local/libexec +install -o root -g wheel -m 755 "$src/stale-routes" "$bin" + +trap 'rm -f "$target.new"' EXIT +cat >"$target.new" < + + + + Label$label + ProgramArguments + $bin + WatchPaths + /Library/Preferences/SystemConfiguration + StartInterval300 + RunAtLoad + ThrottleInterval10 + StandardOutPath$log + StandardErrorPath$log + + +EOF +plutil -lint "$target.new" >/dev/null +chown root:wheel "$target.new" +chmod 644 "$target.new" +mv "$target.new" "$target" +launchctl bootstrap system "$target" +echo "installed $bin; log at $log" diff --git a/macos/stale-routes/stale-routes b/macos/stale-routes/stale-routes new file mode 100755 index 0000000..72e3eae --- /dev/null +++ b/macos/stale-routes/stale-routes @@ -0,0 +1,65 @@ +#!/bin/bash +# Deletes static IPv4 host routes whose gateway is no longer on-link, run as root by launchd. +# +# A VPN or filter client (FortiClient or Cloudflare WARP here) pins per-destination host routes +# (flags UGHS) to the gateway of the network it saw them on, and leaves them behind on a network +# change. Their gateway then sits on no attached subnet, so every connection to those addresses +# fails locally; Slack broke this way on 2026-10-16 and 2026-11-19. A route counts as stale only +# when its gateway is not directly reachable on the route's own interface; nothing is touched +# while there is no default route, since then nothing can be judged. +# +# STALE_ROUTES_DRY=1 prints the commands instead of running them. STALE_ROUTES_TABLE (netstat +# output), STALE_ROUTES_ONLINK (" " lines), STALE_ROUTES_DEFAULT (1 or 0) and +# STALE_ROUTES_NOW replace the live lookups for tests. + +set -uo pipefail + +now="${STALE_ROUTES_NOW:-$(date '+%Y-%m-%d %H:%M:%S')}" + +run() { + [[ "${STALE_ROUTES_DRY:-}" == 1 ]] && { echo "would run: $*"; return 0; } + "$@" >/dev/null +} + +has_default() { + [[ -n "${STALE_ROUTES_DEFAULT:-}" ]] && { [[ "$STALE_ROUTES_DEFAULT" == 1 ]]; return; } + route -n get default >/dev/null 2>&1 +} + +route_table() { + [[ -n "${STALE_ROUTES_TABLE:-}" ]] && { cat "$STALE_ROUTES_TABLE"; return; } + netstat -rn -f inet +} + +# On-link means the kernel reaches the gateway itself without another gateway, on that interface. +on_link() { + local gateway="$1" interface="$2" lookup + [[ -n "${STALE_ROUTES_ONLINK:-}" ]] && { grep -qxF "$gateway $interface" "$STALE_ROUTES_ONLINK"; return; } + lookup="$(route -n get "$gateway" 2>/dev/null)" || return 1 + ! grep -q '^ *gateway:' <<<"$lookup" && grep -qx " *interface: $interface" <<<"$lookup" +} + +static_host_routes() { + route_table | awk ' + $1 ~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/ && $2 ~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/ && + $3 ~ /U/ && $3 ~ /G/ && $3 ~ /H/ && $3 ~ /S/ { print $1, $2, $4 }' +} + +has_default || exit 0 + +# One lookup per gateway and interface; /bin/bash 3.2 has no associative arrays. +kept=$'\n' +stale=$'\n' +removed=0 +while read -r destination gateway interface; do + key="$gateway $interface" + if [[ "$kept$stale" != *$'\n'"$key"$'\n'* ]]; then + on_link "$gateway" "$interface" && kept+="$key"$'\n' || stale+="$key"$'\n' + fi + [[ "$stale" == *$'\n'"$key"$'\n'* ]] || continue + run route -n delete -host "$destination" "$gateway" && removed=$((removed + 1)) + [[ "${STALE_ROUTES_DRY:-}" == 1 ]] || echo "$now removed $destination via $gateway on $interface" +done < <(static_host_routes) + +[[ "$removed" -gt 0 && "${STALE_ROUTES_DRY:-}" != 1 ]] && echo "$now removed $removed stale host routes" +exit 0 diff --git a/tests/test_stale_routes.py b/tests/test_stale_routes.py new file mode 100644 index 0000000..5948202 --- /dev/null +++ b/tests/test_stale_routes.py @@ -0,0 +1,83 @@ +from pathlib import Path +import os +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).parents[1] +SCRIPT = str(ROOT / "macos/stale-routes/stale-routes") + +HEADER = """Routing tables + +Internet: +Destination Gateway Flags Netif Expire +""" + + +class StaleRoutesTests(unittest.TestCase): + """Static host routes via a gateway that is no longer on-link get deleted; everything else stays.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.base = Path(self.tmp.name) + + def tearDown(self): + self.tmp.cleanup() + + def run_script(self, table, on_link, has_default=True): + (self.base / "table").write_text(HEADER + table) + (self.base / "on-link").write_text("".join(f"{entry}\n" for entry in on_link)) + env = { + **os.environ, + "STALE_ROUTES_DRY": "1", + "STALE_ROUTES_TABLE": str(self.base / "table"), + "STALE_ROUTES_ONLINK": str(self.base / "on-link"), + "STALE_ROUTES_NOW": "2026-11-19 11:30", + "STALE_ROUTES_DEFAULT": "1" if has_default else "0", + } + result = subprocess.run(["/bin/bash", SCRIPT], env=env, text=True, capture_output=True, timeout=10) + self.assertEqual(result.returncode, 0, result.stderr) + return [line for line in result.stdout.splitlines() if line.startswith("would run:")] + + def test_which_routes_are_deleted(self): + cases = [ + ("host route via a gateway from an old network", "1.1.1.1 172.20.10.1 UGHS en0\n", + ["10.31.0.1 en0"], ["would run: route -n delete -host 1.1.1.1 172.20.10.1"]), + ("host route via the current gateway", "16.15.183.16 10.31.0.1 UGHS en0\n", + ["10.31.0.1 en0"], []), + ("gateway on-link, but on another interface", "3.68.124.168 10.31.0.1 UGHS en1\n", + ["10.31.0.1 en0"], ["would run: route -n delete -host 3.68.124.168 10.31.0.1"]), + ("dynamic host route", "3.68.124.168 172.20.10.1 UGH en0\n", + ["10.31.0.1 en0"], []), + ("static network route", "100.64/10 172.20.10.1 UGSc en0\n", + ["10.31.0.1 en0"], []), + ("default route", "default 172.20.10.1 UGScg en0\n", + ["10.31.0.1 en0"], []), + ("interface route without a gateway address", "10.52.5.71 link#14 UHS utun4\n", + ["10.31.0.1 en0"], []), + ] + for name, table, on_link, expected in cases: + with self.subTest(name): + self.assertEqual(self.run_script(table, on_link), expected) + + def test_deletes_every_route_via_a_stale_gateway_once(self): + table = ( + "1.1.1.1 172.20.10.1 UGHS en0\n" + "2.18.244.4 172.20.10.1 UGHS en0\n" + "16.15.183.16 10.31.0.1 UGHS en0\n" + ) + self.assertEqual( + self.run_script(table, ["10.31.0.1 en0"]), + [ + "would run: route -n delete -host 1.1.1.1 172.20.10.1", + "would run: route -n delete -host 2.18.244.4 172.20.10.1", + ], + ) + + def test_leaves_everything_alone_without_a_default_route(self): + table = "1.1.1.1 172.20.10.1 UGHS en0\n" + self.assertEqual(self.run_script(table, [], has_default=False), []) + + +if __name__ == "__main__": + unittest.main() -- knotmirror 0.0.1