Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,13 @@ expired token, 403 not allowed, 404 unknown, 405 POST required, 409 conflict, 42
| `POST confirm` / `POST revert` | keep / undo the pending change (a token: only its own) |
| `GET history`, `POST history.diff {rev}`, `POST rollback {rev}` | revisions; the config from before #rev applied as a new change |

When a Web UI apply changes `lan.ipv4`, the response additionally contains `confirm_token` and
`confirm_ip`. The browser uses `http://confirm_ip/#confirm=confirm_token` after the old origin goes
away. The token is 256 bits of random data, valid only for this pending apply and its 120-second
window, accepted only by `POST confirm` from a LAN source, and consumed by the first successful
confirmation. The pending marker stores only a SHA-256 digest; the raw token is held briefly in a
0600 tmpfs file while the apply worker starts and is never written to the job log or history.

`secrets` sets secret values by name (`{"proxy_jp2": "…"}`; empty = keep) — for new credentials; values
never come back. `changes` is the config-level diff against the last applied config (`~ path: old → new`,
`+ path`, `- path`; secrets only as `(changed)`).
Expand Down
1 change: 1 addition & 0 deletions docs/modules/net.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ net 负责路由器的"线":物理网口和网桥、LAN 与额外网络(访
| PPPoE(已有) | `pppd` + 生成的 `/etc/ppp/peers/<wan>`,服务实例 `mr-pppoe.<wan>` | pppd |
| DHCP WAN | busybox `udhcpc -f`,服务实例 `mr-udhcpc.<wan>`(supervise-daemon 守护);事件脚本 `/usr/libexec/mr/net-udhcpc` → `mr wan dhcp <event>` 校验租约后配地址、路由、规则、DNS | udhcpc(busybox,≈100 KB) |
| 静态 WAN | `network.sh` 配地址,`mr routes` 装默认路由 | 无 |
| LAN / 网络地址更新 | `network.sh` 记录并清理上一次由 mr 写入的网桥地址;同网段换地址先启用 `promote_secondaries`,有线 LAN 口短暂 down/up 触发 DHCP 续租 | 不重启 WiFi;外部工具添加的 secondary 地址保留 |
| WAN VLAN | `<device>.<vlan>` 802.1Q 子接口(PPPoE / DHCP / 静态都可以跑在上面);由 mr 创建的子接口带 `alias mini-router`,取消配置时只清理这类接口 | 无 |
| 多线路主备 | `mr-wanmon`:busybox sh 循环,每条线路各自 ping 检测目标;故障线路默认路由 metric +10000,策略路由表去掉默认路由 | sh + 每轮几次 ping |
| 负载均衡 | nft `numgen random` 按权重给新 IPv4 连接打 WAN 标记,connmark 保持 | 无(nftables 规则) |
Expand Down
6 changes: 3 additions & 3 deletions docs/modules/sys.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ services:
lan_only: false # true: listen only on the IPv4 address of every LAN-zone network
authorized_keys: # managed block in /root/.ssh/authorized_keys (other lines are never touched)
- ssh-ed25519 AAAAC3Nza... me@laptop
panel: {enabled: true} # web UI (busybox httpd on the main LAN address, port 80)
panel: {enabled: true} # web UI (busybox httpd on all addresses while nftables is loaded, port 80)
ddns: # dynamic DNS, no daemon (see "DDNS" below)
enabled: true
interval: 10 # minutes between safety checks by crond (5-60); 0 = only on WAN events
Expand Down Expand Up @@ -151,7 +151,7 @@ Validation (the security boundary — everything below ends up in a file, a cron
| `/etc/conf.d/ntpd` | `NTPD_OPTS="-N -S /usr/libexec/mr/clock-save -p … [-l]"`(`clock-save` 每小时最多一次把已同步的时间记到闪存,开机时 `mr-clock` 从它恢复——板子没有 RTC) | restart `ntpd` |
| `/etc/conf.d/dropbear` (ssh on) | `DROPBEAR_OPTS="-p [addr:]port … -K 300 [-s -g]"` | restart `dropbear` |
| `/etc/conf.d/tailscale` (on) | `TS_PORT=` (read by `/etc/init.d/tailscale`) | restart `tailscale` |
| `/etc/conf.d/mr-panel` (on) | `PANEL_ADDR=` main LAN address (was a `sed` on router.yaml) | restart `mr-panel` |
| `/etc/conf.d/mr-panel` (on) | `PANEL_ADDR=0.0.0.0` so both old/new LAN origins remain reachable; when nftables is absent, init falls back to the LAN address for repair | restart `mr-panel` |
| `/etc/conf.d/crond` (schedules) | `CRON_OPTS`, `export TZ=…` | restart `crond` |
| `/etc/crontabs/root` | managed block between markers (schedules; DDNS on with an interval adds `*/N * * * * /usr/sbin/mr ddns sync --cron`; the reverse proxy adds `M H * * * /usr/sbin/mr edge renew --cron`, M and H fixed per router, H 2–5; dns.adblock adds `M * * * * /usr/sbin/mr dns adblock update --cron`; `wan[].require_public_ip` adds `* * * * * /usr/sbin/mr wan public-check --cron`; wifi.steering / wifi.self_heal add `* * * * * /usr/sbin/mr wifi tick`); Alpine's periodic lines and anything else kept | — (crond rescans the directory) |
| `/etc/mini-router/gen/edge.json` (edge on) | port, WAN port, certificate directory, routes (host, target, certificate name, allow) — nothing secret, 0644 | restart `mr-edge` |
Expand Down Expand Up @@ -683,7 +683,7 @@ warn); issued and failed certificates are events of type `cert`.

* New files: `/etc/localtime` (+08), `/etc/modules-load.d/mr-sys.conf`, `/etc/conf.d/sysctl`,
`/etc/conf.d/tailscale` (`TS_PORT=41641`, same as the old hard-coded port), `/etc/conf.d/mr-panel`
(`PANEL_ADDR=192.168.1.6`, what the old `sed` found). The first apply after the update therefore
(`PANEL_ADDR=0.0.0.0`; `mr-panel` starts after the nftables firewall and falls back to the LAN address if its table is absent). The first apply after the update therefore
restarts `syslog`, `tailscale` and `mr-panel` once.
* `conf.d/ntpd`, `conf.d/dropbear`, `90-mini-router.conf`, `hostname`, `tz.sh`: byte-identical.
* No crontab, no authorized_keys change (no schedules, no managed keys), crond stays off.
Expand Down
132 changes: 123 additions & 9 deletions mr/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,13 @@ const (

// the apply job's input and state (variables so tests can point them elsewhere)
var (
CandidateYAML = RunDir + "/candidate.yaml"
CandidateSec = RunDir + "/candidate-secrets.yaml"
JobFile = RunDir + "/job.json"
JobLog = RunDir + "/job.log"
loadLANConfig = func() (*Config, error) { return loadConfig(ConfigPath, SecretsPath) }
lanBridgeAddrs = func(bridge string) ([]net.Addr, error) {
CandidateYAML = RunDir + "/candidate.yaml"
CandidateSec = RunDir + "/candidate-secrets.yaml"
JobFile = RunDir + "/job.json"
JobLog = RunDir + "/job.log"
confirmTokenFile = RunDir + "/confirm-token"
loadLANConfig = func() (*Config, error) { return loadConfig(ConfigPath, SecretsPath) }
lanBridgeAddrs = func(bridge string) ([]net.Addr, error) {
i, err := net.InterfaceByName(bridge)
if err != nil {
return nil, err
Expand Down Expand Up @@ -118,6 +119,80 @@ func normalizedRemoteIP(remote string) net.IP {
return net.ParseIP(strings.SplitN(normalizeRemoteAddr(remote), "%", 2)[0])
}

func newConfirmToken() string {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return ""
}
return base64.RawURLEncoding.EncodeToString(b)
}

func lanIPv4Host(cidr string) string {
ip, _, err := net.ParseCIDR(cidr)
if err != nil || ip.To4() == nil {
return ""
}
return ip.To4().String()
}

// prepareLANConfirmToken stages the raw token only for browser-originated changes
// that can strand the current origin, including web rollbacks. API-token and CLI
// changes keep their existing confirmation semantics.
func prepareLANConfirmToken(candidate, via string) (string, string, error) {
os.Remove(confirmTokenFile)
if via != "web UI" && via != "rollback" {
return "", "", nil
}
live, err := loadConfig(ConfigPath, SecretsPath)
if err != nil {
return "", "", nil
}
next, err := loadConfig(candidate, CandidateSec)
if err != nil || live.LAN.IPv4 == next.LAN.IPv4 {
return "", "", nil
}
token := newConfirmToken()
if token == "" || writeAtomic(confirmTokenFile, []byte(token), 0600) != nil {
return "", "", errors.New("cannot create LAN confirmation token")
}
return token, lanIPv4Host(next.LAN.IPv4), nil
}

// confirmWithToken is deliberately separate from the normal session path. The token
// is scoped to the current pending marker, expires with it, is accepted only here,
// and is consumed by confirm (which removes the marker atomically under its lock).
func confirmWithToken(token, remote string) apiResp {
if len(token) < 32 || len(token) > 128 {
return errResp(401, "invalid confirmation token")
}
okLAN, err := fromLAN(remote)
if err != nil {
return errResp(403, "confirmation is only allowed from the LAN")
}
if !okLAN {
return errResp(403, "confirmation is only allowed from the LAN")
}
unlock := lockPending()
p, err := readPending()
if err != nil || p.ConfirmHash == "" || p.left() <= 0 {
unlock()
return errResp(409, "no matching LAN confirmation is pending")
}
h := sha256.Sum256([]byte(token))
want, err := hex.DecodeString(p.ConfirmHash)
if err != nil || subtle.ConstantTimeCompare(want, h[:]) != 1 {
unlock()
return errResp(401, "invalid confirmation token")
}
r := confirmTransition()
unlock()
ok, err := finishConfirm(r)
if err != nil {
return errResp(409, "%v", err)
}
return apiResp{body: map[string]any{"ok": true, "confirmed": ok}, authed: true}
}

func runAPI() error {
r := apiReq{
method: os.Getenv("REQUEST_METHOD"),
Expand Down Expand Up @@ -176,6 +251,17 @@ func handleAPI(r apiReq) apiResp {
case "setup":
return apiSetup(r, secrets)
}
// A LAN renumber changes the browser's origin, so the old session cookie is not
// available at the new address. The apply response hands the browser a short-lived,
// single-use token that is accepted only by this POST action and only from the LAN.
if r.action == "confirm" && r.method == "POST" {
var in struct {
Token string `json:"token"`
}
if json.Unmarshal(r.body, &in) == nil && in.Token != "" {
return confirmWithToken(in.Token, r.remote)
}
}
if !validSession(r.cookie) {
return errResp(401, "not logged in")
}
Expand Down Expand Up @@ -659,6 +745,7 @@ func apiApply(r apiReq) apiResp {
return errResp(400, "comment: one line, at most 200 characters")
}
os.MkdirAll(RunDir, 0700)
os.Remove(confirmTokenFile)
if len(in.Patch) == 0 && in.YAML == "" {
y = uiConfigYAML(y, c) // a patch's text is already the live file with only its edits; raw text stays as typed
}
Expand All @@ -670,12 +757,24 @@ func apiApply(r apiReq) apiResp {
return errResp(500, "%v", err)
}
if err := writeSecrets(CandidateSec, sec); err != nil {
os.Remove(confirmTokenFile)
return errResp(500, "%v", err)
}
// Keep the raw handoff token only in a root-readable tmpfs file while the apply
// worker starts. The persistent pending marker stores its SHA-256 digest only.
confirmToken, confirmIP, tokenErr := prepareLANConfirmToken(CandidateYAML, via)
if tokenErr != nil {
return errResp(500, "%v", tokenErr)
}
writeJob(jobState{State: "running", Started: time.Now().Unix(), Confirm: confirmSecs, Via: via, From: r.remote, Comment: in.Comment, BaseRev: base})
self, _ := os.Executable()
startDetached(self, "apply-job", strconv.Itoa(confirmSecs))
return apiResp{body: map[string]any{"ok": true, "confirm": confirmSecs}}
body := map[string]any{"ok": true, "confirm": confirmSecs}
if confirmToken != "" {
body["confirm_token"] = confirmToken
body["confirm_ip"] = confirmIP
}
return apiResp{body: body}
}

// runApplyJob executes a web-UI apply in the background and records the outcome for polling.
Expand All @@ -685,7 +784,13 @@ func runApplyJob(confirmSecs int) error {
j0 := readJob()
j0.Pid = os.Getpid()
writeJob(j0)
o := applyOpts{Via: j0.Via, From: j0.From, Comment: j0.Comment, BaseRev: j0.BaseRev}
token := ""
if j0.Via == "" || j0.Via == "web UI" || j0.Via == "rollback" {
tokenBytes, _ := os.ReadFile(confirmTokenFile)
token = strings.TrimSpace(string(tokenBytes))
}
os.Remove(confirmTokenFile)
o := applyOpts{Via: j0.Via, From: j0.From, Comment: j0.Comment, BaseRev: j0.BaseRev, ConfirmToken: token}
if o.Via == "" {
o.Via = "web UI"
}
Expand Down Expand Up @@ -846,10 +951,19 @@ func apiRollback(r apiReq) apiResp {
if r.via != "" {
via = r.via // an API token (the comment says what it is): it may confirm its own rollback
}
confirmToken, confirmIP, tokenErr := prepareLANConfirmToken(CandidateYAML, via)
if tokenErr != nil {
return errResp(500, "%v", tokenErr)
}
writeJob(jobState{State: "running", Started: time.Now().Unix(), Confirm: 120, Via: via, From: r.remote, Comment: comment})
self, _ := os.Executable()
startDetached(self, "apply-job", "120")
return apiResp{body: map[string]any{"ok": true, "confirm": 120}}
body := map[string]any{"ok": true, "confirm": 120}
if confirmToken != "" {
body["confirm_token"] = confirmToken
body["confirm_ip"] = confirmIP
}
return apiResp{body: body}
}

func apiLogs() apiResp {
Expand Down
69 changes: 69 additions & 0 deletions mr/api_test.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,83 @@
package main

import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"net"
"os"
"strconv"
"strings"
"testing"
"time"
)

func TestLANConfirmTokenIsScopedAndHashed(t *testing.T) {
oldConfirm, oldLoad := ConfirmFile, loadLANConfig
t.Cleanup(func() { ConfirmFile, loadLANConfig = oldConfirm, oldLoad })
ConfirmFile = t.TempDir() + "/confirm-pending"
loadLANConfig = func() (*Config, error) { return &Config{LAN: LAN{IPv4: "192.168.2.1/24"}}, nil }
token := newConfirmToken()
h := sha256.Sum256([]byte(token))
if len(token) < 32 || token == newConfirmToken() {
t.Fatal("confirmation token is missing entropy")
}
if err := setPending(pendingApply{Snapshot: "/tmp/snap", State: statePending, Deadline: time.Now().Unix() + 60, ConfirmHash: hex.EncodeToString(h[:])}); err != nil {
t.Fatal(err)
}
if marker, err := os.ReadFile(ConfirmFile); err != nil || bytes.Contains(marker, []byte(token)) {
t.Fatalf("pending marker contains plaintext token: %q", marker)
}
if got := confirmWithToken(token+"x", "192.168.2.44"); got.status != 401 {
t.Fatalf("wrong token status = %d, want 401", got.status)
}
if _, err := os.Stat(ConfirmFile); err != nil {
t.Fatalf("wrong token consumed pending marker: %v", err)
}
// A token cannot confirm while the apply is still running, even when its hash matches.
if err := setPending(pendingApply{Snapshot: "/tmp/snap", State: stateApplying, Pid: os.Getpid(), ConfirmHash: hex.EncodeToString(h[:])}); err != nil {
t.Fatal(err)
}
if got := confirmWithToken(token, "192.168.2.44"); got.status != 409 {
t.Fatalf("applying token status = %d, want 409", got.status)
}
}

func TestLANConfirmTokenSuccessIsOneShotAndLANOnly(t *testing.T) {
_, _, _ = confirmEnv(t)
oldLoad := loadLANConfig
t.Cleanup(func() { loadLANConfig = oldLoad })
loadLANConfig = func() (*Config, error) { return &Config{LAN: LAN{IPv4: "192.168.2.1/24"}}, nil }
token := newConfirmToken()
h := sha256.Sum256([]byte(token))
if err := setPending(pendingApply{Snapshot: "/tmp/snap", State: statePending, Deadline: time.Now().Unix() + 60, ConfirmHash: hex.EncodeToString(h[:])}); err != nil {
t.Fatal(err)
}
if got := confirmWithToken(token, "192.168.2.44"); got.status != 0 {
t.Fatalf("valid LAN token status = %d, want success", got.status)
}
if got := confirmWithToken(token, "192.168.2.44"); got.status != 409 {
t.Fatalf("reused token status = %d, want 409", got.status)
}
if err := setPending(pendingApply{Snapshot: "/tmp/snap", State: statePending, Deadline: time.Now().Unix() + 60, ConfirmHash: hex.EncodeToString(h[:])}); err != nil {
t.Fatal(err)
}
if got := confirmWithToken(token, "192.168.9.44"); got.status != 403 {
t.Fatalf("non-LAN token status = %d, want 403", got.status)
}
if err := setPending(pendingApply{Snapshot: "/tmp/snap", State: statePending, Deadline: time.Now().Unix() - 1, ConfirmHash: hex.EncodeToString(h[:])}); err != nil {
t.Fatal(err)
}
if got := confirmWithToken(token, "192.168.2.44"); got.status != 409 {
t.Fatalf("expired token status = %d, want 409", got.status)
}
if got := handleAPI(apiReq{method: "GET", action: "confirm", header: "1", remote: "192.168.2.44", body: []byte(`{"token":"` + token + `"}`)}); got.status == 0 {
t.Fatal("GET confirmation unexpectedly succeeded")
}
}

func TestNormalizeRemoteAddrBusyboxFormats(t *testing.T) {
for _, tc := range []struct {
raw, want string
Expand Down
Loading
Loading