From 61810c4edd839e415415a62f08cf1ac101b72e12 Mon Sep 17 00:00:00 2001 From: Cd1s <135119404+Cd1s@users.noreply.github.com> Date: Sat, 26 Sep 2026 10:54:19 +0700 Subject: [PATCH] Devices by name, mr pause, policy route fallback: drop MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - devices: / groups: (dev module): a device = name + 1–8 MACs (+ fixed IPv4, type, owner). Referenced by name (or group:NAME) in forwards, access control, policy routes, proxy bypass, the guard, WOL and mr pause; resolved at validate / render time (router.yaml is never rewritten; old keys still work). Each device renders one dhcp-host line; a MAC, name or IP lives in dhcp.hosts or devices, not both. - mr pause DEVICE|group:x|MAC 1h / mr unpause / API dev.pause|unpause|paused: nft sets with timeouts loaded with every firewall load (not in the rendered file: no plan, no confirm window), the kernel lifts them; the reload cuts offloaded flows too. Firewall reloads are serialised. - policy_routes[].fallback: drop — the rule's traffic never leaks to another WAN when its WAN is down. - Web UI: 网络 › 设备 (inventory, groups, references, pause), 暂停 on 终端设备, an overview card for active pauses; device pickers in access control, policy routes, proxy bypass and forwards. Tests; CI (tools/ci.d/dev.sh) with real nft in network namespaces: a paused device's offloaded download stops, others keep going, DNS to the router still works, the pause survives a reload and expires; fallback: drop cuts and restores. Closes #15 Claude-Session: https://claude.ai/code/session_01HWeUjo1dmS7gBkCYHrVjCr --- docs/MODULES.md | 16 +- docs/api.md | 5 +- docs/modules/dev.md | 152 +++++++ docs/modules/dns.md | 6 +- docs/modules/fw.md | 41 +- docs/modules/net.md | 19 +- docs/modules/proxy.md | 1 + examples/lab.d/10-net.yaml | 7 + examples/lab.d/30-dns.yaml | 1 + examples/lab.d/35-dev.yaml | 13 + examples/lab.d/40-fw.yaml | 2 + examples/lab.d/55-proxy.yaml | 1 + examples/lab.d/90-guard.yaml | 2 +- mr/api_token.go | 2 + mr/config.go | 3 + mr/guard.go | 23 +- mr/main.go | 5 +- mr/mod_dev.go | 256 +++++++++++ mr/mod_dev_pause.go | 506 ++++++++++++++++++++++ mr/mod_dev_test.go | 338 +++++++++++++++ mr/mod_dns.go | 10 +- mr/mod_dns_leases.go | 4 +- mr/mod_fw.go | 20 +- mr/mod_fw_nft.go | 53 ++- mr/mod_fw_test.go | 33 +- mr/mod_mon_ct.go | 2 +- mr/mod_net.go | 25 +- mr/mod_net_render.go | 68 ++- mr/mod_net_test.go | 2 +- mr/mod_proxy.go | 20 +- mr/mod_proxy_render.go | 6 +- mr/mod_sys_event.go | 2 +- mr/mod_sys_wol.go | 10 +- mr/mode.go | 21 + mr/mode_test.go | 7 + mr/module.go | 10 +- mr/module_test.go | 2 +- mr/schema.go | 1 + rootfs/www/index.html | 1 + rootfs/www/ui/core.js | 26 +- rootfs/www/ui/dev.js | 180 ++++++++ rootfs/www/ui/dns.js | 26 +- rootfs/www/ui/fw.js | 16 +- rootfs/www/ui/net.js | 9 +- rootfs/www/ui/proxy.js | 14 +- skills/mini-router/SKILL.md | 16 +- tools/ci.d/dev.sh | 193 +++++++++ tools/mock/fixtures/config.d/dev.json | 11 + tools/mock/fixtures/dev.pause.post.json | 1 + tools/mock/fixtures/dev.paused.json | 7 + tools/mock/fixtures/dev.unpause.post.json | 1 + tools/mock/fixtures/status.json | 4 + 52 files changed, 2087 insertions(+), 113 deletions(-) create mode 100644 docs/modules/dev.md create mode 100644 examples/lab.d/35-dev.yaml create mode 100644 mr/mod_dev.go create mode 100644 mr/mod_dev_pause.go create mode 100644 mr/mod_dev_test.go create mode 100644 rootfs/www/ui/dev.js create mode 100644 tools/ci.d/dev.sh create mode 100644 tools/mock/fixtures/config.d/dev.json create mode 100644 tools/mock/fixtures/dev.pause.post.json create mode 100644 tools/mock/fixtures/dev.paused.json create mode 100644 tools/mock/fixtures/dev.unpause.post.json diff --git a/docs/MODULES.md b/docs/MODULES.md index 7d36e09..0c17de1 100644 --- a/docs/MODULES.md +++ b/docs/MODULES.md @@ -14,6 +14,7 @@ file, applies with snapshot + verify + auto-rollback, and serves the web UI API | net | 10 | `mr/mod_net*.go`, `mr/hooks.go` | `rootfs/www/ui/net.js` | `lan`, `networks`, `wan`, `multiwan`, `policy_routes`, `static_routes`, `multicast` | links, bridges, VLANs, WAN (PPPoE/DHCP), multi-WAN failover, routing, IPv6 WAN side (dhcpcd), port status | | wifi | 20 | `mr/mod_wifi*.go` | `ui/wifi.js` | `wifi` | radios, SSIDs, hostapd, stations; tuning: multicast-to-unicast, 802.11v band steering, radio health + self-heal (`mr wifi tick`, a crond line in sys's crontab block; its events are type `wifi`) | | dns | 30 | `mr/mod_dns*.go` | `ui/dns.js` | `dhcp`, `dns`, `networks[].dhcp` (type `Pool`) | dnsmasq: DNS, DHCP, RA/DHCPv6, split lists, local records, stubby.yml, query log; `rootfs/etc/conf.d/dnsmasq` | +| dev | 35 | `mr/mod_dev*.go` | `ui/dev.js` | `devices`, `groups` | device inventory and groups other sections refer to by name (resolved at validate / render; dnsmasq dhcp-host lines through the dns module), `mr pause` / `mr unpause` (runtime nft sets with timeouts, inserted by fwLoad) | | fw | 40 | `mr/mod_fw*.go` | `ui/fw.js` | `firewall` | nftables skeleton + hooks, zones, forwards, rules, NAT, IPv6 pinholes, access control | | mon | 50 | `mr/mod_mon*.go` | `ui/mon.js` | — | realtime graphs, per-device traffic, connections, system load; its per-minute sampler (`mon-collect`) also starts sys's `mr event tick` when due | | proxy | 55 | `mr/mod_proxy*.go` | `ui/proxy.js` | `proxy` | selective transparent proxy: sing-box, fake-ip DNS, tproxy, bypass devices | @@ -39,9 +40,13 @@ Register exactly one `Module` in `init()`: Reject newlines / control chars / quotes wherever they could break out of a config line. - `Render(c, out)` — add generated files (`out.Add(path, mode, data)`); must not touch the system. - `NetSh(c, phase, b)` — idempotent POSIX sh for `network.sh`, phases `links` → `wifi` → `routes` → `tail`. -- `Nft(c, hook, n)` — nftables lines at hook points (`defs`, `input`, `forward_early`, `forward`, - `mark`, `dstnat`, `srcnat`, `output`), see `nftHooks`. A module that needs its own base chain - (different priority) declares it in `defs`. `n.W(format, args...)` writes one line. +- `Nft(c, hook, n)` — nftables lines at hook points (`defs`, `input`, `forward_first`, `forward_early`, + `forward`, `mark`, `dstnat`, `srcnat`, `output`), see `nftHooks`. `forward_first` is the top of + filter/forward, before flow offload and the established accept: only for drops that must also stop + established connections (policy route `fallback: drop`). A module that needs its own base chain + (different priority) declares it in `defs`. `n.W(format, args...)` writes one line. Runtime state + that must survive reloads but never appears in the rendered file (learned sets, `mr pause`) is + appended by `fwLoad` in the same nft transaction, under `/run/mini-router/fw.lock`. - `FlowDevs(c)` — netdevs for the offload flowtable. `Dnsmasq(c)` — extra dnsmasq.conf lines. - `Services(c)` / `Managed` — OpenRC services wanted / owned. `Restart(path)` — service to restart when a generated file changes (`"-"` = none). `RestartOrder` — relative restart order. @@ -106,7 +111,10 @@ by mon's sampler). Messages are English, one line, cleaned (`eventClean`): text markup. A new type needs an entry in `eventTypes` / `eventLabels` and the web UI's `EVT` map (`sys.js`). Cross-module helpers: `c.LANNets()`, `c.BridgeFor(network)`, `c.LANBridges()`, `c.WANIfnames()`, -`c.WANTable(name)`, `c.WANByName(name)`, `c.Secret(key)`. +`c.WANTable(name)`, `c.WANByName(name)`, `c.Secret(key)`. Device inventory (dev, `mod_dev.go`): a key +that names devices resolves them with `devRefMACs` / `devMACs` (a device or `group:NAME` → MACs), +`devHostIP` (a device → its `ip`), validates with `devCheckRefs` (an unknown name is an error at the +place that uses it); `c.knownHosts()` = `dhcp.hosts` + one entry per device MAC (names, fixed addresses). Secrets (passwords, keys) live in `secrets.yaml`; router.yaml stores the secret **name** (`*_secret` fields). The UI sets secrets by name and can never read them back. diff --git a/docs/api.md b/docs/api.md index ecf27a6..b0b21eb 100644 --- a/docs/api.md +++ b/docs/api.md @@ -37,8 +37,8 @@ undone by a rollback. Revoking also drops the hash, so a name used again never b | Scope | Actions | |---|---| -| `read` | `status`, `config`, `schema`, `history`, `history.diff`, `job`, `net`, `net.ports`, `net.routes`, `net.wan`, `wifi.status`, `wifi.stations`, `wifi.survey`, `wifi.health`, `dns.stats`, `dns.leases`, `fw.stats`, `proxy.status`, `mon.now`, `mon.history`, `mon.devices`, `mon.conns`, `mon.procs`, `mon.dmesg`, `sys.services`, `sys.time`, `sys.doctor` (runs the health checks), `sys.events` (the event log), `sys.edge` | -| `operate` | + `net.redial`, `wifi.kick`, `wifi.scan`, `dns.release`, `proxy.delay`, `proxy.select`, `service` (start / stop / restart), `diag` | +| `read` | `status`, `config`, `config.raw`, `schema`, `history`, `history.diff`, `job`, `net`, `net.ports`, `net.routes`, `net.wan`, `wifi.status`, `wifi.stations`, `wifi.survey`, `wifi.health`, `dns.stats`, `dns.leases`, `fw.stats`, `proxy.status`, `proxy.routes`, `mon.now`, `mon.history`, `mon.devices`, `mon.conns`, `mon.procs`, `mon.dmesg`, `sys.services`, `sys.time`, `sys.doctor` (runs the health checks), `sys.events` (the event log), `sys.edge`, `dev.paused` (active pauses) | +| `operate` | + `net.redial`, `wifi.kick`, `wifi.scan`, `dns.release`, `dns.adblock`, `proxy.delay`, `proxy.select`, `service` (start / stop / restart), `diag`, `dev.pause` (`{target, duration}`: a device, `group:NAME`, dhcp.hosts name or MAC; `30m` … `7d`), `dev.unpause` (`{target}`, `all`) | | `apply` | + `plan`, `validate`, `apply`, `confirm`, `revert`, `rollback` | Never, whatever the scope: login / sessions, the web UI password, logs (`logs`, `sys.logs`: they can @@ -78,6 +78,7 @@ R=http://192.168.1.1/cgi-bin/api; H="Authorization: Bearer $MR_TOKEN" curl -sH "$H" "$R?a=status" curl -sH "$H" "$R?a=mon.devices" curl -sH "$H" -d '{"mac":"aa:bb:cc:dd:ee:ff"}' "$R?a=wifi.kick" # operate +curl -sH "$H" -d '{"target":"group:kids","duration":"1h"}' "$R?a=dev.pause" # operate: no internet for an hour ``` POST bodies are JSON. Errors: `{"error": "..."}` with the HTTP status (400 bad input, 401 no / bad / diff --git a/docs/modules/dev.md b/docs/modules/dev.md new file mode 100644 index 0000000..168b842 --- /dev/null +++ b/docs/modules/dev.md @@ -0,0 +1,152 @@ +# dev — device inventory, groups, pausing a device + +Cd1s/mini-router#15. Files: `mr/mod_dev.go` (inventory, groups, name resolution), `mr/mod_dev_pause.go` +(`mr pause`), `rootfs/www/ui/dev.js` (网络 › 设备), `tools/ci.d/dev.sh`, lab fragment `examples/lab.d/35-dev.yaml`. +Nothing resident, no new package, no new process. + +## Inventory (`devices`, `groups`) + +A device is a name for one or more MACs (cable + WiFi, a phone's per-network private address), +optionally with a fixed IPv4. Other sections refer to it by name instead of repeating MACs / addresses: + +```yaml +devices: + - name: office-pc # [a-z]([a-z0-9-]{0,30}[a-z0-9])?: a DNS label that cannot be read as an IP / MAC / lease time + macs: ["02:00:00:00:10:01"] # 1-8 unicast MACs; a MAC belongs to one device and is not also in dhcp.hosts + ip: 192.168.1.70 # optional fixed IPv4 inside a LAN-side network (a static lease) + type: pc # optional label: pc, phone, tablet, tv, console, iot, server, printer, other, … + owner: alice # optional label (the person) + desc: "" # optional, UI only + - {name: kid-tablet, macs: ["aa:bb:cc:00:00:21", "aa:bb:cc:00:00:22"], type: tablet, owner: kid} +groups: + kids: [kid-tablet, game-console] # name: reName ([a-z][a-z0-9_-]{0,14}); 1-256 devices; written group:kids elsewhere +``` + +Where names work (resolved when the config is validated and rendered — router.yaml is never rewritten, +the older keys keep working unchanged): + +| Key | Takes | Becomes | +|---|---|---| +| `firewall.forwards[].to` | an IPv4 or a device with `ip` | the DNAT target | +| `firewall.access[].devices` | devices, `group:NAME` (next to / instead of `macs`) | all their MACs (1-64 in total) | +| `policy_routes[].device` | a device or `group:NAME` (instead of `mac`) | `ether saddr { its MACs }` | +| `proxy.bypass[].device` | a device or `group:NAME` (instead of `mac`) | its MACs in `@proxy_bypass` | +| `guard.always_bypass` | device names too | every MAC of the device must be bypassed | +| `sys.wol`, `mr wol`, `schedules` `wol` | device names too | the device's first MAC | +| `mr pause`, `dev.pause` | device, `group:NAME`, dhcp.hosts name, MAC | all its MACs | + +A name that does not exist is a validation error at the place that uses it +(`firewall.forwards[3].to: unknown device "office-pc" (devices:)`), so deleting a device that is still +referenced lists every reference; a forward to a device without `ip` is refused. + +**dhcp.hosts and devices — one source of truth.** Every device is one dnsmasq line, rendered by the dns +module after the `dhcp.hosts` lines: `dhcp-host=MAC[,MAC…][,IP],NAME[,lease]`. The inventory name is the +device's DHCP / DNS name (`office-pc.lan`); `ip:` makes it a static lease exactly like a `dhcp.hosts` entry. +A MAC, name or address may be in `dhcp.hosts` or in `devices`, never in both (validation), so there are +no two places that disagree. `dhcp.hosts` stays as it is (the web UI can move an entry into the inventory: +网络 › 设备 › 从终端添加 › 静态分配); `dhcp.host_leases` accepts device MACs. Several MACs with one `ip` +share it: only one of them can hold the lease at a time (right for cable / WiFi of one laptop; give a +device that uses both at once no `ip`, or two devices). The inventory also names devices in 终端设备, +流量统计 / 连接 (mon), WOL, and new-device events (an inventory MAC is never "new"). + +## Pausing a device (`mr pause`) + +Runtime only: no config change, no confirm window, nothing resident; the kernel ends the pause. + + mr pause kid-tablet 1h # device, group:kids, a dhcp.hosts name or a MAC; 30m, 2h30m, 1d … (1s – 7d) + mr pause list [--json] # MAC, name, what was paused, time left, addresses + mr unpause kid-tablet | all # end it early + +Web UI: 暂停 on 网络 › 设备 (devices and groups) and 状态 › 终端设备 (every DHCP client; a MAC of the +inventory pauses the whole device), durations 30 分钟 / 1 / 2 小时 / 到明早 7:00 / custom; active pauses +on 总览 with 恢复. API: `GET dev.paused` (read), `POST dev.pause {target, duration}` and +`POST dev.unpause {target}` (operate; recorded in `/etc/router-changes.log` like other web UI actions). + +How it works: + +- State: `/run/mini-router/pause.json` (tmpfs — a reboot ends every pause): the MACs, when each pause + ends in **seconds since boot** (the clock the kernel's set timeouts run on, so NTP setting the clock at + boot changes nothing), who paused it, and the device's addresses (neighbour table, DHCP lease, fixed ip). +- `fwLoad` (every firewall reload: apply, PPPoE / DHCP hooks, `mr fw`, `mr pause`) adds, in the same nft + transaction as the ruleset: sets `paused` (ether_addr), `paused_4`, `paused_6` with per-element + timeouts = the time left, and inserts at the top of both chains: + + forward: iifname {LAN-side} ether saddr @paused oifname {WANs} counter drop comment "pause" + iifname {WANs} ip daddr @paused_4 counter drop comment "pause" (and ip6 / @paused_6) + input: iifname {LAN-side} ether saddr @paused fib daddr type != { local, broadcast, multicast, anycast } drop + + (input: a transparent proxy takes the device's traffic through input; DHCP, DNS, ND to the router keep + working). None of this is in the rendered `nftables.nft`, so `mr plan` never shows it. +- Cutting what already runs: a pause replaces the whole table. That replaces the flowtable, which sends + every offloaded flow (PPE / WED or software fast path) back to the CPU path; the paused device's packets + then meet the drops in both directions (replies from the WAN first — hence the address sets), everyone + else's flows are offloaded again by their next packet. The issue proposed deleting the device's conntrack + entries; the platform kernel has no `nf_conntrack_netlink` (checked on the router: no `conntrack` tool, + no module), and a reload does the same job without one. +- An address another MAC holds now (neighbour table) is left out, so a lease given away while the paused + device was gone is not cut. The addresses matter only for connections from before the pause. +- The end: the kernel drops the elements; the (then empty) rules stay until the next reload. +- Reloads are serialized (`/run/mini-router/fw.lock`) and read the state under that lock, so a PPPoE hook + reloading during `mr pause` cannot load a copy without the pause last. `mr pause` checks that the + loaded `@paused` set holds the MACs and fails otherwise. + +Not offloaded while paused (dropped instead); a device that is not paused is never affected. + +## Cost + +Binary: stripped linux/arm64 `mr` 10 158 240 → 10 223 776 bytes (+64 KiB; text +74.5 KiB) for the whole +issue (inventory, name resolution, pause, policy fallback, API); init allocation unchanged (lazy regexps). +RAM: nothing resident; while a pause is active 3 small sets and 4 rules. Flash: none for a pause from +the CLI; one line in `/etc/router-changes.log` per pause / unpause from the web UI / API. Home config: +no inventory → rendered files unchanged (`tools/ci.d/dev.sh` checks that no pause state is in them). + +## Left out (see the issue) + +- `watch: true` (online / offline events per device), `firewall.unknown_devices: allow | notify | isolate` + (new-device *notification* exists: event `new_device`; isolation of unknown MACs needs a default-deny + set of known MACs and would lock out every phone with a new private address), device type guessing + (OUI table + DHCP fingerprints), a per-device detail page (lease / signal / traffic / connections / + rules on one screen), `runtime.json` for all temporary states. + +## 怎么用 + +**网页** + +- **网络 › 设备**:设备清单。每行显示名称、类型 / 归属 / 所在分组、MAC(可多个)、IP(固定的或当前租约)、 + 是否在线(WiFi 在线 / 有租约)、是否暂停、被几处引用(鼠标悬停看是哪里)。 + - “从终端添加…”:从 DHCP 终端里挑一台加进清单;也可以把“静态分配”里的旧条目移进清单(移完旧条目自动删掉)。 + - “编辑”:改名会同时改掉端口转发、设备管控、策略路由、代理例外、分组里对它的引用;填“固定 IPv4”= 静态分配。 + - “删除”:还有地方在用时列出这些地方,不让删;只在分组里的会顺带移出分组。 + - “暂停”:选 30 分钟 / 1 小时 / 2 小时 / 到明早 7:00 或自己填(如 45m、1d,最长 7 天)。只断外网,内网、 + DHCP、DNS 照常;正在看的视频、在玩的游戏立即断开;到时自动恢复,也可以点“恢复”。不改配置、没有确认倒计时。 + - “分组”:建 `kids` 这样的分组,“暂停整组”一次停掉一家人的设备;其他地方写 `group:kids`。 +- **状态 › 终端设备**:每个 DHCP 终端都有“暂停”按钮(属于清单里的设备时整台设备一起暂停)。 +- **总览**:有设备在暂停时显示“暂停上网中”卡片,可直接恢复。 +- **防火墙 › 设备管控**、**路由 › 策略路由**、**代理 › 例外设备**、**端口转发**:都可以直接选 / 写设备名或 `group:分组`。 + +清单、分组的改动和其他配置一样点底部“保存并应用”;暂停 / 恢复立即生效,不需要应用。 + +**命令行 / agent** + +```sh +mr pause kid-tablet 1h # 暂停一小时 +mr pause group:kids 9h # 整组 +mr pause aa:bb:cc:dd:ee:ff 30m # 不在清单里的设备按 MAC +mr pause list # 谁在暂停、还剩多久 +mr unpause kid-tablet # 提前恢复(all = 全部) +``` + +router.yaml(改完 `mr validate` → `mr plan` → `mr apply --confirm 120` → `mr confirm`): + +```yaml +devices: + - {name: nas, macs: ["aa:bb:cc:dd:ee:10"], ip: 192.168.1.10, type: server} + - {name: kid-tablet, macs: ["aa:bb:cc:dd:ee:21"], type: tablet, owner: kid} +groups: + kids: [kid-tablet] +firewall: + forwards: [{name: nas-https, proto: [tcp], port: "8443", to: nas, to_port: "443"}] + access: [{name: kids-night, devices: ["group:kids"], schedule: [{days: [sun, mon, tue, wed, thu], time: "21:30-07:00"}]}] +policy_routes: + - {name: nas-wan2-only, device: nas, via: wan2, fallback: drop} # wan2 断线时 nas 断网,不换线 +``` diff --git a/docs/modules/dns.md b/docs/modules/dns.md index cacc2f6..1e151bc 100644 --- a/docs/modules/dns.md +++ b/docs/modules/dns.md @@ -92,7 +92,11 @@ it off the internet. `hosts[].name` may not be something dnsmasq reads as a lease time or keyword in `dhcp-host=` (`12345`, `5m`, `2w`, `infinite`, `ignore` — the last one would stop DHCP for that device); "设为静态" in the UI turns such a DHCP-supplied name into `host-`. -`host_leases` keys must be MACs of `dhcp.hosts` entries. (It is a separate map because the core test +Devices of the inventory (`devices:`, dev module, [dev.md](dev.md)) are rendered here too, after the +`dhcp.hosts` lines: one `dhcp-host=MAC[,MAC…][,IP],NAME[,lease]` per device (the name becomes its DHCP / DNS +name; `ip:` makes it a static lease). A MAC, name or address may be in `dhcp.hosts` or in `devices`, not in +both. `host_leases` keys must be MACs of `dhcp.hosts` entries or devices (a device takes the lease time of its +first MAC that has one). (It is a separate map because the core test `render_test.go` builds `Host` with a positional literal; moving it to `hosts[].lease` needs that one line changed — see the integration notes.) diff --git a/docs/modules/fw.md b/docs/modules/fw.md index 6837eab..19b2497 100644 --- a/docs/modules/fw.md +++ b/docs/modules/fw.md @@ -45,16 +45,19 @@ goes through tailscale, never through an open SSH / web port. Chain order (first match wins): - input: [access: proxy bypass guard] → ct state (invalid dropped) → lo → [rules towards the router] - → lan accept → guest DHCP/DNS/ICMP, rest dropped → SYN-flood limit → WAN ping + input: [pause] → [access: proxy bypass guard] → ct state (invalid dropped) → lo → [rules towards + the router] → lan accept → guest DHCP/DNS/ICMP, rest dropped → SYN-flood limit → WAN ping → required ICMPv6 / MLD / DHCPv6 / DHCPv4 / IGMP → hook input (open ports, tailscale, …) → [log] → counted WAN drop → policy drop - forward: [access control] → flow offload → ct state → hook forward_early (traffic rules, …) - → lan accept → guest → WAN → DNAT'ed accept → hook forward (IPv6 pinholes, …) - → IPv6 ICMP errors/echo → policy drop + forward: [pause] → hook forward_first (policy route fallback: drop) → [access control] → flow offload + → ct state → hook forward_early (traffic rules, …) → lan accept → guest → WAN → DNAT'ed + accept → hook forward (IPv6 pinholes, …) → IPv6 ICMP errors/echo → policy drop Every hook in `nftHooks` (module.go) is still emitted at its documented place; the fw-internal -parts (access control, router-bound rules) sit around them. +parts (access control, router-bound rules) sit around them. `[pause]` is runtime state (`mr pause`, +[dev.md](dev.md)): fwLoad inserts it in the same transaction while a pause is active; it is never in +the rendered `nftables.nft`. Every reload is serialized by a lock (`/run/mini-router/fw.lock`), so the +state a reload carries over (learned sets, pauses) is never replaced by a stale copy. ## Performance @@ -80,7 +83,8 @@ firewall: enabled: true # default true; false keeps the entry but renders nothing proto: [tcp] # tcp and/or udp port: "7443" # external port or range "45000-45100" - to: 192.168.1.66 # host inside a LAN-side network (guest networks allowed), not the router + to: 192.168.1.66 # host inside a LAN-side network (guest networks allowed), not the router, + # or a device of the inventory with ip: (to: desktop → its address; dev.md) to_port: "9999" # optional; a range maps only to the same range or to one port wan: [wan2] # optional: only these WANs (default all) src_ip: [203.0.113.0/24, 198.51.100.7] # optional: only these IPv4 sources @@ -129,6 +133,8 @@ firewall: access: # block internet (WAN) for devices; LAN, DHCP, DNS keep working - name: kid-bedtime macs: ["aa:bb:cc:dd:ee:01", "aa:bb:cc:dd:ee:02"] + devices: ["group:kids", tv-box] # optional: devices / groups of the inventory (dev.md), all their MACs; + # macs and / or devices, 1-64 MACs in total schedule: # blocked only in these windows; empty = always blocked - {days: [sun, mon, tue, wed, thu], time: "21:30-07:00"} - {days: [fri, sat], time: "23:00-08:00"} @@ -171,10 +177,16 @@ PPPoE reconnect, apply, `mr fw`). Limits: a phone using a per-network random MAC must be listed with the MAC it uses on this WiFi (iOS/Android "private address" is stable per network). A device on a guest network is matched too. +Access control is config (schedules, permanent blocks). For "no internet for this device for the next +hour" without a config change there is `mr pause` / 暂停 (dev module, [dev.md](dev.md)): the same +drops in both chains, but on runtime sets with kernel timeouts, and the device stays offloaded +until it is paused (the pause replaces the ruleset once, which ends every offloaded flow). + ## Web UI API `GET fw.stats` — read-only, no parameters: `{counters: {"": {packets, bytes}}, log: [...]}`. -Comments: `wan-in-drop`, `rule:` (rules with `counter: true`), `access:`, `v6in:`. +Comments: `wan-in-drop`, `rule:` (rules with `counter: true`), `access:`, `v6in:`, +`fallback:` (policy routes with `fallback: drop`, net module), `pause` (while a pause is active). `log` = the last 100 kernel log lines from `log_drops` / rule logging (`dmesg`). Mock fixture: `tools/mock/fixtures/fw.stats.json`; sample config: `tools/mock/fixtures/config.d/fw.json`. @@ -209,9 +221,11 @@ chain changed intentionally: 后规则仍然有效。表格“命中”列是计数。 - **通信规则**:按顺序匹配(↑ 调整顺序)。源 / 目标区域、IP、MAC、协议、端口、生效时间段、计数、 日志。目标选“路由器本机”可限制某台设备访问路由器服务(只能丢弃 / 拒绝)。 -- **设备管控**:选设备(从已知设备下拉或填 MAC),选“始终禁止上网”或“按时间段禁止”,勾选星期、 - 填时间段(如 `21:30-07:00`,跨午夜自动算到次日)。到点立即断网,已经在播的视频也会停;内网、 - DHCP、DNS 不受影响。 +- **设备管控**:选设备(从设备清单选设备 / 分组,或从已知设备下拉填 MAC),选“始终禁止上网”或 + “按时间段禁止”,勾选星期、填时间段(如 `21:30-07:00`,跨午夜自动算到次日)。到点立即断网,已经在 + 播的视频也会停;内网、DHCP、DNS 不受影响。临时断网一会儿(不改配置)用 网络 › 设备 或 + 状态 › 终端设备 里的“暂停”。 +- **端口转发**的内部 IP 也可以直接写设备清单里有固定 IP 的设备名(如 `desktop`)。 改完点底部“保存并应用”:先校验并显示变更计划,应用后 120 秒内点“保留”,否则自动回滚。 @@ -233,5 +247,8 @@ firewall: - {name: nas-https, iid: "::10", proto: [tcp], port: "443"} ``` -查看命中计数:`nft list table inet mr | grep -E 'rule:|access:|v6in:|wan-in-drop'`; +设备清单里的名字(dev.md):`access: [{name: kids-night, devices: ["group:kids"], schedule: …}]`、 +`forwards: [{name: nas-https, proto: [tcp], port: "8443", to: nas, to_port: "443"}]`。 + +查看命中计数:`nft list table inet mr | grep -E 'rule:|access:|v6in:|fallback:|pause|wan-in-drop'`; 查看拦截日志:`dmesg | grep mr-drop`。 diff --git a/docs/modules/net.md b/docs/modules/net.md index 27746b7..48d0ece 100644 --- a/docs/modules/net.md +++ b/docs/modules/net.md @@ -209,10 +209,24 @@ policy_routes: domains: [video.example, "*.cdn.example.net"] # 按域名:写 example.com = 它和它的所有子域名 domains_file: /etc/mini-router/video.domains # 可选:更多域名,一行一个,# 注释 via: wan2 + - name: office-wan2-only + device: office-pc # 代替 mac:设备清单(devices,见 dev.md)里的设备或 group:分组,它的所有 MAC + via: wan2 + fallback: drop # main(默认)| drop:见下 ``` 没写 src / dst 时 IPv4 + IPv6 都生效;写了 src / dst 就只管那个地址族。访问 LAN 侧网络、tailscale、静态路由的流量不受影响。 +#### 断线兜底(fallback) + +`via` 的 WAN 断线(PPPoE 掉线)或健康检测失败时,它的路由表里没有默认路由,打了标记的流量会落到 main 表, +从别的 WAN 出去——这是默认的 `fallback: main`(能上网,但换了出口)。`fallback: drop` = 这些流量只准走 `via`: +filter/forward 最前面(hook `forward_first`,在 flow offload 和“已建立连接放行”之前)加一条 +`iifname {LAN} <同样的条件> oifname {其它所有 WAN} counter drop comment "fallback:<名称>"`,所以断线期间 +新连接和已有连接都出不去,恢复后自动恢复;访问 LAN、tailscale 不受影响。注意:`via` 没有 IPv6 时,这台设备 +也就没有 IPv6 外网(想只管 IPv4 就写 `src`);设备的 DNS 仍由路由器经任意线路查询;被透明代理接管的连接走代理。 +家里配置没有用它,输出不变。 + #### 按域名(domains / domains_file) 域名条件和 MAC / src / dst 一样可以组合(同时满足),也可以单独用。做法(不新增任何进程): @@ -298,8 +312,9 @@ multicast: {igmp_snooping: false, igmp_proxy: false, upstream: wan2} 或者填 VLAN ID 并勾选带标签端口(接支持 VLAN 的交换机 / AP);DHCP 地址池也在这里。WiFi 的 SSID 在“无线设置”里选网络。 - **网络 → LAN 与网络 → 工作模式**:选旁路由或纯 AP,填主路由地址。旁路由默认“只管代理”:卡片里列出主路由要添加的静态路由; 在主路由的 DHCP 里把 DNS 改成本机地址。选“全部设备”或“指定设备”时先关掉主路由的 DHCP。 -- **路由 → 策略路由**:按 MAC / 源地址 / 目标地址 / 域名指定出口 WAN(域名一栏填 `example.com, video.example`, - 含子域名;更长的列表用 router.yaml 的 `domains_file`);下面是实时 `ip rule`(v4 / v6)。 +- **路由 → 策略路由**:按 MAC(或设备清单里的设备名 / `group:分组`)/ 源地址 / 目标地址 / 域名指定出口 WAN(域名一栏填 + `example.com, video.example`,含子域名;更长的列表用 router.yaml 的 `domains_file`);“该 WAN 断线时”选“断网”= + 只走这条线,断线时不换线(`fallback: drop`);下面是实时 `ip rule`(v4 / v6)。 - **路由 → 静态路由**:静态路由表格 + 当前所有路由表。 - 所有修改点底部“保存并应用”:先校验、显示变更计划,应用后 120 秒内点“保留”,否则自动回滚。 diff --git a/docs/modules/proxy.md b/docs/modules/proxy.md index 249f223..57848a4 100644 --- a/docs/modules/proxy.md +++ b/docs/modules/proxy.md @@ -166,6 +166,7 @@ proxy: cidr_file: /etc/mini-router/proxy/telegram.cidrs # 可选 bypass: # 例外设备:永不代理,DNS 由主 dnsmasq 解析 - {name: desktop, mac: "02:c3:06:d6:7f:8a"} + - {name: kids, device: "group:kids"} # 或设备清单(devices,dev.md)里的设备 / 分组:它的所有 MAC subscriptions: # 只给 Web UI 的“导入”用:获取 → 预览 → 添加;不会自动更新节点 - {name: airport, url_secret: proxy_airport_sub} # 订阅链接(含令牌)在 secrets.yaml ``` diff --git a/examples/lab.d/10-net.yaml b/examples/lab.d/10-net.yaml index cee5647..c2a2776 100644 --- a/examples/lab.d/10-net.yaml +++ b/examples/lab.d/10-net.yaml @@ -101,6 +101,13 @@ policy_routes: src: 192.168.1.80 domains: [docs.video.example] via: isp3 + - name: office-wan2-only # a device of the inventory (35-dev.yaml); never another WAN when wan2 is down + device: office-pc + via: wan2 + fallback: drop + - name: kids-via-isp3 # a group of devices + device: "group:kids" + via: isp3 static_routes: - {name: lab-v4, target: 10.9.0.0/16, via: 192.168.1.50} diff --git a/examples/lab.d/30-dns.yaml b/examples/lab.d/30-dns.yaml index 6074357..41e3a25 100644 --- a/examples/lab.d/30-dns.yaml +++ b/examples/lab.d/30-dns.yaml @@ -30,6 +30,7 @@ dhcp: - {name: desktop, mac: "02:c3:06:d6:7f:8a", ip: 192.168.1.66} host_leases: "02:c3:06:d6:7f:8a": infinite + "02:00:00:00:10:01": infinite # a device of the inventory (35-dev.yaml) dns: cache_size: 8000 diff --git a/examples/lab.d/35-dev.yaml b/examples/lab.d/35-dev.yaml new file mode 100644 index 0000000..e3f4cde --- /dev/null +++ b/examples/lab.d/35-dev.yaml @@ -0,0 +1,13 @@ +# lab config — dev module fragment (devices, groups): the device inventory other sections refer to by +# name (firewall.forwards[].to, firewall.access[].devices, policy_routes[].device, proxy.bypass[].device, +# guard.always_bypass). CI concatenates examples/lab.d/*.yaml into one router.yaml; keep only this +# module's top-level keys here. tools/ci.d/dev.sh pauses devices (mr pause) in network namespaces. + +devices: + - {name: office-pc, macs: ["02:00:00:00:10:01"], ip: 192.168.1.70, type: pc, owner: alice, desc: "RDP forward; wan2 only (policy fallback: drop)"} + - {name: kid-tablet, macs: ["aa:bb:cc:00:00:21", "aa:bb:cc:00:00:22"], ip: 192.168.1.121, type: tablet, owner: kid} # cable adapter + WiFi + - {name: game-console, macs: ["aa:bb:cc:00:00:23"], type: console, owner: kid} # a name, no fixed address + - {name: tv-box, macs: ["02:00:00:00:10:02"], type: tv} + +groups: + kids: [kid-tablet, game-console] diff --git a/examples/lab.d/40-fw.yaml b/examples/lab.d/40-fw.yaml index 54a189b..536708f 100644 --- a/examples/lab.d/40-fw.yaml +++ b/examples/lab.d/40-fw.yaml @@ -24,6 +24,7 @@ firewall: - {name: guest-cam, proto: [tcp], port: "8554", to: 192.168.20.50, desc: "camera in the guest network"} - {name: iot-hub, proto: [udp], port: "5683", to: 192.168.30.20} - {name: old-game, enabled: false, proto: [udp], port: "27015", to: 192.168.1.166} + - {name: office-rdp, proto: [tcp], port: "3390", to: office-pc, to_port: "3389", desc: "to a device of the inventory (its ip)"} open: - {name: lucky-https, proto: [tcp], port: "443"} @@ -73,3 +74,4 @@ firewall: - {name: blocked-tv, macs: ["aa:bb:cc:dd:ee:03"]} - {name: school-hours, macs: ["aa:bb:cc:dd:ee:04"], schedule: [{days: [mon, tue, wed, thu, fri]}]} - {name: off-entry, enabled: false, macs: ["aa:bb:cc:dd:ee:05"]} + - {name: kids-school-night, macs: ["aa:bb:cc:dd:ee:06"], devices: ["group:kids"], schedule: [{days: [sun, mon, tue, wed, thu], time: "22:00-06:30"}]} diff --git a/examples/lab.d/55-proxy.yaml b/examples/lab.d/55-proxy.yaml index 2b762d2..b888e28 100644 --- a/examples/lab.d/55-proxy.yaml +++ b/examples/lab.d/55-proxy.yaml @@ -54,5 +54,6 @@ proxy: cidr_file: @REPO@/mr/testdata/proxy.cidrs bypass: - {name: desktop, mac: "02:c3:06:d6:7f:8a"} + - {name: kids, device: "group:kids"} # devices of the inventory (35-dev.yaml) subscriptions: - {name: airport, url_secret: proxy_sub_airport} diff --git a/examples/lab.d/90-guard.yaml b/examples/lab.d/90-guard.yaml index ac8187e..93a607e 100644 --- a/examples/lab.d/90-guard.yaml +++ b/examples/lab.d/90-guard.yaml @@ -1,6 +1,6 @@ # guard (mr/guard.go): baselines `mr validate` enforces whichever way a change arrives — the lab keeps all of them guard: never_expose: [ssh, panel, dns] # no firewall.open / forward to the router reaches these from the WAN - always_bypass: [desktop] # proxy.bypass (or dhcp.hosts) name: never proxied + always_bypass: [desktop, kid-tablet] # proxy.bypass, dhcp.hosts or devices name: never proxied offload: hardware # firewall.offload may not drop below hardware ssh_lan_only: true # SSH listens on LAN-zone addresses only diff --git a/mr/api_token.go b/mr/api_token.go index b29a951..67743cc 100644 --- a/mr/api_token.go +++ b/mr/api_token.go @@ -71,9 +71,11 @@ var tokenActions = map[string]string{ "dns.stats": "read", "dns.leases": "read", "fw.stats": "read", "proxy.status": "read", "proxy.routes": "read", "mon.now": "read", "mon.history": "read", "mon.devices": "read", "mon.conns": "read", "mon.procs": "read", "mon.dmesg": "read", "sys.services": "read", "sys.time": "read", "sys.doctor": "read", "sys.events": "read", "sys.edge": "read", + "dev.paused": "read", // operate: runtime actions that do not change the config "net.redial": "operate", "wifi.kick": "operate", "wifi.scan": "operate", "dns.release": "operate", "dns.adblock": "operate", "proxy.delay": "operate", "proxy.select": "operate", "service": "operate", "diag": "operate", + "dev.pause": "operate", "dev.unpause": "operate", // apply: config changes, through plan → apply → confirm with automatic rollback "plan": "apply", "validate": "apply", "apply": "apply", "confirm": "apply", "revert": "apply", "rollback": "apply", } diff --git a/mr/config.go b/mr/config.go index f1db6ea..bfafe43 100644 --- a/mr/config.go +++ b/mr/config.go @@ -32,6 +32,9 @@ type Config struct { API APIConf `yaml:"api,omitempty"` // api: tokens for scripts and agents (api_token.go) Notify Notify `yaml:"notify,omitempty"` // sys: where events are pushed (mod_sys_notify.go) Bypass Bypass `yaml:"bypass,omitempty"` // mode bypass: which clients use this box (mode.go) + // dev: the device inventory and groups that other sections refer to by name (mod_dev.go) + Devices []Device `yaml:"devices,omitempty"` + Groups map[string][]string `yaml:"groups,omitempty"` secrets map[string]string } diff --git a/mr/guard.go b/mr/guard.go index d930a66..57fef54 100644 --- a/mr/guard.go +++ b/mr/guard.go @@ -7,7 +7,7 @@ package main // // guard: // never_expose: [ssh, panel, dns] # never reachable from the WAN (firewall.open, forwards to the router, services.edge routes) -// always_bypass: [desktop] # these devices (dhcp.hosts / proxy.bypass names) never go through the proxy +// always_bypass: [desktop] # these devices (devices / dhcp.hosts / proxy.bypass names) never go through the proxy // offload: hardware # flow offload may not drop below this (hardware > software > off) // ssh_lan_only: true # SSH, when on, listens on the LAN-zone addresses only @@ -61,7 +61,7 @@ func guardValidate(c *Config, v *Validator) { } } for _, f := range c.Firewall.Forwards { - if f.Enabled != nil && !*f.Enabled || !c.isRouterAddr(f.To) { + if f.Enabled != nil && !*f.Enabled || !c.isRouterAddr(devHostIP(c, f.To)) { continue } to := f.ToPort @@ -78,18 +78,25 @@ func guardValidate(c *Config, v *Validator) { edgeGuard(c, v, s, ports) } if len(g.AlwaysBypass) > 0 && c.Proxy.Enabled { - bypass := map[string]bool{} + bypass := map[string]bool{} // entry names and every bypassed MAC for _, d := range c.Proxy.Bypass { bypass[strings.ToLower(d.Name)] = true - bypass[strings.ToLower(d.MAC)] = true + for _, m := range proxyBypassMACs(c, d) { + bypass[m] = true + } } - hosts := map[string]string{} - for _, h := range c.DHCP.Hosts { - hosts[strings.ToLower(h.Name)] = strings.ToLower(h.MAC) + hosts := map[string][]string{} // a name → its MACs (a device may have several: all must be bypassed) + for _, h := range c.knownHosts() { + n := strings.ToLower(h.Name) + hosts[n] = append(hosts[n], strings.ToLower(h.MAC)) } for _, name := range g.AlwaysBypass { n := strings.ToLower(name) - if !bypass[n] && (hosts[n] == "" || !bypass[hosts[n]]) { + all := len(hosts[n]) > 0 + for _, m := range hosts[n] { + all = all && bypass[m] + } + if !bypass[n] && !all { v.Add("guard.always_bypass: device %q is not in proxy.bypass", name) } } diff --git a/mr/main.go b/mr/main.go index 1c25f9b..b97936a 100644 --- a/mr/main.go +++ b/mr/main.go @@ -61,7 +61,10 @@ module commands (JSON output unless noted): mr mon now | history | devices | conns [JSON] | procs | dmesg mr sys run ACTION [TARGET] | backup [-secrets] FILE|- | restore [-confirm SECS] FILE | keys mr ddns status | update [--force] [NAME...] DDNS records; update now (sync --hook|--cron: WAN hooks / crond) - mr wol MAC|HOST [NETWORK] Wake-on-LAN magic packet (HOST: a dhcp.hosts name) to the LAN's broadcast + mr wol MAC|HOST [NETWORK] Wake-on-LAN magic packet (HOST: a device or dhcp.hosts name) to the LAN's broadcast + mr pause DEVICE|group:NAME|MAC DURATION | list [--json] pause internet access now (30m, 1h, 1d; max 7d; + runtime only: no config change, ends by itself, a reboot ends it too) + mr unpause DEVICE|group:NAME|MAC|all end a pause early mr doctor [--json] health and security checks: every finding ok / warn / risk / skip with its fix mr event list [--json] [N] the event log: WAN down / up, failover, changes, login locks, new devices, boots (tick: mr-mon's sampler; boot | shutdown: mr-bootlog) diff --git a/mr/mod_dev.go b/mr/mod_dev.go new file mode 100644 index 0000000..73bc3c1 --- /dev/null +++ b/mr/mod_dev.go @@ -0,0 +1,256 @@ +package main + +// dev module: the device inventory (router.yaml devices, groups) and runtime pauses (mod_dev_pause.go). +// +// A device is a name for one or more MACs (a laptop's cable + WiFi, a phone's per-network private +// address), optionally with a fixed IPv4. Other sections refer to it by name instead of repeating +// MACs / addresses. Names are resolved when the config is validated and rendered; router.yaml is +// never rewritten, and the older keys (dhcp.hosts, macs, mac, IPv4 targets) keep working as before: +// +// firewall.forwards[].to a device with ip: → its address +// firewall.access[].devices devices and group:NAME → their MACs (next to macs:) +// policy_routes[].device a device or group:NAME → ether saddr { its MACs } (instead of mac:) +// proxy.bypass[].device a device or group:NAME → its MACs in @proxy_bypass (instead of mac:) +// guard.always_bypass, sys.wol / mr wol, mr pause device names +// +// An unknown name is a validation error at the place that uses it, so deleting a device that is +// still referenced lists every reference. dnsmasq: every device is one dhcp-host line +// (dhcp-host=MAC[,MAC…][,IP],NAME[,lease]) rendered by the dns module: the inventory name is the +// device's DHCP / DNS name, ip: makes it a static lease (like dhcp.hosts). A MAC, name or address +// may be in devices or in dhcp.hosts, not in both, so there is one source of truth per device. +// Owns: router.yaml devices, groups. Docs: docs/modules/dev.md. + +import ( + "fmt" + "net" + "sort" + "strings" +) + +// Device is one entry of the device inventory. +type Device struct { + Name string `yaml:"name"` + MACs []string `yaml:"macs"` + IP string `yaml:"ip,omitempty"` // fixed IPv4: a static DHCP lease; forwards may use the name + Type string `yaml:"type,omitempty"` // free label: pc, phone, tablet, tv, console, iot, server, … + Owner string `yaml:"owner,omitempty"` // free label (the person) + Desc string `yaml:"desc,omitempty"` +} + +const ( + devMax = 256 // devices (and members of one group) + devMaxMACs = 8 + devGroupMax = 32 +) + +var ( + // a DNS label that cannot be read as an IPv4 address, a MAC or a dnsmasq lease time + reDevName = lazyRegexp(`^[a-z]([a-z0-9-]{0,30}[a-z0-9])?$`) + reDevLabel = lazyRegexp(`^[a-z0-9][a-z0-9_-]{0,15}$`) +) + +func init() { + register(&Module{ + Name: "dev", + Prio: 35, + Validate: devValidate, + Status: pauseStatus, + API: map[string]func(r apiReq) apiResp{ + "dev.paused": apiDevPaused, + "dev.pause": apiDevPause, + "dev.unpause": apiDevUnpause, + }, + Commands: map[string]func(c *Config, args []string) error{ + "pause": pauseCommand, + "unpause": unpauseCommand, + }, + }) +} + +func devValidate(c *Config, v *Validator) { + if len(c.Devices) > devMax { + v.Add("devices: at most %d", devMax) + } + hostName, hostMAC, hostIP := map[string]bool{}, map[string]bool{}, map[string]bool{} + for _, h := range c.DHCP.Hosts { + hostName[strings.ToLower(h.Name)] = h.Name != "" + hostMAC[strings.ToLower(h.MAC)] = true + hostIP[h.IP] = true + } + names, macs, ips := map[string]bool{}, map[string]string{}, map[string]string{} + for i, d := range c.Devices { + p := fmt.Sprintf("devices[%d]", i) + switch { + case !reDevName.MatchString(d.Name): + v.Add("%s.name: lowercase letters, digits and - (1-32, starting with a letter), got %q", p, d.Name) + case names[d.Name]: + v.Add("%s.name: duplicate %q", p, d.Name) + case hostName[d.Name]: + v.Add("%s.name: %q is also a dhcp.hosts name", p, d.Name) + } + names[d.Name] = true + if len(d.MACs) == 0 || len(d.MACs) > devMaxMACs { + v.Add("%s.macs: 1-%d MACs", p, devMaxMACs) + } + for _, m := range d.MACs { + l := strings.ToLower(m) + switch hw, err := net.ParseMAC(m); { + case !reMAC.MatchString(m) || err != nil: + v.Add("%s.macs: invalid %q", p, m) + continue + case hw[0]&1 != 0: + v.Add("%s.macs: %s is not a unicast MAC", p, m) + case macs[l] != "": + v.Add("%s.macs: %s is also in device %s", p, m, macs[l]) + case hostMAC[l]: + v.Add("%s.macs: %s is also in dhcp.hosts (keep each device in one place)", p, m) + } + macs[l] = d.Name + } + if d.IP != "" { + if e := fwCheckTarget(c, d.IP); e != "" { + v.Add("%s.ip: an IPv4 inside a LAN-side network, got %q: %s", p, d.IP, e) + } else if ips[d.IP] != "" { + v.Add("%s.ip: %s is also the address of device %s", p, d.IP, ips[d.IP]) + } else if hostIP[d.IP] { + v.Add("%s.ip: %s is also in dhcp.hosts", p, d.IP) + } + ips[d.IP] = d.Name + } + if d.Type != "" && !reDevLabel.MatchString(d.Type) { + v.Add("%s.type: a short label (lowercase letters, digits, _ -; max 16), got %q", p, d.Type) + } + if !safeText(d.Owner) || len(d.Owner) > 40 { + v.Add("%s.owner: max 40 characters, no control characters", p) + } + fwCheckDesc(v, p, d.Desc) + } + if len(c.Groups) > devGroupMax { + v.Add("groups: at most %d", devGroupMax) + } + for _, g := range devGroupNames(c) { + if !reName.MatchString(g) { + v.Add("groups: name %q: lowercase letters, digits, _ - (1-15, starting with a letter)", g) + continue + } + members := c.Groups[g] + if len(members) == 0 || len(members) > devMax { + v.Add("groups.%s: 1-%d devices", g, devMax) + } + seen := map[string]bool{} + for _, m := range members { + if c.device(m) == nil { + v.Add("groups.%s: unknown device %q (devices:)", g, m) + } else if seen[m] { + v.Add("groups.%s: duplicate %q", g, m) + } + seen[m] = true + } + } +} + +func devGroupNames(c *Config) []string { + out := make([]string, 0, len(c.Groups)) + for g := range c.Groups { + out = append(out, g) + } + sort.Strings(out) + return out +} + +// device returns the inventory entry named name (nil if there is none). +func (c *Config) device(name string) *Device { + for i := range c.Devices { + if c.Devices[i].Name == name { + return &c.Devices[i] + } + } + return nil +} + +// devRefMACs resolves one reference — a device name or group:NAME — to lowercase MACs; ok is false +// when it names nothing. +func devRefMACs(c *Config, ref string) ([]string, bool) { + if g, isGroup := strings.CutPrefix(ref, "group:"); isGroup { + members, ok := c.Groups[g] + if !ok { + return nil, false + } + var out []string + for _, m := range members { + if d := c.device(m); d != nil { + out = append(out, lowerAll(d.MACs)...) + } + } + return dedup(out), true + } + if d := c.device(ref); d != nil { + return lowerAll(d.MACs), true + } + return nil, false +} + +// devMACs: the MACs of every reference (unknown ones contribute nothing; validation reports them). +func devMACs(c *Config, refs []string) []string { + var out []string + for _, r := range refs { + m, _ := devRefMACs(c, r) + out = append(out, m...) + } + return dedup(out) +} + +// devCheckRefs reports every reference in refs that names no device / group, at path p. +func devCheckRefs(c *Config, v *Validator, p string, refs []string) { + for _, r := range refs { + if _, ok := devRefMACs(c, r); ok { + continue + } + if strings.HasPrefix(r, "group:") { + v.Add("%s: unknown group %q (groups:)", p, r) + } else { + v.Add("%s: unknown device %q (devices:)", p, r) + } + } +} + +// devHostIP: the address a target names — a device's ip, anything else as it is. +func devHostIP(c *Config, s string) string { + if d := c.device(s); d != nil { + return d.IP + } + return s +} + +// knownHosts: dhcp.hosts plus one entry per MAC of every device (IP empty when it has none) — the +// names and fixed addresses the router knows, for neighbour hints, names in lists and events. +func (c *Config) knownHosts() []Host { + out := append([]Host{}, c.DHCP.Hosts...) + for _, d := range c.Devices { + for _, m := range d.MACs { + out = append(out, Host{Name: d.Name, MAC: m, IP: d.IP}) + } + } + return out +} + +// devDHCPHosts: one dnsmasq dhcp-host line per device — its MACs, the fixed address if any, the name +// and the per-host lease time from dhcp.host_leases (the first of its MACs that has one). +func devDHCPHosts(c *Config) []string { + var out []string + for _, d := range c.Devices { + parts := lowerAll(d.MACs) + if d.IP != "" { + parts = append(parts, d.IP) + } + parts = append(parts, d.Name) + for _, m := range d.MACs { + if l := hostLease(c, m); l != "" { + parts = append(parts, l) + break + } + } + out = append(out, "dhcp-host="+strings.Join(parts, ",")) + } + return out +} diff --git a/mr/mod_dev_pause.go b/mr/mod_dev_pause.go new file mode 100644 index 0000000..d05fc27 --- /dev/null +++ b/mr/mod_dev_pause.go @@ -0,0 +1,506 @@ +package main + +// dev module: pausing a device's internet access at runtime — `mr pause`, `mr unpause`, the web UI's +// 暂停 buttons (dev.pause / dev.unpause / dev.paused). Nothing in router.yaml changes, there is no +// confirm window and nothing resident: the kernel ends the pause by itself. +// +// State: /run/mini-router/pause.json (tmpfs: a reboot ends every pause) lists the paused MACs, when +// each pause ends in seconds since boot (the clock the kernel's set timeouts run on; wall-clock jumps +// at boot, when NTP first sets the clock, do not matter) and the addresses the device had. fwLoad +// (every firewall reload: apply, PPPoE / DHCP hooks, `mr fw`) turns it into, in the same transaction +// as the ruleset: +// +// set paused { type ether_addr; flags timeout } the MACs, each with its remaining time +// set paused_4 / paused_6 their addresses, same timeouts +// input: LAN-side, ether saddr @paused, not for the router itself (DNS, DHCP stay) → drop +// (a transparent proxy takes traffic through input, not forward) +// forward: LAN-side, ether saddr @paused, to a WAN → drop +// from a WAN to @paused_4 / @paused_6 → drop +// +// inserted at the top of both chains, above flow offload and the established accept. A pause always +// reloads the whole table: replacing it replaces the flowtable, which sends every offloaded flow (PPE +// or software fast path) back to the CPU path, so the device's established connections — a running +// video, a game — stop at once in both directions; everyone else's flows are offloaded again by +// their next packet. (Deleting the device's conntrack entries would need nf_conntrack_netlink, which +// the platform kernel does not build.) The addresses matter for connections that were established +// before the pause: their replies arrive from the WAN before the device sends anything. +// Pausing again sets a new end time; unpausing reloads without the device. When all pauses have +// ended the (empty) rules stay until the next reload. + +import ( + "encoding/json" + "fmt" + "net" + "os" + "sort" + "strconv" + "strings" + "time" +) + +const ( + pauseMaxSecs = 7 * 86400 + pauseMaxMACs = 256 +) + +// variables so tests can point them elsewhere +var ( + pauseFile = RunDir + "/pause.json" + pauseLock = RunDir + "/pause.lock" + pauseLeaseFile = LeaseFile + devConfigPath = ConfigPath + devSecretsPath = SecretsPath + pauseUptime = func() int64 { // seconds since boot + f := strings.Fields(readFile("/proc/uptime")) + if len(f) > 0 { + if s, err := strconv.ParseFloat(f[0], 64); err == nil { + return int64(s) + } + } + return time.Now().Unix() + } + pauseReload = fwLoad + // pauseLoaded reports whether the loaded @paused set holds mac (a failed reload keeps the old table). + pauseLoaded = func(macs []string) error { + out, err := run("nft", "list", "set", "inet", "mr", "paused") + if err != nil { + return fmt.Errorf("the pause is not in the firewall (nft: %s)", firstLine(strings.TrimSpace(out))) + } + for _, m := range macs { + if !strings.Contains(out, m) { + return fmt.Errorf("the pause of %s is not in the firewall", m) + } + } + return nil + } +) + +type pauseEntry struct { + MAC string `json:"mac"` + Until int64 `json:"until"` // seconds since boot + Ref string `json:"ref,omitempty"` // what was paused: a device, group:NAME, a dhcp.hosts name or the MAC + By string `json:"by,omitempty"` // cli | web | api: + IPs []string `json:"ips,omitempty"` // the device's addresses (cut inbound replies after a reload) +} + +// pauseRead returns the pauses that have not ended at now. Everything is checked again: it is +// rendered into nft commands. +func pauseRead(now int64) []pauseEntry { + var st struct { + Paused []pauseEntry `json:"paused"` + } + b, err := os.ReadFile(pauseFile) + if err != nil || json.Unmarshal(b, &st) != nil { + return nil + } + var out []pauseEntry + for _, e := range st.Paused { + if !reMAC.MatchString(e.MAC) || e.Until <= now || e.Until-now > pauseMaxSecs || len(out) >= pauseMaxMACs { + continue + } + e.MAC = strings.ToLower(e.MAC) + var ips []string + for _, a := range e.IPs { + if ip := net.ParseIP(a); ip != nil && len(ips) < 32 { + ips = append(ips, ip.String()) + } + } + e.IPs = ips + if !safeText(e.Ref) || len(e.Ref) > 64 { + e.Ref = "" + } + if !safeText(e.By) || len(e.By) > 64 { + e.By = "" + } + out = append(out, e) + } + return out +} + +func pauseWrite(ents []pauseEntry) error { + if len(ents) == 0 { + if err := os.Remove(pauseFile); err != nil && !os.IsNotExist(err) { + return err + } + return nil + } + b, _ := json.Marshal(map[string]any{"paused": ents}) + return writeAtomic(pauseFile, b, 0600) +} + +// pauseScript: the nft commands for the active pauses ("" when there is none), run by fwLoad after +// the ruleset in the same transaction. +func pauseScript(c *Config) string { + now := pauseUptime() + ents := pauseRead(now) + if len(ents) == 0 { + return "" + } + neigh, owner := pauseNeigh(c) + lans := "{ " + quoteList(c.LANBridges()) + " }" + wans := "{ " + quoteList(c.WANIfnames()) + " }" + var b strings.Builder + w := func(f string, a ...any) { fmt.Fprintf(&b, f+"\n", a...) } + w("add set inet mr paused { type ether_addr; size %d; flags timeout; }", pauseMaxMACs) + w("add set inet mr paused_4 { type ipv4_addr; size 4096; flags timeout; }") + w("add set inet mr paused_6 { type ipv6_addr; size 4096; flags timeout; }") + // insert = at the top: the last one inserted ends up first + w("insert rule inet mr input iifname %s ether saddr @paused fib daddr type != { local, broadcast, multicast, anycast } counter drop comment \"pause\"", lans) + w("insert rule inet mr forward iifname %s ip6 daddr @paused_6 counter drop comment \"pause\"", wans) + w("insert rule inet mr forward iifname %s ip daddr @paused_4 counter drop comment \"pause\"", wans) + w("insert rule inet mr forward iifname %s ether saddr @paused oifname %s counter drop comment \"pause\"", lans, wans) + var macs []string + elems := map[string][]string{} + left := map[string]int64{} // address → the longest remaining pause among the MACs that use it + for _, e := range ents { + secs := e.Until - now + macs = append(macs, fmt.Sprintf("%s timeout %ds", e.MAC, secs)) + for _, a := range dedup(append(append([]string{}, e.IPs...), neigh[e.MAC]...)) { + ip := net.ParseIP(a) + if ip == nil || ip.IsLinkLocalUnicast() || ip.IsMulticast() || ip.IsUnspecified() || ip.IsLoopback() { + continue + } + if o := owner[ip.String()]; o != "" && o != e.MAC { + continue // another device uses it now (the paused one left, its lease was given away) + } + set := "paused_6" + if ip.To4() != nil { + set = "paused_4" + } + k := ip.String() + if _, seen := left[k]; !seen { + elems[set] = append(elems[set], k) + } + left[k] = max(left[k], secs) + } + } + w("add element inet mr paused { %s }", strings.Join(macs, ", ")) + for _, set := range []string{"paused_4", "paused_6"} { + if len(elems[set]) == 0 { + continue + } + var xs []string + for _, a := range elems[set] { + xs = append(xs, fmt.Sprintf("%s timeout %ds", a, left[a])) + } + w("add element inet mr %s { %s }", set, strings.Join(xs, ", ")) + } + return b.String() +} + +// pauseNeigh: the addresses the router knows for each MAC right now — neighbour table (ARP + NDP), +// DHCP leases, fixed addresses of dhcp.hosts / devices — and, from the neighbour table, which MAC +// holds an address now. +var pauseNeigh = func(c *Config) (byMAC map[string][]string, owner map[string]string) { + out, owner := map[string][]string{}, map[string]string{} + if nb, err := monNeighbours(); err == nil { + for _, x := range nb { + m := strings.ToLower(x.MAC) + if m == "" || !x.Addr.IsValid() { + continue + } + out[m] = append(out[m], x.Addr.String()) + owner[x.Addr.Unmap().String()] = m + } + } + v4, _ := parseLeases(readFile(pauseLeaseFile)) + for _, l := range v4 { + m := strings.ToLower(l.MAC) + out[m] = append(out[m], l.IP) + } + for _, h := range c.knownHosts() { + if h.IP != "" { + m := strings.ToLower(h.MAC) + out[m] = append(out[m], h.IP) + } + } + return out, owner +} + +// pauseTarget resolves what to pause: a device, group:NAME, a dhcp.hosts name or a MAC. +func pauseTarget(c *Config, t string) ([]string, error) { + switch { + case reMAC.MatchString(t): + if hw, _ := net.ParseMAC(t); hw[0]&1 != 0 { + return nil, fmt.Errorf("%s is not a unicast MAC", t) + } + return []string{strings.ToLower(t)}, nil + case len(t) > 64 || !safeText(t): + return nil, fmt.Errorf("a device, group:NAME, dhcp.hosts name or MAC") + } + if m, ok := devRefMACs(c, t); ok { + if len(m) == 0 { + return nil, fmt.Errorf("%s has no devices", t) + } + return m, nil + } + for _, h := range c.DHCP.Hosts { + if h.Name != "" && strings.EqualFold(h.Name, t) && reMAC.MatchString(h.MAC) { + return []string{strings.ToLower(h.MAC)}, nil + } + } + return nil, fmt.Errorf("unknown device %q (a device, group:NAME, dhcp.hosts name or MAC)", t) +} + +// pauseDuration parses 30m, 1h, 1h30m, 90s, 1d, 2d (1 second to 7 days) into seconds. +func pauseDuration(s string) (int64, error) { + var secs int64 + if n, ok := strings.CutSuffix(s, "d"); ok && monIsNum(n) && len(n) <= 2 { + secs = int64(atoi(n)) * 86400 + } else if d, err := time.ParseDuration(s); err == nil { + secs = int64(d / time.Second) + } + if secs < 1 || secs > pauseMaxSecs { + return 0, fmt.Errorf("duration: 30m, 1h, 2h30m, 1d … (1s to 7d), got %q", s) + } + return secs, nil +} + +// pauseSet pauses every MAC of target for secs and reloads the firewall. +func pauseSet(c *Config, target string, secs int64, by string) ([]string, error) { + macs, err := pauseTarget(c, target) + if err != nil { + return nil, err + } + if lk := flock(pauseLock, true); lk != nil { + defer lk.Close() + } + now := pauseUptime() + ents := pauseRead(now) + neigh, _ := pauseNeigh(c) + for _, m := range macs { + i := 0 + for i < len(ents) && ents[i].MAC != m { + i++ + } + if i == len(ents) { + ents = append(ents, pauseEntry{MAC: m}) + } + e := &ents[i] + e.Until, e.Ref, e.By = now+secs, target, by + e.IPs = dedup(append(e.IPs, neigh[m]...)) + if len(e.IPs) > 32 { + e.IPs = e.IPs[len(e.IPs)-32:] + } + } + if len(ents) > pauseMaxMACs { + return nil, fmt.Errorf("at most %d paused MACs", pauseMaxMACs) + } + if err := pauseWrite(ents); err != nil { + return nil, err + } + if err := pauseReload(c); err != nil { + return nil, err + } + logf("pause: %s (%s) for %ds by %s", target, strings.Join(macs, " "), secs, by) + return macs, pauseLoaded(macs) +} + +// pauseClear ends the pauses of target ("all": every pause) and reloads the firewall. +func pauseClear(c *Config, target, by string) ([]string, error) { + var macs []string + if target != "all" { + var err error + if macs, err = pauseTarget(c, target); err != nil { + return nil, err + } + } + if lk := flock(pauseLock, true); lk != nil { + defer lk.Close() + } + ents := pauseRead(pauseUptime()) + var keep []pauseEntry + var gone []string + for _, e := range ents { + if target == "all" || containsString(macs, e.MAC) { + gone = append(gone, e.MAC) + } else { + keep = append(keep, e) + } + } + if err := pauseWrite(keep); err != nil { + return nil, err + } + if len(gone) == 0 { + return nil, nil // nothing was paused: no reload + } + logf("unpause: %s (%s) by %s", target, strings.Join(gone, " "), by) + return gone, pauseReload(c) +} + +// pauseView is one active pause as the web UI and `mr pause list` show it. +type pauseView struct { + MAC string `json:"mac"` + Name string `json:"name,omitempty"` // device / dhcp.hosts / DHCP client name + Ref string `json:"ref,omitempty"` + By string `json:"by,omitempty"` + Left int64 `json:"left"` // seconds + IPs []string `json:"ips,omitempty"` +} + +func pauseList(c *Config) []pauseView { + now := pauseUptime() + ents := pauseRead(now) + if len(ents) == 0 { + return []pauseView{} + } + names := map[string]string{} + v4, _ := parseLeases(readFile(pauseLeaseFile)) + for _, l := range v4 { + if l.Name != "" && l.Name != "*" { + names[strings.ToLower(l.MAC)] = eventClean(l.Name, 64) + } + } + for _, h := range c.knownHosts() { + if h.Name != "" { + names[strings.ToLower(h.MAC)] = h.Name + } + } + out := []pauseView{} + for _, e := range ents { + out = append(out, pauseView{MAC: e.MAC, Name: names[e.MAC], Ref: e.Ref, By: e.By, Left: e.Until - now, IPs: e.IPs}) + } + sort.SliceStable(out, func(i, j int) bool { return out[i].Left < out[j].Left }) + return out +} + +// pauseStatus (status JSON, overview card): the active pauses, only when there are some. +func pauseStatus(c *Config, st map[string]any) { + if l := pauseList(c); len(l) > 0 { + st["paused"] = l + } +} + +// ---- web UI / API ---- + +func pauseBy(r apiReq) string { + if r.via != "" { + return r.via + } + return "web" +} + +func apiDevPaused(r apiReq) apiResp { + c, err := loadConfig(devConfigPath, devSecretsPath) + if err != nil { + return errResp(500, "%v", err) + } + return apiResp{body: map[string]any{"paused": pauseList(c)}} +} + +// apiDevPause (POST {target, duration}): pause a device, group or MAC. +func apiDevPause(r apiReq) apiResp { + if r.method != "POST" { + return errResp(405, "POST required") + } + var in struct { + Target string `json:"target"` + Duration string `json:"duration"` + } + if err := json.Unmarshal(r.body, &in); err != nil { + return errResp(400, "bad request") + } + secs, err := pauseDuration(in.Duration) + if err != nil { + return errResp(400, "%v", err) + } + c, err := loadConfig(devConfigPath, devSecretsPath) + if err != nil { + return errResp(500, "%v", err) + } + macs, err := pauseSet(c, in.Target, secs, pauseBy(r)) + if err != nil { + return errResp(400, "%v", err) + } + appendChangeLog(fmt.Sprintf("%s: pause %s (%s) for %s", pauseBy(r), in.Target, strings.Join(macs, " "), in.Duration)) + return apiResp{body: map[string]any{"ok": true, "paused": pauseList(c)}} +} + +// apiDevUnpause (POST {target}): end the pause of a device, group or MAC ("all": every pause). +func apiDevUnpause(r apiReq) apiResp { + if r.method != "POST" { + return errResp(405, "POST required") + } + var in struct { + Target string `json:"target"` + } + if err := json.Unmarshal(r.body, &in); err != nil { + return errResp(400, "bad request") + } + c, err := loadConfig(devConfigPath, devSecretsPath) + if err != nil { + return errResp(500, "%v", err) + } + gone, err := pauseClear(c, in.Target, pauseBy(r)) + if err != nil { + return errResp(400, "%v", err) + } + if len(gone) > 0 { + appendChangeLog(fmt.Sprintf("%s: unpause %s (%s)", pauseBy(r), in.Target, strings.Join(gone, " "))) + } + return apiResp{body: map[string]any{"ok": true, "paused": pauseList(c)}} +} + +// ---- mr pause / mr unpause ---- + +const pauseUsage = `mr pause TARGET DURATION pause internet access: TARGET = device, group:NAME, dhcp.hosts name or MAC; + DURATION = 30m, 1h, 2h30m, 1d … (max 7d); pausing again sets a new end +mr pause list [--json] the active pauses +mr unpause TARGET|all end a pause now` + +func pauseCommand(c *Config, args []string) error { + if len(args) >= 1 && args[0] == "list" { + l := pauseList(c) + if len(args) > 1 && args[1] == "--json" { + b, _ := json.MarshalIndent(map[string]any{"paused": l}, "", " ") + fmt.Println(string(b)) + return nil + } + if len(l) == 0 { + fmt.Println("nothing paused") + } + for _, p := range l { + fmt.Printf("%-17s %-20s %-12s %s left %s\n", p.MAC, orDash(p.Name), orDash(p.Ref), fmtLeft(p.Left), strings.Join(p.IPs, " ")) + } + return nil + } + if len(args) != 2 { + return fmt.Errorf("usage:\n%s", pauseUsage) + } + secs, err := pauseDuration(args[1]) + if err != nil { + return err + } + macs, err := pauseSet(c, args[0], secs, "cli") + if err != nil { + return err + } + fmt.Printf("paused %s (%s) for %s\n", args[0], strings.Join(macs, " "), fmtLeft(secs)) + return nil +} + +func unpauseCommand(c *Config, args []string) error { + if len(args) != 1 { + return fmt.Errorf("usage:\n%s", pauseUsage) + } + gone, err := pauseClear(c, args[0], "cli") + if err != nil { + return err + } + if len(gone) == 0 { + fmt.Println("was not paused") + return nil + } + fmt.Printf("unpaused %s\n", strings.Join(gone, " ")) + return nil +} + +func orDash(s string) string { + if s == "" { + return "-" + } + return s +} + +// fmtLeft: 59m59s, 1h0m0s, 25h0m0s (whole seconds). +func fmtLeft(secs int64) string { return (time.Duration(secs) * time.Second).String() } diff --git a/mr/mod_dev_test.go b/mr/mod_dev_test.go new file mode 100644 index 0000000..fb362dd --- /dev/null +++ b/mr/mod_dev_test.go @@ -0,0 +1,338 @@ +package main + +import ( + "encoding/json" + "net/netip" + "os" + "path/filepath" + "strings" + "testing" +) + +// devConfig: the home config plus a small inventory that every section refers to. +func devConfig(t *testing.T) *Config { + t.Helper() + c := testConfig(t) + c.Devices = []Device{ + {Name: "office-pc", MACs: []string{"02:00:00:00:10:01"}, IP: "192.168.1.70", Type: "pc", Owner: "Alice"}, + {Name: "kid-tablet", MACs: []string{"AA:BB:CC:00:00:21", "aa:bb:cc:00:00:22"}, IP: "192.168.1.121"}, + {Name: "game-console", MACs: []string{"aa:bb:cc:00:00:23"}}, + } + c.Groups = map[string][]string{"kids": {"kid-tablet", "game-console"}} + return c +} + +func TestDevValidate(t *testing.T) { + c := devConfig(t) + c.Firewall.Forwards = append(c.Firewall.Forwards, Forward{Name: "rdp", Proto: []string{"tcp"}, Port: "3390", To: "office-pc", ToPort: "3389"}) + c.Firewall.Access = []FwAccess{{Name: "kids", Devices: []string{"group:kids"}}} + c.Policy = append(c.Policy, Policy{Name: "office", Device: "office-pc", Via: "wan2", Fallback: "drop"}) + c.Proxy.Bypass = []ProxyDevice{{Name: "kids", Device: "group:kids"}} + c.Guard.AlwaysBypass = []string{"kid-tablet"} + c.defaults() + if errs := c.Validate(); len(errs) > 0 { + t.Fatalf("valid inventory refused: %v", errs) + } + + bad := devConfig(t) + bad.Devices = append(bad.Devices, + Device{Name: "Bad_Name", MACs: []string{"02:00:00:00:20:01"}}, + Device{Name: "office-pc", MACs: []string{"02:00:00:00:10:01"}, IP: "192.168.1.70"}, // duplicate everything + Device{Name: "desktop", MACs: []string{"02:00:00:00:20:02"}}, // a dhcp.hosts name + Device{Name: "nomac", MACs: nil}, + Device{Name: "mcast", MACs: []string{"01:00:5e:00:00:01"}}, + Device{Name: "outside", MACs: []string{"02:00:00:00:20:03"}, IP: "10.9.9.9"}, + Device{Name: "router", MACs: []string{"02:00:00:00:20:04"}, IP: "192.168.1.6"}, + Device{Name: "evil", MACs: []string{"02:00:00:00:20:05"}, Type: "a b", Owner: "x\ny"}, + ) + bad.Devices = append(bad.Devices, Device{Name: "stolen", MACs: []string{bad.DHCP.Hosts[0].MAC}, IP: bad.DHCP.Hosts[0].IP}) + bad.Groups["kids"] = append(bad.Groups["kids"], "ghost", "game-console") + bad.Groups["Bad"] = []string{"office-pc"} + bad.Groups["empty"] = nil + wantErrs(t, bad, + `devices[3].name: lowercase letters`, `devices[4].name: duplicate "office-pc"`, + `devices[4].macs: 02:00:00:00:10:01 is also in device office-pc`, `devices[4].ip: 192.168.1.70 is also the address of device office-pc`, + `devices[5].name: "desktop" is also a dhcp.hosts name`, `devices[6].macs: 1-8 MACs`, `devices[7].macs: 01:00:5e:00:00:01 is not a unicast MAC`, + `devices[8].ip: an IPv4 inside a LAN-side network, got "10.9.9.9"`, `devices[9].ip`, `that is the router itself`, + `devices[10].type: a short label`, `devices[10].owner: max 40 characters`, + `devices[11].macs: `+strings.ToLower(bad.DHCP.Hosts[0].MAC)+` is also in dhcp.hosts`, `devices[11].ip: `+bad.DHCP.Hosts[0].IP+` is also in dhcp.hosts`, + `groups.kids: unknown device "ghost"`, `groups.kids: duplicate "game-console"`, `groups: name "Bad"`, `groups.empty: 1-256 devices`) + + // references to names that do not exist (a device deleted while still in use): every place is listed + ref := devConfig(t) + ref.Devices = ref.Devices[1:] // office-pc deleted + ref.Firewall.Forwards = append(ref.Firewall.Forwards, + Forward{Name: "rdp", Proto: []string{"tcp"}, Port: "3390", To: "office-pc"}, + Forward{Name: "cons", Proto: []string{"tcp"}, Port: "3391", To: "game-console"}) + ref.Firewall.Access = []FwAccess{{Name: "kids", Devices: []string{"group:kidz", "office-pc"}}} + ref.Policy = append(ref.Policy, Policy{Name: "office", Device: "office-pc", Via: "wan2"}, + Policy{Name: "both", MAC: "02:00:00:00:30:01", Device: "group:kids", Via: "wan2", Fallback: "never"}) + ref.Proxy.Bypass = []ProxyDevice{{Name: "pc", Device: "office-pc"}, {Name: "x", MAC: "02:00:00:00:30:02", Device: "game-console"}} + ref.Guard.AlwaysBypass = []string{"office-pc"} + ref.Proxy.Enabled = true + ref.defaults() + wantErrs(t, ref, + `firewall.forwards[3].to: unknown device "office-pc"`, `firewall.forwards[4].to: device game-console has no ip`, + `firewall.access[0].devices: unknown group "group:kidz"`, `firewall.access[0].devices: unknown device "office-pc"`, + `policy_routes[1].device: unknown device "office-pc"`, `policy_routes[2]: set mac or device, not both`, + `policy_routes[2].fallback: main|drop, got "never"`, + `proxy.bypass[0].device: unknown device "office-pc"`, `proxy.bypass[1]: set mac or device, not both`, + `guard.always_bypass: device "office-pc" is not in proxy.bypass`) + // an access entry needs at least one MAC, from macs or devices + e := devConfig(t) + e.Firewall.Access = []FwAccess{{Name: "none"}} + e.defaults() + wantErrs(t, e, `firewall.access[0].macs: 1-64 device MACs required (macs and / or devices)`) +} + +func TestDevRender(t *testing.T) { + c := devConfig(t) + c.Firewall.Forwards = append(c.Firewall.Forwards, Forward{Name: "rdp", Proto: []string{"tcp"}, Port: "3390", To: "office-pc", ToPort: "3389"}) + c.Firewall.Access = []FwAccess{{Name: "kids", MACs: []string{"02:00:00:00:30:01"}, Devices: []string{"group:kids", "kid-tablet"}}} + c.Policy = append(c.Policy, Policy{Name: "office", Device: "office-pc", Via: "wan2", Fallback: "drop"}, + Policy{Name: "kids", Device: "group:kids", Src: "192.168.1.0/24", Via: "wan", Fallback: "drop"}) + c.Proxy.Bypass = []ProxyDevice{{Name: "kids", Device: "group:kids"}, {Name: "x", MAC: "02:00:00:00:30:02"}} + c.DHCP.HostLeases = map[string]string{"aa:bb:cc:00:00:22": "infinite"} + c.defaults() + if errs := c.Validate(); len(errs) > 0 { + t.Fatal(errs) + } + files, err := Render(c) + if err != nil { + t.Fatal(err) + } + var dnsmasq string + for _, f := range files { + if f.Path == "/etc/dnsmasq.conf" { + dnsmasq = f.Data + } + } + mustContain(t, "dnsmasq.conf", dnsmasq, + "dhcp-host=02:00:00:00:10:01,192.168.1.70,office-pc\n", + "dhcp-host=aa:bb:cc:00:00:21,aa:bb:cc:00:00:22,192.168.1.121,kid-tablet,infinite\n", + "dhcp-host=aa:bb:cc:00:00:23,game-console\n") + nft := renderNft(c, allExist) + kids := "{ aa:bb:cc:00:00:21, aa:bb:cc:00:00:22, aa:bb:cc:00:00:23 }" + mustContain(t, "nft", nft, + `tcp dport 3390 dnat ip to 192.168.1.70:3389 comment "rdp"`, + `ether saddr { 02:00:00:00:30:01, aa:bb:cc:00:00:21, aa:bb:cc:00:00:22, aa:bb:cc:00:00:23 } update @ac_4`, + `iifname "br-lan" ether saddr 02:00:00:00:10:01 ip daddr != 192.168.1.0/24 ct state new ct mark set 0x102`, + `iifname "br-lan" ether saddr `+kids+` ip saddr 192.168.1.0/24 ip daddr != 192.168.1.0/24 ct state new`, + // fallback: drop, at the top of forward (before the access rules and flow offload) + `iifname "br-lan" ether saddr 02:00:00:00:10:01 oifname "pppoe-wan" counter drop comment "fallback:office"`, + `iifname "br-lan" ether saddr `+kids+` ip saddr 192.168.1.0/24 oifname "pppoe-wan2" counter drop comment "fallback:kids"`) + fwd := nft[strings.Index(nft, "chain forward {"):] + if a, b := strings.Index(fwd, "fallback:office"), strings.Index(fwd, "update @ac_4"); a < 0 || b < 0 || a > b || b > strings.Index(fwd, "flow add") { + t.Errorf("forward chain order: fallback, access, flow offload\n%s", fwd[:min(len(fwd), 1500)]) + } + // the rendered file never holds runtime pauses + mustNotContain(t, "nft", nft, "@paused") + + // the proxy's bypass set (rendered only with the proxy services present) + var macs []string + for _, d := range c.Proxy.Bypass { + macs = append(macs, proxyBypassMACs(c, d)...) + } + if got := strings.Join(dedup(macs), ", "); got != "aa:bb:cc:00:00:21, aa:bb:cc:00:00:22, aa:bb:cc:00:00:23, 02:00:00:00:30:02" { + t.Errorf("bypass MACs = %s", got) + } + // knownHosts: names for lists, events, WOL; static only with an ip + if mac, host, _, err := wolTarget(c, "kid-tablet", ""); err != nil || host != "kid-tablet" || mac.String() != "aa:bb:cc:00:00:21" { + t.Errorf("wol kid-tablet = %v %q %v", mac, host, err) + } +} + +// The real home config has no devices: its rendered files do not change (tools/ci.sh compares the +// whole render with the previous commit's too). +func TestDevHomeUnchanged(t *testing.T) { + c := testConfig(t) + if len(c.Devices) > 0 || len(c.Groups) > 0 { + t.Skip("the home config has an inventory now") + } + nft := renderNft(c, allExist) + mustNotContain(t, "home nft", nft, "fallback:", "@paused", "ac_4") + for _, p := range c.Policy { + if p.Fallback != "" || p.Device != "" { + t.Errorf("home policy %s uses new keys", p.Name) + } + } +} + +// pauseEnv: pause state in a temp dir, a fixed clock, a fake neighbour table, reloads recorded. +func pauseEnv(t *testing.T, now *int64) (reloads *int) { + t.Helper() + d := t.TempDir() + oldF, oldL, oldU, oldR, oldLd, oldN, oldCL, oldLF := pauseFile, pauseLock, pauseUptime, pauseReload, pauseLoaded, monNeighbours, ChangeLog, pauseLeaseFile + t.Cleanup(func() { + pauseFile, pauseLock, pauseUptime, pauseReload, pauseLoaded, monNeighbours, ChangeLog, pauseLeaseFile = oldF, oldL, oldU, oldR, oldLd, oldN, oldCL, oldLF + }) + pauseFile, pauseLock, ChangeLog, pauseLeaseFile = filepath.Join(d, "pause.json"), filepath.Join(d, "pause.lock"), filepath.Join(d, "changes.log"), filepath.Join(d, "leases") + os.WriteFile(pauseLeaseFile, []byte("1900000000 aa:bb:cc:00:00:23 192.168.1.140 console *\n"), 0644) + pauseUptime = func() int64 { return *now } + n := 0 + pauseReload = func(*Config) error { n++; return nil } + pauseLoaded = func([]string) error { return nil } + monNeighbours = func() ([]monNeigh, error) { + return []monNeigh{ + {Addr: netip.MustParseAddr("192.168.1.121"), MAC: "aa:bb:cc:00:00:21"}, + {Addr: netip.MustParseAddr("2001:db8:1::21"), MAC: "aa:bb:cc:00:00:21"}, + {Addr: netip.MustParseAddr("fe80::21"), MAC: "aa:bb:cc:00:00:21"}, + {Addr: netip.MustParseAddr("192.168.1.99"), MAC: "02:00:00:00:99:99"}, // took over an old address + }, nil + } + return &n +} + +func TestPause(t *testing.T) { + now := int64(1000) + reloads := pauseEnv(t, &now) + c := devConfig(t) + c.defaults() + + for _, d := range []string{"0s", "8d", "90", "1x", "-1h", ""} { + if _, err := pauseDuration(d); err == nil { + t.Errorf("duration %q accepted", d) + } + } + for d, want := range map[string]int64{"30m": 1800, "1h": 3600, "2h30m": 9000, "1d": 86400, "7d": 604800, "45s": 45} { + if got, err := pauseDuration(d); err != nil || got != want { + t.Errorf("duration %q = %d, %v", d, got, err) + } + } + for _, bad := range []string{"nobody", "group:none", "01:00:5e:00:00:01", strings.Repeat("x", 80), "a\nb"} { + if _, err := pauseTarget(c, bad); err == nil { + t.Errorf("target %q accepted", bad) + } + } + if m, err := pauseTarget(c, strings.ToUpper(c.DHCP.Hosts[0].Name)); err != nil || len(m) != 1 { + t.Errorf("a dhcp.hosts name: %v %v", m, err) + } + + if s := pauseScript(c); s != "" { + t.Fatalf("nothing paused but a script: %s", s) + } + macs, err := pauseSet(c, "group:kids", 3600, "cli") + if err != nil || strings.Join(macs, " ") != "aa:bb:cc:00:00:21 aa:bb:cc:00:00:22 aa:bb:cc:00:00:23" || *reloads != 1 { + t.Fatalf("pause group:kids = %v, %v (%d reloads)", macs, err, *reloads) + } + now += 600 + if _, err := pauseSet(c, "02:00:00:00:99:99", 60, "web"); err != nil { + t.Fatal(err) + } + s := pauseScript(c) + mustContain(t, "pause script", s, + "add set inet mr paused { type ether_addr; size 256; flags timeout; }", + `insert rule inet mr forward iifname { "br-lan" } ether saddr @paused oifname { "pppoe-wan", "pppoe-wan2" } counter drop comment "pause"`, + `insert rule inet mr forward iifname { "pppoe-wan", "pppoe-wan2" } ip daddr @paused_4 counter drop comment "pause"`, + `insert rule inet mr forward iifname { "pppoe-wan", "pppoe-wan2" } ip6 daddr @paused_6 counter drop comment "pause"`, + `insert rule inet mr input iifname { "br-lan" } ether saddr @paused fib daddr type != { local, broadcast, multicast, anycast } counter drop comment "pause"`, + "add element inet mr paused { aa:bb:cc:00:00:21 timeout 3000s, aa:bb:cc:00:00:22 timeout 3000s, aa:bb:cc:00:00:23 timeout 3000s, 02:00:00:00:99:99 timeout 60s }", + "192.168.1.121 timeout 3000s", "192.168.1.140 timeout 3000s", "192.168.1.99 timeout 60s", + "add element inet mr paused_6 { 2001:db8:1::21 timeout 3000s }") + mustNotContain(t, "pause script", s, "fe80::21") + + // an address another (not paused) device holds now is left alone + monNeighbours = func() ([]monNeigh, error) { + return []monNeigh{{Addr: netip.MustParseAddr("192.168.1.140"), MAC: "02:00:00:00:77:77"}}, nil + } + mustNotContain(t, "pause script", pauseScript(c), "192.168.1.140") + + l := pauseList(c) + if len(l) != 4 || l[0].MAC != "02:00:00:00:99:99" || l[0].Left != 60 || l[1].Name != "kid-tablet" || l[1].Ref != "group:kids" || l[1].By != "cli" { + t.Errorf("list = %+v", l) + } + st := map[string]any{} + pauseStatus(c, st) + if _, ok := st["paused"]; !ok { + t.Error("status lacks the pauses") + } + + // expiry: the 60 s one is gone, the kernel does the same on its own + now += 61 + if l := pauseList(c); len(l) != 3 { + t.Errorf("after 61 s: %+v", l) + } + // unpause one device of the group, then everything + gone, err := pauseClear(c, "kid-tablet", "cli") + if err != nil || len(gone) != 2 { + t.Errorf("unpause kid-tablet = %v %v", gone, err) + } + if gone, _ := pauseClear(c, "office-pc", "cli"); len(gone) != 0 { + t.Errorf("unpausing a device that is not paused: %v", gone) + } + r := *reloads + if gone, err := pauseClear(c, "all", "cli"); err != nil || len(gone) != 1 || *reloads != r+1 { + t.Errorf("unpause all = %v %v", gone, err) + } + if _, err := os.Stat(pauseFile); !os.IsNotExist(err) { + t.Error("state file left behind with nothing paused") + } + st = map[string]any{} + pauseStatus(c, st) + if _, ok := st["paused"]; ok { + t.Error("status shows pauses with nothing paused") + } + + // a tampered state file renders nothing it should not + os.WriteFile(pauseFile, []byte(`{"paused":[{"mac":"aa:bb:cc:00:00:21 } ; flush ruleset","until":99999},{"mac":"02:00:00:00:00:05","until":1700,"ips":["1.2.3.4; drop","192.168.1.5"]},{"mac":"02:00:00:00:00:06","until":999999999}]}`), 0600) + s = pauseScript(c) + mustNotContain(t, "tampered state", s, "flush", "1.2.3.4", "02:00:00:00:00:06") + mustContain(t, "tampered state", s, "02:00:00:00:00:05 timeout", "192.168.1.5 timeout") +} + +func TestPauseAPI(t *testing.T) { + now := int64(5000) + pauseEnv(t, &now) + d := t.TempDir() + y, _ := os.ReadFile("../examples/router.yaml") + y = append(y, []byte("\ndevices:\n - {name: kid-tablet, macs: [\"aa:bb:cc:00:00:21\"]}\n")...) + os.WriteFile(filepath.Join(d, "router.yaml"), y, 0644) + oldC, oldS := devConfigPath, devSecretsPath + t.Cleanup(func() { devConfigPath, devSecretsPath = oldC, oldS }) + devConfigPath, devSecretsPath = filepath.Join(d, "router.yaml"), "testdata/secrets.yaml" + + var m *Module + for _, x := range modules { + if x.Name == "dev" { + m = x + } + } + call := func(action, method, body string) apiResp { + return m.API[action](apiReq{method: method, action: action, body: []byte(body)}) + } + if r := call("dev.pause", "GET", ""); r.status != 405 { + t.Errorf("GET dev.pause: %d", r.status) + } + if r := call("dev.unpause", "GET", ""); r.status != 405 { + t.Errorf("GET dev.unpause: %d", r.status) + } + for _, b := range []string{`{"target":"kid-tablet","duration":"9d"}`, `{"target":"nobody","duration":"1h"}`, `not json`} { + if r := call("dev.pause", "POST", b); r.status != 400 { + t.Errorf("POST dev.pause %s: %d", b, r.status) + } + } + r := call("dev.pause", "POST", `{"target":"kid-tablet","duration":"1h"}`) + if r.status != 0 { + t.Fatalf("POST dev.pause: %d %v", r.status, r.body) + } + b, _ := json.Marshal(call("dev.paused", "GET", "").body) + if !strings.Contains(string(b), `"mac":"aa:bb:cc:00:00:21","name":"kid-tablet","ref":"kid-tablet","by":"web","left":3600`) { + t.Errorf("dev.paused = %s", b) + } + if log, _ := os.ReadFile(ChangeLog); !strings.Contains(string(log), "web: pause kid-tablet (aa:bb:cc:00:00:21) for 1h") { + t.Errorf("change log: %s", log) + } + if r := call("dev.unpause", "POST", `{"target":"kid-tablet"}`); r.status != 0 { + t.Errorf("POST dev.unpause: %d %v", r.status, r.body) + } + b, _ = json.Marshal(call("dev.paused", "GET", "").body) + if string(b) != `{"paused":[]}` { + t.Errorf("after unpause: %s", b) + } + // tokens: listing is read, pausing is operate + for a, scope := range map[string]string{"dev.paused": "read", "dev.pause": "operate", "dev.unpause": "operate"} { + if tokenActions[a] != scope { + t.Errorf("tokenActions[%s] = %q, want %s", a, tokenActions[a], scope) + } + } +} diff --git a/mr/mod_dns.go b/mr/mod_dns.go index a05b17d..901cd50 100644 --- a/mr/mod_dns.go +++ b/mr/mod_dns.go @@ -340,6 +340,9 @@ func renderDnsmasq(c *Config) string { } b.WriteString(line + "\n") } + for _, l := range devDHCPHosts(c) { // the device inventory (mod_dev.go) + b.WriteString(bypassTagHost(l, bypassTag) + "\n") + } for _, m := range c.Bypass.MACs { // selected devices without a static lease (config order) if bypassTag[strings.ToLower(m)] { w("dhcp-host=%s,set:bypass", strings.ToLower(m)) @@ -737,9 +740,14 @@ func dnsValidate(c *Config, v *Validator) { } ips[h.IP] = true } + for _, d := range c.Devices { + for _, m := range d.MACs { + macs[strings.ToLower(m)] = true + } + } for mac, l := range c.DHCP.HostLeases { if !macs[strings.ToLower(mac)] { - v.Add("dhcp.host_leases: %q is not the MAC of a dhcp.hosts entry", mac) + v.Add("dhcp.host_leases: %q is not the MAC of a dhcp.hosts entry or a device", mac) } if !reLease.MatchString(l) { v.Add("dhcp.host_leases[%s]: e.g. 12h, 30m, 1d or infinite, got %q", mac, l) diff --git a/mr/mod_dns_leases.go b/mr/mod_dns_leases.go index dd21722..6ad16ca 100644 --- a/mr/mod_dns_leases.go +++ b/mr/mod_dns_leases.go @@ -71,8 +71,8 @@ func parseLeases(data string) (v4 []lease, v6 []lease6) { func readLeases(c *Config) ([]lease, []lease6) { v4, v6 := parseLeases(readFile(LeaseFile)) static := map[string]bool{} - for _, h := range c.DHCP.Hosts { - static[strings.ToLower(h.MAC)] = true + for _, h := range c.knownHosts() { + static[strings.ToLower(h.MAC)] = h.IP != "" } for i := range v4 { l := &v4[i] diff --git a/mr/mod_fw.go b/mr/mod_fw.go index 2be6432..538e123 100644 --- a/mr/mod_fw.go +++ b/mr/mod_fw.go @@ -38,7 +38,7 @@ type Forward struct { Enabled *bool `yaml:"enabled,omitempty"` // default true Proto []string `yaml:"proto"` Port string `yaml:"port"` // external port or range a-b - To string `yaml:"to"` // LAN-side IPv4 + To string `yaml:"to"` // LAN-side IPv4, or a device (devices:) with ip ToPort string `yaml:"to_port"` WAN []string `yaml:"wan,omitempty"` // only these WANs (default: all) SrcIP []string `yaml:"src_ip,omitempty"` // only these IPv4 sources (default: any) @@ -94,6 +94,7 @@ type FwAccess struct { Name string `yaml:"name"` Enabled *bool `yaml:"enabled,omitempty"` MACs []string `yaml:"macs"` + Devices []string `yaml:"devices,omitempty"` // devices / group:NAME from the inventory (mod_dev.go), with or instead of macs Schedule []FwTime `yaml:"schedule,omitempty"` // blocked only in these windows; empty = always blocked Desc string `yaml:"desc,omitempty"` } @@ -190,8 +191,14 @@ func fwValidate(c *Config, v *Validator) { } else if x.ToPort != "" && x.ToPort != x.Port && strings.Contains(x.Port, "-") && strings.Contains(x.ToPort, "-") { v.Add("%s.to_port: a port range maps to the same range or to one port, got %s -> %s", p, x.Port, x.ToPort) } - if err := fwCheckTarget(c, x.To); err != "" { - v.Add("%s.to: must be an IPv4 inside a LAN-side network (%s), got %q: %s", p, c.LAN.IPv4, x.To, err) + if d := c.device(x.To); d != nil { + if d.IP == "" { + v.Add("%s.to: device %s has no ip (a forward needs a fixed address)", p, x.To) + } + } else if net.ParseIP(x.To) == nil && reDevName.MatchString(x.To) { + v.Add("%s.to: unknown device %q (devices:)", p, x.To) + } else if err := fwCheckTarget(c, x.To); err != "" { + v.Add("%s.to: must be an IPv4 inside a LAN-side network (%s) or a device, got %q: %s", p, c.LAN.IPv4, x.To, err) } if !validProtos(x.Proto) { v.Add("%s.proto: tcp/udp list, got %v", p, x.Proto) @@ -259,14 +266,15 @@ func fwValidate(c *Config, v *Validator) { p := fmt.Sprintf("firewall.access[%d]", i) fwCheckName(v, p, a.Name, names) fwCheckDesc(v, p, a.Desc) - if len(a.MACs) == 0 || len(a.MACs) > fwMaxList { - v.Add("%s.macs: 1-%d device MACs required", p, fwMaxList) - } for _, m := range a.MACs { if !reMAC.MatchString(m) { v.Add("%s.macs: invalid %q", p, m) } } + devCheckRefs(c, v, p+".devices", a.Devices) + if n := len(fwAccessMACs(c, a)); n == 0 || n > fwMaxList || len(a.MACs) > fwMaxList { + v.Add("%s.macs: 1-%d device MACs required (macs and / or devices)", p, fwMaxList) + } fwCheckSchedule(v, p, a.Schedule) } } diff --git a/mr/mod_fw_nft.go b/mr/mod_fw_nft.go index 7ae786f..c1a1847 100644 --- a/mr/mod_fw_nft.go +++ b/mr/mod_fw_nft.go @@ -7,11 +7,15 @@ package main // // Chain order (filter): // -// input: [access: proxy bypass] → ct state → lo → [rules → router] → lan accept → guest (dhcp/dns/icmp) -// → synflood → wan ping → required ICMPv6 / DHCPv6 / MLD / IGMP → hook input (open ports, -// tailscale, …) → [log] → counted wan drop → policy drop -// forward: [access control] → flow offload → ct state → hook forward_early (traffic rules, …) -// → lan accept → guest→wan → dnat accept → hook forward (IPv6 pinholes, …) → ICMPv6 → drop +// input: [pause] → [access: proxy bypass] → ct state → lo → [rules → router] → lan accept → guest +// (dhcp/dns/icmp) → synflood → wan ping → required ICMPv6 / DHCPv6 / MLD / IGMP → hook input +// (open ports, tailscale, …) → [log] → counted wan drop → policy drop +// forward: [pause] → hook forward_first (policy route fallback: drop) → [access control] → flow +// offload → ct state → hook forward_early (traffic rules, …) → lan accept → guest→wan → +// dnat accept → hook forward (IPv6 pinholes, …) → ICMPv6 → drop +// +// [pause] (`mr pause`, mod_dev_pause.go) is runtime state, not config: fwLoad inserts it in the same +// transaction while a pause is active, so it is never in the rendered file (nor in `mr plan`). import ( "encoding/json" @@ -136,6 +140,7 @@ func renderNft(c *Config, exists func(string) bool) string { w("\t}") w("\tchain forward {\n\t\ttype filter hook forward priority filter; policy drop;") + hook("forward_first") acc := fwAccessForward(c, clk) for _, l := range acc { r("%s", l) @@ -208,7 +213,7 @@ func fwNft(c *Config, hook string, n *Nft) { n.W("chain reflect {\n\t\ttype nat hook prerouting priority dstnat + 1; policy accept;") for _, f := range fwd { for _, p := range f.Proto { - n.W("\tiifname %s fib daddr type local ip daddr != %s %s dport %s dnat ip to %s", iif, routers, p, nftPorts(f.Port), fwdTo(f)) + n.W("\tiifname %s fib daddr type local ip daddr != %s %s dport %s dnat ip to %s", iif, routers, p, nftPorts(f.Port), fwdTo(c, f)) } } n.W("}") @@ -255,7 +260,7 @@ func fwNft(c *Config, hook string, n *Nft) { src = "ip saddr " + nftSet(v4) + " " } for _, p := range f.Proto { - n.W("iifname %s %s%s dport %s dnat ip to %s comment %q", fwWANSet(c, f.WAN), src, p, nftPorts(f.Port), fwdTo(f), f.Name) + n.W("iifname %s %s%s dport %s dnat ip to %s comment %q", fwWANSet(c, f.WAN), src, p, nftPorts(f.Port), fwdTo(c, f), f.Name) } } case "srcnat": @@ -287,11 +292,13 @@ func fwEnabledForwards(c *Config) []Forward { return out } -func fwdTo(f Forward) string { +// fwdTo: the DNAT target (a device name resolves to its ip), with the port when it differs. +func fwdTo(c *Config, f Forward) string { + to := devHostIP(c, f.To) if f.ToPort != "" && f.ToPort != f.Port { - return fmt.Sprintf("%s:%s", f.To, nftPorts(f.ToPort)) + return fmt.Sprintf("%s:%s", to, nftPorts(f.ToPort)) } - return f.To + return to } // fwReflectMatch: input interfaces and router addresses for the NAT loopback chain. @@ -447,11 +454,16 @@ func fwRuleLines(c *Config, x FwRule, clk fwClock) []string { // ---- device access control ---- +// fwAccessMACs: an entry's MACs and those of its devices / groups, lowercase, each once. +func fwAccessMACs(c *Config, a FwAccess) []string { + return dedup(append(lowerAll(a.MACs), devMACs(c, a.Devices)...)) +} + // fwAccessEntries returns the indices of enabled access entries. func fwAccessEntries(c *Config) []int { var out []int for i, a := range c.Firewall.Access { - if on(a.Enabled) && len(a.MACs) > 0 { + if on(a.Enabled) && len(fwAccessMACs(c, a)) > 0 { out = append(out, i) } } @@ -469,7 +481,7 @@ func fwAccessForward(c *Config, clk fwClock) []string { wanSet := "{ " + quoteList(c.WANIfnames()) + " }" for _, i := range fwAccessEntries(c) { a := c.Firewall.Access[i] - macs := nftSet(lowerAll(a.MACs)) + macs := nftSet(fwAccessMACs(c, a)) cm := fmt.Sprintf("%q", "access:"+a.Name) out = append(out, fmt.Sprintf("iifname %s ether saddr %s update @ac_4 { ip saddr } update @ac%d_4 { ip saddr }", lanSide, macs, i), @@ -502,7 +514,7 @@ func fwAccessInput(c *Config, clk fwClock) []string { if tm != "" { tm += " " } - out = append(out, fmt.Sprintf("iifname %s ether saddr %s %sfib daddr type != { local, broadcast, multicast, anycast } counter drop comment %q", lanSide, nftSet(lowerAll(a.MACs)), tm, "access:"+a.Name)) + out = append(out, fmt.Sprintf("iifname %s ether saddr %s %sfib daddr type != { local, broadcast, multicast, anycast } counter drop comment %q", lanSide, nftSet(fwAccessMACs(c, a)), tm, "access:"+a.Name)) } } return out @@ -519,14 +531,14 @@ func fwAccessInput(c *Config, clk fwClock) []string { func fwAccessElements(c *Config, neigh []fwNeigh, prev []fwLearnedElem) string { idx := map[string][]int{} for _, i := range fwAccessEntries(c) { - for _, m := range lowerAll(c.Firewall.Access[i].MACs) { + for _, m := range fwAccessMACs(c, c.Firewall.Access[i]) { idx[m] = append(idx[m], i) } } if len(idx) == 0 { return "" } - for _, h := range c.DHCP.Hosts { + for _, h := range c.knownHosts() { neigh = append(neigh, fwNeigh{Dst: h.IP, LLAddr: h.MAC}) } elems := map[string][]string{} @@ -668,8 +680,15 @@ func netdevExists(name string) bool { return err == nil } +// fwLockFile serializes reloads: the runtime state a reload carries over (learned sets, pauses) is +// read under it, so two reloads at once (a PPPoE hook during `mr pause`) cannot load a stale copy last. +var fwLockFile = RunDir + "/fw.lock" + // fwLoad renders against live devices and loads atomically; keeps the last good ruleset on failure. func fwLoad(c *Config) error { + if lk := flock(fwLockFile, true); lk != nil { + defer lk.Close() + } rules := renderNft(c, netdevExists) path := GenDir + "/nftables.nft" tmp := path + ".new" @@ -691,6 +710,10 @@ func fwLoad(c *Config) error { // the addresses dnsmasq learned for policy_routes domains (net module): dnsmasq only adds them when // it asks upstream, so a reload that emptied the sets would send cached names to the wrong WAN elems += policyDomainCarry(c) + // active pauses (dev module): their sets and rules, in the same transaction. Replacing the table + // also replaces the flowtable, so a paused device's offloaded flows come back to the CPU path, + // where these rules drop them in both directions. + elems += pauseScript(c) loaded := false if elems != "" { if out, err := runStdin(rules+elems, "nft", "-f", "-"); err == nil { diff --git a/mr/mod_fw_test.go b/mr/mod_fw_test.go index be9bec0..498f2cd 100644 --- a/mr/mod_fw_test.go +++ b/mr/mod_fw_test.go @@ -19,7 +19,8 @@ func fixedClock(t *testing.T, kernelMW int) { } // fwLabConfig: the home config plus a guest and an IoT network, with the firewall section of the -// lab fragment examples/lab.d/40-fw.yaml (every fw feature). +// lab fragment examples/lab.d/40-fw.yaml (every fw feature) and the device inventory it refers to +// (35-dev.yaml). func fwLabConfig(t *testing.T) *Config { t.Helper() c := testConfig(t) @@ -27,19 +28,23 @@ func fwLabConfig(t *testing.T) *Config { {Name: "guest", IPv4: "192.168.20.1/24", Zone: "guest", DHCP: Pool{Enabled: true, Start: 100, End: 199}}, {Name: "iot", IPv4: "192.168.30.1/24", Zone: "lan"}, } - b, err := os.ReadFile("../examples/lab.d/40-fw.yaml") - if err != nil { - t.Fatal(err) - } var frag struct { - Firewall Firewall `yaml:"firewall"` - } - dec := yaml.NewDecoder(strings.NewReader(string(b))) - dec.KnownFields(true) - if err := dec.Decode(&frag); err != nil { - t.Fatal(err) + Firewall Firewall `yaml:"firewall"` + Devices []Device `yaml:"devices"` + Groups map[string][]string `yaml:"groups"` + } + for _, f := range []string{"40-fw.yaml", "35-dev.yaml"} { + b, err := os.ReadFile("../examples/lab.d/" + f) + if err != nil { + t.Fatal(err) + } + dec := yaml.NewDecoder(strings.NewReader(string(b))) + dec.KnownFields(true) + if err := dec.Decode(&frag); err != nil { + t.Fatal(err) + } } - c.Firewall = frag.Firewall + c.Firewall, c.Devices, c.Groups = frag.Firewall, frag.Devices, frag.Groups c.defaults() return c } @@ -358,10 +363,12 @@ func TestFwAccessElements(t *testing.T) { {"192.168.1.101", 20}, // also in the neighbour table: seen now, full timeout {"192.168.1.44", 0}, // expiring: dropped }) + // ac4: kids-school-night controls devices of the inventory; kid-tablet's fixed address is a hint too want := "add element inet mr ac0_4 { 192.168.1.101 }\n" + "add element inet mr ac0_6 { 2001:db8:1::5 }\n" + "add element inet mr ac1_4 { 192.168.1.80 }\n" + - "add element inet mr ac_4 { 192.168.1.33 timeout 3600s, 192.168.1.101, 192.168.1.80 }\n" + + "add element inet mr ac4_4 { 192.168.1.121 }\n" + + "add element inet mr ac_4 { 192.168.1.33 timeout 3600s, 192.168.1.101, 192.168.1.80, 192.168.1.121 }\n" + "add element inet mr ac_6 { 2001:db8:1::77 timeout 100s, 2001:db8:1::5 }\n" if got != want { t.Errorf("got:\n%s\nwant:\n%s", got, want) diff --git a/mr/mod_mon_ct.go b/mr/mod_mon_ct.go index 1a11e44..3c3f2cc 100644 --- a/mr/mod_mon_ct.go +++ b/mr/mod_mon_ct.go @@ -293,7 +293,7 @@ func monLoadNames(c *Config) *monNames { } } if c != nil { - for _, h := range c.DHCP.Hosts { + for _, h := range c.knownHosts() { mac := strings.ToLower(h.MAC) if h.Name != "" { n.macName[mac] = h.Name diff --git a/mr/mod_net.go b/mr/mod_net.go index ba7f900..9765ffc 100644 --- a/mr/mod_net.go +++ b/mr/mod_net.go @@ -85,16 +85,21 @@ type Mcast struct { // these names (and their subdomains) into nft sets, the rule matches the destination against them // (mod_net_domains.go). Table/Mark are optional: the first policy via a WAN may pin that WAN's // routing table and fwmark (the home config keeps table 102 / 0x102 for wan2); otherwise 200+i / 0x200+i. +// Device: a device or group:NAME of the inventory (mod_dev.go) instead of one MAC. Fallback: while +// Via has no route (down, health check failed) its traffic takes the main table's default route +// ("main", default) or is dropped ("drop": this WAN only, never another one; policyFallbackRules). type Policy struct { Name string `yaml:"name"` MAC string `yaml:"mac,omitempty"` + Device string `yaml:"device,omitempty"` // a device / group:NAME: ether saddr { its MACs } Src string `yaml:"src,omitempty"` // source IP or CIDR (LAN side) Dst string `yaml:"dst,omitempty"` // destination IP or CIDR Domains []string `yaml:"domains,omitempty"` // destination by DNS name: example.com = it and every subdomain DomainsFile string `yaml:"domains_file,omitempty"` // more domains, one per line (# comments) Via string `yaml:"via"` // WAN name Table int `yaml:"table,omitempty"` - Mark string `yaml:"mark,omitempty"` // e.g. 0x102 + Mark string `yaml:"mark,omitempty"` // e.g. 0x102 + Fallback string `yaml:"fallback,omitempty"` // main (default) | drop } // byDomain reports whether the policy selects destinations by DNS name. @@ -615,8 +620,22 @@ func netValidatePolicy(c *Config, v *Validator) { if !reLabel.MatchString(pr.Name) { v.Add("%s.name: invalid %q", p, pr.Name) } - if pr.MAC == "" && pr.Src == "" && pr.Dst == "" && !pr.byDomain() { - v.Add("%s: need at least one of mac, src, dst, domains", p) + if pr.MAC == "" && pr.Device == "" && pr.Src == "" && pr.Dst == "" && !pr.byDomain() { + v.Add("%s: need at least one of mac, device, src, dst, domains", p) + } + if pr.Device != "" { + if pr.MAC != "" { + v.Add("%s: set mac or device, not both", p) + } + devCheckRefs(c, v, p+".device", []string{pr.Device}) + if m, ok := devRefMACs(c, pr.Device); ok && (len(m) == 0 || len(m) > fwMaxList) { + v.Add("%s.device: %s stands for %d MACs (1-%d)", p, pr.Device, len(m), fwMaxList) + } + } + switch pr.Fallback { + case "", "main", "drop": + default: + v.Add("%s.fallback: main|drop, got %q", p, pr.Fallback) } for _, d := range pr.Domains { if _, ok := proxyNormDomain(d); !ok { diff --git a/mr/mod_net_render.go b/mr/mod_net_render.go index d032b30..256f888 100644 --- a/mr/mod_net_render.go +++ b/mr/mod_net_render.go @@ -367,13 +367,71 @@ func cidrStr(n *net.IPNet) string { return n.String() } -// policyRules: nft rules (mark hook) for policy route i; one per address family it covers. -func policyRules(c *Config, i int, p Policy) []string { - _, mark := c.WANTable(p.Via) +// policyHead: the LAN-side interfaces and the source MAC(s) every rule of policy p starts with. +func policyHead(c *Config, p Policy) string { head := "iifname " + nftIfnames(c.LANBridges()) if p.MAC != "" { head += " ether saddr " + strings.ToLower(p.MAC) + } else if p.Device != "" { + head += " ether saddr " + nftSet(devMACs(c, []string{p.Device})) } + return head +} + +// policyFallbackRules (hook forward_first): a policy with fallback: drop may only use its own WAN. +// While that WAN has no route (down, or failed the health check: its table lost the default route) +// the mark lookup falls through to the main table and would leave through another WAN; this rule +// drops exactly that, for established connections too (it sits before flow offload and the +// established accept). Destinations routed elsewhere (LAN, tailscale) are not affected. +func policyFallbackRules(c *Config) []string { + var out []string + for i, p := range c.Policy { + w := c.WANByName(p.Via) + if p.Fallback != "drop" || w == nil { + continue + } + var others []string + for _, x := range c.WANIfnames() { + if x != w.Ifname() { + others = append(others, x) + } + } + if len(others) == 0 { + continue + } + var src, dst *net.IPNet + if p.Src != "" { + src, _ = parseIPOrCIDR(p.Src) + } + if p.Dst != "" { + dst, _ = parseIPOrCIDR(p.Dst) + } + fams := []int{0} // 0: no address match, both families + if src != nil || dst != nil || p.byDomain() { + fams = policyFams(p) + } + for _, fam := range fams { + s := policyHead(c, p) + kw := map[int]string{4: "ip", 6: "ip6"}[fam] + if src != nil { + s += fmt.Sprintf(" %s saddr %s", kw, cidrStr(src)) + } + if dst != nil { + s += fmt.Sprintf(" %s daddr %s", kw, cidrStr(dst)) + } + if p.byDomain() { + s += fmt.Sprintf(" %s daddr @%s", kw, policySet(i, fam)) + } + out = append(out, fmt.Sprintf("%s oifname %s counter drop comment %q", s, nftIfnames(others), "fallback:"+p.Name)) + } + } + return out +} + +// policyRules: nft rules (mark hook) for policy route i; one per address family it covers. +func policyRules(c *Config, i int, p Policy) []string { + _, mark := c.WANTable(p.Via) + head := policyHead(c, p) var src, dst *net.IPNet if p.Src != "" { src, _ = parseIPOrCIDR(p.Src) @@ -459,6 +517,10 @@ func netNft(c *Config, hook string, n *Nft) { switch hook { case "defs": policyDomainDefs(c, n) + case "forward_first": + for _, r := range policyFallbackRules(c) { + n.W("%s", r) + } case "mark": // connmark: remember which WAN an inbound connection used; LAN-side packets of that connection // (replies, port-forward traffic) get the mark back and leave through the same WAN. diff --git a/mr/mod_net_test.go b/mr/mod_net_test.go index 16a96d1..6fd1117 100644 --- a/mr/mod_net_test.go +++ b/mr/mod_net_test.go @@ -187,7 +187,7 @@ func TestNetValidation(t *testing.T) { c.Networks = []Network{{Name: "iot", IPv4: "192.168.30.1/24", VLAN: 10, Trunk: []string{"wan"}}} }, "wan[0].device: wan carries VLAN 10 of network iot"}, {"mtu", func(c *Config) { c.WAN[0].MTU = 100 }, "mtu: 576-9000"}, - {"policy-empty", func(c *Config) { c.Policy[0].MAC = "" }, "need at least one of mac, src, dst"}, + {"policy-empty", func(c *Config) { c.Policy[0].MAC = "" }, "need at least one of mac, device, src, dst"}, {"policy-family", func(c *Config) { c.Policy[0].Src, c.Policy[0].Dst = "192.168.1.5", "2001:db8::/32" }, "same family"}, {"policy-src", func(c *Config) { c.Policy[0].Src = "192.168.1.0/33" }, "src: IP or CIDR"}, {"policy-dst-inject", func(c *Config) { c.Policy[0].Dst = "1.2.3.4 accept" }, "dst: IP or CIDR"}, diff --git a/mr/mod_proxy.go b/mr/mod_proxy.go index 584c3ad..f7166a7 100644 --- a/mr/mod_proxy.go +++ b/mr/mod_proxy.go @@ -123,8 +123,17 @@ type ProxyRule struct { // ProxyDevice is never proxied and always gets real DNS answers (matched by MAC, so dynamic // IPv4 and IPv6 addresses are covered). type ProxyDevice struct { - Name string `yaml:"name"` - MAC string `yaml:"mac"` + Name string `yaml:"name"` + MAC string `yaml:"mac,omitempty"` + Device string `yaml:"device,omitempty"` // or: a device / group:NAME of the inventory (mod_dev.go) +} + +// proxyBypassMACs: the MACs a bypass entry stands for (lowercase). +func proxyBypassMACs(c *Config, d ProxyDevice) []string { + if d.Device != "" { + return devMACs(c, []string{d.Device}) + } + return []string{strings.ToLower(d.MAC)} } const ( @@ -420,6 +429,13 @@ func proxyValidate(c *Config, v *Validator) { if !safeText(d.Name) || len(d.Name) > 64 { v.Add("%s.name: printable text up to 64 bytes", path) } + if d.Device != "" { + if d.MAC != "" { + v.Add("%s: set mac or device, not both", path) + } + devCheckRefs(c, v, path+".device", []string{d.Device}) + continue + } if !reMAC.MatchString(d.MAC) { v.Add("%s.mac: invalid %q", path, d.MAC) } diff --git a/mr/mod_proxy_render.go b/mr/mod_proxy_render.go index 83e80bf..d1d4a2a 100644 --- a/mr/mod_proxy_render.go +++ b/mr/mod_proxy_render.go @@ -492,9 +492,11 @@ func proxyNft(c *Config, hook string, n *Nft) { if len(p.Bypass) > 0 { var macs []string for _, d := range p.Bypass { - macs = append(macs, strings.ToLower(d.MAC)) + macs = append(macs, proxyBypassMACs(c, d)...) + } + if macs = dedup(macs); len(macs) > 0 { // a bypass group may be empty of devices + n.W("\telements = { %s }", strings.Join(macs, ", ")) } - n.W("\telements = { %s }", strings.Join(dedup(macs), ", ")) } n.W("}") n.W("set proxy4 {\n\t\ttype ipv4_addr\n\t\tflags interval\n\t\tauto-merge\n\t\telements = { %s }\n\t}", nftElems(v4)) diff --git a/mr/mod_sys_event.go b/mr/mod_sys_event.go index b2e09bc..e166c27 100644 --- a/mr/mod_sys_event.go +++ b/mr/mod_sys_event.go @@ -517,7 +517,7 @@ func eventScanLeases(c *Config) { } } learning := now.Unix() < learnUntil - for _, h := range c.DHCP.Hosts { + for _, h := range c.knownHosts() { // dhcp.hosts and the device inventory are never "new" known[strings.ToLower(h.MAC)] = true } var added []string diff --git a/mr/mod_sys_wol.go b/mr/mod_sys_wol.go index 498e0c4..db3dba2 100644 --- a/mr/mod_sys_wol.go +++ b/mr/mod_sys_wol.go @@ -6,7 +6,7 @@ package main // The magic packet (6 × 0xff, then the MAC 16 times: 102 bytes) is a UDP datagram to port 9 of the // LAN-side network's directed broadcast (e.g. 192.168.1.255), sent three times from the router's address // on that network with the socket pinned to its bridge (SO_BINDTODEVICE): it can only leave there, never -// through a WAN (255.255.255.255 would follow the default route). HOST is a dhcp.hosts name; the network +// through a WAN (255.255.255.255 would follow the default route). HOST is a dhcp.hosts name or a device; the network // is the one the host's address is in, else the main LAN. No config, nothing resident. Waking a device // from outside goes through the web UI (e.g. over Tailscale): there is no WOL listener on the WAN. @@ -41,13 +41,13 @@ func wolTarget(c *Config, target, network string) (net.HardwareAddr, string, LAN switch { case reMAC.MatchString(target): mac, _ = net.ParseMAC(target) - for _, h := range c.DHCP.Hosts { + for _, h := range c.knownHosts() { if strings.EqualFold(h.MAC, target) { host, hostIP = h.Name, net.ParseIP(h.IP) } } case reHostname.MatchString(target): - for _, h := range c.DHCP.Hosts { + for _, h := range c.knownHosts() { // a device with several MACs: the first one if h.Name != "" && strings.EqualFold(h.Name, target) { mac, _ = net.ParseMAC(h.MAC) host, hostIP = h.Name, net.ParseIP(h.IP) @@ -55,10 +55,10 @@ func wolTarget(c *Config, target, network string) (net.HardwareAddr, string, LAN } } if mac == nil { - return nil, "", LANNet{}, fmt.Errorf("no dhcp.hosts entry named %q", target) + return nil, "", LANNet{}, fmt.Errorf("no dhcp.hosts entry or device named %q", target) } default: - return nil, "", LANNet{}, fmt.Errorf("a MAC address (aa:bb:cc:dd:ee:ff) or a dhcp.hosts name, got %q", target) + return nil, "", LANNet{}, fmt.Errorf("a MAC address (aa:bb:cc:dd:ee:ff), a dhcp.hosts name or a device, got %q", target) } if len(mac) != 6 || mac[0]&1 != 0 || bytes.Equal(mac, make(net.HardwareAddr, 6)) { return nil, "", LANNet{}, fmt.Errorf("%s is not a unicast MAC address", target) diff --git a/mr/mode.go b/mr/mode.go index f23f9fd..7488805 100644 --- a/mr/mode.go +++ b/mr/mode.go @@ -165,3 +165,24 @@ func modeNetSh(c *Config, phase string, b *strings.Builder) { fmt.Fprintf(b, "ip -4 route replace default via %s dev %s table %d\n", c.LAN.Gateway, br, bypassTable) } } + +// bypassTagHost: a dhcp-host line of the device inventory gets the bypass tag (clients selected) when +// one of its MACs is selected; those MACs then need no line of their own. +func bypassTagHost(line string, tag map[string]bool) string { + if len(tag) == 0 { + return line + } + fields := strings.Split(strings.TrimPrefix(line, "dhcp-host="), ",") + n, hit := 0, false + for ; n < len(fields) && reMAC.MatchString(fields[n]); n++ { + if m := strings.ToLower(fields[n]); tag[m] { + hit = true + delete(tag, m) + } + } + if !hit { + return line + } + out := append(append(append([]string{}, fields[:n]...), "set:bypass"), fields[n:]...) + return "dhcp-host=" + strings.Join(out, ",") +} diff --git a/mr/mode_test.go b/mr/mode_test.go index ef28853..c058f45 100644 --- a/mr/mode_test.go +++ b/mr/mode_test.go @@ -179,6 +179,13 @@ func TestModeBypassDHCP(t *testing.T) { if strings.Count(conf, "02:00:00:00:00:21") != 1 { t.Error("a selected device with a static lease has two dhcp-host lines") } + // a selected MAC that belongs to a device of the inventory: the device's line carries the tag + c.Devices = []Device{{Name: "tablet", MACs: []string{"02:00:00:00:00:22", "02:00:00:00:00:23"}}} + mustValid(t, c) + conf = modeFiles(t, c)["/etc/dnsmasq.conf"] + if !strings.Contains(conf, "dhcp-host=02:00:00:00:00:22,02:00:00:00:00:23,set:bypass,") || strings.Count(conf, "02:00:00:00:00:22") != 1 { + t.Errorf("device line:\n%s", conf) + } } // ap: bridging only — forwarding off, no flowtable, no NAT, no DHCP. diff --git a/mr/module.go b/mr/module.go index 3307447..ce56751 100644 --- a/mr/module.go +++ b/mr/module.go @@ -15,7 +15,7 @@ import ( type Module struct { Name string // Prio orders modules wherever order matters (network.sh fragments, nft hook emission, - // render output): lower runs first. net=10 wifi=20 dns=30 fw=40 mon=50 proxy=55 sys=70 api=80. + // render output): lower runs first. net=10 wifi=20 dns=30 dev=35 fw=40 mon=50 proxy=55 sys=70 api=80. Prio int // Defaults fills in zero values after loading (runs before Validate). @@ -106,14 +106,16 @@ func (n *Nft) W(f string, a ...any) { fmt.Fprintf(n.b, n.indent+f+"\n", a...) } // // defs table level: sets, maps, counters, extra chains (with or without hooks) // input filter/input after established/related/lo/LAN accepts; accept or drop WAN-side traffic -// forward_early filter/forward before the LAN accept (blocks: traffic rules, guest isolation); -// fw's device access control sits at the very top of forward, before `flow add` +// forward_first filter/forward at the very top, before `flow add` and the established accept: drops +// that must also stop established connections (policy route fallback: drop); fw's +// device access control follows it, `mr pause` inserts its rules above both +// forward_early filter/forward before the LAN accept (blocks: traffic rules, guest isolation) // forward filter/forward after the LAN accept (extra accepts, e.g. igmpproxy) // mark prerouting mangle (policy routing marks, connmark); runs before routing // dstnat nat prerouting (port forwards, DNS redirect) // srcnat nat postrouting (masquerade, SNAT) // output filter/output (policy accept) -var nftHooks = []string{"defs", "input", "forward_early", "forward", "mark", "dstnat", "srcnat", "output"} +var nftHooks = []string{"defs", "input", "forward_first", "forward_early", "forward", "mark", "dstnat", "srcnat", "output"} func emitNft(c *Config, hook string, b *strings.Builder, exists func(string) bool) { indent := "\t\t" diff --git a/mr/module_test.go b/mr/module_test.go index 25e0c65..d9eae2b 100644 --- a/mr/module_test.go +++ b/mr/module_test.go @@ -6,7 +6,7 @@ import ( ) func TestModulesRegistered(t *testing.T) { - want := []string{"net", "wifi", "dns", "fw", "mon", "proxy", "sys", "api"} + want := []string{"net", "wifi", "dns", "dev", "fw", "mon", "proxy", "sys", "api"} var got []string for _, m := range modules { got = append(got, m.Name) diff --git a/mr/schema.go b/mr/schema.go index 974f986..23e4188 100644 --- a/mr/schema.go +++ b/mr/schema.go @@ -30,6 +30,7 @@ func schemaEnums() map[string][]string { "WAN.Proto": e("pppoe", "dhcp", "static"), "Network.Zone": e("", "guest", "lan"), "MultiWAN.Mode": e("", "failover", "balance"), + "Policy.Fallback": e("", "main", "drop"), "Radio.Band": e("2g", "5g"), "Radio.Profile": e("", "mt7986", "generic"), "Radio.HTMode": e("HT20", "HT40", "VHT20", "VHT40", "VHT80", "VHT160", "HE20", "HE40", "HE80", "HE160"), diff --git a/rootfs/www/index.html b/rootfs/www/index.html index e85905f..ad5d64b 100644 --- a/rootfs/www/index.html +++ b/rootfs/www/index.html @@ -164,6 +164,7 @@ + diff --git a/rootfs/www/ui/core.js b/rootfs/www/ui/core.js index 80f466d..e9cfb81 100644 --- a/rootfs/www/ui/core.js +++ b/rootfs/www/ui/core.js @@ -364,6 +364,23 @@ function cpuBusy(a, b){ } // confirmBtn(label, question, fn): a red button that asks before running fn. function confirmBtn(label, question, fn){ return h("button",{class:"btn sm d",onclick:async()=>{ if(!confirm(question)) return; try{ await fn(); }catch(e){ toast(e.message,4000); } }}, label); } +// pauseDlg(target, label, done): 暂停上网 (dev.pause) — target is a device, group:NAME, a dhcp.hosts name or a +// MAC. Runtime only (no config change, no confirm window); the router ends the pause by itself. +function pauseDlg(target, label, done){ + const t = new Date(), m = new Date(t); m.setHours(7,0,0,0); if (m<=t) m.setDate(m.getDate()+1); + const toMorning = Math.max(1, Math.round((m-t)/60000))+"m"; + const custom = h("input",{type:"text",placeholder:"如 45m、3h、1d",style:"width:140px",title:"最长 7 天"}); + const go = async d=>{ if (!d) return toast("请填写时长"); + try { await api("dev.pause",{target, duration:d}); dlg.remove(); toast("已暂停 "+label, 3000); done&&done(); } catch(e){ toast("暂停失败:"+e.message, 5000); } }; + const opt = (l, d)=>h("button",{class:"btn",onclick:()=>go(d)}, l); + const dlg = modal("暂停上网 · "+label, [ + h("div",{class:"mut",style:"margin-bottom:10px"},"只断开外网(WAN),内网、DHCP、DNS 照常;正在进行的连接(视频、游戏)立即中断。不改配置,到时自动恢复,也可随时提前恢复;路由器重启后恢复。"), + h("div",{class:"row"}, opt("30 分钟","30m"), opt("1 小时","1h"), opt("2 小时","2h"), opt("到明早 7:00", toMorning)), + h("div",{class:"row",style:"margin-top:10px"}, custom, h("button",{class:"btn p",onclick:()=>go(custom.value.trim())},"暂停"))], + [h("button",{class:"btn",onclick:()=>dlg.remove()},"取消")]); +} +// pauseLeft(p): "剩余 1时 5分" for a dev.paused entry +const pauseLeft = p=>"剩余 "+fmtDur(Math.max(60, p.left||0)); // ---------- core pages ---------- // overview gauges keep a short history for their sparklines (40 points = 2 min at 3 s) @@ -398,12 +415,19 @@ registerPage("status", "overview", "总览", 10, async ()=>{ h("div",{}, probs.map(p=>h("div",{style:"margin:2px 0"}, h("span",{class:"tag "+(p.sev==="risk"?"bad":"warn")}, p.sev==="risk"?"风险":"警告"), " ", h("b",{},p.title), " ", p.detail)), h("div",{class:"mut",style:"margin-top:6px;font-size:12px"}, "体检时间 "+new Date(doc.time*1000).toLocaleString())), h("a",{class:"btn sm",href:"#doctor"},"体检 →")) : null; + // devices paused with 暂停上网 (dev module; runtime, ends by itself) + const pz = s.paused||[]; + const pzCard = pz.length ? card(h("span",{}, h("span",{class:"dot",style:"background:var(--warn)"}), "暂停上网中 ("+pz.length+")"), + h("div",{}, pz.map(p=>h("div",{class:"row",style:"margin:3px 0"}, h("b",{}, p.name||p.mac), h("span",{class:"mono mut"}, p.mac), + p.ref && p.ref!==p.name && p.ref!==p.mac ? h("span",{class:"tag"}, p.ref) : null, h("span",{class:"mut"}, pauseLeft(p)), + h("button",{class:"btn sm",onclick:async()=>{ try { await api("dev.unpause",{target:p.mac}); toast("已恢复 "+(p.name||p.mac)); draw(); } catch(e){ toast(e.message,4000); } }},"恢复")))), + h("a",{class:"btn sm",href:"#devices"},"设备 →")) : null; const evs = s.events||[]; const evCard = evs.length ? card("最近事件", h("div",{}, evs.map(e=>h("div",{style:"margin:2px 0"}, h("span",{class:"mut mono"}, new Date(e.t*1000).toLocaleString()), " ", e.sev!=="info" ? h("span",{class:"tag "+(e.sev==="risk"?"bad":"warn")}, e.sev==="risk"?"风险":"警告") : null, " ", e.msg))), h("a",{class:"btn sm",href:"#doctor"},"全部 →")) : card("最近变更", h("pre",{}, (s.changes||[]).slice().reverse().join("\n")||"(无)")); - wrap.replaceChildren(docCard||"", + wrap.replaceChildren(docCard||"", pzCard||"", h("div",{class:"grid gauges"}, gauge({label:"CPU", pct:busy, value:busy==null ? "…" : busy.toFixed(0)+" %", sub:cores+"负载 "+s.load, extra:spark(OV.h.cpu, null, 100)}), gauge({label:"内存", pct:memPct, value:fmtBytes(memUsed*1024), sub:"共 "+fmtBytes(s.mem_total_kb*1024)+" · 可用 "+fmtBytes(s.mem_avail_kb*1024), extra:spark(OV.h.mem, COLORS[4], 100)}), diff --git a/rootfs/www/ui/dev.js b/rootfs/www/ui/dev.js new file mode 100644 index 0000000..0ecdd75 --- /dev/null +++ b/rootfs/www/ui/dev.js @@ -0,0 +1,180 @@ +// mini-router web UI — dev module page (网络 › 设备): the device inventory (router.yaml devices, groups) +// with its live state, where each device is used, and 暂停上网 (dev.pause: runtime, no config change). +// Uses only the helpers in ui/core.js; see docs/MODULES.md and docs/modules/dev.md. +"use strict"; +(()=>{ +addCSS(` +.dev-bar{display:flex;gap:8px;align-items:center;flex-wrap:wrap;padding:10px 16px} +.dev-bar input[type=search]{font:inherit;color:var(--fg);background:var(--in);border:1px solid var(--line);border-radius:5px;padding:4px 8px;min-height:28px;width:200px;max-width:100%} +.dev-bar select{max-width:100%} +.dev-sub{color:var(--mut);font-size:12px} +.dev-macs{font-size:12px;line-height:1.5} +.dev-chk{display:flex;flex-wrap:wrap;gap:4px 14px} +.dev-note{padding:10px 16px;color:var(--mut);font-size:12px;line-height:1.6} +.dev-t td{white-space:nowrap} +.dev-t .row{flex-wrap:nowrap} +`); + +const TYPES = [["","(未指定)"],["pc","电脑"],["phone","手机"],["tablet","平板"],["tv","电视 / 盒子"],["console","游戏机"], + ["iot","智能家居"],["server","服务器 / NAS"],["printer","打印机"],["other","其他"]]; +const typeName = t=>(TYPES.find(x=>x[0]===t)||[t,t])[1]; +const mono = s=>h("span",{class:"mono"}, s); +const lc = s=>String(s||"").toLowerCase(); +// devices / groups are attached to S.cfg only on the first edit: visiting the page is not a change +const devs = ()=>S.cfg.devices||[]; +const groups = ()=>S.cfg.groups||{}; +const attach = ()=>{ S.cfg.devices ||= []; S.cfg.groups ||= {}; }; +// a DHCP client name → a device name (lowercase letters, digits, -; starts with a letter) +const cleanName = s=>lc(s).replace(/[^a-z0-9-]+/g,"-").replace(/^[^a-z]+/,"").slice(0,32).replace(/-+$/,""); + +// where a device (or group:NAME) is used — the places the router resolves names +function refsOf(name){ + const c = S.cfg, f = c.firewall||{}, out = []; + for (const x of f.forwards||[]) if (x.to===name) out.push("端口转发 "+x.name); + for (const x of f.access||[]) if ((x.devices||[]).includes(name)) out.push("设备管控 "+x.name); + for (const x of c.policy_routes||[]) if (x.device===name) out.push("策略路由 "+x.name); + for (const x of (c.proxy||{}).bypass||[]) if (x.device===name) out.push("代理例外 "+x.name); + if (((c.guard||{}).always_bypass||[]).includes(name)) out.push("guard.always_bypass"); + for (const x of c.schedules||[]) if (x.action==="wol" && x.target===name) out.push("计划任务 "+x.name); + return out; +} +// renaming follows every reference (the change shows in the apply plan) +function renameRefs(from, to){ + const c = S.cfg, f = c.firewall||{}, sw = a=>a.map(d=>d===from?to:d); + for (const x of f.forwards||[]) if (x.to===from) x.to = to; + for (const x of f.access||[]) if (x.devices) x.devices = sw(x.devices); + for (const x of c.policy_routes||[]) if (x.device===from) x.device = to; + for (const x of (c.proxy||{}).bypass||[]) if (x.device===from) x.device = to; + if (c.guard && c.guard.always_bypass) c.guard.always_bypass = sw(c.guard.always_bypass); + for (const x of c.schedules||[]) if (x.action==="wol" && x.target===from) x.target = to; + for (const g of Object.keys(groups())) S.cfg.groups[g] = sw(S.cfg.groups[g]); +} +const refsCell = refs=>refs.length ? h("span",{title:refs.join("\n"), style:"cursor:help"}, refs.length+" 处") : h("span",{class:"mut"},"—"); +const okBtn = t=>h("button",{class:"btn p",onclick:e=>e.target.closest(".modal").remove()}, t||"知道了"); + +function editDevice(orig, save){ + const o = clone(orig); o.macs ||= []; + const dom = (S.cfg.dhcp||{}).domain||"lan"; + const m = modal(orig.name ? "编辑设备 · "+orig.name : "添加设备", form( + ...field("名称", inText(o,"name",{placeholder:"kid-tablet"}), "小写字母、数字和 -,以字母开头;也是它的 DNS 名 <名称>."+dom+"。端口转发、设备管控、策略路由、代理例外里直接写这个名字"), + ...field("MAC 地址", inList(o,"macs",{placeholder:"aa:bb:cc:dd:ee:ff, …"}), "可填多个(有线 + 无线、手机在本网络的私有 Wi-Fi 地址)"), + ...field("固定 IPv4", inText(o,"ip",{placeholder:"留空 = 动态分配"}), "填了就是静态 DHCP 分配,端口转发可以写设备名;多个 MAC 共用它时同一时间只能一个在线"), + ...field("类型", inSel(o,"type",TYPES)), + ...field("归属", inText(o,"owner",{placeholder:"例如 小明"})), + ...field("说明", inText(o,"desc"))), + [h("button",{class:"btn",onclick:()=>m.remove()},"取消"), + h("button",{class:"btn p",onclick:()=>{ + o.name = String(o.name||"").trim(); + if (!o.name) return toast("请填写名称"); + if (!o.macs.length) return toast("至少填一个 MAC"); + if (o.name!==orig.name && devs().some(d=>d.name===o.name)) return toast("已有设备 "+o.name); + for (const k of ["ip","type","owner","desc"]) if (!o[k]) delete o[k]; + save(o); m.remove(); touch(); }},"确定")]); +} + +registerPage("network", "devices", "设备", 30, async ()=>{ + let filter = "", ls = {}, cl = {}, pz = []; + const body = h("div"), info = h("span",{class:"mut",style:"flex:1 1 180px"}); + const load = async ()=>{ + [ls, cl, pz] = await Promise.all([api("dns.leases").catch(()=>({})), api("clients").catch(()=>({stations:[]})), + api("dev.paused").then(j=>j.paused||[]).catch(()=>[])]); + render(); + }; + const unpause = async (target, label)=>{ + try { await api("dev.unpause",{target}); toast("已恢复 "+label); await load(); } catch(e){ toast(e.message,4000); } }; + const del = (d, i)=>{ + const refs = refsOf(d.name); + if (refs.length) return modal("设备 "+d.name+" 还在使用", [h("div",{},"先修改这些地方,再删除它:"), h("ul",{}, refs.map(r=>h("li",{},r)))], [okBtn()]); + const inG = Object.keys(groups()).filter(g=>groups()[g].includes(d.name)); + if (!confirm("删除设备 "+d.name+"?"+(inG.length ? "\n同时从分组 "+inG.join("、")+" 中移除。" : ""))) return; + attach(); S.cfg.devices.splice(i,1); + for (const g of inG){ const a = S.cfg.groups[g].filter(x=>x!==d.name); if (a.length || refsOf("group:"+g).length) S.cfg.groups[g] = a; else delete S.cfg.groups[g]; } + touch(); render(); + }; + const editGroup = g=>{ + const o = {name:g||"", members:[...(groups()[g]||[])]}; + const box = h("div",{class:"dev-chk"}, devs().length ? devs().map(d=>h("label",{}, h("input",{type:"checkbox", checked:o.members.includes(d.name), onchange:e=>{ + const s = new Set(o.members); e.target.checked ? s.add(d.name) : s.delete(d.name); o.members = devs().map(x=>x.name).filter(n=>s.has(n)); }}), " "+d.name)) + : h("span",{class:"mut"},"先添加设备")); + const m = modal(g ? "编辑分组 · "+g : "添加分组", form( + ...field("名称", inText(o,"name",{placeholder:"kids"}), "小写字母、数字、_ -,以字母开头(最长 15);其他地方写 group:名称"), + ...field("成员", box)), + [h("button",{class:"btn",onclick:()=>m.remove()},"取消"), h("button",{class:"btn p",onclick:()=>{ + const n = String(o.name||"").trim(); + if (!n) return toast("请填写名称"); + if (!o.members.length) return toast("至少选一台设备"); + if (n!==g && groups()[n]) return toast("已有分组 "+n); + attach(); + if (g && n!==g){ delete S.cfg.groups[g]; renameRefs("group:"+g, "group:"+n); } + S.cfg.groups[n] = o.members; m.remove(); touch(); render(); }},"确定")]); + }; + const delGroup = g=>{ + const refs = refsOf("group:"+g); + if (refs.length) return modal("分组 "+g+" 还在使用", [h("div",{},"先修改这些地方,再删除它:"), h("ul",{}, refs.map(r=>h("li",{},r)))], [okBtn()]); + if (!confirm("删除分组 "+g+"?(设备本身保留)")) return; + delete S.cfg.groups[g]; touch(); render(); + }; + + const render = ()=>{ + const lease = {}; for (const l of ls.leases||[]) lease[lc(l.mac)] = l; + const wifi = {}; for (const s of cl.stations||[]) wifi[lc(s.mac)] = s; + const paused = {}; for (const p of pz) paused[lc(p.mac)] = p; + const mine = new Set(devs().flatMap(d=>(d.macs||[]).map(lc))); + const match = (...xs)=>!filter || xs.some(x=>lc(x).includes(filter)); + const rows = devs().map((d,i)=>[d,i]).filter(([d])=>match(d.name, d.owner, d.type, d.ip, ...(d.macs||[]))).map(([d,i])=>{ + const macs = (d.macs||[]).map(lc); + const l = macs.map(m=>lease[m]).find(Boolean), w = macs.map(m=>wifi[m]).find(Boolean), p = macs.map(m=>paused[m]).find(Boolean); + const inG = Object.keys(groups()).filter(g=>groups()[g].includes(d.name)); + return [ + h("div",{}, h("b",{},d.name), h("div",{class:"dev-sub"}, [d.type?typeName(d.type):"", d.owner||"", inG.map(g=>"#"+g).join(" ")].filter(Boolean).join(" · "))), + h("div",{class:"dev-macs mono"}, macs.map(m=>h("div",{},m))), + d.ip ? mono(d.ip) : l ? h("span",{class:"mono mut",title:"动态分配的当前地址"}, l.ip) : h("span",{class:"mut"},"—"), + h("span",{class:"row"}, w ? h("span",{class:"tag ok",title:w.ifname+" · "+w.signal},"WiFi 在线") : l ? h("span",{class:"tag"},"有租约") : h("span",{class:"mut"},"—"), + p ? h("span",{class:"tag warn"},"已暂停 · "+pauseLeft(p)) : null), + refsCell(refsOf(d.name)), + h("span",{class:"row",style:"flex-wrap:nowrap"}, + p ? h("button",{class:"btn sm",onclick:()=>unpause(d.name, d.name)},"恢复") : h("button",{class:"btn sm",onclick:()=>pauseDlg(d.name, d.name, load)},"暂停"), + h("button",{class:"btn sm",onclick:()=>editDevice(d, v=>{ attach(); if (v.name!==d.name) renameRefs(d.name, v.name); S.cfg.devices[i] = v; render(); })},"编辑"), + h("button",{class:"btn sm d",onclick:()=>del(d, i)},"删除"))]; + }); + // add from a DHCP client, or move a dhcp.hosts entry into the inventory (a MAC may be in one place only) + const hosts = S.cfg.dhcp.hosts||[], hostMacs = new Set(hosts.map(x=>lc(x.mac))); + const cand = (ls.leases||[]).filter(l=>!mine.has(lc(l.mac)) && !hostMacs.has(lc(l.mac))); + const pick = h("select",{style:"width:auto;max-width:220px",onchange:e=>{ + const v = e.target.value; e.target.value = ""; + if (v.startsWith("h:")){ const k = +v.slice(2), x = hosts[k]; if (!x) return; + return editDevice({name:cleanName(x.name), macs:[lc(x.mac)], ip:x.ip}, d=>{ attach(); S.cfg.dhcp.hosts.splice(S.cfg.dhcp.hosts.indexOf(x),1); S.cfg.devices.push(d); render(); }); } + const l = cand.find(x=>lc(x.mac)===v); if (!l) return; + editDevice({name:cleanName(l.name==="*"?"":l.name), macs:[lc(l.mac)]}, d=>{ attach(); S.cfg.devices.push(d); render(); }); }}, + h("option",{value:""},"从终端添加…"), + cand.length ? h("optgroup",{label:"DHCP 终端"}, cand.map(l=>h("option",{value:lc(l.mac)}, (l.name&&l.name!=="*"?l.name:"未命名")+" · "+l.ip+" · "+lc(l.mac)))) : null, + hosts.length ? h("optgroup",{label:"静态分配(移入设备清单)"}, hosts.map((x,k)=>h("option",{value:"h:"+k}, (x.name||"未命名")+" · "+x.ip+" · "+lc(x.mac)))) : null); + const gRows = Object.keys(groups()).sort().map(g=>{ + const members = groups()[g]||[]; + const anyPaused = members.some(n=>((devs().find(d=>d.name===n)||{}).macs||[]).some(m=>paused[lc(m)])); + return [h("b",{},g), h("span",{class:"row"}, members.map(n=>h("span",{class:"tag"},n))), refsCell(refsOf("group:"+g)), + h("span",{class:"row",style:"flex-wrap:nowrap"}, + anyPaused ? h("button",{class:"btn sm",onclick:()=>unpause("group:"+g, "分组 "+g)},"恢复") : h("button",{class:"btn sm",onclick:()=>pauseDlg("group:"+g, "分组 "+g, load)},"暂停"), + h("button",{class:"btn sm",onclick:()=>editGroup(g)},"编辑"), h("button",{class:"btn sm d",onclick:()=>delGroup(g)},"删除"))]; + }); + const pRows = pz.map(p=>[h("b",{}, p.name||"-"), mono(p.mac), p.ref||"-", pauseLeft(p), + h("button",{class:"btn sm",onclick:()=>unpause(p.mac, p.name||p.mac)},"恢复")]); + info.textContent = devs().length+" 台设备 · "+Object.keys(groups()).length+" 个分组"+(pz.length ? " · "+pz.length+" 个 MAC 暂停中" : ""); + body.replaceChildren(...[ + card("设备清单("+rows.length+")", h("div",{class:"dev-t"}, roTable(["名称","MAC","IPv4","状态","引用","操作"], rows)), h("span",{class:"row"}, pick, + h("button",{class:"btn sm p",onclick:()=>editDevice({name:"",macs:[]}, d=>{ attach(); S.cfg.devices.push(d); render(); })},"+ 添加")), true), + pRows.length ? card("暂停中("+pRows.length+")", h("div",{class:"dev-t"}, roTable(["名称","MAC","暂停对象","剩余","操作"], pRows)), + h("button",{class:"btn sm",onclick:()=>unpause("all","全部")},"全部恢复"), true) : null, + card("分组("+gRows.length+")", h("div",{class:"dev-t"}, roTable(["分组","设备","引用","操作"], gRows)), h("button",{class:"btn sm p",onclick:()=>editGroup("")},"+ 添加"), true), + card("说明", h("div",{class:"dev-note"}, + "设备 = 一个名字对应一个或多个 MAC(可选固定 IPv4)。端口转发的目标、设备管控、策略路由、代理例外都可以直接写设备名,或 group:分组名;", + "引用了不存在的名字会在应用前报错。设备的名字就是它的 DHCP / DNS 名,填了固定 IPv4 就是静态分配(和“静态分配”页的旧条目效果相同,同一 MAC 只能在一处)。", + h("br"), "暂停上网不改配置、没有确认倒计时:只断外网(内网、DHCP、DNS 照常),正在进行的连接立即中断,到时自动恢复;路由器重启也会结束暂停。"), null, true) + ].filter(Boolean)); + }; + await load(); + return h("div",{}, h("div",{class:"card"}, h("div",{class:"dev-bar"}, + h("input",{type:"search", placeholder:"筛选:名称 / 归属 / MAC / IP", oninput:e=>{ filter = lc(e.target.value.trim()); render(); }}), info, + h("button",{class:"btn sm",onclick:()=>load().catch(e=>toast(e.message,4000))},"刷新"))), body); +}); +})(); diff --git a/rootfs/www/ui/dns.js b/rootfs/www/ui/dns.js index 2a052a5..0940e74 100644 --- a/rootfs/www/ui/dns.js +++ b/rootfs/www/ui/dns.js @@ -35,21 +35,35 @@ const wakeBtn = (mac, network)=>h("button",{class:"btn sm",title:"发送网络 // ---------------- 状态 › 终端设备 ---------------- registerPage("status", "clients", "终端设备", 20, async ()=>{ - let filter = "", ls = {}, cl = {}; + let filter = "", ls = {}, cl = {}, pz = []; const body = h("div"), info = h("span",{class:"mut",style:"flex:1"}); - const load = async ()=>{ [ls, cl] = await Promise.all([api("dns.leases"), api("clients").catch(()=>({stations:[]}))]); render(); }; + const load = async ()=>{ [ls, cl, pz] = await Promise.all([api("dns.leases"), api("clients").catch(()=>({stations:[]})), + api("dev.paused").then(j=>j.paused||[]).catch(()=>[])]); render(); }; const render = ()=>{ const now = ls.now || Date.now()/1000; const byMac = {}; for (const l of ls.leases||[]) byMac[l.mac.toLowerCase()] = l; - const cfgMacs = new Set((S.cfg.dhcp.hosts||[]).map(x=>(x.mac||"").toLowerCase())); + const devOf = {}; for (const d of S.cfg.devices||[]) for (const m of d.macs||[]) devOf[m.toLowerCase()] = d; // 网络 › 设备 + const cfgMacs = new Set([...(S.cfg.dhcp.hosts||[]).map(x=>(x.mac||"").toLowerCase()), ...Object.keys(devOf).filter(m=>devOf[m].ip)]); + const paused = {}; for (const p of pz) paused[p.mac.toLowerCase()] = p; const match = (...xs)=>!filter || xs.some(x=>String(x||"").toLowerCase().includes(filter)); + // 暂停上网: a device of the inventory is paused as a whole (all its MACs), anything else by MAC + const pauseCtl = (mac, name)=>{ + const d = devOf[mac], p = paused[mac], target = d ? d.name : mac, label = d ? d.name : (name && name!=="*" ? name : mac); + return p ? [h("span",{class:"tag warn"},"已暂停 · "+pauseLeft(p)), h("button",{class:"btn sm",onclick:async()=>{ + try { await api("dev.unpause",{target}); toast("已恢复 "+label); await load(); } catch(e){ toast(e.message,4000); } }},"恢复")] + : h("button",{class:"btn sm",title:"暂停它的外网访问(不改配置,到时自动恢复)",onclick:()=>pauseDlg(target, label, load)},"暂停"); + }; const leaseRows = (ls.leases||[]).filter(l=>match(l.name,l.ip,l.mac,l.network)).map(l=>{ - const mac = l.mac.toLowerCase(); + const mac = l.mac.toLowerCase(), d = devOf[mac]; const st = l.static ? h("span",{class:"tag ok"},"静态") : cfgMacs.has(mac) ? h("span",{class:"tag warn"},"待应用") : - h("button",{class:"btn sm",title:"把当前地址固定给这台设备",onclick:e=>{ S.cfg.dhcp.hosts.push({name:cleanName(l.name,l.ip), mac, ip:l.ip}); touch(); e.target.replaceWith(h("span",{class:"tag warn"},"待应用")); }},"设为静态"); + h("button",{class:"btn sm",title:"把当前地址固定给这台设备",onclick:e=>{ + if (d) d.ip = l.ip; else S.cfg.dhcp.hosts.push({name:cleanName(l.name,l.ip), mac, ip:l.ip}); + touch(); e.target.replaceWith(h("span",{class:"tag warn"},"待应用")); }},"设为静态"); const rel = confirmBtn("释放", "释放 "+l.ip+"("+l.mac+")的租约?\n设备下次续约时会重新申请地址;适合清理已离线设备或把地址腾给静态分配。", async()=>{ await api("dns.release",{ip:l.ip, mac:l.mac}); toast("已释放 "+l.ip); await load(); }); - return [l.name==="*"?h("span",{class:"mut"},"-"):l.name, mono(l.ip), mono(l.mac), l.network||"-", remain(l.expires, now), h("span",{class:"row"}, st, wakeBtn(l.mac, l.network), rel)]; + const name = d ? h("span",{}, d.name, l.name && l.name!=="*" && l.name.toLowerCase()!==d.name ? h("span",{class:"dns-sub"}, l.name) : null) + : l.name==="*" ? h("span",{class:"mut"},"-") : l.name; + return [name, mono(l.ip), mono(l.mac), l.network||"-", remain(l.expires, now), h("span",{class:"row"}, st, pauseCtl(mac, l.name), wakeBtn(l.mac, l.network), rel)]; }); const v6Rows = (ls.leases6||[]).filter(l=>match(l.name,l.ip,l.duid)).map(l=>[l.name==="*"?"-":l.name, mono(l.ip), mono(l.iaid), h("span",{class:"mono",title:l.duid}, (l.duid||"").slice(0,23)+((l.duid||"").length>23?"…":"")), remain(l.expires, now)]); diff --git a/rootfs/www/ui/fw.js b/rootfs/www/ui/fw.js index b4cc5b2..cab327e 100644 --- a/rootfs/www/ui/fw.js +++ b/rootfs/www/ui/fw.js @@ -86,6 +86,7 @@ function hits(ctr, key){ async function stats(){ try { return await api("fw.stats"); } catch(e){ return {counters:{}, log:[]}; } } async function knownDevices(){ const m = new Map(); + for (const d of S.cfg.devices||[]) for (const x of d.macs||[]) m.set(x.toLowerCase(), {name:d.name, ip:d.ip||"", mac:x.toLowerCase(), dev:true}); for (const x of S.cfg.dhcp.hosts||[]) m.set((x.mac||"").toLowerCase(), {name:x.name, ip:x.ip, mac:(x.mac||"").toLowerCase()}); try { for (const l of (await api("status")).leases||[]) { const k=l.mac.toLowerCase(); if(!m.has(k)) m.set(k, {name:l.name==="*"?"":l.name, ip:l.ip, mac:k}); } } catch(e){} return [...m.values()]; @@ -187,7 +188,9 @@ registerPage("firewall", "forward", "端口转发", 20, async ()=>{ const f = F(); const devs = await knownDevices(); const ipList = "fw-hosts"; - const dl = h("datalist",{id:ipList}, devs.filter(d=>d.ip).map(d=>h("option",{value:d.ip}, d.name||d.mac))); + // devices of the inventory with a fixed address can be the target by name (网络 › 设备) + const dl = h("datalist",{id:ipList}, (S.cfg.devices||[]).filter(d=>d.ip).map(d=>h("option",{value:d.name}, d.ip)), + devs.filter(d=>d.ip && !d.dev).map(d=>h("option",{value:d.ip}, d.name||d.mac))); return h("div",{}, dl, listCard("端口转发(IPv4 DNAT)", f.forwards, [ {l:"名称", f:x=>x.name}, {l:"协议", f:x=>joinL(x.proto).toUpperCase()}, {l:"外部端口", f:x=>mono(x.port)}, {l:"内部地址", f:x=>mono(x.to+(x.to_port&&x.to_port!==x.port?":"+x.to_port:""))}, @@ -197,7 +200,7 @@ registerPage("firewall", "forward", "端口转发", 20, async ()=>{ ...field("名称", inText(o,"name",{placeholder:"nas-https"})), ...field("协议", inProto(o,"proto")), ...field("外部端口", inText(o,"port",{placeholder:"8080 或 1000-2000"})), - ...field("内部 IP", inText(o,"to",{placeholder:"192.168.1.x", list:ipList}), "必须在某个内网 / 访客网络之内"), + ...field("内部 IP", inText(o,"to",{placeholder:"192.168.1.x 或设备名", list:ipList}), "必须在某个内网 / 访客网络之内;也可以写设备清单里有固定 IP 的设备名"), ...field("内部端口", inText(o,"to_port",{placeholder:"留空 = 同外部端口"}), "端口段只能映射到相同端口段或单个端口"), ...field("WAN", wanPick(o)), ...field("来源限制", inList(o,"src_ip",{placeholder:"留空 = 任意;例如 203.0.113.0/24"}), "只允许这些 IPv4 地址 / 网段访问"), @@ -295,7 +298,8 @@ registerPage("firewall", "fwrules", "通信规则", 40, async ()=>{ registerPage("firewall", "access", "设备管控", 50, async ()=>{ const f = F(); const [st, devs] = await Promise.all([stats(), knownDevices()]); - const macsText = x=>(x.macs||[]).map(m=>{ const n=devName(devs,m); return n ? n+" ("+m+")" : m; }).join(", "); + const macsText = x=>[...(x.devices||[]), ...(x.macs||[]).map(m=>{ const n=devName(devs,m); return n ? n+" ("+m+")" : m; })].join(", "); + const inv = [...(S.cfg.devices||[]).map(d=>[d.name, d.name+(d.owner?" · "+d.owner:"")]), ...Object.keys(S.cfg.groups||{}).map(g=>["group:"+g, "分组 "+g])]; return h("div",{}, listCard("禁止上网的设备", f.access, [ {l:"名称", f:x=>x.name}, {l:"设备", f:x=>mono(macsText(x))}, @@ -315,13 +319,17 @@ registerPage("firewall", "access", "设备管控", 50, async ()=>{ schedSlot.replaceChildren(...field("禁止时间段", schedEdit(o,"schedule"), "按系统时区;跨午夜自动算到次日")); } }; drawSched(); + const devIn = inList(o,"devices",{placeholder:"设备名 / group:分组"}); + const devPick = h("select",{onchange:e=>{ const v=e.target.value; if(!v) return; o.devices ||= []; if(!o.devices.includes(v)) o.devices.push(v); devIn.value=o.devices.join(", "); e.target.value=""; touch(); }}, + h("option",{value:""},"从设备清单添加…"), inv.map(([v,l])=>h("option",{value:v}, l))); return form( ...field("名称", inText(o,"name",{placeholder:"kid-ipad"})), + ...field("设备 / 分组", h("div",{style:"display:grid;gap:6px"}, devIn, devPick), "网络 › 设备 里的设备名或 group:分组名(设备的所有 MAC 都受管控)"), ...field("设备 MAC", h("div",{style:"display:grid;gap:6px"}, macIn, pick), "可填多个;手机请关闭该 WiFi 的“私有地址”或填它在本网络使用的 MAC"), ...field("模式", inSel(mode,"m",[["always","始终禁止上网"],["sched","按时间段禁止"]], ()=>drawSched())), schedSlot, ...field("说明", inText(o,"desc"))); - }, o=>save(prune(o,["schedule","desc"]))), + }, o=>save(prune(o,["devices","schedule","desc"]))), note:"只禁止访问外网(WAN),内网、DHCP、DNS 照常。到点立即生效,已建立的连接也会断开——为此这些设备的流量不走硬件加速。"})); }); })(); diff --git a/rootfs/www/ui/net.js b/rootfs/www/ui/net.js index 09f9e38..43cf200 100644 --- a/rootfs/www/ui/net.js +++ b/rootfs/www/ui/net.js @@ -275,11 +275,14 @@ registerPage("routing", "policy", "策略路由", 20, async ()=>{ const c = S.cfg; let n = {}; try { n = await api("net.routes"); } catch(e){} return h("div",{}, tableCard("策略路由(指定出口 WAN)", c.policy_routes, [ - {k:"name",l:"名称"},{k:"mac",l:"设备 MAC",ph:"aa:bb:cc:dd:ee:ff"},{k:"src",l:"源地址 / 网段",ph:"192.168.1.66"},{k:"dst",l:"目标地址 / 网段",ph:"1.2.3.0/24"}, + {k:"name",l:"名称"},{k:"mac",l:"设备 MAC",ph:"aa:bb:cc:dd:ee:ff"},{k:"device",l:"或设备 / 分组",ph:"desktop / group:kids"}, + {k:"src",l:"源地址 / 网段",ph:"192.168.1.66"},{k:"dst",l:"目标地址 / 网段",ph:"1.2.3.0/24"}, {k:"domains",l:"目标域名",t:"list",ph:"example.com, video.example"}, - {k:"via",l:"出口 WAN",t:"sel",o:()=>c.wan.map(w=>w.name)},{k:"table",l:"路由表",t:"num",w:"80px",ph:"自动"},{k:"mark",l:"标记",w:"90px",ph:"自动"}], + {k:"via",l:"出口 WAN",t:"sel",o:()=>c.wan.map(w=>w.name)}, + {k:"fallback",l:"该 WAN 断线时",t:"sel",o:[["","换线"],["drop","断网"]]}, + {k:"table",l:"路由表",t:"num",w:"80px",ph:"自动"},{k:"mark",l:"标记",w:"90px",ph:"自动"}], ()=>({name:"",mac:"",src:"",dst:"",via:(c.wan[1]||c.wan[0]||{}).name||"",table:0,mark:""}), - "条件同时满足;MAC / 源 / 目标 / 域名至少填一项。没填源 / 目标地址时 IPv4 + IPv6 都生效,填了就只管该地址族。只影响新连接;访问内网、tailscale 和静态路由不受影响。域名含子域名:设备通过路由器 DNS 解析到的地址走该 WAN,连接照常硬件加速(DoH / 自定义 DNS 的设备不生效)。路由表填 0、标记留空 = 自动(200+序号 / 0x200+序号)。"), + "条件同时满足;MAC(或 网络 › 设备 里的设备名 / group:分组)/ 源 / 目标 / 域名至少填一项。没填源 / 目标地址时 IPv4 + IPv6 都生效,填了就只管该地址族。只影响新连接;访问内网、tailscale 和静态路由不受影响。域名含子域名:设备通过路由器 DNS 解析到的地址走该 WAN,连接照常硬件加速(DoH / 自定义 DNS 的设备不生效)。“断网”= 该 WAN 断线或健康检查失败时这些流量直接丢弃,绝不从其他 WAN 出去(该 WAN 没有 IPv6 时,这些设备也就没有 IPv6 外网)。路由表填 0、标记留空 = 自动(200+序号 / 0x200+序号)。"), tabs([["p4","IPv4 策略规则", ()=>card("ip -4 rule", roTable(RULE_COLS, (n.rules4||[]).map(fmtRule)), null, true)], ["p6","IPv6 策略规则", ()=>card("ip -6 rule", roTable(RULE_COLS, (n.rules6||[]).map(fmtRule)), null, true)]])); }); diff --git a/rootfs/www/ui/proxy.js b/rootfs/www/ui/proxy.js index 0aeb5e3..a751d7b 100644 --- a/rootfs/www/ui/proxy.js +++ b/rootfs/www/ui/proxy.js @@ -491,12 +491,18 @@ registerPage("proxy", "proxy-bypass", "例外设备", 30, async ()=>{ const known = new Map(); for (const x of S.cfg.dhcp.hosts||[]) if (x.mac) known.set(x.mac.toLowerCase(), {name:x.name||x.mac, ip:x.ip, tag:"静态"}); for (const l of leases) if (l.mac && !known.has(l.mac.toLowerCase())) known.set(l.mac.toLowerCase(), {name:l.name&&l.name!=="*"?l.name:l.mac, ip:l.ip, tag:"租约"}); - const t = etable(p.bypass, [{k:"name",l:"名称"},{k:"mac",l:"MAC",ph:"aa:bb:cc:dd:ee:ff"}], {name:"",mac:""}, {noMove:true}); + const t = etable(p.bypass, [{k:"name",l:"名称"},{k:"mac",l:"MAC",ph:"aa:bb:cc:dd:ee:ff"},{k:"device",l:"或设备 / 分组",ph:"desktop / group:kids"}], {name:"",mac:""}, {noMove:true}); const pick = {v:""}; + // devices / groups of the inventory (网络 › 设备): every MAC of the device is bypassed + const inv = [...(S.cfg.devices||[]).map(d=>d.name), ...Object.keys(S.cfg.groups||{}).map(g=>"group:"+g)]; const picker = ()=>{ - const have = new Set(p.bypass.map(b=>(b.mac||"").toLowerCase())); - const opts = [["","从 DHCP 设备中选择…"], ...[...known].filter(([m])=>!have.has(m)).map(([m,d])=>[m, d.name+" · "+(d.ip||"")+" · "+m+"("+d.tag+")"])]; - return inSel(pick,"v",opts, m=>{ if(!m) return; const d=known.get(m); p.bypass.push({name:d.name, mac:m}); pick.v=""; touch(); t.redraw(); pickBox.replaceChildren(picker()); }); + const have = new Set(p.bypass.map(b=>(b.mac||"").toLowerCase())), haveDev = new Set(p.bypass.map(b=>b.device).filter(Boolean)); + const opts = [["","从设备中选择…"], ...inv.filter(n=>!haveDev.has(n)).map(n=>["dev:"+n, (n.startsWith("group:") ? "分组 "+n.slice(6) : n)+"(设备清单)"]), + ...[...known].filter(([m])=>!have.has(m)).map(([m,d])=>[m, d.name+" · "+(d.ip||"")+" · "+m+"("+d.tag+")"])]; + return inSel(pick,"v",opts, m=>{ if(!m) return; + if (m.startsWith("dev:")){ const n=m.slice(4); p.bypass.push({name:n.replace(/^group:/,""), device:n}); } + else { const d=known.get(m); p.bypass.push({name:d.name, mac:m}); } + pick.v=""; touch(); t.redraw(); pickBox.replaceChildren(picker()); }); }; const pickBox = h("span",{}, picker()); return h("div",{}, diff --git a/skills/mini-router/SKILL.md b/skills/mini-router/SKILL.md index fd9b86b..9cfd2b0 100644 --- a/skills/mini-router/SKILL.md +++ b/skills/mini-router/SKILL.md @@ -63,18 +63,22 @@ lan: {bridge: br-lan, ports: [lan1, lan2], ipv4: 192.168.1.1/24, ipv6_ra: true} wan: - {name: wan, device: wan, proto: pppoe, username: "…", password_secret: pppoe_password, ipv6: true, ipv6_pd: true} # mtu: 1500 = RFC 4638 (falls back to 1492) - {name: wan2, device: eth2, proto: dhcp} # proto: pppoe | dhcp | static (ipv4:, gateway:, dns:) +devices: # inventory: other sections use the name (docs/modules/dev.md) + - {name: nas, macs: ["aa:bb:cc:dd:ee:02"], ip: 192.168.1.20, type: server} # ip = static lease; a MAC not also in dhcp.hosts + - {name: kid-tablet, macs: ["aa:bb:cc:dd:ee:21", "aa:bb:cc:dd:ee:22"], owner: kid} +groups: {kids: [kid-tablet]} # elsewhere: "group:kids" policy_routes: # pick the WAN for NEW connections (selectors are ANDed) - - {name: nas, mac: "aa:bb:cc:dd:ee:02", via: wan2} # mac / src / dst / domains + - {name: nas, device: nas, via: wan2, fallback: drop} # mac / device / src / dst / domains; drop = never another WAN - {name: video, domains: [video.example], via: wan2} # + subdomains; dnsmasq fills nft set pr__4/_6 dhcp: start: 100 end: 249 hosts: # static leases (IP outside start..end) - - {name: nas, mac: "aa:bb:cc:dd:ee:ff", ip: 192.168.1.20} + - {name: printer, mac: "aa:bb:cc:dd:ee:ff", ip: 192.168.1.30} # older form of a device with ip firewall: offload: hardware # hardware | software | off forwards: # WAN → LAN port forwards - - {name: web, proto: [tcp], port: "8443", to: 192.168.1.20, to_port: "443"} + - {name: web, proto: [tcp], port: "8443", to: nas, to_port: "443"} # to: an IPv4 or a device with ip - {name: game, proto: [tcp, udp], port: 27000-27010, to: 192.168.1.30} open: # ports on the router itself, from WAN - {name: https, proto: [tcp], port: "443"} @@ -146,7 +150,11 @@ Secrets: add `name: value` to `/etc/mini-router/secrets.yaml` without echoing th port is refused while it is on (remove lucky's `lucky-https`, disable lucky in the same apply). Plan risk is high. Check: `mr edge status` (`serving`, certificates `state` / `error`, requests per route); issue now: `mr edge renew` (certificates come from Let's Encrypt via DNS-01 in 1–2 minutes; renewed daily when a third of the lifetime is left). -- **Wake a device (WOL)**: `mr wol ` or `mr wol aa:bb:cc:dd:ee:ff [network]` — magic packet to that +- **Pause a device's internet** (runtime only: no apply, no confirm, ends by itself; a reboot ends it too): + `mr pause 1h` (30m, 2h30m, 1d; max 7d), `mr pause list`, + `mr unpause <…|all>`. Cuts running connections at once (the firewall reload ends offloaded flows); LAN, DHCP and + DNS keep working. Permanent / scheduled blocks stay in `firewall.access` (`devices: ["group:kids"]` works there). +- **Wake a device (WOL)**: `mr wol ` or `mr wol aa:bb:cc:dd:ee:ff [network]` — magic packet to that LAN network's broadcast through its bridge (never a WAN). Scheduled: `schedules: [{name: wake-nas, cron: "0 7 * * 1-5", action: wol, target: nas}]`. The device needs WOL enabled in its BIOS / NIC and usually a cable. diff --git a/tools/ci.d/dev.sh b/tools/ci.d/dev.sh new file mode 100644 index 0000000..77f0c93 --- /dev/null +++ b/tools/ci.d/dev.sh @@ -0,0 +1,193 @@ +#!/bin/sh +# dev module CI checks (run by tools/ci.sh with OUT and ROOT, inside its private mount namespace): +# 1. the lab inventory renders: dnsmasq dhcp-host lines per device, names resolved in forwards / +# access / policy routes / proxy bypass, the policy fallback rule; no runtime pause in any file; +# 2. `mr pause` with real nftables in network namespaces: a paused device's established, offloaded +# download stops at once (both directions), its new connections fail, the router's DNS still +# answers it, another device keeps flowing; a firewall reload keeps the pause; it ends by itself +# (kernel timeout, no reload); `mr unpause` ends it early; pausing by MAC; +# 3. policy_routes fallback: drop: while the policy's WAN has no route the device cannot leave +# through another WAN; once the WAN's table has a route it works (through that WAN only). +set -eu +: "${OUT:?}" "${ROOT:?}" +MR=$OUT/mr-host +fail() { echo "FAIL: $*"; exit 1; } + +echo "-- lab render: inventory resolved, no pause in generated files" +L=$OUT/lab +grep -qx 'dhcp-host=02:00:00:00:10:01,192.168.1.70,office-pc,infinite' "$L/etc/dnsmasq.conf" || fail "dnsmasq: office-pc static lease" +grep -qx 'dhcp-host=aa:bb:cc:00:00:21,aa:bb:cc:00:00:22,192.168.1.121,kid-tablet' "$L/etc/dnsmasq.conf" || fail "dnsmasq: kid-tablet (two MACs)" +grep -qx 'dhcp-host=aa:bb:cc:00:00:23,game-console' "$L/etc/dnsmasq.conf" || fail "dnsmasq: a device without a fixed address" +N=$L/etc/mini-router/gen/nftables.nft +for s in \ + 'tcp dport 3390 dnat ip to 192.168.1.70:3389 comment "office-rdp"' \ + 'ether saddr { aa:bb:cc:dd:ee:06, aa:bb:cc:00:00:21, aa:bb:cc:00:00:22, aa:bb:cc:00:00:23 } update @ac_4' \ + 'ether saddr 02:00:00:00:10:01 ip daddr != { 192.168.1.0/24, 192.168.20.0/24, 192.168.30.0/24 } ct state new ct mark set 0x102' \ + 'ether saddr 02:00:00:00:10:01 oifname { "pppoe-wan", "pppoe-isp3", "wan.20", "wan.30" } counter drop comment "fallback:office-wan2-only"' \ + 'ether saddr { aa:bb:cc:00:00:21, aa:bb:cc:00:00:22, aa:bb:cc:00:00:23 } ip daddr != { 192.168.1.0/24'; do + grep -qF -- "$s" "$N" || fail "lab ruleset lacks: $s" +done +if grep -rq '@paused\|set paused' "$L" "$OUT/home"; then fail "a generated file holds runtime pause state"; fi +grep -q 'fallback:\|dhcp-host=.*,office-pc' "$OUT/home/etc/mini-router/gen/nftables.nft" "$OUT/home/etc/dnsmasq.conf" && fail "home output has inventory lines" +echo "ok: lab inventory rendered; home and lab files carry no pause" + +echo "-- mr pause / policy fallback: packets through the lab ruleset" +PY=$OUT/devnet.py +cat > "$PY" <<'EOF' +import os, socket, sys, time +cmd = sys.argv[1] +if cmd == "serve": # serve PORT: tell every client its source address + s = socket.socket(socket.AF_INET); s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + s.bind(("0.0.0.0", int(sys.argv[2]))); s.listen(64) + while True: + c, a = s.accept(); c.sendall(("ok from " + a[0] + "\n").encode()); c.close() +elif cmd == "connect": # connect ADDR PORT + s = socket.socket(socket.AF_INET); s.settimeout(1.5) + try: + s.connect((sys.argv[2], int(sys.argv[3]))); print(s.recv(200).decode().strip()) + except Exception as e: + print("ERR " + type(e).__name__); sys.exit(1) +elif cmd == "stream": # stream PORT: send data forever to every client + s = socket.socket(socket.AF_INET); s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + s.bind(("0.0.0.0", int(sys.argv[2]))); s.listen(8) + while True: + c, a = s.accept() + if os.fork() == 0: + try: + while True: c.sendall(b"x" * 1400); time.sleep(0.01) + except Exception: pass + os._exit(0) +elif cmd == "sink": # sink ADDR PORT FILE: receive, keep the byte count in FILE + s = socket.socket(socket.AF_INET); s.settimeout(1.5); s.connect((sys.argv[2], int(sys.argv[3]))); s.settimeout(0.2) + n = 0 + while True: + try: + d = s.recv(65536) + if not d: break + n += len(d) + except socket.timeout: pass + with open(sys.argv[4] + ".tmp", "w") as f: f.write(str(n)) + os.replace(sys.argv[4] + ".tmp", sys.argv[4]) +EOF + +P=mrdev$$ +R=${P}r W=${P}w A=${P}a B=${P}b O=${P}o +cleanup() { + for n in $R $W $A $B $O; do + for p in $(ip netns pids "$n" 2>/dev/null); do kill "$p" 2>/dev/null || true; done + ip netns del "$n" 2>/dev/null || true + done + umount /run/mini-router 2>/dev/null || true +} +trap cleanup EXIT +mkdir -p /run/mini-router && mount -t tmpfs tmpfs /run/mini-router # private mount namespace: pause.json, fw.lock +for n in $R $W $A $B $O; do ip netns add "$n"; ip -n "$n" link set lo up; done +veth() { # veth NS1 NAME1 NS2 NAME2 [MAC2] + ip link add "${P}x" type veth peer name "${P}y" + ip link set "${P}x" netns "$1"; ip link set "${P}y" netns "$3" + ip -n "$1" link set "${P}x" name "$2"; ip -n "$3" link set "${P}y" name "$4" + [ -z "${5:-}" ] || ip -n "$3" link set "$4" address "$5" + ip -n "$1" link set "$2" up; ip -n "$3" link set "$4" up +} +x() { ns=$1; shift; ip netns exec "$ns" "$@"; } +spawn() { setsid -f ip netns exec "$@" >/dev/null 2>&1 < /dev/null; } + +# router: br-lan over lan2 (A = tv-box of the inventory), lan3 (B, not in the inventory), lan4 (O = office-pc) +ip -n "$R" link add br-lan type bridge +ip -n "$R" link set br-lan up +veth "$R" lan2 "$A" eth0 02:00:00:00:10:02 +veth "$R" lan3 "$B" eth0 02:00:00:00:10:99 +veth "$R" lan4 "$O" eth0 02:00:00:00:10:01 +for p in lan2 lan3 lan4; do ip -n "$R" link set "$p" master br-lan; done +veth "$R" pppoe-wan "$W" eth0 +veth "$R" pppoe-wan2 "$W" eth1 +x "$R" sysctl -qw net.ipv4.ip_forward=1 +ip -n "$R" addr add 192.168.1.6/24 dev br-lan +ip -n "$R" addr add 203.0.113.1/24 dev pppoe-wan +ip -n "$R" addr add 198.51.100.1/24 dev pppoe-wan2 +ip -n "$R" route add default via 203.0.113.2 dev pppoe-wan # main: wan (wan2's table has no route yet) +ip -n "$A" addr add 192.168.1.60/24 dev eth0 +ip -n "$B" addr add 192.168.1.61/24 dev eth0 +ip -n "$O" addr add 192.168.1.70/24 dev eth0 +for n in $A $B $O; do ip -n "$n" route add default via 192.168.1.6; done +ip -n "$W" addr add 203.0.113.2/24 dev eth0 +ip -n "$W" addr add 198.51.100.7/24 dev eth1 + +mkdir -p /etc/mini-router/gen +cp "$OUT/lab-secrets.yaml" /etc/mini-router/secrets.yaml +# software offload (veths cannot do PPE); the proxy's tproxy rules are not part of this test +sed -e 's/offload: hardware/offload: software/' -e '/^proxy:/,/^[a-z]/ s/^ enabled: true/ enabled: false/' "$OUT/lab.yaml" > /etc/mini-router/router.yaml +x "$R" "$MR" fw || fail "mr fw" + +spawn "$R" python3 "$PY" serve 53 # the router's own service (DNS port, TCP) +spawn "$W" python3 "$PY" serve 8080 +spawn "$W" python3 "$PY" stream 9000 +sleep 1 +ok() { # ok NS ADDR PORT WHAT [EXPECT] + out=$(x "$1" python3 "$PY" connect "$2" "$3") || fail "$4: expected to connect, got: $out" + [ -z "${5:-}" ] || echo "$out" | grep -qF -- "$5" || fail "$4: expected '$5', got: $out" + echo "ok: $4 ($out)" +} +blocked() { # blocked NS ADDR PORT WHAT + if out=$(x "$1" python3 "$PY" connect "$2" "$3"); then fail "$4: expected to be blocked, got: $out"; fi + echo "ok: $4 ($out)" +} +bytes() { cat "$OUT/$1" 2>/dev/null || echo 0; } +flowing() { # flowing FILE: bytes still arriving + a=$(bytes "$1"); sleep 1; b=$(bytes "$1") + [ $((b - a)) -gt 20000 ] +} + +ok "$A" 203.0.113.2 8080 "tv-box -> internet before the pause" "ok from 203.0.113.1" +spawn "$A" python3 "$PY" sink 203.0.113.2 9000 "$OUT/dev-a" +spawn "$B" python3 "$PY" sink 203.0.113.2 9000 "$OUT/dev-b" +sleep 1.5 +flowing dev-a || fail "tv-box download not flowing" +flowing dev-b || fail "other device's download not flowing" +if x "$R" grep -q 'OFFLOAD' /proc/net/nf_conntrack 2>/dev/null; then echo "ok: downloads are in the flowtable ([OFFLOAD])"; fi + +x "$R" "$MR" pause tv-box 20s | grep -q 'paused tv-box (02:00:00:00:10:02)' || fail "mr pause tv-box" +x "$R" nft list set inet mr paused | grep -q '02:00:00:00:10:02' || fail "@paused lacks tv-box" +x "$R" nft list set inet mr paused_4 | grep -q '192.168.1.60' || fail "@paused_4 lacks tv-box's address (neighbour table)" +sleep 0.5 +if flowing dev-a; then fail "paused device's established download kept flowing"; fi +echo "ok: the paused device's established (offloaded) download stopped" +flowing dev-b || fail "another device's download stopped too" +echo "ok: another device keeps flowing" +blocked "$A" 203.0.113.2 8080 "paused device -> internet (new connection)" +ok "$A" 192.168.1.6 53 "paused device -> the router's DNS port still works" +ok "$B" 203.0.113.2 8080 "another device -> internet" +x "$R" "$MR" pause list | grep -q '02:00:00:00:10:02 tv-box' || fail "mr pause list: $(x "$R" "$MR" pause list)" +x "$R" "$MR" pause list --json | grep -q '"ref": "tv-box"' || fail "mr pause list --json" +x "$R" "$MR" fw || fail "reload during a pause" +x "$R" nft list set inet mr paused | grep -q '02:00:00:00:10:02' || fail "a reload lost the pause" +blocked "$A" 203.0.113.2 8080 "paused device, after a firewall reload" +x "$R" nft list chain inet mr forward | grep 'comment "pause"' | grep -qv 'packets 0 ' || fail "pause counter did not count" +i=0 # the kernel ends the pause: no reload, no command +while x "$R" nft list set inet mr paused | grep -q '02:00:00:00:10:02'; do + i=$((i + 1)) + [ $i -lt 30 ] || fail "the pause did not end" + sleep 1 +done +ok "$A" 203.0.113.2 8080 "the pause ended by itself (kernel timeout)" "ok from 203.0.113.1" +x "$R" "$MR" pause list | grep -q 'nothing paused' || fail "ended pause still listed" + +x "$R" "$MR" pause 02:00:00:00:10:99 1h > /dev/null || fail "mr pause by MAC" +blocked "$B" 203.0.113.2 8080 "paused by MAC" +ok "$A" 203.0.113.2 8080 "a device that is not paused" +x "$R" "$MR" unpause all | grep -q 'unpaused 02:00:00:00:10:99' || fail "mr unpause all" +ok "$B" 203.0.113.2 8080 "unpaused early (mr unpause)" +x "$R" "$MR" pause nobody 1h 2>/dev/null && fail "pausing an unknown device" +x "$R" "$MR" pause tv-box 9d 2>/dev/null && fail "a pause longer than 7 days" +echo "mr pause: ok" + +# office-pc: policy office-wan2-only (via wan2, fallback: drop). wan2's table (0x102 → 102) has no route: +# the mark lookup falls through to main, whose default leaves through pppoe-wan — dropped. +x "$R" ip rule add fwmark 0x102 lookup 102 pref 5300 +blocked "$O" 203.0.113.2 8080 "fallback: drop — no way out through another WAN while wan2 has no route" +x "$R" nft list chain inet mr forward | grep '"fallback:office-wan2-only"' | grep -qv 'packets 0 ' || fail "fallback counter did not count" +ok "$B" 203.0.113.2 8080 "a device without the policy still uses the main route" "ok from 203.0.113.1" +x "$R" ip route add default via 198.51.100.7 dev pppoe-wan2 table 102 +ok "$O" 203.0.113.2 8080 "fallback: drop — through wan2 once its table has a route" "ok from 198.51.100.1" +rm -f "$OUT/dev-a" "$OUT/dev-b" +echo "dev: all packet checks passed" diff --git a/tools/mock/fixtures/config.d/dev.json b/tools/mock/fixtures/config.d/dev.json new file mode 100644 index 0000000..03febb6 --- /dev/null +++ b/tools/mock/fixtures/config.d/dev.json @@ -0,0 +1,11 @@ +{ + "config": { + "devices": [ + {"name": "kid-tablet", "macs": ["02:c8:61:52:f4:45"], "type": "tablet", "owner": "kid"}, + {"name": "kid-phone", "macs": ["02:d9:44:2f:7a:85", "02:00:00:00:10:03"], "type": "phone", "owner": "kid", "desc": "WiFi private address + home address"}, + {"name": "office-pc", "macs": ["02:00:00:00:10:01"], "ip": "192.168.1.70", "type": "pc", "owner": "alice"}, + {"name": "tv-box", "macs": ["02:00:00:00:10:02"], "type": "tv"} + ], + "groups": {"kids": ["kid-tablet", "kid-phone"]} + } +} diff --git a/tools/mock/fixtures/dev.pause.post.json b/tools/mock/fixtures/dev.pause.post.json new file mode 100644 index 0000000..dd8edcb --- /dev/null +++ b/tools/mock/fixtures/dev.pause.post.json @@ -0,0 +1 @@ +{"ok": true, "paused": [{"mac": "02:00:00:00:10:02", "name": "tv-box", "ref": "tv-box", "by": "web", "left": 3600}]} diff --git a/tools/mock/fixtures/dev.paused.json b/tools/mock/fixtures/dev.paused.json new file mode 100644 index 0000000..d001e86 --- /dev/null +++ b/tools/mock/fixtures/dev.paused.json @@ -0,0 +1,7 @@ +{ + "paused": [ + {"mac": "02:c8:61:52:f4:45", "name": "kid-tablet", "ref": "group:kids", "by": "web", "left": 2710, "ips": ["192.168.1.170"]}, + {"mac": "02:d9:44:2f:7a:85", "name": "kid-phone", "ref": "group:kids", "by": "web", "left": 2710, "ips": ["192.168.1.217"]}, + {"mac": "02:00:00:00:10:03", "name": "kid-phone", "ref": "group:kids", "by": "web", "left": 2710} + ] +} diff --git a/tools/mock/fixtures/dev.unpause.post.json b/tools/mock/fixtures/dev.unpause.post.json new file mode 100644 index 0000000..935b2f6 --- /dev/null +++ b/tools/mock/fixtures/dev.unpause.post.json @@ -0,0 +1 @@ +{"ok": true, "paused": []} diff --git a/tools/mock/fixtures/status.json b/tools/mock/fixtures/status.json index a764eec..87501c5 100644 --- a/tools/mock/fixtures/status.json +++ b/tools/mock/fixtures/status.json @@ -1,4 +1,8 @@ { + "paused": [ + {"mac": "02:c8:61:52:f4:45", "name": "kid-tablet", "ref": "group:kids", "by": "web", "left": 2710, "ips": ["192.168.1.170"]}, + {"mac": "02:d9:44:2f:7a:85", "name": "kid-phone", "ref": "group:kids", "by": "web", "left": 2710} + ], "changes": [ "2026-09-24 10:29:01 mr apply: network.sh, hostapd-phy0.conf, hostapd-phy1.conf, services, firewall, +mr-zram", "2026-09-24 10:32:15 mr apply: failed and rolled back — not confirmed within 180s",