mihomo: no control API of any kind, and the gates the JSON drivers have

The MIHOMO_CONTROLLER setting is gone: mihomo gets no external-controller (nor -tls, -unix, -pipe, -cors, external-ui*, external-doh-server, tls, secret) from a setting, an older store or a legacy vpn.conf, so the TUN is the only thing that listens and no unauthenticated API can reconfigure it. The reader now refuses, as the JSON drivers refuse a misspelled shape key, a top-level key that is a kept name or one of ours in another spelling (case, _ for -), a key of the driver's reserved names (mu300-anchor-N), and takes the size cap before anything reads the file; merge keys, aliases and anchors at column 0 and merge tags stay refused, and what an alias brings into a kept block comes from an anchored block that went through the same removals. The written-file guard lost its controller argument and refuses any external-*, secret, tls, port or listener in any spelling. Tests mirror the sing-box ones (nothing listens, keys spelled differently, the size cap first, an alias cannot bring a key in); spec, README and tests/README follow.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DqKKtBQZCfxYnHuBCuDqqn
This commit is contained in:
Abdurrahman Kaan DikeçandClaude Fable 5.1 committed 2026-10-09 09:21:25 +03:00
1 parent 49869fcc7c
commit d7e5ebc730
6 files changed
+229 -92

No files matched your search

