diff --git a/README.md b/README.md index 82be863..82d29b0 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,7 @@ Plugin package that fixes and enhances the Tailscale integration on GL.iNet rout or not Tailscale or the kill switch is on, and is kept current as internet connections change — on every connection event, and re-checked by the watchdog about every 30 seconds. Applied automatically — no user action required beyond GL's own setting. +- **IoT Network Access** — bidirectional firewall forwardings between IoT network (br-iot) and Tailscale interface (tailscale0), IoT subnet route advertisement, and policy route fixup that ensure IoT clients can use exit nodes and are covered by the kill switch. Requires the IoT Network feature, which the firmware creates since 4.9.0; the toggle is hidden on older firmware, which has no iot network. The kill switch has covered iot since v1.0.22; this adds the remote-access side (route advertisement and the forwardings), which v1.0.22 does not do. - **Tailscale SSH** — GUI toggle for `tailscale set --ssh`, which enables Tailscale's ACL-based SSH authentication. Most users don't need this — SSH to the router's tailscale IP already works via the normal SSH daemon (Dropbear) without any extra setup. Enable this only if you specifically want identity-based access controlled by a Tailscale SSH ACL rule (Access Controls → Tailscale SSH tab). While enabled, `tailscaled` takes over port 22 for tailnet-origin traffic, which breaks SSH from LAN clients that reach the router via Tailscale subnet routing; in that case, run Dropbear on an alternate port (System → Administration → SSH Access) to keep a path open for both Tailscale and LAN clients. - **Hide Tailscale Search Domain** (v1.0.22+, optional) — off by default. GL writes your tailnet's MagicDNS suffix (`x.ts.net`) into dnsmasq's advertised domain, so every LAN client receives it over DHCP as its domain/search suffix. On firmware 4.9 GL *replaces* your local domain rather than appending to it, which also breaks `.lan` name resolution. When enabled, the plugin keeps your own local domain as the advertised value and re-asserts it whenever GL writes the suffix back — including against the background re-assert loop 4.9 runs for up to a minute after an interface comes up. Tailnet name resolution is deliberately left intact: the router's split-DNS entry for `ts.net` is untouched, so an explicit `host.x.ts.net` still resolves and only the broadcast hint goes away. This removes one passive indicator that a device sits behind a Tailscale node — it does not hide Tailscale generally, since the router still holds a tailnet address and still answers `ts.net` queries. Turning it off restores GL's behavior at the next network event rather than instantly. - **Tailscale Version Manager** — installed vs latest version display, one-click update using space-optimized combined binaries, factory restore. Since v1.0.22, versions are compared as full build strings, so an upstream *rebuild* — same Tailscale version re-released with a new build suffix, as happened with the 2026-06-04 `ipnbus` fix — is detected and offered as "(rebuild)" instead of reporting "already at latest" forever. Downloads are bounded by connect and overall timeouts with a guaranteed terminal status, so a dead or crawling network path produces a clean error instead of a stuck "Downloading..." spinner. diff --git a/pkg/control b/pkg/control index d7cd7cc..30a616f 100644 --- a/pkg/control +++ b/pkg/control @@ -7,8 +7,8 @@ Priority: optional Description: Tailscale enhancements for GL.iNet routers Adds features that complement GL's native Tailscale integration: a kernel-level policy-routing kill switch (IPv4 and IPv6) that - survives tailscaled crashes, guest network routing through the - Tailscale exit node, optional Tailscale SSH toggle for ACL-based + survives tailscaled crashes, guest and IoT network routing through + the Tailscale exit node, optional Tailscale SSH toggle for ACL-based authentication, and a Tailscale binary version manager. On firmware 4.9+, the plugin auto-adapts to coexist with GL's native Tailscale features. diff --git a/pkg/prerm b/pkg/prerm index c9b2724..0a98dfd 100644 --- a/pkg/prerm +++ b/pkg/prerm @@ -200,12 +200,25 @@ else logger -t ts-fix "prerm: guest_net helper not found in /usr/bin/ts-fix-reapply - guest route fixup (to table main) not removed" fi -# Remove guest routing firewall forwardings, the kill switch's lan -> tailscale0 tunnel path, +# Remove IoT subnet policy route fixup. The IoT network comes from reapply's own tested helper +# (iot_net: ipcalc.sh, right for any prefix length — zeroing the last octet is right only for a +# /24 and misses the rule on any other IoT network). It is loaded from the installed reapply, +# which opkg deletes only after this script, rather than copied here. The eval runs nothing but +# the marked helper block of our own root-owned package file. +eval "$(awk '/^# ---8<--- iot_net/,/^# ---8<--- end iot_net/' /usr/bin/ts-fix-reapply 2>/dev/null)" +if command -v iot_net >/dev/null 2>&1; then + _iot=$(iot_net) + [ -n "$_iot" ] && ip rule del to "$_iot" table main 2>/dev/null +else + logger -t ts-fix "prerm: iot_net helper not found in /usr/bin/ts-fix-reapply - IoT route fixup (to table main) not removed" +fi + +# Remove guest and IoT routing firewall forwardings, the kill switch's lan -> tailscale0 tunnel path, # and legacy kill switch rules. ts_fix_lan2ts is normally dropped by the disarm above (only when # the engine recorded creating it); this catches the case where disarm never ran or did not # finish. The name is ours — GL's own lan -> tailscale0 forwarding is a different section and is # not reachable by this delete. -for section in ts_fix_guest2ts ts_fix_ts2guest ts_fix_lan2ts ts_ks_lan2wan ts_ks_guest2wan; do +for section in ts_fix_guest2ts ts_fix_ts2guest ts_fix_iot2ts ts_fix_ts2iot ts_fix_lan2ts ts_ks_lan2wan ts_ks_guest2wan; do uci -q delete firewall."$section" 2>/dev/null done diff --git a/src/config/ts-fix b/src/config/ts-fix index 909efc1..0af373b 100644 --- a/src/config/ts-fix +++ b/src/config/ts-fix @@ -5,6 +5,7 @@ config settings 'settings' option hide_ts_domain '0' option user_domain '' option route_guest '0' + option route_iot '0' option tailscale_ssh '0' option ks_upgrade_hint_pending '0' option wan_masq6_set_by_plugin '0' diff --git a/src/rpc/ts-fix b/src/rpc/ts-fix index de4b526..845fb53 100644 --- a/src/rpc/ts-fix +++ b/src/rpc/ts-fix @@ -160,6 +160,25 @@ local function get_guest_subnet() return cidr end +-- Helper: get the IoT network as NETWORK/PREFIX for br-iot's IPv4 address, or nil. The network +-- comes from /bin/ipcalc.sh, the tool GL's own script relies on, never from zeroing the last +-- octet: that is right only for a /24 (192.168.10.1/23 is network 192.168.10.0/23), and a wrong +-- network misses GL's "from " rule in fix_iot_policy_route and advertises a route that is +-- not a network address. Both values end up in "sh -c" strings: the address capture admits only +-- digits, dots and one slash, and the result must match the CIDR pattern below or nil is returned. +local function get_iot_subnet() + local data = exec("ip -4 addr show br-iot 2>/dev/null") or "" + local addr = data:match("inet (%d+%.%d+%.%d+%.%d+/%d+)") + if not addr then return nil end + local calc = exec("/bin/ipcalc.sh " .. addr .. " 2>/dev/null") or "" + local network = calc:match("NETWORK=([^\n]*)") + local prefix = calc:match("PREFIX=([^\n]*)") + if not network or not prefix then return nil end + local cidr = network .. "/" .. prefix + if not cidr:match("^%d+%.%d+%.%d+%.%d+/%d+$") then return nil end + return cidr +end + -- Helper: get currently advertised routes from tailscale prefs local function get_current_routes() local data = exec("/usr/sbin/tailscale debug prefs 2>/dev/null") @@ -213,6 +232,34 @@ local function update_guest_route(enable) exec("/usr/sbin/tailscale set --advertise-routes=" .. routes_str .. " 2>/dev/null") end +-- Helper: update advertised routes, adding or removing IoT subnet +local function update_iot_route(enable) + local iot_subnet = get_iot_subnet() + if not iot_subnet then return end + + local routes = get_current_routes() + local new_routes = {} + local found = false + + for _, route in ipairs(routes) do + if route == iot_subnet then + found = true + if enable then + new_routes[#new_routes + 1] = route + end + else + new_routes[#new_routes + 1] = route + end + end + + if enable and not found then + new_routes[#new_routes + 1] = iot_subnet + end + + local routes_str = table.concat(new_routes, ",") + exec("/usr/sbin/tailscale set --advertise-routes=" .. routes_str .. " 2>/dev/null") +end + -- Helper: set guest→tailscale firewall forwardings enabled/disabled local function set_guest_ts_fw(enabled) local c = uci.cursor() @@ -244,6 +291,37 @@ local function set_guest_ts_fw(enabled) return changed end +-- Helper: set iot→tailscale firewall forwardings enabled/disabled +local function set_iot_ts_fw(enabled) + local c = uci.cursor() + local changed = false + + local forwardings = { + {name = "ts_fix_iot2ts", src = "iot", dest = "tailscale0"}, + {name = "ts_fix_ts2iot", src = "tailscale0", dest = "iot"}, + } + + for _, fwd in ipairs(forwardings) do + local exists = c:get(FW_CONFIG, fwd.name) + if exists and not enabled then + c:delete(FW_CONFIG, fwd.name) + changed = true + elseif not exists and enabled then + c:set(FW_CONFIG, fwd.name, "forwarding") + c:set(FW_CONFIG, fwd.name, "src", fwd.src) + c:set(FW_CONFIG, fwd.name, "dest", fwd.dest) + changed = true + end + end + + if changed then + c:commit(FW_CONFIG) + ngx.pipe.spawn({"/etc/init.d/firewall", "reload"}) + end + + return changed +end + -- Helper: ensure tailscale0 zone masquerade is enabled (defense-in-depth -- for cross-subnet routing — Tailscale's built-in SNAT can fail to -- reinitialize after daemon restart on fw3 kernels). @@ -388,6 +466,30 @@ local function fix_guest_policy_route(enabled) end end +-- Helper: fix IoT subnet policy route for exit node compatibility. Mirrors +-- fix_guest_policy_route above, against br-iot: GL's gl_tailscale adds +-- "from lookup main" at priority 0 whenever a Custom Exit Node is +-- set and the IoT network is enabled, which routes all IoT client traffic to +-- the main table → WAN, bypassing the exit node and the kill switch's routing +-- layer. Replaced with the destination-based "to table main". +-- Since v1.0.22 the kill switch covers iot (its engine's source-rule swap keeps +-- this same rule in place of GL's "from" rule), so the disabled path re-asserts +-- the engine's layer the same way the guest path does. +local function fix_iot_policy_route(enabled) + local iot_subnet = get_iot_subnet() + if not iot_subnet then return end + + -- Always clean up both rule types to avoid duplicates + exec("ip rule del from " .. iot_subnet .. " lookup main 2>/dev/null") + exec("ip rule del to " .. iot_subnet .. " table main 2>/dev/null") + + if enabled then + exec("ip rule add to " .. iot_subnet .. " table main priority 0") + else + exec("/usr/bin/ts-fix-ks rules-ensure /dev/null 2>&1") + end +end + -- Firmware detection — on GL 4.9+, some features overlap with GL's native -- Tailscale enhancements. We keep the plugin fully active but hide UI for -- features GL provides natively (Advertise Exit Node) and skip the @@ -442,6 +544,7 @@ function M.get_config() res.advertise_exit_node = c:get(TS_FIX_CONFIG, "settings", "advertise_exit_node") == "1" res.kill_switch = c:get(TS_FIX_CONFIG, "settings", "kill_switch") == "1" res.route_guest = c:get(TS_FIX_CONFIG, "settings", "route_guest") == "1" + res.route_iot = c:get(TS_FIX_CONFIG, "settings", "route_iot") == "1" res.tailscale_ssh = c:get(TS_FIX_CONFIG, "settings", "tailscale_ssh") == "1" res.ks_follow_exit_node = c:get(TS_FIX_CONFIG, "settings", "ks_follow_exit_node") == "1" res.hide_ts_domain = c:get(TS_FIX_CONFIG, "settings", "hide_ts_domain") == "1" @@ -535,6 +638,9 @@ function M.get_config() -- Guest routing firewall forwarding state res.route_guest_fw_active = c:get(FW_CONFIG, "ts_fix_guest2ts") ~= nil + -- IoT routing firewall forwarding state + res.route_iot_fw_active = c:get(FW_CONFIG, "ts_fix_iot2ts") ~= nil + -- Tailscale0 zone masquerade state — reported active only when BOTH -- families' masquerade are set (mirrors kill_switch_fw_active semantics; -- a torn state surfaces in the UI rather than silently claiming @@ -553,6 +659,7 @@ end @in bool ?advertise_exit_node Enable/disable exit node advertisement @in bool ?kill_switch Enable/disable kill switch @in bool ?route_guest Enable/disable guest network routing via Tailscale + @in bool ?route_iot Enable/disable IoT network routing via Tailscale @in bool ?tailscale_ssh Enable/disable Tailscale SSH server @in bool ?ks_follow_exit_node Kill switch mirrors GL's Custom Exit Node setting (watchdog-enforced) @in bool ?hide_ts_domain Stop advertising the tailnet search domain to LAN clients @@ -629,6 +736,14 @@ function M.set_config(params) route_changed = true end + -- Handle route_iot + if params.route_iot ~= nil then + local val = params.route_iot and "1" or "0" + c:set(TS_FIX_CONFIG, "settings", "route_iot", val) + set_iot_ts_fw(params.route_iot) + route_changed = true + end + -- Handle tailscale_ssh if params.tailscale_ssh ~= nil then local val = params.tailscale_ssh and "1" or "0" @@ -695,7 +810,7 @@ function M.set_config(params) end end - -- Apply route changes (only when route_guest was actually changed) + -- Apply route changes (only when route_guest or route_iot was actually changed) if route_changed then local rg = c:get(TS_FIX_CONFIG, "settings", "route_guest") == "1" update_guest_route(rg) @@ -703,6 +818,11 @@ function M.set_config(params) -- node) with "to " (allows it). Must run after -- update_guest_route which triggers Tailscale to create its rules. fix_guest_policy_route(rg) + + local ri = c:get(TS_FIX_CONFIG, "settings", "route_iot") == "1" + update_iot_route(ri) + -- Same policy route fixup for the IoT subnet. + fix_iot_policy_route(ri) end -- Ensure tailscale0 zone masquerade (defense-in-depth for subnet routing + diff --git a/src/scripts/ts-fix-reapply b/src/scripts/ts-fix-reapply index 2a2ff2f..203c542 100644 --- a/src/scripts/ts-fix-reapply +++ b/src/scripts/ts-fix-reapply @@ -135,7 +135,7 @@ ts_domain_clean() { } # ---8<--- end ts_domain_clean ---8<--- -# Guest network helpers for Route Guest. +# Guest network helper for Route Guest. # # guest_net echoes br-guest's IPv4 network as NETWORK/PREFIX, or nothing when br-guest has no IPv4 # address or ipcalc fails. The network comes from ipcalc.sh, the tool GL's own script relies on to @@ -145,11 +145,6 @@ ts_domain_clean() { # is read, as the RPC reads it, and only one of the form a.b.c.d/N is handed to ipcalc: for an # empty or prefix-less argument ipcalc answers 0.0.0.0/0, which must never reach the code below. # -# route_list_drop echoes the comma-separated route list $1 without the entry $2, comparing whole -# entries as strings. Removal used to run sed with the subnet inside the program, where its "/" -# ended the s command — sed failed, and its empty output took the --advertise-routes= branch — and -# its dots would have matched any character. -# # IPCALC exists so tests/unit/test-guest-net.sh can substitute a fake; nothing else sets it. # ---8<--- guest_net (unit-tested by tests/unit/test-guest-net.sh) ---8<--- IPCALC=${IPCALC:-/bin/ipcalc.sh} @@ -165,7 +160,49 @@ guest_net() { $1 == "PREFIX" { p = $2 } END { if (n ~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/ && p ~ /^[0-9]+$/) print n "/" p }' } +# ---8<--- end guest_net ---8<--- + +# IoT network helper for Route IoT. +# +# iot_net echoes br-iot's IPv4 network as NETWORK/PREFIX, or nothing when br-iot has no IPv4 +# address or ipcalc fails. The network comes from ipcalc.sh, the tool GL's own script relies on to +# build its "from " rule, never from zeroing the last octet: that is right only for a +# /24. 192.168.10.1/23 is network 192.168.10.0/23, and 192.168.10.0/23 would miss GL's rule in +# the swap below and advertise a route that is not a network address. Only the first IPv4 address +# is read, as the RPC reads it, and only one of the form a.b.c.d/N is handed to ipcalc: for an +# empty or prefix-less argument ipcalc answers 0.0.0.0/0, which must never reach the code below. +# br-iot is absent on firmware without the IoT network (created since 4.9.0, disabled by default), +# and this echoes nothing then. +# +# IPCALC exists so tests/unit/test-iot-net.sh can substitute a fake; nothing else sets it. +# +# This block carries its own markers because prerm evals it on its own; IPCALC is defaulted again +# here so the block stands alone. +# ---8<--- iot_net (unit-tested by tests/unit/test-iot-net.sh) ---8<--- +IPCALC=${IPCALC:-/bin/ipcalc.sh} + +iot_net() { + local addr out + addr=$(ip -4 addr show br-iot 2>/dev/null | + awk '$1 == "inet" && $2 ~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\/[0-9]+$/ { print $2; exit }') + [ -n "$addr" ] || return 0 + out=$("$IPCALC" "$addr" 2>/dev/null) || return 0 + printf '%s\n' "$out" | awk -F= ' + $1 == "NETWORK" { n = $2 } + $1 == "PREFIX" { p = $2 } + END { if (n ~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/ && p ~ /^[0-9]+$/) print n "/" p }' +} +# ---8<--- end iot_net ---8<--- +# route_list_drop echoes the comma-separated route list $1 without the entry $2, comparing whole +# entries as strings. Removal used to run sed with the subnet inside the program, where its "/" +# ended the s command — sed failed, and its empty output took the --advertise-routes= branch — and +# its dots would have matched any character. +# +# Shared: Route Guest and Route IoT both remove a subnet this way, so it is kept in its own block +# rather than in either network's helper block. Its cases live in tests/unit/test-guest-net.sh, +# where they already were; the Route IoT advertisement block only calls it. +# ---8<--- route_list_drop (unit-tested by tests/unit/test-guest-net.sh) ---8<--- route_list_drop() { local out="" r for r in $(printf '%s\n' "$1" | tr ',' ' '); do @@ -173,7 +210,7 @@ route_list_drop() { done printf '%s\n' "$out" } -# ---8<--- end guest_net ---8<--- +# ---8<--- end route_list_drop ---8<--- # ---8<--- ts_state # The kill switch's intent, read as the engine reads it (_ks_intent in /usr/bin/ts-fix-ks). This @@ -261,6 +298,10 @@ if [ "$ts_en" = "0" ]; then _gs=$(guest_net) [ -n "$_gs" ] && ip rule del to "$_gs" table main 2>/dev/null + # Remove IoT policy route fixup + _iot=$(iot_net) + [ -n "$_iot" ] && ip rule del to "$_iot" table main 2>/dev/null + # Remove guest subnet from advertised routes (pgrep guard — avoids # spawning ~60MB Go process if daemon already stopped during disable) if [ -n "$_gs" ] && pgrep tailscaled >/dev/null 2>&1; then @@ -279,18 +320,41 @@ if [ "$ts_en" = "0" ]; then esac fi + # Remove IoT subnet from advertised routes (pgrep guard — avoids + # spawning ~60MB Go process if daemon already stopped during disable) + if [ -n "$_iot" ] && pgrep tailscaled >/dev/null 2>&1; then + _cur=$(timeout 10 /usr/sbin/tailscale debug prefs 2>/dev/null | jsonfilter -e '@.AdvertiseRoutes[*]' 2>/dev/null | tr '\n' ',') + case ",$_cur," in + *",$_iot,"*) + _new=$(route_list_drop "$_cur" "$_iot") + if [ -n "$_new" ]; then + timeout 10 /usr/sbin/tailscale set --advertise-routes="$_new" 2>/dev/null || \ + logger -t ts-fix "route iot off: tailscale set --advertise-routes failed or timed out (rc $?) - the IoT subnet may still be advertised" + else + timeout 10 /usr/sbin/tailscale set --advertise-routes= 2>/dev/null || \ + logger -t ts-fix "route iot off: tailscale set --advertise-routes= failed or timed out (rc $?) - the IoT subnet may still be advertised" + fi + ;; + esac + fi + # Remove legacy UCI firewall kill switch rules (pre-v1.0.9) for section in ts_ks_lan2wan ts_ks_guest2wan; do uci -q delete firewall.$section 2>/dev/null done - # Remove guest<->tailscale firewall forwardings and masquerade + # Remove guest<->tailscale and iot<->tailscale firewall forwardings and masquerade _fw=0 [ -n "$(uci -q get firewall.ts_fix_guest2ts)" ] && { uci -q delete firewall.ts_fix_guest2ts uci -q delete firewall.ts_fix_ts2guest _fw=1 } + [ -n "$(uci -q get firewall.ts_fix_iot2ts)" ] && { + uci -q delete firewall.ts_fix_iot2ts + uci -q delete firewall.ts_fix_ts2iot + _fw=1 + } # masq6 (IPv6) is plugin-owned on ALL firmware (GL never sets it), so clear # it here regardless of firmware. masq (IPv4) is GL's on 4.9+ — only clear # it pre-4.9 (deleting on 4.9 would trample GL's state). @@ -327,6 +391,7 @@ if [ "$ts_en" = "0" ]; then # Reset all ts-fix UCI settings to 0 uci -q set ts-fix.settings.kill_switch=0 uci -q set ts-fix.settings.route_guest=0 + uci -q set ts-fix.settings.route_iot=0 uci -q set ts-fix.settings.advertise_exit_node=0 uci -q set ts-fix.settings.tailscale_ssh=0 uci commit ts-fix @@ -667,6 +732,54 @@ else fi # ---8<--- end route guest advertise ---8<--- +# Re-apply IoT subnet route advertisement +route_iot=$(uci -q get ts-fix.settings.route_iot) +iot_subnet=$(iot_net) +# ---8<--- route iot advertise ---8<--- +if [ "$route_iot" = "1" ]; then + if [ -n "$iot_subnet" ]; then + # Get current routes, add IoT subnet if missing. --advertise-routes REPLACES the whole + # list, so the routes are read on their own first: a read that fails or times out prints + # nothing, and nothing must not pass for "no routes" — the add would then drop every other + # advertised route. Such a pass writes nothing and leaves the daemon-pending flag, as a + # pass with the daemon down does, so the watchdog retries it. + if prefs=$(timeout 10 /usr/sbin/tailscale debug prefs 2>/dev/null) && [ -n "$prefs" ]; then + current=$(printf '%s\n' "$prefs" | jsonfilter -e '@.AdvertiseRoutes[*]' 2>/dev/null | tr '\n' ',') + case ",$current," in + *",$iot_subnet,"*) ;; # already present + *) + new_routes="${current}${iot_subnet}" + new_routes=$(echo "$new_routes" | sed 's/,$//') + timeout 10 /usr/sbin/tailscale set --advertise-routes="$new_routes" 2>/dev/null || \ + logger -t ts-fix "route iot: tailscale set --advertise-routes failed or timed out (rc $?) - the IoT subnet is not advertised" + ;; + esac + else + logger -t ts-fix "route iot: tailscale debug prefs failed or timed out - advertised routes unknown, IoT subnet not added; pending for the watchdog's retry" + routes_unread=1 + fi + fi +else + # Remove IoT subnet from advertised routes if present. A failed read prints nothing, which + # matches no route, so nothing is written — as with the daemon down. + if [ -n "$iot_subnet" ]; then + current=$(timeout 10 /usr/sbin/tailscale debug prefs 2>/dev/null | jsonfilter -e '@.AdvertiseRoutes[*]' 2>/dev/null | tr '\n' ',') + case ",$current," in + *",$iot_subnet,"*) + new_routes=$(route_list_drop "$current" "$iot_subnet") + if [ -n "$new_routes" ]; then + timeout 10 /usr/sbin/tailscale set --advertise-routes="$new_routes" 2>/dev/null || \ + logger -t ts-fix "route iot off: tailscale set --advertise-routes failed or timed out (rc $?) - the IoT subnet may still be advertised" + else + timeout 10 /usr/sbin/tailscale set --advertise-routes= 2>/dev/null || \ + logger -t ts-fix "route iot off: tailscale set --advertise-routes= failed or timed out (rc $?) - the IoT subnet may still be advertised" + fi + ;; + esac + fi +fi +# ---8<--- end route iot advertise ---8<--- + # Fix guest subnet policy route for exit node compatibility. # GL's gl_tailscale adds "from lookup main" at priority 0 # whenever a Custom Exit Node is set and the guest network is enabled. This @@ -690,6 +803,30 @@ else } fi + +# Fix IoT subnet policy route for exit node compatibility. GL's gl_tailscale adds +# "from lookup main" at priority 0 whenever a Custom Exit Node is set and +# the IoT network is enabled. This blocks IoT clients from using the exit node. Replace +# with "to " (destination-based, the shape of GL's own LAN rule). +if [ "$route_iot" = "1" ] && [ -n "$iot_subnet" ]; then + ip rule del from "$iot_subnet" lookup main 2>/dev/null + ip rule del to "$iot_subnet" table main 2>/dev/null + ip rule add to "$iot_subnet" table main priority 0 +else + # Clean up our destination-based rule if present + _is=$(iot_net) + [ -n "$_is" ] && { + ip rule del to "$_is" table main 2>/dev/null + # That is also the kill switch's own rule: while armed, the engine's source-rule swap keeps + # exactly this "to " rule in place of GL's "from" rule. Put it back at once rather + # than leave IoT-bound traffic to the exit node's table until the next engine pass. + # rules-ensure takes no lock and self-gates on armed intent and Router mode, so on a + # disarmed router it is a no-op. + /usr/bin/ts-fix-ks rules-ensure " "" "$(grep -nF '".0/"' "$RPC")" report GUARD "RPC derives the network with /bin/ipcalc.sh" "1" \ - "$(grep -cF '"/bin/ipcalc.sh ' "$RPC")" + "$(awk '/^local function get_guest_subnet/,/^end/' "$RPC" | grep -cF '"/bin/ipcalc.sh ')" # Route Guest's advertisement block, extracted between its markers. --advertise-routes REPLACES # the whole list, so the add reads the current routes first — and a read that fails or times diff --git a/tests/unit/test-iot-net.sh b/tests/unit/test-iot-net.sh new file mode 100644 index 0000000..ff48172 --- /dev/null +++ b/tests/unit/test-iot-net.sh @@ -0,0 +1,259 @@ +#!/bin/sh +# Unit test for iot_net() and route_list_drop() in src/scripts/ts-fix-reapply (Route IoT), and +# for reapply's Route IoT advertisement block (the RIA cases at the end, helper mode only). +# Runs on the dev laptop, no router required: +# sh tests/unit/test-iot-net.sh the shipping helper, extracted from reapply +# sh tests/unit/test-iot-net.sh legacy negative control: the pre-fix code copied below, +# run against the cases it can answer — every DEFECT +# case must FAIL there, every GUARD case pass +# +# The helper is extracted from the real source between its marker comments rather than duplicated +# here, so this tests shipping code. If the markers or the names change, extraction yields nothing +# and the run fails loudly — which is the intended signal. +# +# `ip` is shimmed by a function that answers only "ip -4 addr show br-iot"; any other call fails +# the run. IPCALC points at a fake in a temp dir that logs its calls. For the addresses below it +# prints the lines GL's /bin/ipcalc.sh prints for them; for an empty or prefix-less argument it +# prints NETWORK=0.0.0.0 and PREFIX=0, which is what the real script answers there too — so a +# helper that ever handed ipcalc such an argument would fail the no-address cases. + +MODE=${1:-helper} +SRC="$(dirname "$0")/../../src/scripts/ts-fix-reapply" +RPC="$(dirname "$0")/../../src/rpc/ts-fix" + +T=$(mktemp -d) || { echo "FAIL: mktemp"; exit 1; } +trap 'rm -rf "$T"' EXIT +FAKE_IPCALC_LOG="$T/ipcalc.calls" +export FAKE_IPCALC_LOG + +cat > "$T/ipcalc.sh" <<'EOF' +#!/bin/sh +printf '%s:%s\n' "$#" "$*" >> "$FAKE_IPCALC_LOG" +case "$#:$1" in + 1:192.168.11.1/23) + printf 'IP=192.168.11.1\nNETMASK=255.255.254.0\nBROADCAST=192.168.11.255\n' + printf 'NETWORK=192.168.10.0\nPREFIX=23\n' ;; + 1:192.168.10.1/24) + printf 'IP=192.168.10.1\nNETMASK=255.255.255.0\nBROADCAST=192.168.10.255\n' + printf 'NETWORK=192.168.10.0\nPREFIX=24\n' ;; + 1:10.76.0.1/24) echo "ipcalc: simulated failure" >&2; exit 1 ;; + 1:10.77.0.1/24) ;; + 1:10.78.0.1/24) printf 'NETWORK=10.78.0.0\nPREFIX=24\n'; exit 1 ;; + 1:10.79.0.1/24) printf 'NETWORK=10.79.0.0\n' ;; + 1:10.80.0.1/24) printf 'NETWORK=10.80.0.0 x\nPREFIX=24\n' ;; + 1:*/*) exit 1 ;; + *) printf 'NETWORK=0.0.0.0\nPREFIX=0\n' ;; +esac +EOF +chmod +x "$T/ipcalc.sh" + +INET="" +ip() { + if [ "$*" != "-4 addr show br-iot" ]; then + printf 'ip %s\n' "$*" >> "$T/unexpected" + return 1 + fi + printf '7: br-iot: mtu 1500 qdisc noqueue state UP\n' + [ -z "$INET" ] || printf '%s\n' "$INET" +} +line() { printf ' inet %s scope global br-iot' "$1"; } +extract() { + awk '/^# ---8<--- route_list_drop/,/^# ---8<--- end route_list_drop/' "$SRC" + awk '/^# ---8<--- iot_net/,/^# ---8<--- end iot_net/' "$SRC" +} + +if [ "$MODE" = legacy ]; then + # The pre-fix code, copied from ts-fix-reapply as it stood before this change: the derivation + # used at its three sites, and the route removal (the second removal site is the same + # expression over _cur/_iot). + iot_impl() { + ip -4 addr show br-iot 2>/dev/null | awk '/inet /{print $2}' | sed 's|\.[0-9]*/|.0/|' + } + drop_impl() { + echo "$1" | sed "s/${2},//;s/,${2}//;s/^${2}$//;s/,$//" + } +else + IPCALC="$T/ipcalc.sh" + eval "$(extract)" + if ! command -v iot_net >/dev/null 2>&1 || ! command -v route_list_drop >/dev/null 2>&1 + then + echo "FAIL: could not extract iot_net/route_list_drop from $SRC (markers missing?)" + exit 1 + fi + iot_impl() { iot_net; } + drop_impl() { route_list_drop "$1" "$2"; } +fi + +fails=0 +report() { # $1 = class, $2 = description, $3 = want, $4 = got + if [ "$3" = "$4" ]; then + printf 'ok %-6s %s\n' "$1" "$2" + else + printf 'FAIL %-6s %s\n want=[%s]\n got =[%s]\n' "$1" "$2" "$3" "$4" + fails=$((fails + 1)) + fi +} +net() { # $1 = class, $2 = description, $3 = br-iot inet line(s), $4 = expected output + INET=$3 + rm -f "$FAKE_IPCALC_LOG" + report "$1" "$2" "$4" "$(iot_impl)" +} +not_called() { # after a net case: the fake must not have been invoked at all + got="no ipcalc call" + [ -e "$FAKE_IPCALC_LOG" ] && got=$(cat "$FAKE_IPCALC_LOG") + report GUARD "$1" "no ipcalc call" "$got" +} +drop() { # $1 = class, $2 = description, $3 = route list, $4 = entry to drop, $5 = expected + report "$1" "$2" "$5" "$(drop_impl "$3" "$4")" +} +default_ipcalc() { # run in a subshell: what IPCALC is when nothing overrides it + unset IPCALC + eval "$(extract)" + printf '%s' "$IPCALC" +} + +net DEFECT "/23 iot -> true network, not a.b.c.0" "$(line 192.168.11.1/23)" "192.168.10.0/23" +net GUARD "/24 iot -> network unchanged" "$(line 192.168.10.1/24)" "192.168.10.0/24" +net GUARD "no IPv4 address on br-iot -> nothing" "" "" +[ "$MODE" = legacy ] || not_called " ...and ipcalc is not called without an address" +net DEFECT "two IPv4 addresses -> the first one's network, as the RPC reads it" \ + "$(line 192.168.10.1/24) +$(line 10.99.0.1/16)" "192.168.10.0/24" + +drop DEFECT "drop the IoT route from the middle" \ + "192.168.8.0/24,192.168.10.0/24,0.0.0.0/0," "192.168.10.0/24" "192.168.8.0/24,0.0.0.0/0" +drop DEFECT "drop it from the end (where the add path puts it)" \ + "192.168.8.0/24,0.0.0.0/0,::/0,192.168.10.0/24," "192.168.10.0/24" "192.168.8.0/24,0.0.0.0/0,::/0" +drop DEFECT "drop it from the front" "192.168.10.0/24,::/0," "192.168.10.0/24" "::/0" +drop GUARD "drop the only route -> empty (the caller then clears)" \ + "192.168.10.0/24," "192.168.10.0/24" "" +drop DEFECT "dots are literal: 192.168.10.0/24 never matches 192x168x10x0/24" \ + "192x168x10x0/24,10.0.0.0/8," "192.168.10.0/24" "192x168x10x0/24,10.0.0.0/8" +drop DEFECT "whole entries only: dropping 192.168.10.0/2 leaves 192.168.10.0/24" \ + "10.0.0.0/8,192.168.10.0/24," "192.168.10.0/2" "10.0.0.0/8,192.168.10.0/24" + +if [ "$MODE" != legacy ]; then + net GUARD "ipcalc fails -> nothing" "$(line 10.76.0.1/24)" "" + net GUARD "ipcalc prints nothing -> nothing" "$(line 10.77.0.1/24)" "" + net GUARD "ipcalc prints, then fails -> nothing" "$(line 10.78.0.1/24)" "" + net GUARD "ipcalc prints NETWORK only -> nothing" "$(line 10.79.0.1/24)" "" + net GUARD "ipcalc prints a malformed NETWORK -> nothing" "$(line 10.80.0.1/24)" "" + net GUARD "address without a prefix -> nothing" "$(line 192.168.10.1)" "" + not_called " ...and a prefix-less address never reaches ipcalc (it would answer 0.0.0.0/0)" + _saved=$IPCALC; IPCALC="$T/missing" + net GUARD "ipcalc missing -> nothing" "$(line 192.168.11.1/23)" "" + IPCALC=$_saved + report GUARD "IPCALC defaults to /bin/ipcalc.sh" "/bin/ipcalc.sh" "$(default_ipcalc)" + + # Static checks on the source files. + report GUARD "the /24 sed shortcut no longer appears in reapply" "" \ + "$(grep -nF 's|\.[0-9]*/|.0/|' "$SRC")" + report GUARD "reapply reads br-iot's address in one place (the helper)" "1" \ + "$(grep -c 'ip -4 addr show br-iot' "$SRC")" + report GUARD "no sed program in reapply interpolates the IoT subnet" "" \ + "$(grep -nE 'sed .*\$\{?(_iot|iot_subnet)' "$SRC")" + report GUARD "RPC no longer builds a.b.c.0/" "" "$(grep -nF '".0/"' "$RPC")" + report GUARD "RPC derives the network with /bin/ipcalc.sh" "1" \ + "$(awk '/^local function get_iot_subnet/,/^end/' "$RPC" | grep -cF '"/bin/ipcalc.sh ')" + + # Route IoT's advertisement block, extracted between its markers. --advertise-routes REPLACES + # the whole list, so the add reads the current routes first — and a read that fails or times + # out prints nothing, which must not pass for "no routes": the add would drop every other + # route. The block's tailscale path is rewritten to the ts_cli fake; timeout, jsonfilter and + # logger are fakes too. timeout records its arguments and plays a call cut off at its bound + # (rc 124, nothing run, no output) when the command contains FAKE_EXPIRE — only that call, so + # a bounded write after an expired read still shows. ts_cli's debug prefs prints a JSON + # stand-in, or fails with FAKE_PREFS_FAIL set; jsonfilter prints FAKE_ROUTES one per line, as + # jsonfilter prints an array, and nothing for empty input. Each case runs in a subshell. + RIA=$(awk '/^# ---8<--- route iot advertise/,/^# ---8<--- end route iot advertise/' "$SRC") + ria=$(printf '%s\n' "$RIA" | sed 's|/usr/sbin/tailscale |ts_cli |g') + report GUARD "RIA the block was extracted, and all 5 tailscale calls (2 reads, 3 sets) now go to the fake" "5 0" \ + "$(printf '%s\n' "$ria" | grep -c 'ts_cli ') $(printf '%s\n' "$ria" | grep -c '/usr/sbin/tailscale')" + timeout() { + printf '%s\n' "$*" >> "$T/timeout.calls" + shift + if [ -n "$FAKE_EXPIRE" ]; then + case "$*" in *"$FAKE_EXPIRE"*) return 124 ;; esac + fi + "$@" + } + ts_cli() { + case "$1 $2" in + "debug prefs") [ -n "$FAKE_PREFS_FAIL" ] && return 1; printf '{"stand-in":1}\n' ;; + set\ *) printf '%s\n' "$*" >> "$T/set.calls" ;; + *) printf 'ts_cli %s\n' "$*" >> "$T/unexpected"; return 1 ;; + esac + } + jsonfilter() { + _in=$(cat) + [ -n "$_in" ] || return 1 + [ "$*" = "-e @.AdvertiseRoutes[*]" ] || { printf 'jsonfilter %s\n' "$*" >> "$T/unexpected"; return 1; } + for _r in $FAKE_ROUTES; do printf '%s\n' "$_r"; done + } + logger() { printf '%s\n' "$*" >> "$T/log"; } + fakes="" + for f in timeout ts_cli jsonfilter logger; do + case "$(type "$f" 2>&1)" in *function*) fakes="$fakes $f" ;; esac + done + report GUARD "RIA instrument lint: every fake resolves to its function in this shell" \ + " timeout ts_cli jsonfilter logger" "$fakes" + report GUARD "RIA instrument lint: jsonfilter prints the routes one per line, nothing for no input" \ + "a/1 +b/2|" "$(printf 'x' | FAKE_ROUTES='a/1 b/2' jsonfilter -e '@.AdvertiseRoutes[*]')|$(printf '' | jsonfilter -e '@.AdvertiseRoutes[*]')" + : > "$T/timeout.calls"; : > "$T/set.calls" + report GUARD "RIA instrument lint: the expiring call is rc 124 and runs nothing" "124" \ + "$(FAKE_EXPIRE='debug prefs' timeout 10 ts_cli debug prefs; echo "$?")" + report GUARD "RIA instrument lint: any other call still runs" "0 set --x" \ + "$(FAKE_EXPIRE='debug prefs' timeout 10 ts_cli set --x; echo "$?") $(cat "$T/set.calls")" + # ria_run -> "|" + # routes_unread is seeded here because in reapply it is Route Guest's block that initializes it + # (Route Guest runs first); this block only ever raises it to 1, so that a guest read failure + # is not cleared by the IoT pass that follows. + ria_run() { + : > "$T/set.calls"; : > "$T/timeout.calls"; : > "$T/log" + _u=$( + route_iot=$1; iot_subnet=192.168.10.0/24; FAKE_ROUTES=$2; routes_unread=0 + case "$3" in fail) FAKE_PREFS_FAIL=1 ;; expire) FAKE_EXPIRE='debug prefs' ;; esac + eval "$ria" + printf '%s' "$routes_unread" + ) + printf '%s|%s' "$(cat "$T/set.calls")" "$_u" + } + lan_up="192.168.50.0/24 0.0.0.0/0 ::/0" + got=$(ria_run 1 "$lan_up" ok) + report GUARD "RIA on, read ok: the IoT subnet is appended to every route already there" \ + "set --advertise-routes=192.168.50.0/24,0.0.0.0/0,::/0,192.168.10.0/24" "${got%|*}" + report DEFECT "RIA ... nothing is left pending" "0" "${got##*|}" + report DEFECT "RIA ... and both tailscale calls ran under timeout 10" "10 ts_cli debug prefs +10 ts_cli set --advertise-routes=192.168.50.0/24,0.0.0.0/0,::/0,192.168.10.0/24" "$(cat "$T/timeout.calls")" + got=$(ria_run 1 "" ok) + report GUARD "RIA on, read ok with no routes at all: the IoT subnet alone is right" \ + "set --advertise-routes=192.168.10.0/24" "${got%|*}" + got=$(ria_run 1 "$lan_up" fail) + report DEFECT "RIA on, the read fails: no write (the add would drop every other route)" "" "${got%|*}" + report DEFECT "RIA ... left pending for the watchdog, and logged" "1 1" \ + "${got##*|} $(grep -c 'route iot: tailscale debug prefs failed or timed out' "$T/log")" + got=$(ria_run 1 "$lan_up" expire) + report DEFECT "RIA on, the read times out: no write, left pending" "|1" "$got" + got=$(ria_run 1 "$lan_up 192.168.10.0/24" ok) + report GUARD "RIA on, the IoT subnet already advertised: no write" "" "${got%|*}" + got=$(ria_run 0 "$lan_up 192.168.10.0/24" ok) + report GUARD "RIA off, read ok: the IoT subnet is dropped, the rest kept" \ + "set --advertise-routes=192.168.50.0/24,0.0.0.0/0,::/0" "${got%|*}" + got=$(ria_run 0 "192.168.10.0/24" ok) + report GUARD "RIA off, the IoT subnet the only route: the list is cleared" "set --advertise-routes=" "${got%|*}" + got=$(ria_run 0 "$lan_up 192.168.10.0/24" fail) + report GUARD "RIA off, the read fails: no write" "" "${got%|*}" + report DEFECT "RIA ... and nothing is left pending (the flag is Route IoT's add only)" "0" "${got##*|}" + got=$(ria_run 0 "$lan_up 192.168.10.0/24" expire) + report DEFECT "RIA off, the read times out: no write" "" "${got%|*}" + unset -f timeout ts_cli jsonfilter logger +fi + +if [ -e "$T/unexpected" ]; then + printf 'FAIL unexpected ip calls:\n%s\n' "$(cat "$T/unexpected")" + fails=$((fails + 1)) +fi + +[ "$fails" -eq 0 ] && { echo "PASS (all cases, mode: $MODE)"; exit 0; } +echo "$fails case(s) failed (mode: $MODE)"; exit 1 diff --git a/tests/unit/test-ks-armdisarm.sh b/tests/unit/test-ks-armdisarm.sh index 6ba4002..70f5e30 100644 --- a/tests/unit/test-ks-armdisarm.sh +++ b/tests/unit/test-ks-armdisarm.sh @@ -4289,7 +4289,7 @@ INIT="$(dirname "$0")/../../src/init.d/ts-fix-preboot" REAPPLY="$(dirname "$0")/../../src/scripts/ts-fix-reapply" is "S16 the init script invokes preboot exactly once" 1 "$(grep -cF '/usr/bin/ts-fix-ks preboot' "$INIT")" is "S16 ... prefixed TS_FIX_KS_BOOT=1" 1 "$(grep -cE '^[[:space:]]*TS_FIX_KS_BOOT=1 /usr/bin/ts-fix-ks preboot( |$)' "$INIT")" -is "S16 reapply calls rules-ensure exactly twice (after GL's chain; after Route Guest's delete, case SG)" 2 "$(grep -cF 'ts-fix-ks rules-ensure' "$REAPPLY")" +is "S16 reapply calls rules-ensure exactly thrice (after GL's chain; after Route Guest's delete, case SG; after Route IoT's delete)" 3 "$(grep -cF 'ts-fix-ks rules-ensure' "$REAPPLY")" wait_ln=$(grep -nF 'pgrep -f "gl_tailscale restart"' "$REAPPLY" | cut -d: -f1) run_ln=$(grep -n '^# Now wait for Running state' "$REAPPLY" | cut -d: -f1) re_ln=$(grep -n '^/usr/bin/ts-fix-ks rules-ensure /dev/null 2>&1")' "$fg_else") -is "SG RPC: exactly one rules-ensure in the module" 1 "$(grep -cF 'ts-fix-ks rules-ensure' "$RPC")" +is "SG RPC: exactly two rules-ensure in the module (Route Guest's and Route IoT's)" 2 "$(grep -cF 'ts-fix-ks rules-ensure' "$RPC")" if [ -n "$fg_fn" ] && [ -n "$fg_del" ] && [ -n "$fg_if" ] && [ -n "$fg_else" ] && [ -n "$fg_end" ] && [ -n "$fg_call" ] && [ "$fg_call" -lt "$fg_end" ]; then ok "SG RPC: the call follows the deletes, in the branch taken when Route Guest is off" @@ -4402,9 +4402,9 @@ is "TS instrument lint: the fixture's calls, each classified" "1 UNBOUNDED 11 UNBOUNDED" "$(ts_set_calls "$T/ts-set-fixture")" ts_calls=$(ts_set_calls "$REAPPLY") is "TS reapply: no unbounded or unhandled call" "" "$(printf '%s\n' "$ts_calls" | grep -e UNBOUNDED -e UNHANDLED)" -is "TS reapply: ten calls, eight logging their failure and the reconcile's two" "8 2" \ +is "TS reapply: fifteen calls, thirteen logging their failure and the reconcile's two" "13 2" \ "$(printf '%s\n' "$ts_calls" | grep -c ' bounded logged$') $(printf '%s\n' "$ts_calls" | grep -c ' bounded reconcile$')" -is "TS ... and every bound is exactly timeout 10" 10 "$(grep -c 'timeout 10 /usr/sbin/tailscale set' "$REAPPLY")" +is "TS ... and every bound is exactly timeout 10" 15 "$(grep -c 'timeout 10 /usr/sbin/tailscale set' "$REAPPLY")" # Every call into the CLI, reads included, in reapply and in the watchdog, which runs reapply # synchronously. ts_cli_calls prints " bounded" when the text right before # `/usr/sbin/tailscale` is `timeout `, else " UNBOUNDED". Calls are @@ -4467,13 +4467,13 @@ is "TS instrument lint, every CLI call: the fixture's calls, each classified" "1 for f in "$REAPPLY" "$WATCHDOG"; do is "TS ${f##*/}: no unbounded call into the tailscale CLI" "" "$(ts_cli_calls "$f" | grep -e UNBOUNDED)" done -is "TS reapply: its 17 calls by subcommand, every one bounded" "4 debug -10 set +is "TS reapply: its 25 calls by subcommand, every one bounded" "7 debug +15 set 1 status 2 version" "$(ts_cli_calls "$REAPPLY" | grep ' bounded$' | cut -d' ' -f2 | sort | uniq -c | command awk '{ print $1, $2 }')" is "TS watchdog: its 4 calls by subcommand, every one bounded" "2 set 2 status" "$(ts_cli_calls "$WATCHDOG" | grep ' bounded$' | cut -d' ' -f2 | sort | uniq -c | command awk '{ print $1, $2 }')" -is "TS ... and every bound in both files is exactly timeout 10" "17 4" \ +is "TS ... and every bound in both files is exactly timeout 10" "25 4" \ "$(grep -c 'timeout 10 /usr/sbin/tailscale ' "$REAPPLY") $(grep -c 'timeout 10 /usr/sbin/tailscale ' "$WATCHDOG")" echo "--- case TF: the timeout fallback line in reapply, the watchdog and the updater" diff --git a/tests/unit/test-ts-state.sh b/tests/unit/test-ts-state.sh index 49cfad4..229592e 100644 --- a/tests/unit/test-ts-state.sh +++ b/tests/unit/test-ts-state.sh @@ -169,6 +169,7 @@ ip() { "-4 rule list priority 0") return 0 ;; "-4 route show table 52") [ -n "$FK_T52" ] && printf '%s\n' "$FK_T52"; return 0 ;; "-4 addr show br-guest") return 0 ;; + "-4 addr show br-iot") return 0 ;; esac printf 'ip %s\n' "$*" >> "$FK_DIR/unexpected" return 1