-1
View File
@@ -487,7 +487,6 @@ VPN that is on uses a new value from its next `mu300-vpn restart`):
| `REMOTE_DNS` | an address | 1.1.1.1 | DNS for the device and its clients, through the tunnel |
| `BOOTSTRAP_DNS` | an address | 1.1.1.1 | for the server's own name, outside the tunnel (sing-box, mihomo) |
| `LAN_CIDRS` | CIDRs, comma-separated | empty | more networks that stay local (the device's own LAN always does) |
| `MIHOMO_CONTROLLER` | empty, `127.0.0.1:PORT` | empty | mihomo's external controller, loopback only |
| `XRAY` `HEV` `SING_BOX` `MIHOMO` `OPENVPN` | a path | empty | another binary for that engine |
**Engines.** Each type runs on its own engine, and `mu300-vpn engines` says which are present and how to get the
@@ -70,7 +70,6 @@ Everything under `/etc/mu300`, which updates keep. Each system (Ubuntu, OpenWrt,
| REMOTE_DNS | IPv4/IPv6 address | 1.1.1.1 | DNS for the device and clients, through the tunnel |
| BOOTSTRAP_DNS | IPv4/IPv6 address | 1.1.1.1 | for server names, outside the tunnel (sing-box, mihomo) |
| LAN_CIDRS | comma list of CIDRs | empty | the device's own LAN is always added (as today) |
| MIHOMO_CONTROLLER | empty or `127.0.0.1:PORT` / `[::1]:PORT` | empty | mihomo's external-controller; off by default |
| XRAY HEV SING_BOX MIHOMO OPENVPN | absolute path | empty | another engine binary (as XRAY= in vpn.conf today) |
`settings set` validates and refuses (exit 2) a value outside these; on read an invalid value counts as the default.
@@ -143,8 +142,8 @@ The kill switch lets only marked traffic out on an uplink, and rule 9000 keeps i
top-level key and its indented block; every other block is removed) and ours appended: TUN `mh-mu300`, stack from
the profile's `MIHOMO_STACK` (default gvisor), `auto-route: false`, `auto-detect-interface: false`, no DNS hijack;
`dns` with `proxy-server-nameserver`/`default-nameserver` = BOOTSTRAP_DNS, `nameserver` = REMOTE_DNS,
`respect-rules: true`; `allow-lan: false`; `bind-address: '127.0.0.1'`; `external-controller` only when
MIHOMO_CONTROLLER is set. Checked with `mihomo -t`.
`respect-rules: true`; `allow-lan: false`; `bind-address: '127.0.0.1'`; no `external-controller` of any kind (the
TUN is the only thing that listens). Checked with `mihomo -t`.
* **wireguard**: `wg set wg-mu300 fwmark 0x2d0`. `wg.conf`'s wg-quick keys (Address, DNS, MTU, Table, Pre/PostUp/Down,
SaveConfig) are stripped for `wg setconf`, and so are ListenPort (a config opens no port on the device) and
FwMark (the mark is ours, set by `wg set` after setconf); the Endpoint name is resolved, Address goes on with `ip addr`, MTU
@@ -403,9 +402,10 @@ Per system, at every start of `mu300-vpn` (any command), idempotent, and only wh
not refused. Kept: `proxies`, `proxy-groups`, `proxy-providers`, `rules`, `rule-providers`, `sub-rules`, `hosts`,
`mode`, `log-level`, `ipv6`, `geodata-mode`, `geodata-loader`, `geox-url`, `profile`, `sniffer`. Written by the
driver, whatever the file had: `tun` (ours), `dns` (ours), `routing-mark: 720`, `allow-lan: false`,
`bind-address: '127.0.0.1'`, and `external-controller` only as MIHOMO_CONTROLLER, which must be a 127.0.0.1
address (no `external-controller-tls`/`-unix`/`-pipe`, no `external-ui*`; the file's `secret` is removed with the
rest - the controller listens on loopback only, where every user of this device is root). `port`, `socks-port`,
`bind-address: '127.0.0.1'`. No controller or API of any kind is written: `external-controller`,
`external-controller-tls`/`-unix`/`-pipe`/`-cors`, `external-ui*`, `external-doh-server`, `tls` and `secret` are
removed with the rest (there is no setting that asks for one; an unauthenticated control API could reconfigure
mihomo, and a secret of the file's would be the file author's). `port`, `socks-port`,
`mixed-port`, `redir-port` and `tproxy-port` are removed (the TUN is the only
inbound; were one ever written, `allow-lan: false` and the bind address keep it on loopback). Everything else is
removed with the unlisted keys - among them `listeners`, `tunnels`, `ss-config`, `vmess-config`, `tuic-server`
@@ -436,10 +436,13 @@ Per system, at every start of `mu300-vpn` (any command), idempotent, and only wh
middle of a value belongs to the value), a hex escape (`\x`, `\u`, `\U`: the one way a key can be spelled
without its text on one line), a column-0 line that is not `KEY:` (a quoted key, a list item, a merge key, an anchor, a flow collection
continued at column 0: YAML would read it as top-level content that the line rules cannot see), a kept key
given twice (mihomo's YAML reader refuses it anyway), and a file without `proxies` and `proxy-providers`. A
given twice (mihomo's YAML reader refuses it anyway), a top-level key that is a kept name or one of ours in
another spelling (case, `_` for `-`: refused by the name it collides with, as the JSON drivers refuse a
misspelled shape key), a key of the driver's own reserved names (`mu300-anchor-N`), and a file without
`proxies` and `proxy-providers`. The size cap comes before anything reads the file, as in the JSON drivers. A
first line `---`, a BOM and CRLF line ends are taken. The written file is checked again before `mihomo -t`
(no line break but LF, the guard's line model being yaml.v3's; every column-0 key one of the kept list, ours or `mu300-anchor-N`, `tun` and `dns` exactly once, `routing-mark: 720`,
`allow-lan: false`, `bind-address` once, `external-controller` exactly when MIHOMO_CONTROLLER is set), and
`allow-lan: false`, `bind-address` once, no `external-*` key), and
`mihomo -t`'s own output is not shown (its YAML errors quote values); the message gives the command to run.
* The kill switch is unchanged: only marked traffic, NTP and the Wi-Fi client's DHCP leave on an uplink; forwarded
traffic to an uplink is dropped. Every new driver marks its own sockets, so none of them needs an exception.
@@ -450,7 +453,7 @@ Per system, at every start of `mu300-vpn` (any command), idempotent, and only wh
* `tests/test_vpn_drivers.py` (every shell): the driver contract per type with stub engines recording their
arguments (`xray`, `hev-socks5-tunnel`, `sing-box`, `mihomo`, `wg`, `openvpn`, `ip`, `nft`); the URI parsers
(vless, vmess base64 JSON, trojan, ss SIP002 and legacy base64, wg .conf); raw JSON/YAML forcing (marks, inbounds,
TUN, controller); migration (first, idempotent, an edited vpn.conf, not writable); profile CRUD, ID validation,
TUN, no controller); migration (first, idempotent, an edited vpn.conf, not writable); profile CRUD, ID validation,
`use` keeping the kill switch (no `delete table` between two runs); settings validation; `engines` output;
reserved types; nothing secret in stdout/stderr of `list`/`show`/`status`/`run`.
* `tests/test_static.py`: the vpn-mihomo extra in make-release's build and audit lists and mu300-update's EXTRAS;
+1 -6
View File
@@ -128,10 +128,6 @@ setting_valid() {
case $2 in ,*|*,|*,,*|*[!0-9A-Fa-f.:/,]*) return 1 ;; esac
_o=$IFS; IFS=,; set -- $2; IFS=$_o
for _c; do cidr_ok "$_c" || return 1; done ;;
# mihomo's external controller can reconfigure it: never anywhere but loopback
MIHOMO_CONTROLLER)
case $2 in '') return 0 ;; 127.0.0.1:*) port_ok "${2#127.0.0.1:}" ;; '[::1]:'*) port_ok "${2#\[::1\]:}" ;;
*) return 1 ;; esac ;;
XRAY|HEV|SING_BOX|MIHOMO|OPENVPN) case $2 in ''|/*) return 0 ;; esac; return 1 ;;
*) return 1 ;;
esac
@@ -149,7 +145,6 @@ setting() { setting_var _sv "$1"; printf '%s\n' "$_sv"; }
settings_load() {
setting_var KILL_SWITCH KILL_SWITCH; setting_var TAILSCALE TAILSCALE; setting_var IPV6 IPV6
setting_var REMOTE_DNS REMOTE_DNS; setting_var BOOTSTRAP_DNS BOOTSTRAP_DNS; setting_var LAN_CIDRS LAN_CIDRS
setting_var MIHOMO_CONTROLLER MIHOMO_CONTROLLER
setting_var _xray XRAY; setting_var _hev HEV; setting_var _sb SING_BOX; setting_var _mihomo MIHOMO
setting_var _openvpn OPENVPN
}
@@ -1262,7 +1257,7 @@ profile_cmd() {
esac
}
SETTING_KEYS='KILL_SWITCH TAILSCALE IPV6 REMOTE_DNS BOOTSTRAP_DNS LAN_CIDRS MIHOMO_CONTROLLER XRAY HEV SING_BOX MIHOMO OPENVPN'
SETTING_KEYS='KILL_SWITCH TAILSCALE IPV6 REMOTE_DNS BOOTSTRAP_DNS LAN_CIDRS XRAY HEV SING_BOX MIHOMO OPENVPN'
# setting_show KEY: the value in force - from the store, or as vpn.conf gave it where the store is not used
setting_show() {
if [ -n "$STORE" ]; then setting "$1"; return; fi
+41 -33
View File
@@ -9,8 +9,9 @@
# profile's file: the driver reads it once, line by line (awk; there is no YAML parser on the device, and the rules
# below are about lines, see mihomo_read), keeps the top-level blocks of an allowlist, removes the rest (Clash files
# carry many harmless keys, so an unknown key is dropped, not refused), takes interface-name and routing-mark out of
# every proxy and group, appends what is ours last (the mark, allow-lan, bind-address, tun, dns, the controller),
# checks the written file once more (mihomo_written_ok), and only then lets mihomo check (-t) and run it. The
# every proxy and group, appends what is ours last (the mark, allow-lan, bind-address, tun, dns; no controller or
# API of any kind: the TUN is the only thing that listens, and nothing can ask for more), checks the written file
# once more (mihomo_written_ok), and only then lets mihomo check (-t) and run it. The
# profile keeps the file as imported (profile export gives it back). A refusal names a key of our own lists or a
# rule, never a value or a line of the file, and mihomo's own messages are not repeated (its YAML errors quote values).
DRV_EXTRA=vpn-mihomo
@@ -26,8 +27,10 @@ unset SAFE_PATHS SKIP_SAFE_PATH_CHECK
# the top-level keys of the file that survive, as the spec's Security section lists them; every other one is removed
MIHOMO_KEYS='proxies proxy-groups proxy-providers rules rule-providers sub-rules hosts mode log-level ipv6 geodata-mode geodata-loader geox-url profile sniffer'
# the top-level keys this driver writes (external-controller only when MIHOMO_CONTROLLER is set)
MIHOMO_OURS='routing-mark allow-lan bind-address tun dns external-controller'
# the top-level keys this driver writes, and the only ones besides the kept list that the written file may have:
# external-controller (and -tls, -unix, -pipe, -cors), external-ui*, external-doh-server, secret and tls are not
# among them, so no control API of the file's or of a setting's ever reaches mihomo
MIHOMO_OURS='routing-mark allow-lan bind-address tun dns'
# The binary: the MIHOMO setting when there is one, else the extra's (or /opt/mu300/bin, or PATH).
mihomo_bin() { if [ -n "${_mihomo:-}" ]; then printf '%s\n' "$_mihomo"; else engine_path mihomo vpn-mihomo; fi; }
@@ -61,9 +64,12 @@ mihomo_home() {
# line ending in a backslash and a quoted scalar not closed on its line (the other ways a key can span lines), a
# hex escape (\x, \u, \U: the one way a key can be spelled without its text on one line), a column-0 line that is
# not "KEY:" (a quoted key, a list item, a merge key, an anchor, a flow collection continued at column 0), a kept
# key given twice (mihomo's reader refuses it anyway) and a file with neither proxies nor proxy-providers. A first
# line "---", a BOM and CRLF line ends are taken. The size and the control bytes are checked in the shell, before
# awk sees the file.
# key given twice (mihomo's reader refuses it anyway), a top-level key that is a kept name or one of ours in another
# spelling (another case, _ for -: mihomo's reader would not read it, and the JSON drivers refuse a misspelled
# shape key the same way; the refusal names the name it collides with, not the file's key), a key of the driver's
# own reserved names (mu300-anchor-N) and a file with neither proxies nor proxy-providers. A first line "---", a
# BOM and CRLF line ends are taken. The size cap comes first (before the control-byte count, which is the shell's,
# and before awk sees a line), as in the JSON drivers.
mihomo_read() {
json_size_ok "$2" || { [ "$1" != check ] || echo "the mihomo config is larger than 1 MiB"; return 1; }
# what is left after removing TAB, LF, CR, printable ASCII and the bytes from 0x80 is a control character or NUL
@@ -72,7 +78,7 @@ mihomo_read() {
[ "$1" != check ] || echo "the mihomo config has a control character (NUL, escape, form feed ...), which it may not contain"
return 1
fi
LC_ALL=C awk -v mode="$1" -v keep="$MIHOMO_KEYS" '
LC_ALL=C awk -v mode="$1" -v keep="$MIHOMO_KEYS" -v ours="$MIHOMO_OURS" '
function bad(m) { if (mode == "check") print "the mihomo config " m; err = 1 }
function atline(m) { bad("(line " NR ") " m) }
function emit(s) { out[++no] = s }
@@ -193,8 +199,12 @@ mihomo_read() {
dropto = -1
for (i = 2; i <= npend; i++) body(pend[i])
}
# fold(k): a key as a case-insensitive reader with - for _ would see it; foldk maps the folds of the kept names
# and ours back to the name, so a key spelled otherwise is caught by the name it collides with
function fold(k) { k = tolower(k); gsub(/_/, "-", k); return k }
BEGIN {
n = split(keep, a, " "); for (i = 1; i <= n; i++) keepk[a[i]] = 1
n = split(keep, a, " "); for (i = 1; i <= n; i++) { keepk[a[i]] = 1; foldk[fold(a[i])] = a[i] }
n = split(ours, a, " "); for (i = 1; i <= n; i++) foldk[fold(a[i])] = a[i]
dk[1] = "interface-name"; dk[2] = "routing-mark"
dropto = -1; keeping = 0; dropping = 0; ngone = 0; nanch = 0
}
@@ -234,6 +244,11 @@ mihomo_read() {
keeping = 0; next
}
k = $0; sub(/[ \t]*:.*/, "", k)
f = fold(k)
if (f ~ /^mu300-anchor-[0-9]+$/) { atline("has the top-level key mu300-anchor-N, a name reserved for this driver"); keeping = 0; next }
if ((f in foldk) && k != foldk[f]) {
atline("has a top-level key spelled differently from " foldk[f] " (another case, or _ for -)"); keeping = 0; next
}
if (k in keepk) {
if (k in seen) bad("has the top-level key " k " twice")
seen[k] = 1; keeping = 1
@@ -259,16 +274,16 @@ mihomo_read() {
}
if (err) exit 1
if (mode == "gen") { for (i = 1; i <= no; i++) print out[i]; exit 0 }
if (gonelist != "") print "note: top-level keys of the file that are not used (this driver writes its own tun, dns, ports and controller):" gonelist (ngone > 40 ? " ..." : "")
if (gonelist != "") print "note: top-level keys of the file that are not used (this driver writes its own tun and dns; nothing listens but the TUN):" gonelist (ngone > 40 ? " ..." : "")
if (anchored != "") print "note: kept for the anchors (&name) they define, under names mihomo does not read:" anchored
}' "$2"
}
# mihomo_ours STACK CONTROLLER: the top-level keys this driver writes, after the file's own (the last wins in no
# reader; they are the only ones, see mihomo_written_ok). The TUN is the only inbound (no port of any kind, and
# allow-lan off with the bind address on loopback should one ever be written); auto-route and auto-detect-interface
# are off (the core routes, the kernel picks the uplink); DNS: the server names through BOOTSTRAP_DNS over mihomo's
# own marked sockets, everything else through REMOTE_DNS behind the rules.
# mihomo_ours STACK: the top-level keys this driver writes, after the file's own (the last wins in no reader; they
# are the only ones, see mihomo_written_ok). The TUN is the only inbound (no port of any kind, no controller or
# API, and allow-lan off with the bind address on loopback should one ever be written); auto-route and
# auto-detect-interface are off (the core routes, the kernel picks the uplink); DNS: the server names through
# BOOTSTRAP_DNS over mihomo's own marked sockets, everything else through REMOTE_DNS behind the rules.
mihomo_ours() {
cat <<EOF
routing-mark: $((MARK))
@@ -292,16 +307,15 @@ dns:
proxy-server-nameserver: ['$BOOTSTRAP_DNS']
nameserver: ['$REMOTE_DNS']
EOF
[ -z "$2" ] || printf "external-controller: '%s'\n" "$2"
}
# mihomo_written_ok CONTROLLER FILE: the guard behind the rebuild, on the file mihomo gets: no line break but LF
# (yaml.v3's line is the guard's line), every column-0 line a "KEY:" line whose key is one of the kept list, ours
# or an anchor holder of ours (mu300-anchor-N, see flush_dropped), tun and dns exactly once, routing-mark 720 and allow-lan
# false (once each), bind-address once, external-controller exactly when CONTROLLER is set. A later change to the
# reduction that let something through fails closed here instead of reaching mihomo.
# mihomo_written_ok FILE: the guard behind the rebuild, on the file mihomo gets: no line break but LF (yaml.v3's
# line is the guard's line), every column-0 line a "KEY:" line whose key is one of the kept list, ours or an anchor
# holder of ours (mu300-anchor-N, see flush_dropped) - so no external-*, secret, tls, port or listener in any
# spelling - tun and dns exactly once, routing-mark 720 and allow-lan false (once each), bind-address once. A later
# change to the reduction that let something through fails closed here instead of reaching mihomo.
mihomo_written_ok() {
LC_ALL=C awk -v keep="$MIHOMO_KEYS" -v ours="$MIHOMO_OURS" -v ctl="$1" -v mark="$((MARK))" '
LC_ALL=C awk -v keep="$MIHOMO_KEYS" -v ours="$MIHOMO_OURS" -v mark="$((MARK))" '
BEGIN { n = split(keep " " ours, a, " "); for (i = 1; i <= n; i++) ok[a[i]] = 1 }
# the line model is that of yaml.v3: a CR, NEL, LS or PS anywhere is a line end to mihomo, so a line holding one
# fails the file (the reduction writes none: a CRLF end is stripped, a break inside a line refused)
@@ -316,30 +330,24 @@ mihomo_written_ok() {
if (k == "bind-address" && $0 != "bind-address: \047127.0.0.1\047") bad = 1
if (bad) exit }
END { if (bad) exit 1
if (c["tun"] != 1 || c["dns"] != 1 || c["routing-mark"] != 1 || c["allow-lan"] != 1 || c["bind-address"] != 1) exit 1
if (c["external-controller"] + 0 != (ctl != "" ? 1 : 0)) exit 1 }' "$2"
if (c["tun"] != 1 || c["dns"] != 1 || c["routing-mark"] != 1 || c["allow-lan"] != 1 || c["bind-address"] != 1) exit 1 }' "$1"
}
# mihomo_rebuild SRC OUT: SRC reduced (mihomo_read) with ours appended, into OUT (0600), or a refusal on stderr and
# no OUT. The stack is the profile's MIHOMO_STACK (gvisor unless it says system or mixed), the controller the
# MIHOMO_CONTROLLER setting - checked once more here, as are the two resolvers: where the store is not used they come
# from vpn.conf, which nothing validated.
# no OUT. The stack is the profile's MIHOMO_STACK (gvisor unless it says system or mixed); the two resolvers are
# checked once more here: where the store is not used they come from vpn.conf, which nothing validated.
mihomo_rebuild() {
_src=$1; _out=$2
rm -f "$_out"
mihomo_read check "$_src" >&2 || return 1
_stack=; kv_var _stack "$PDIR/meta" MIHOMO_STACK
case $_stack in gvisor|system|mixed) ;; *) _stack=gvisor ;; esac
_ctl=${MIHOMO_CONTROLLER:-}
if [ -n "$_ctl" ] && ! setting_valid MIHOMO_CONTROLLER "$_ctl"; then
echo "MIHOMO_CONTROLLER is not a loopback address (127.0.0.1:PORT or [::1]:PORT): not written" >&2; return 1
fi
{ ip4_ok "$REMOTE_DNS" || ip6_ok "$REMOTE_DNS"; } && { ip4_ok "$BOOTSTRAP_DNS" || ip6_ok "$BOOTSTRAP_DNS"; } ||
{ echo "REMOTE_DNS and BOOTSTRAP_DNS must be IP addresses" >&2; return 1; }
if ! ( umask 077; { mihomo_read gen "$_src" && mihomo_ours "$_stack" "$_ctl"; } > "$_out.r" ); then
if ! ( umask 077; { mihomo_read gen "$_src" && mihomo_ours "$_stack"; } > "$_out.r" ); then
rm -f "$_out.r"; echo "cannot write $_out" >&2; return 1
fi
if ! mihomo_written_ok "$_ctl" "$_out.r"; then
if ! mihomo_written_ok "$_out.r"; then
rm -f "$_out.r"; echo "the rebuilt mihomo config is not what this driver writes: refused" >&2; return 1
fi
mv "$_out.r" "$_out" && chmod 600 "$_out" && return 0
+1 -1
View File
@@ -16,7 +16,7 @@ macOS and Windows (`.github/workflows/tests.yml`).
| `test_device_scripts.py` | `mu300-device`, `mu300-lan-ip`, `mu300-led` (both devices, 4G/5G, the timeout, the siren, the 5.4 LDO switches), `thermal-guard` (the heat alarm), `mu300-nfc` (a fake NFC tag: ZTE's own Wi-Fi record byte for byte, URLs, text, what `sync` leaves alone), `mu300-ttl` (stub `nft`), `mu300-wifi-band`, `mu300-buttons`, `mu300-usb` (a fake charger: never 5 V against a supply), `mu300-next-boot` and `early-recorder` on slot a and slot b (`NextBoot`, `EarlyRecorder`) |
| `test_installer.py` | which adb device the installers take: they ask whenever it is not the only one and an F50/U30 Air; the storage choice (`Storage`), the settings the installer hands to the device (`InstallEnv`), the hotspot import on a card (`ImportHotspot`), erasing the card (`SdErase`) and the free region (`Region`) |
| `test_vpn.py` | `mu300-vpn`: VLESS URI parsing, JSON, which networks stay out of the tunnel, the sing-box config, where the engines are found and how a VPN that is on gets them back, Tailscale through the tunnel (`Tailscale`: rules 5199/5200 with both engines, never doubled, gone with the routes, `TAILSCALE=0`, nothing past the kill switch) |
| `test_vpn_drivers.py` | `mu300-vpn`'s profiles and engine drivers (every shell): the driver contract per type with stub engines recording their arguments (`xray`, `hev-socks5-tunnel`, `sing-box`, `mihomo`, `wg`, `openvpn`, `ip`, `nft`), the URI parsers (vless, vmess, trojan, ss, a wg `.conf`), raw Xray/sing-box JSON and mihomo YAML rebuilt from the allowlist (marks, our inbounds, the TUN, the controller; listeners, key paths and unknown keys refused), an `.ovpn` tokenized and held to its allowlist, migration of a legacy `vpn.conf` (first, idempotent, an edited file, not writable), profile CRUD and ID validation, `use` keeping the kill switch, settings validation, `engines`, reserved types, nothing secret in the output of `list`/`show`/`status`/`run` |
| `test_vpn_drivers.py` | `mu300-vpn`'s profiles and engine drivers (every shell): the driver contract per type with stub engines recording their arguments (`xray`, `hev-socks5-tunnel`, `sing-box`, `mihomo`, `wg`, `openvpn`, `ip`, `nft`), the URI parsers (vless, vmess, trojan, ss, a wg `.conf`), raw Xray/sing-box JSON and mihomo YAML rebuilt from the allowlist (marks, our inbounds, the TUN; listeners, controllers, key paths and unknown keys refused), an `.ovpn` tokenized and held to its allowlist, migration of a legacy `vpn.conf` (first, idempotent, an edited file, not writable), profile CRUD and ID validation, `use` keeping the kill switch, settings validation, `engines`, reserved types, nothing secret in the output of `list`/`show`/`status`/`run` |
| `test_wifi_client.py` | `wifi-client`: the scan (iw and wpa_cli output: WPA2, WPA2/3, WPA3, UTF-8 names, no neighbour-report BSSID or hidden network), the password from stdin or a file and never on a command line, a WPA3-only network refused at once without SAE and joined with it, the uplink shared (the exact nft rules closed, shared and removed, through a join, a lost and a returning link, a failed or interrupted join and a supplicant that will not stop; nothing past the VPN's kill switch; fw4's wan zone on OpenWrt), hostile names shown as text everywhere, one validator for every way a name or passphrase comes in (the toolkit too), `disconnect` keeping the hotspot after a reboot |
| `test_extra.py` | extras: `mu300-update`'s install, adopt and update of extras (a VPN in use keeps its engines), `mu300-extra` install/remove/link against a fake release server; the lang extra (`LangExtra`: catalogs linked into LuCI and registered in `luci.languages`, enable/disable, Ubuntu refused, hostile archives refused) |
| `test_update.py` | `mu300-update`: release files per system and kernel, boot image byte helpers, whether a kernel bundle may go onto this device, the Linux slot it works on, and the boot image it builds from a device's own stock image (`FromStock`) |
+174 -42
View File
@@ -180,14 +180,14 @@ class Store(ShellTest):
good = [('KILL_SWITCH', '0'), ('KILL_SWITCH', '1'), ('TAILSCALE', '0'), ('IPV6', '1'),
('REMOTE_DNS', '1.1.1.1'), ('REMOTE_DNS', '2606:4700::1111'), ('BOOTSTRAP_DNS', '8.8.4.4'),
('LAN_CIDRS', '10.0.0.0/8,fd00::/8'), ('LAN_CIDRS', ''), ('LAN_CIDRS', '192.168.1.0/24'),
('MIHOMO_CONTROLLER', '127.0.0.1:9090'), ('MIHOMO_CONTROLLER', '[::1]:9090'),
('MIHOMO_CONTROLLER', ''), ('XRAY', '/x/xray'), ('HEV', '/x/hev'), ('SING_BOX', '/x/sb'),
('XRAY', '/x/xray'), ('HEV', '/x/hev'), ('SING_BOX', '/x/sb'),
('MIHOMO', '/x/m'), ('OPENVPN', '/usr/sbin/openvpn'), ('XRAY', '')]
# (MIHOMO_CONTROLLER is no setting: mihomo gets no control API of any kind, see Mihomo.test_nothing_listens)
bad = [('KILL_SWITCH', 'yes'), ('KILL_SWITCH', ''), ('IPV6', '2'), ('REMOTE_DNS', 'a;b'),
('REMOTE_DNS', '1.1.1.256'), ('REMOTE_DNS', '1.1.1'), ('REMOTE_DNS', ''), ('LAN_CIDRS', '10.0.0.0'),
('LAN_CIDRS', '10.0.0.0/33'), ('LAN_CIDRS', '10.0.0.0/8,'), ('LAN_CIDRS', 'fd00::/129'),
('MIHOMO_CONTROLLER', '0.0.0.0:9090'), ('MIHOMO_CONTROLLER', '127.0.0.1:99999'),
('MIHOMO_CONTROLLER', '127.0.0.1'), ('XRAY', 'relative/xray'), ('UNKNOWN', 'x')]
('MIHOMO_CONTROLLER', '127.0.0.1:9090'), ('MIHOMO_CONTROLLER', ''),
('XRAY', 'relative/xray'), ('UNKNOWN', 'x')]
for shell in self.each_shell():
self.reset()
code = '; '.join(f"setting_valid {k} '{v}' && echo 1 || echo 0" for k, v in good + bad)
@@ -792,7 +792,8 @@ class Cli(ShellTest):
got = dict(l.split('=', 1) for l in r.stdout.splitlines())
self.assertEqual((got['REMOTE_DNS'], got['KILL_SWITCH'], got['LAN_CIDRS'], got['XRAY']),
('9.9.9.9', '1', '', ''))
self.assertEqual(len(got), 12)
self.assertEqual(len(got), 11)
self.assertNotIn('MIHOMO_CONTROLLER', got)
# empty: back to the default
r = self.vpn(shell, 'settings', 'set', 'REMOTE_DNS', '')
self.assertEqual(r.returncode, 0, r.stderr)
@@ -2698,12 +2699,16 @@ rules:
- MATCH,a
'''
MH_OURS = ('routing-mark', 'allow-lan', 'bind-address', 'tun', 'dns')
# the smallest file the driver takes: one proxy and one rule
MH_BASE = ('proxies:\n - {name: a, type: ss, server: ss.example, port: 8388, cipher: aes-256-gcm, password: hunter2}\n'
'rules:\n - MATCH,a\n')
class Mihomo(ShellTest):
"""The mihomo driver: the YAML is reduced to the top-level keys the spec allows (awk, no YAML parser), ours
(routing-mark, allow-lan, bind-address, tun, dns, the controller) are appended, interface-name and routing-mark
go from every proxy and group, mihomo checks and runs only the file we wrote, and no secret is printed."""
(routing-mark, allow-lan, bind-address, tun, dns) are appended, nothing of the file listens (no port, no
controller or API of any kind), interface-name and routing-mark go from every proxy and group, mihomo checks and
runs only the file we wrote, and no secret is printed."""
def setUp(self):
super().setUp()
@@ -2881,7 +2886,7 @@ class Mihomo(ShellTest):
self.assertFalse((self.tmp / 'mihomo.args').exists())
# no server address to keep off the tunnel: mihomo marks its own sockets
self.assertEqual((self.run_dir / 'server-ip').read_text(), '')
# the settings go in: the resolvers, and the controller only when set
# the settings go in: the resolvers
r = self.cli(shell, 'settings', 'set', 'REMOTE_DNS', '9.9.9.9')
self.assertEqual(r.returncode, 0, r.stderr)
r = self.cli(shell, 'settings', 'set', 'BOOTSTRAP_DNS', '8.8.8.8')
@@ -2891,17 +2896,12 @@ class Mihomo(ShellTest):
self.assertIn(" default-nameserver: ['8.8.8.8']", gen.splitlines())
self.assertIn(" proxy-server-nameserver: ['8.8.8.8']", gen.splitlines())
self.assertNotIn('external-controller', gen)
r = self.cli(shell, 'settings', 'set', 'MIHOMO_CONTROLLER', '127.0.0.1:9090')
self.assertEqual(r.returncode, 0, r.stderr)
gen = self.gen(shell)
self.assertIn("external-controller: '127.0.0.1:9090'", gen.splitlines())
self.assertEqual(self.top_keys(gen), ['proxies', 'rules'] + list(MH_OURS) + ['external-controller'])
self.assertEqual(gen.count('external-controller'), 1)
# a controller that is not loopback (a legacy vpn.conf could say anything) is not written
r = self.run_lib(shell, 'drv_gen', 'MIHOMO_CONTROLLER=0.0.0.0:9090; ')
self.assertNotEqual(r.returncode, 0)
self.assertNotIn('0.0.0.0', r.stdout + r.stderr)
self.assertFalse((self.run_dir / 'mihomo.yaml').exists())
# a controller is written for nobody: not for a setting of an older store, not for a legacy vpn.conf
(self.store / 'settings').write_text("MIHOMO_CONTROLLER='127.0.0.1:9090'\n")
gen = self.gen(shell, 'MIHOMO_CONTROLLER=127.0.0.1:9090; ')
self.assertNotIn('external-controller', gen)
self.assertNotIn('9090', gen)
self.assertEqual(self.top_keys(gen), ['proxies', 'rules'] + list(MH_OURS))
# a mihomo that rejects the file fails the gen, without repeating what mihomo said
self.mihomo_stub('echo "yaml: cannot unmarshal !!str hunter2" >&2; exit 1')
r = self.run_lib(shell, 'drv_gen')
@@ -3158,7 +3158,12 @@ rules:
('a quoted top-level key', base + '"tun":\n enable: true\n', 'top-level line'),
('a flow collection at column 0', 'proxies: [\n{name: a, type: ss, server: s, port: 1, password: hunter2}\n]\n', 'top-level line'),
('a merge key', base + '<<: {tun: {enable: true}}\n', 'top-level line'),
('a merge key of an anchor', base + 'x: &x {tun: {enable: true}}\n<<: *x\n', 'top-level line'),
('an alias at column 0', base + 'x: &x {tun: {enable: true}}\n*x\n', 'top-level line'),
('an anchor at column 0', base + '&x tun:\n enable: true\n', 'top-level line'),
('a merge tag', base + 'x: &x {udp: true}\nproxy-groups:\n - !!merge <<: *x\n', 'tag'),
('a name reserved for the driver', base + 'mu300-anchor-1: {}\n', 'reserved'),
('a reserved name in another case', base + 'MU300-Anchor-1: &p {}\n', 'reserved'),
('a kept key twice', base + 'rules:\n - MATCH,a\n', 'twice'),
('no proxies', 'rules:\n - MATCH,DIRECT\n', 'no proxies'),
('empty', '', 'no proxies'),
@@ -3288,34 +3293,38 @@ rules:
for shell in self.each_shell():
self.setup_profile(shell)
f = self.tmp / 'w.yaml'
for name, text, ctl, ok in (
('as written', good, '', True),
('with the controller', good + "external-controller: '127.0.0.1:9090'\n", '127.0.0.1:9090', True),
('a controller that was not asked for', good + "external-controller: '127.0.0.1:9090'\n", '', False),
('no controller although asked', good, '127.0.0.1:9090', False),
('two tun', good + 'tun:\n enable: true\n', '', False),
('two dns', good + 'dns:\n enable: true\n', '', False),
('no tun', good.replace('tun:\n enable: true\n', ''), '', False),
('a stray secret', good + 'secret: x\n', '', False),
('a stray listener', good + 'listeners:\n - x\n', '', False),
('an anchor holder of ours', good + 'mu300-anchor-12: &p {type: http}\n', '', True),
('an anchor holder spelled otherwise', good + 'mu300-anchor-x: &p {type: http}\n', '', False),
('allow-lan true', good.replace('allow-lan: false', 'allow-lan: true'), '', False),
('another mark', good.replace('routing-mark: 720', 'routing-mark: 721'), '', False),
('no mark', good.replace('routing-mark: 720\n', ''), '', False),
('a quoted key', good + '"x": 1\n', '', False),
('a list', good + '- x\n', '', False),
for name, text, ok in (
('as written', good, True),
('a controller', good + "external-controller: '127.0.0.1:9090'\n", False),
('a unix controller', good + "external-controller-unix: /run/x.sock\n", False),
('a tls controller', good + "external-controller-tls: '127.0.0.1:9443'\n", False),
('a pipe controller', good + "external-controller-pipe: x\n", False),
('an external ui', good + "external-ui: /x\n", False),
('a key of ours in another case', good + "External-Controller: '127.0.0.1:9090'\n", False),
('two tun', good + 'tun:\n enable: true\n', False),
('two dns', good + 'dns:\n enable: true\n', False),
('no tun', good.replace('tun:\n enable: true\n', ''), False),
('a stray secret', good + 'secret: x\n', False),
('a stray listener', good + 'listeners:\n - x\n', False),
('a stray port', good + 'mixed-port: 7890\n', False),
('an anchor holder of ours', good + 'mu300-anchor-12: &p {type: http}\n', True),
('an anchor holder spelled otherwise', good + 'mu300-anchor-x: &p {type: http}\n', False),
('allow-lan true', good.replace('allow-lan: false', 'allow-lan: true'), False),
('another mark', good.replace('routing-mark: 720', 'routing-mark: 721'), False),
('no mark', good.replace('routing-mark: 720\n', ''), False),
('a quoted key', good + '"x": 1\n', False),
('a list', good + '- x\n', False),
# the guard's line model is yaml.v3's: a line break hidden in a line is several lines to mihomo
('a lone CR in a line', good.encode().replace(b'type: ss}\n', b'type: ss}\rlisteners: []\n'), '', False),
('a NEL in a line', good.encode().replace(b'type: ss}\n', b'type: ss}\xc2\x85listeners: []\n'), '', False),
('an LS in a line', good.encode().replace(b'type: ss}\n', b'type: ss}\xe2\x80\xa8listeners: []\n'), '', False),
('a PS in a line', good.encode().replace(b'type: ss}\n', b'type: ss}\xe2\x80\xa9listeners: []\n'), '', False),
('a CR at the end of a line', good.encode().replace(b'type: ss}\n', b'type: ss}\r\n'), '', False)):
('a lone CR in a line', good.encode().replace(b'type: ss}\n', b'type: ss}\rlisteners: []\n'), False),
('a NEL in a line', good.encode().replace(b'type: ss}\n', b'type: ss}\xc2\x85listeners: []\n'), False),
('an LS in a line', good.encode().replace(b'type: ss}\n', b'type: ss}\xe2\x80\xa8listeners: []\n'), False),
('a PS in a line', good.encode().replace(b'type: ss}\n', b'type: ss}\xe2\x80\xa9listeners: []\n'), False),
('a CR at the end of a line', good.encode().replace(b'type: ss}\n', b'type: ss}\r\n'), False)):
if isinstance(text, bytes):
f.write_bytes(text)
else:
f.write_text(text)
r = self.run_lib(shell, f'mihomo_written_ok "{ctl}" "{f}" && echo OK')
r = self.run_lib(shell, f'mihomo_written_ok "{f}" && echo OK')
self.assertEqual('OK' in r.stdout, ok, (name, r.stderr))
def test_engine_and_extra(self):
@@ -3390,6 +3399,129 @@ rules:
self.assertEqual(r.stdout.splitlines(), ['mode: global', 'proxies: 1'])
self.no_secrets(r)
# ---- the gates the JSON drivers have, one for one (RawJson) ----
def test_nothing_listens(self):
# RawJson.test_listener_guard's sibling: every port, listener, control API and UI a Clash file can carry is
# gone from the written file, in any spelling; the driver writes no controller for anybody (there is no
# MIHOMO_CONTROLLER setting, and a value of an older store or a legacy vpn.conf is not read), and the guard
# behind the rebuild refuses a file that has one
text = ('mixed-port: 7890\nport: 7891\nsocks-port: 7892\nredir-port: 7893\ntproxy-port: 7894\n'
'allow-lan: true\nbind-address: "*"\nlan-allowed-ips: [0.0.0.0/0]\nlan-disallowed-ips: []\n'
'authentication: ["u:ctl-secret"]\nskip-auth-prefixes: [127.0.0.1/8]\n'
"external-controller: '127.0.0.1:9090'\nexternal-controller-tls: 0.0.0.0:9443\n"
'external-controller-unix: /run/mihomo.sock\nexternal-controller-pipe: x\n'
'external-controller-cors: {allow-origins: ["*"]}\nexternal-ui: /tmp/ui\nexternal-ui-name: x\n'
'external-ui-url: https://x.example/ui.zip\nexternal-doh-server: /dns-query\nsecret: ctl-secret\n'
'External-Controller-Unix: /run/x.sock\nEXTERNAL-UI: /tmp/ui\n'
'tls: {certificate: /etc/ssl/x.pem, private-key: /etc/ssl/x.key}\n'
'listeners:\n - {name: l, type: socks, port: 9999, listen: 0.0.0.0}\n'
'tunnels: [tcp/udp,127.0.0.1:6553,8.8.8.8:53,proxy]\n'
'ss-config: ss://x@0.0.0.0:1\nvmess-config: x\ntuic-server: {enable: true, listen: 0.0.0.0:443}\n'
'dns:\n enable: true\n listen: 0.0.0.0:53\n'
'tun:\n enable: true\n auto-route: true\n auto-detect-interface: true\n auto-redirect: true\n'
+ MH_BASE)
for shell in self.each_shell():
self.setup_profile(shell, text)
(self.store / 'settings').write_text("MIHOMO_CONTROLLER='127.0.0.1:9090'\n")
gen = self.gen(shell, 'MIHOMO_CONTROLLER=127.0.0.1:9090; ')
self.assertEqual(self.top_keys(gen), ['proxies', 'rules'] + list(MH_OURS))
for gone in ('\nport:', '-port:', 'listen', 'external', 'External', 'EXTERNAL', 'secret', 'ctl-secret', 'authentication',
'skip-auth', 'lan-allowed', 'lan-disallowed', '/etc/ssl', 'certificate', 'private-key',
'tunnels', 'ss-config', 'vmess-config', 'tuic-server', '0.0.0.0', '9090', '9443', '.sock',
'auto-route: true', 'auto-detect-interface: true', 'auto-redirect: true', 'dns-query', '/tmp/ui'):
self.assertNotIn(gone, gen, gone)
self.assertIn(' auto-route: false', self.block(gen, 'tun'))
self.assertIn(' auto-detect-interface: false', self.block(gen, 'tun'))
self.assertNotIn('listen', '\n'.join(self.block(gen, 'dns')))
r = self.cli(shell, 'check', 'sub')
self.assertEqual(r.returncode, 0, r.stderr)
self.no_secrets(r)
self.assertNotIn('ctl-secret', r.stdout + r.stderr)
# nothing can ask for a controller
r = self.cli(shell, 'settings', 'set', 'MIHOMO_CONTROLLER', '127.0.0.1:9090')
self.assertNotEqual(r.returncode, 0)
r = self.cli(shell, 'settings', 'get')
self.assertNotIn('MIHOMO_CONTROLLER', r.stdout + r.stderr)
r = self.run_lib(shell, 'mihomo_ours gvisor; echo "ours=[$MIHOMO_OURS]"', 'MIHOMO_CONTROLLER=127.0.0.1:9090; ')
self.assertEqual(r.returncode, 0, r.stderr)
self.assertNotIn('external', r.stdout)
self.assertNotIn('9090', r.stdout)
self.assertIn('ours=[routing-mark allow-lan bind-address tun dns]', r.stdout)
def test_keys_spelled_differently_are_refused(self):
# RawJson.test_keys_are_the_shapes_named_exactly's sibling: a top-level key that is one of the kept names
# or ours in another spelling (another case, _ for -) is refused, naming the name it collides with and
# nothing of the file. (mihomo's reader is case-sensitive and would not read it; the file is refused rather
# than reduced to something its author did not mean, as the JSON drivers do.)
for shell in self.each_shell():
for extra, name in (('Proxies: []\n', 'proxies'), ('proxy_groups: []\n', 'proxy-groups'),
('RULES: []\n', 'rules'), ('Rule_Providers: {}\n', 'rule-providers'),
('Tun:\n enable: true\n', 'tun'), ('DNS: {listen: 0.0.0.0:53}\n', 'dns'),
('Routing_Mark: 1\n', 'routing-mark'), ('Allow-LAN: true\n', 'allow-lan'),
('Bind_Address: "*"\n', 'bind-address'), ('Mode: global\n', 'mode')):
with self.subTest(what=extra):
r = self.refused(shell, MH_BASE + extra, 'spelled differently from ' + name, extra)
self.assertNotIn(extra.split(':')[0], r.stderr)
self.assertNotIn('0.0.0.0', r.stderr)
# the exact spelling next to the other one is refused the same way, not taken as "twice"
r = self.refused(shell, MH_BASE + 'Rules: []\n', 'spelled differently from rules')
self.assertNotIn('twice', r.stderr)
def test_the_size_cap_comes_before_any_read(self):
# RawJson.test_the_size_cap_comes_before_any_full_read's sibling: the cap is the first thing the reader
# and the import run, before the control-character count and before awk sees a line
big = self.tmp / 'big.yaml'
big.write_text(MH_BASE + '# ' + 'x' * (1 << 20) + '\n')
for shell in self.each_shell():
self.setup_profile(shell)
r = self.run_lib(shell, 'awk() { echo AWK-RAN; }; '
f'mihomo_read check "{big}" || echo no; mihomo_read gen "{big}" || echo no; '
f'drv_import "{big}" || echo no')
self.assertEqual(r.stdout.splitlines(), ['the mihomo config is larger than 1 MiB', 'no', 'no', 'no'], r.stderr)
self.assertIn('1 MiB', r.stderr)
self.assertNotIn('AWK-RAN', r.stdout + r.stderr)
self.assertEqual((self.store / 'profiles/sub/config.yaml').read_text(), MH_CONF)
text = (LIB / 'mihomo.sh').read_text()
for fn in ('mihomo_read() {', 'drv_import() {'):
body = text[text.index(fn):text.index('\n}\n', text.index(fn))]
for reader in (' awk ', ' tr ', ' cat ', ' is_json ', ' mihomo_read '):
if reader in body:
self.assertLess(body.index('json_size_ok'), body.index(reader), (fn, reader))
def test_an_alias_cannot_bring_a_key_in(self):
# the JSON drivers strip the dial fields at every depth; here what an alias or a merge key can bring into
# a kept block comes from an anchored block that went through the same removals and the same text check,
# and the top-level keys stay the lines the reader saw (a merge key, an alias or an anchor at column 0 is
# no KEY: line, see test_refusals_name_the_rule_and_nothing_of_the_file)
text = ('x: &x\n Interface-Name: eth0\n routing-mark: 9\n udp: true\n'
't: &t {enable: true, auto-route: true, auto-detect-interface: true, interface-name: eth0}\n'
'd: &d {enable: true, listen: 0.0.0.0:53, ROUTING-MARK: 9}\n'
+ MH_BASE + 'proxy-groups:\n - name: g\n type: select\n <<: *x\n proxies: [a]\n'
'profile: *t\nsniffer: *d\n')
for shell in self.each_shell():
self.setup_profile(shell, text)
gen = self.gen(shell)
lines = gen.splitlines()
self.assertEqual(self.top_keys(gen), ['mu300-anchor-1', 'mu300-anchor-2', 'mu300-anchor-3',
'proxies', 'rules', 'proxy-groups', 'profile', 'sniffer'] + list(MH_OURS))
self.assertEqual(self.block(gen, 'mu300-anchor-1'), ['mu300-anchor-1: &x', ' udp: true'])
self.assertIn('mu300-anchor-2: &t {enable: true, auto-route: true, auto-detect-interface: true}', lines)
self.assertIn('mu300-anchor-3: &d {enable: true, listen: 0.0.0.0:53}', lines)
self.assertIn(' <<: *x', lines)
self.assertIn('profile: *t', lines)
for gone in ('eth0', 'routing-mark: 9', 'ROUTING-MARK', 'Interface-Name', 'interface-name'):
self.assertNotIn(gone, gen, gone)
self.assertEqual(lines.count('tun:'), 1)
self.assertEqual(lines.count('dns:'), 1)
self.assertIn(' auto-route: false', self.block(gen, 'tun'))
self.assertEqual(gen.count('routing-mark'), 1)
self.assertIn('routing-mark: 720', lines)
# the written file passes its own guard, and the check says which blocks were kept for their anchors
r = self.cli(shell, 'check', 'sub')
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn(' x t d\n', r.stderr)
self.no_secrets(r)
class EnginesCmd(ShellTest):
"""mu300-vpn engines: one TSV line per engine, present with its path or missing with how to get it, with the