From 2d444befaf4bb355b4ff351990ffd5e79fbdfa84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Abdurrahman=20Kaan=20Dike=C3=A7?= Date: Tue, 22 Sep 2026 23:16:46 +0300 Subject: [PATCH] vpn: Xray engine on a kernel TUN, with a self-managing certificate pin mu300-vpn gains ENGINE=xray, now the default: Xray-core speaks VLESS and hev-socks5-tunnel owns a plain kernel TUN (xtun), handing every flow to Xray's SOCKS port on loopback. It reads the same VLESS_URI through the same parser; ENGINE=sing-box keeps the old engine, and an image without the xray binaries falls back to it by itself. The script does the routing neither program does, with sing-box's rule prefs and table so routing_cleanup and the kill switch cover both: Xray's own sockets carry the 0x2d0 mark to main, the LAN and the server's address go to main, everything else to xtun, and the device's own DNS is DNAT'd to REMOTE_DNS. The server name is resolved before any of that exists and handed to Xray as an address. Xray, hev and the rules are torn down together on every exit path. Xray 26 removed allowInsecure. For a link that asks for it the leaf certificate is fetched with openssl once, pinned as TLS_PIN_SHA256 in vpn.conf, and re-fetched only when Xray reports a pin mismatch (a renewal), after which the service restarts. That report is info-level, so Xray runs at info and only warnings reach the system log. Release: tools/fetch-xray.sh pins both binaries by sha256; make-release, assemble.sh and the OpenWrt build carry them, and both images get openssl. The example config ships KILL_SWITCH=0 until the kill switch is re-tested with Xray. Measured on OpenWrt on the device: exit IP is the server's, apk works through the tunnel, a Wi-Fi client is forwarded into xtun, and the three pin paths (none, present, mismatched) behave as described. Ubuntu is not yet run on the device. FINDINGS 26e also records that busybox nc here has no -w - the reason an earlier test read every destination as closed. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_017Z17MBkdHmZPvNPNSLxcHk --- .gitignore | 2 + README.md | 7 +- docs/BUILD.md | 5 +- docs/FINDINGS.md | 30 +++ openwrt/build-rootfs.sh | 10 +- openwrt/overlay/etc/init.d/mu300-vpn | 2 +- rootfs/Dockerfile | 2 +- rootfs/assemble.sh | 6 +- rootfs/overlay/etc/mu300/vpn.conf.example | 19 +- .../etc/systemd/system/mu300-vpn.service | 7 +- rootfs/overlay/opt/mu300/bin/mu300-toolkit | 2 +- rootfs/overlay/opt/mu300/bin/mu300-vpn | 249 +++++++++++++++++- tools/fetch-xray.sh | 24 ++ tools/make-release.sh | 6 +- 14 files changed, 334 insertions(+), 37 deletions(-) create mode 100755 tools/fetch-xray.sh diff --git a/.gitignore b/.gitignore index 130aaf3f..2aa96134 100644 --- a/.gitignore +++ b/.gitignore @@ -22,6 +22,8 @@ openwrt/*.tar.gz upstream/stub/*.elf upstream/stub/*.bin sing-box +/xray +/hev-socks5-tunnel release/ backup/ !stock/*.img diff --git a/README.md b/README.md index 13816f08..6b1b6079 100644 --- a/README.md +++ b/README.md @@ -151,8 +151,11 @@ button that reboots the device into Linux, and `su -c mu300-linux` does the same ### VPN -The device can send its own traffic **and** everything from connected clients through a VLESS server (sing-box), -with a kill switch so nothing leaks over mobile data if the tunnel drops. +The device can send its own traffic **and** everything from connected clients through a VLESS server. The default +engine is [Xray](https://github.com/XTLS/Xray-core) behind [hev-socks5-tunnel](https://github.com/heiher/hev-socks5-tunnel) +on a kernel TUN; `ENGINE=sing-box` in the config switches back to sing-box. Links that ask for `allowInsecure` +work: Xray 26 dropped that option, so the server's certificate is fetched once, pinned, and re-fetched by itself +when the server renews it. The kill switch (`KILL_SWITCH=1`) is off by default until it is re-tested with Xray. ```sh sudo cp /etc/mu300/vpn.conf.example /etc/mu300/vpn.conf diff --git a/docs/BUILD.md b/docs/BUILD.md index aeffe0f8..52263dd4 100644 --- a/docs/BUILD.md +++ b/docs/BUILD.md @@ -80,10 +80,11 @@ python3 boot/build-boot-image.py --stock-boot dumps/boot_a.img --misc-head dumps 3. Assemble and deploy: ```sh cid=$(docker create mu300-ubuntu:24.04); docker export $cid > rootfs/base.tar; docker rm $cid -tools/fetch-sing-box.sh # optional: VLESS client for mu300-vpn (pinned release, sha256-checked) +tools/fetch-xray.sh # optional: xray + hev-socks5-tunnel, mu300-vpn's default engine (pinned, sha256-checked) +tools/fetch-sing-box.sh # optional: the sing-box engine for mu300-vpn (pinned release, sha256-checked) docker run --rm -v "$PWD/rootfs":/w -v "$PWD/out/modules":/kmods:ro -v "$PWD/out":/kout:ro \ -v "$PWD/firmware":/firmware:ro -v "$PWD/android-subset":/android-subset:ro -v "$PWD/tools/logdw/logdw":/logdw:ro \ - -v "$PWD/tools/bt-init/mu300-bt-init":/bt-init:ro -v "$PWD/sing-box":/sing-box:ro mu300-ubuntu:24.04 bash /w/assemble.sh + -v "$PWD/tools/bt-init/mu300-bt-init":/bt-init:ro -v "$PWD/sing-box":/sing-box:ro -v "$PWD/xray":/xray:ro -v "$PWD/hev-socks5-tunnel":/hev-socks5-tunnel:ro mu300-ubuntu:24.04 bash /w/assemble.sh ``` Push `mu300-ubuntu-24.04-rootfs.tar.gz` to the device and extract it with `tools/android-mount-mu300root.sh`. `firmware/` holds `wcnmodem.bin`, `gnssmodem.bin` and `wifi_board_config*.ini` from the device's `/odm/firmware`, plus diff --git a/docs/FINDINGS.md b/docs/FINDINGS.md index f47c0f2f..dd6c7b44 100644 --- a/docs/FINDINGS.md +++ b/docs/FINDINGS.md @@ -672,6 +672,36 @@ not always first, and the language element never is. Sending picks the encoding from the text - GSM 7-bit while every character fits it, UCS-2 otherwise, which is what makes `ığşçöü ÇĞİÖŞÜ` survive. Verified by sending to the SIM's own number and reading it back intact. +### 26e. The Xray engine, and a connectivity test that could only say no +`mu300-vpn` now defaults to `ENGINE=xray`: Xray-core does VLESS, hev-socks5-tunnel owns a plain kernel TUN (`xtun`) +and hands each flow to Xray's SOCKS port on loopback. Neither installs routes, so the script does, with sing-box's +rule prefs and table (9000-9010, table 2022): Xray's own sockets carry mark `0x2d0` and go to `main`, as do the LAN +and the server's address; everything else goes to `xtun`. The device's own DNS - dnsmasq's upstream, which is the +carrier resolver and does not answer from the far end of a tunnel - is DNAT'd to `REMOTE_DNS`. Every exit path +removes all of it, because routing left behind by a dead engine is what made sing-box's crashes look like a dead +modem. The same mark means the kill switch should apply unchanged, but that has not been measured with Xray yet, +so the example config ships with `KILL_SWITCH=0`. + +Measured on OpenWrt: the device's exit IP is the server's, `apk add` works through the tunnel, and a Wi-Fi client's +flows are forwarded into `xtun`. The Ubuntu side uses the same script but has not been run on the device. + +**allowInsecure is gone in Xray 26.** Its replacement, `pinnedPeerCertSha256`, accepts exactly one leaf +certificate. For a link that asks for allowInsecure the script manages the pin: fetched once with openssl when +there is none and stored as `TLS_PIN_SHA256` in `vpn.conf`, left alone on later starts, and fetched again only when +Xray reports `peer cert is unrecognized (against pinnedPeerCertSha256)` - a renewal - after which the service +restarts itself. Xray reports that failure at **info** level, which a `warning` log level hides completely; the +script runs Xray at info with the access log off and passes only warnings and worse to the system log. `xray tls +ping` is no substitute for openssl here: it tries without SNI first, and a server that ignores that attempt keeps it +waiting past any sensible timeout. (The server this was tested against presents a Let's Encrypt certificate that +expired in December 2025 - which is why its link asks for allowInsecure. The pin skips the expiry check.) + +**busybox `nc` on this OpenWrt has no `-w`.** `nc -w 6 HOST PORT` prints the usage text and exits 1, so a +reachability test built on its exit status reports every destination as closed. That produced a confident and +wrong "this SIM reaches nothing but the carrier's DNS" - the same bearer carried the VPN minutes later. Test TCP +with `wget -T` or `curl -m`, check the tool's own exit status rather than a pipe's, and run the test once against +something that must succeed before believing a failure. To test the bearer while a tunnel runs, route a single +address around it: `ip rule add pref 8999 to lookup main`, test, delete the rule. + ## Default boot ### 17. Linux as default without losing the Android fallback diff --git a/openwrt/build-rootfs.sh b/openwrt/build-rootfs.sh index e3a534eb..93e6f013 100755 --- a/openwrt/build-rootfs.sh +++ b/openwrt/build-rootfs.sh @@ -5,7 +5,7 @@ # Inputs (same as rootfs/assemble.sh, all optional except modules): # out/modules/*.ko out/modules.builtin* firmware/ android-subset/ android-gpu-subset/ # tools/logdw/logdw tools/bt-init/mu300-bt-init tools/gpu/cltest busybox (static, full) -# sing-box (tools/fetch-sing-box.sh, for mu300-vpn) +# xray, hev-socks5-tunnel (tools/fetch-xray.sh) and sing-box (tools/fetch-sing-box.sh), for mu300-vpn # upstream/out/modules/*.ko (optional: out-of-tree WCN modules for the mainline 6.18 kernel) set -eu FLAVOUR=${MU300_FLAVOUR:-openwrt} @@ -46,7 +46,7 @@ ls "$IN/out/modules"/*.ko >/dev/null 2>&1 || { } # The optional ones decide whether the image can use the modem, Wi-Fi, the GPU or the VPN at all. Missing ones # used to be skipped silently, which produces an image that boots and then does nothing useful. -for o in firmware android-subset android-gpu-subset tools/logdw/logdw tools/bt-init/mu300-bt-init tools/gpu/cltest busybox sing-box upstream/out/modules; do +for o in firmware android-subset android-gpu-subset tools/logdw/logdw tools/bt-init/mu300-bt-init tools/gpu/cltest busybox sing-box xray hev-socks5-tunnel upstream/out/modules; do [ -e "$IN/$o" ] && echo " + $o" || echo " - $o (missing: the image is built without it)" done # shellcheck disable=SC2046 @@ -56,11 +56,12 @@ docker run --rm --platform linux/arm64 \ $(opt out/modules.builtin modules.builtin) $(opt out/modules.builtin.modinfo modules.builtin.modinfo) \ $(opt firmware firmware) $(opt android-subset android-subset) $(opt android-gpu-subset android-gpu-subset) \ $(opt tools/logdw/logdw logdw) $(opt tools/bt-init/mu300-bt-init bt-init) $(opt tools/gpu/cltest cltest) \ - $(opt busybox busybox) $(opt sing-box sing-box) $(opt upstream/out/modules mainline-modules) -v "$TOP/openwrt":/out -v "$REGDB":/in/regdb:ro \ + $(opt busybox busybox) $(opt sing-box sing-box) $(opt xray xray) $(opt hev-socks5-tunnel hev-socks5-tunnel) $(opt upstream/out/modules mainline-modules) -v "$TOP/openwrt":/out -v "$REGDB":/in/regdb:ro \ -e KREL=$KREL -e OUT="$(basename "$OUT")" -e MU300_VERSION="${MU300_VERSION:-dev}" mu300-$FLAVOUR-base:$VER /bin/sh -eu -c ' mkdir -p /var/lock /var/run /tmp apk update >/dev/null -apk add wpad-basic-mbedtls wifi-scripts iwinfo wireless-regdb iw bash ip-full coreutils-stty >/dev/null +# openssl-util: mu300-vpn fetches the VPN server certificate with it to pin, for links that ask for allowInsecure +apk add wpad-basic-mbedtls wifi-scripts iwinfo wireless-regdb iw bash ip-full coreutils-stty openssl-util >/dev/null # ujail drops CAP_PERFMON (38), which this 5.4 kernel does not know: jailed services (dnsmasq, ntpd) crash-loop apk del procd-ujail procd-seccomp >/dev/null 2>&1 || true # online firmware upgrades flash whole-disk armsr images: that would overwrite the eMMC, so remove them @@ -99,6 +100,7 @@ fi [ -e /in/logdw ] && { cp /in/logdw $R/opt/mu300/bin/logdw; chmod 755 $R/opt/mu300/bin/logdw; } [ -e /in/bt-init ] && { cp /in/bt-init $R/opt/mu300/bin/mu300-bt-init; chmod 755 $R/opt/mu300/bin/mu300-bt-init; } [ -f /in/sing-box ] && { cp /in/sing-box $R/opt/mu300/bin/sing-box; chmod 755 $R/opt/mu300/bin/sing-box; } +for b in xray hev-socks5-tunnel; do [ -f /in/$b ] && { cp /in/$b $R/opt/mu300/bin/$b; chmod 755 $R/opt/mu300/bin/$b; }; done # full static busybox for the tools OpenWrt busybox leaves out (od, timeout, mountpoint, losetup, rfkill, telnetd) if [ -e /in/busybox ]; then cp /in/busybox $R/opt/mu300/bin/busybox; chmod 755 $R/opt/mu300/bin/busybox diff --git a/openwrt/overlay/etc/init.d/mu300-vpn b/openwrt/overlay/etc/init.d/mu300-vpn index 56056aad..ab09f6af 100755 --- a/openwrt/overlay/etc/init.d/mu300-vpn +++ b/openwrt/overlay/etc/init.d/mu300-vpn @@ -1,5 +1,5 @@ #!/bin/sh /etc/rc.common -# VLESS via sing-box (TUN + kill switch); settings in /etc/mu300/vpn.conf, see /opt/mu300/bin/mu300-vpn +# VLESS via Xray (default) or sing-box, on a TUN; settings in /etc/mu300/vpn.conf, see /opt/mu300/bin/mu300-vpn START=95 USE_PROCD=1 export PATH="$PATH:/opt/mu300/busybox-bin" diff --git a/rootfs/Dockerfile b/rootfs/Dockerfile index c57895e7..dfdae71a 100644 --- a/rootfs/Dockerfile +++ b/rootfs/Dockerfile @@ -10,7 +10,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ iproute2 iputils-ping net-tools nftables dnsmasq-base ethtool \ openssh-server busybox-static \ wpasupplicant hostapd iw wireless-regdb rfkill bluez \ - ca-certificates curl wget nano vim-tiny less htop sudo bash-completion \ + ca-certificates openssl curl wget nano vim-tiny less htop sudo bash-completion \ libcap2-bin locales tzdata e2fsprogs dosfstools file procps psmisc lsof strace usbutils pciutils \ && rm -rf /var/lib/apt/lists/* RUN sed -i 's/^# *\(en_US.UTF-8\|tr_TR.UTF-8\)/\1/' /etc/locale.gen && locale-gen \ diff --git a/rootfs/assemble.sh b/rootfs/assemble.sh index f5ef7f35..4232c103 100755 --- a/rootfs/assemble.sh +++ b/rootfs/assemble.sh @@ -19,7 +19,7 @@ if [ -n "$miss" ]; then fi # Optional inputs decide whether the image can use the modem, Wi-Fi and the GPU at all. Missing ones used to # pass silently and produce an image that boots and does nothing useful, so say what went in. -for o in /firmware /android-subset /android-gpu-subset /bt-init /cltest /sing-box; do +for o in /firmware /android-subset /android-gpu-subset /bt-init /cltest /sing-box /xray /hev-socks5-tunnel; do [ -e "$o" ] && echo "assemble.sh: + $o" || echo "assemble.sh: - $o (not mounted; the image will be built without it)" done @@ -50,8 +50,10 @@ cp /logdw $R/opt/mu300/bin/logdw if [ -d /android-gpu-subset ]; then cp -an /android-gpu-subset/. $R/opt/mu300/android/; fi if [ -e /cltest ]; then install -D -m755 /cltest $R/opt/mu300/android/system/bin/cltest; fi if [ -e /bt-init ]; then cp /bt-init $R/opt/mu300/bin/mu300-bt-init; fi -# VLESS client for mu300-vpn (tools/fetch-sing-box.sh) +# VLESS clients for mu300-vpn: the xray engine (tools/fetch-xray.sh) and sing-box (tools/fetch-sing-box.sh) if [ -f /sing-box ]; then install -m755 /sing-box $R/opt/mu300/bin/sing-box; fi +if [ -f /xray ]; then install -m755 /xray $R/opt/mu300/bin/xray; fi +if [ -f /hev-socks5-tunnel ]; then install -m755 /hev-socks5-tunnel $R/opt/mu300/bin/hev-socks5-tunnel; fi for u in mu300-vendor.service:sysinit.target mu300-lan.service:multi-user.target mu300-ssh-hostkeys.service:sysinit.target mu300-telnetd.service:multi-user.target serial-getty@ttyGS0.service:getty.target ssh.socket:sockets.target mu300-wifi.service:multi-user.target mu300-wifi-client.service:multi-user.target mu300-mobile-data.service:multi-user.target mu300-mobile-data-watch.service:multi-user.target mu300-fixups.service:sysinit.target mu300-zram.service:swap.target mu300-boot-ok.service:multi-user.target mu300-cp_diskserver.service:multi-user.target mu300-refnotify.service:multi-user.target mu300-extra-modules.service:multi-user.target mu300-hotspot.service:multi-user.target mu300-bluetooth.service:multi-user.target mu300-thermal-guard.service:multi-user.target mu300-firewall.service:sysinit.target mu300-kmsg.service:sysinit.target mu300-toolkit.service:multi-user.target mu300-atd.service:multi-user.target mu300-modem-log.service:multi-user.target systemd-networkd.service:multi-user.target; do svc=${u%%:*}; tgt=${u##*:} mkdir -p $R/etc/systemd/system/$tgt.wants diff --git a/rootfs/overlay/etc/mu300/vpn.conf.example b/rootfs/overlay/etc/mu300/vpn.conf.example index 1092affe..b4c3721a 100644 --- a/rootfs/overlay/etc/mu300/vpn.conf.example +++ b/rootfs/overlay/etc/mu300/vpn.conf.example @@ -1,17 +1,24 @@ -# MU300 VPN (VLESS through sing-box). Copy to /etc/mu300/vpn.conf, edit, then: mu300-vpn gen && restart the service +# MU300 VPN (VLESS). Copy to /etc/mu300/vpn.conf, edit, then: mu300-vpn gen && restart the service # Ubuntu: sudo systemctl restart mu300-vpn OpenWrt: /etc/init.d/mu300-vpn restart ENABLE=1 # the share link from your server/panel (vless://uuid@host:port?type=...&security=...#name) VLESS_URI="" -# 1: nothing leaves through the cellular interface except the tunnel itself (also while the tunnel is down) -KILL_SWITCH=1 +# xray: Xray-core behind hev-socks5-tunnel on a kernel TUN (default) +# sing-box: sing-box's own TUN (the engine this device used before; FINDINGS 26b) +ENGINE=xray +# 1: nothing leaves through the cellular interface except the tunnel itself (also while the tunnel is down). +# Off by default for now: it was written and measured with sing-box, and has not been re-tested with xray. +KILL_SWITCH=0 # DNS for the device and its clients, resolved through the tunnel REMOTE_DNS=1.1.1.1 -# only used to look up the VPN server's own name (sent directly, outside the tunnel) +# sing-box only: used to look up the VPN server's own name (sent directly, outside the tunnel) BOOTSTRAP_DNS=1.1.1.1 # networks that stay local (USB/Wi-Fi LAN) LAN_CIDRS=192.168.77.0/24 -# 1: also carry IPv6 (only if the server has IPv6 connectivity; 0 keeps DNS and the tunnel IPv4-only) +# 1: also carry IPv6 (sing-box only, and only if the server has IPv6 connectivity) IPV6=0 -# optional: reach the VPN server through an HTTP proxy (host:port), e.g. for testing over a PC's connection +# sing-box only, optional: reach the VPN server through an HTTP proxy (host:port) UPSTREAM_HTTP_PROXY= +# xray only. Xray 26 no longer has allowInsecure; for a link that asks for it, the certificate the server presents +# is fetched once (needs openssl), pinned here, and fetched again by itself if the server renews it. Leave empty. +TLS_PIN_SHA256= diff --git a/rootfs/overlay/etc/systemd/system/mu300-vpn.service b/rootfs/overlay/etc/systemd/system/mu300-vpn.service index d429752f..e802d656 100644 --- a/rootfs/overlay/etc/systemd/system/mu300-vpn.service +++ b/rootfs/overlay/etc/systemd/system/mu300-vpn.service @@ -1,5 +1,5 @@ [Unit] -Description=MU300 VPN (VLESS via sing-box, TUN + kill switch) +Description=MU300 VPN (VLESS via Xray or sing-box, TUN) After=mu300-firewall.service mu300-mobile-data.service Wants=mu300-mobile-data.service ConditionPathExists=/etc/mu300/vpn.conf @@ -7,8 +7,9 @@ StartLimitIntervalSec=0 [Service] ExecStart=/opt/mu300/bin/mu300-vpn run -# sing-box exits with "missing default interface" when it starts before the modem has a default route; -# keep retrying instead of hitting the start limit and giving up +# the engine exits when it starts before the modem has a route to the server (sing-box: "missing default +# interface"; xray: the server name does not resolve yet), and on a renewed server certificate; keep retrying +# instead of hitting the start limit and giving up Restart=always RestartSec=10 diff --git a/rootfs/overlay/opt/mu300/bin/mu300-toolkit b/rootfs/overlay/opt/mu300/bin/mu300-toolkit index 8d40f30e..0b8c4bb2 100755 --- a/rootfs/overlay/opt/mu300/bin/mu300-toolkit +++ b/rootfs/overlay/opt/mu300/bin/mu300-toolkit @@ -559,7 +559,7 @@ menu_wifi() { vpn_enabled() { [ -r "$VPN_CONF" ] && grep -q '^ENABLE=1' "$VPN_CONF"; } menu_vpn() { while :; do - title "VPN (VLESS / sing-box)" + title "VPN (VLESS)" printf ' service: %s config: %s\n\n' "$(state_color "$(svc status mu300-vpn)")" \ "$( [ -r "$VPN_CONF" ] && (vpn_enabled && echo "enabled" || echo "disabled") || echo "missing")" /opt/mu300/bin/mu300-vpn status 2>/dev/null | sed 's/^/ /' diff --git a/rootfs/overlay/opt/mu300/bin/mu300-vpn b/rootfs/overlay/opt/mu300/bin/mu300-vpn index ff8405ab..422c1da9 100755 --- a/rootfs/overlay/opt/mu300/bin/mu300-vpn +++ b/rootfs/overlay/opt/mu300/bin/mu300-vpn @@ -1,20 +1,30 @@ #!/bin/sh -# VLESS client for the MU300 (Ubuntu and OpenWrt): sing-box with a TUN device and policy routing, so the device's -# own traffic and USB/Wi-Fi clients all leave through the tunnel. Settings: /etc/mu300/vpn.conf -# mu300-vpn gen build /run/mu300-vpn/config.json from vpn.conf and check it -# mu300-vpn run gen + kill switch + run sing-box in the foreground (used by the service) +# VLESS client for the MU300 (Ubuntu and OpenWrt): a TUN device and policy routing, so the device's own traffic +# and USB/Wi-Fi clients all leave through the tunnel. Settings: /etc/mu300/vpn.conf +# ENGINE=xray Xray-core (the VLESS reference client) behind hev-socks5-tunnel, a small C program on a +# plain kernel TUN - the default +# ENGINE=sing-box sing-box with its own TUN inbound (gvisor stack, see FINDINGS 26b) +# mu300-vpn gen build the engine's config under /run/mu300-vpn from vpn.conf and check it +# mu300-vpn run gen + kill switch + run the engine in the foreground (used by the service) # mu300-vpn off remove the kill switch (the service stop does not, so a crash never leaks), -# and any routing sing-box left behind if it is no longer running +# and any routing an engine left behind if it is no longer running # mu300-vpn status service, tunnel, exit IP set -e CONF=${MU300_VPN_CONF:-/etc/mu300/vpn.conf} RUN=/run/mu300-vpn -BIN=${SING_BOX:-/opt/mu300/bin/sing-box} -TUN=sbtun -MARK=0x2d0 # routing mark on sing-box's own connections: they bypass the tunnel and the kill switch +MARK=0x2d0 # routing mark on the engine's own connections: they bypass the tunnel and the kill switch [ -r "$CONF" ] && . "$CONF" ENABLE=${ENABLE:-0}; KILL_SWITCH=${KILL_SWITCH:-1}; REMOTE_DNS=${REMOTE_DNS:-1.1.1.1} BOOTSTRAP_DNS=${BOOTSTRAP_DNS:-1.1.1.1}; LAN_CIDRS=${LAN_CIDRS:-192.168.77.0/24}; IPV6=${IPV6:-0} +ENGINE=${ENGINE:-xray} +XRAY=${XRAY:-/opt/mu300/bin/xray}; HEV=${HEV:-/opt/mu300/bin/hev-socks5-tunnel} +BIN=${SING_BOX:-/opt/mu300/bin/sing-box} +SOCKS_PORT=10808 +# an image built before the xray engine existed has only sing-box: keep working with what is there +if [ "$ENGINE" = xray ] && { [ ! -x "$XRAY" ] || [ ! -x "$HEV" ]; }; then + [ -x "$BIN" ] && { echo "xray engine not installed, using sing-box" >&2; ENGINE=sing-box; } +fi +case "$ENGINE" in xray) TUN=xtun ;; *) TUN=sbtun ;; esac # json_str VALUE : JSON string literal json_str() { printf '"%s"' "$(printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g')"; } @@ -82,7 +92,7 @@ outbound_json() { printf '}' } -gen() { +gen_singbox() { [ -n "$VLESS_URI" ] || { echo "VLESS_URI is not set in $CONF" >&2; exit 1; } parse_uri mkdir -p "$RUN"; chmod 700 "$RUN" @@ -120,6 +130,217 @@ gen() { "$BIN" check -c "$RUN/config.json" } +# ---- xray engine ---------------------------------------------------------------------------------------------- +# Xray does VLESS and nothing else here; hev-socks5-tunnel owns the TUN and hands every TCP/UDP flow to Xray's +# SOCKS port on loopback. Neither installs routes, so this script does, with the same rule prefs and table as +# sing-box's auto_route - which is what lets routing_cleanup and the kill switch serve both engines. + +# first IPv4 address for a name, from the system resolver. Runs before any rule points into the tunnel, so the +# answer comes over the plain bearer. +resolve4() { + case "$1" in *[!0-9.]*) ;; *) printf '%s' "$1"; return 0 ;; esac + # glibc's getent on Ubuntu; OpenWrt has no getent but its busybox has nslookup (Ubuntu's image does not) + if command -v getent >/dev/null 2>&1; then + getent ahostsv4 "$1" 2>/dev/null | awk '{print $1; exit}' + else + nslookup "$1" 2>/dev/null | awk '/^Name:/ {n = 1} n && /^Address/ {sub(/^Address( [0-9]+)?: */, ""); if ($0 ~ /^[0-9.]+$/) {print; exit}}' + fi +} +listening() { { ss -ltn 2>/dev/null || netstat -ltn 2>/dev/null; } | grep -q "127.0.0.1:$1 "; } + +xray_stream_json() { + case "$TYPE" in tcp|raw) net=raw ;; ws|grpc|httpupgrade|xhttp) net=$TYPE ;; + *) echo "transport type '$TYPE' is not supported by this helper" >&2; exit 1 ;; esac + printf '"streamSettings":{"network":"%s"' "$net" + case "$TYPE" in + ws) printf ',"wsSettings":{"path":%s' "$(json_str "${WSPATH:-/}")"; [ -n "$WSHOST" ] && printf ',"host":%s' "$(json_str "$WSHOST")"; printf '}' ;; + grpc) printf ',"grpcSettings":{"serviceName":%s}' "$(json_str "$SVC")" ;; + httpupgrade) printf ',"httpupgradeSettings":{"path":%s' "$(json_str "${WSPATH:-/}")"; [ -n "$WSHOST" ] && printf ',"host":%s' "$(json_str "$WSHOST")"; printf '}' ;; + xhttp) printf ',"xhttpSettings":{"path":%s' "$(json_str "${WSPATH:-/}")"; [ -n "$WSHOST" ] && printf ',"host":%s' "$(json_str "$WSHOST")" + [ -n "$XMODE" ] && printf ',"mode":%s' "$(json_str "$XMODE")"; printf '}' ;; + esac + case "$SECURITY" in + tls) + printf ',"security":"tls","tlsSettings":{"serverName":%s' "$(json_str "${SNI:-$HOST}")" + # Xray 26 removed allowInsecure. Its replacement pins the one certificate the server presents, + # which is stricter: anything else is refused, including a correctly signed certificate for a + # different host. It also skips the expiry check, so an expired certificate keeps working until + # the server renews it - and then the pin has to change with it. + [ -n "$PIN" ] && printf ',"pinnedPeerCertSha256":%s' "$(json_str "$PIN")" + [ -n "$VCN" ] && printf ',"verifyPeerCertByName":%s' "$(json_str "$VCN")" + [ -n "$ALPN" ] && printf ',"alpn":%s' "$(json_list "$ALPN")" + [ -n "$FP" ] && printf ',"fingerprint":%s' "$(json_str "$FP")" + printf '}' ;; + reality) + printf ',"security":"reality","realitySettings":{"serverName":%s,"fingerprint":%s,"publicKey":%s,"shortId":%s' \ + "$(json_str "${SNI:-$HOST}")" "$(json_str "${FP:-chrome}")" "$(json_str "$PBK")" "$(json_str "$SID")" + [ -n "$SPX" ] && printf ',"spiderX":%s' "$(json_str "$SPX")" + printf '}' ;; + esac + printf ',"sockopt":{"mark":%d}}' "$((MARK))" +} + +# Xray 26 has no allowInsecure; pinnedPeerCertSha256 is its replacement. For a link that asks for allowInsecure the +# pin is managed here: fetched once when there is none, kept in vpn.conf, and fetched again only when Xray reports +# that the server's certificate no longer matches (a renewal). A pin that came from the link (pcs) or was written +# by hand without allowInsecure is left alone. +pin_managed() { [ "$SECURITY" = tls ] && case "$INSECURE" in 1|true) true ;; *) false ;; esac; } + +# SHA-256 of the leaf certificate the server presents, in the form Xray expects. Goes out directly: at start the +# tunnel's rules are not in place yet, and while it runs rule 9002 keeps the server's address off the tunnel. +fetch_pin() { + command -v openssl >/dev/null 2>&1 || { echo "fetching the server certificate needs openssl (OpenWrt: apk add openssl-util)" >&2; return 1; } + t=; command -v timeout >/dev/null 2>&1 && t="timeout 20" + h=$($t openssl s_client -connect "$SERVER_IP:$PORT" -servername "${SNI:-$HOST}" /dev/null | + openssl x509 -outform DER 2>/dev/null | sha256sum | cut -d' ' -f1) + # the hash of nothing is what an empty pipe produces when the handshake failed + case "$h" in ""|e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855) return 1 ;; esac + printf '%s' "$h" +} + +save_pin() { + if grep -q '^TLS_PIN_SHA256=' "$CONF"; then sed -i "s/^TLS_PIN_SHA256=.*/TLS_PIN_SHA256=$1/" "$CONF" + else printf '# fetched by mu300-vpn: the VPN server certificate, standing in for allowInsecure (Xray 26)\nTLS_PIN_SHA256=%s\n' "$1" >> "$CONF"; fi +} + +gen_xray() { + [ -n "$VLESS_URI" ] || { echo "VLESS_URI is not set in $CONF" >&2; exit 1; } + parse_uri + XMODE=$(param mode); SPX=$(urldecode "$(param spx)"); ENC=$(urldecode "$(param encryption)") + # pcs/vcn are the share-link spellings of pinnedPeerCertSha256/verifyPeerCertByName; TLS_PIN_SHA256 in + # vpn.conf is for links written before those existed + PIN=${TLS_PIN_SHA256:-$(urldecode "$(param pcs)")}; VCN=$(urldecode "$(param vcn)") + # the name is looked up now and Xray is given the address, so it never has to resolve anything itself - the + # resolver it would use sits behind the tunnel it is trying to build. The name stays as the SNI. + SERVER_IP=$(resolve4 "$HOST") + [ -n "$SERVER_IP" ] || { echo "cannot resolve the VPN server $HOST" >&2; exit 1; } + # allowInsecure with nothing pinned yet: take whatever certificate the server presents now and keep it + if pin_managed && [ -z "$PIN" ]; then + PIN=$(fetch_pin) || { echo "the link asks for allowInsecure, which Xray no longer has, and the server's" \ + "certificate could not be fetched to pin instead. Set TLS_PIN_SHA256 in $CONF, or ENGINE=sing-box." >&2; exit 1; } + save_pin "$PIN" + echo "pinned the server's current certificate ($PIN)" + fi + mkdir -p "$RUN"; chmod 700 "$RUN" + { + # info, not warning: a failed outbound - including a pin mismatch - is only reported at info. run_xray's + # reader scans every line and passes on only warnings and worse, so the system log does not fill up. + printf '{"log":{"loglevel":"info","access":"none"},\n' + printf '"inbounds":[{"tag":"socks-in","listen":"127.0.0.1","port":%d,"protocol":"socks","settings":{"auth":"noauth","udp":true,"ip":"127.0.0.1"}}],\n' "$SOCKS_PORT" + printf '"outbounds":[{"tag":"proxy","protocol":"vless","settings":{"vnext":[{"address":%s,"port":%s,"users":[{"id":%s,"encryption":%s' \ + "$(json_str "$SERVER_IP")" "$PORT" "$(json_str "$UUID")" "$(json_str "${ENC:-none}")" + [ -n "$FLOW" ] && printf ',"flow":%s' "$(json_str "$FLOW")" + printf '}]}]},'; xray_stream_json; printf '},\n' + printf '{"tag":"direct","protocol":"freedom","streamSettings":{"sockopt":{"mark":%d}}}]}\n' "$((MARK))" + } > "$RUN/xray.json" + chmod 600 "$RUN/xray.json" + cat > "$RUN/hev.yml" < "$RUN/server-ip" + "$XRAY" run -test -c "$RUN/xray.json" >/dev/null || { "$XRAY" run -test -c "$RUN/xray.json" >&2; exit 1; } + echo "xray config OK ($RUN/xray.json), server $HOST -> $SERVER_IP" +} + +xray_routes_up() { + ip rule add pref 9000 fwmark "$MARK" lookup main + for c in $(printf '%s' "$LAN_CIDRS" | tr ',' ' '); do ip rule add pref 9001 to "$c" lookup main; done + ip rule add pref 9002 to "$(cat "$RUN/server-ip")" lookup main + ip route replace default dev "$TUN" table 2022 + ip rule add pref 9010 lookup 2022 + # the device's own lookups: dnsmasq forwards to whatever the bearer handed out, and the carrier's resolver + # does not answer from the far end of the tunnel. Send them to REMOTE_DNS instead, which the routing above + # then carries through the tunnel. Clients that use their own DNS are already going through it. + nft -f - </dev/null || true + for pref in 9000 9001 9002 9003 9010; do + while ip rule del pref "$pref" 2>/dev/null; do :; done + done + ip route flush table 2022 2>/dev/null || true +} + +# Two processes and the routing between them, torn down together: if either dies the service exits, the routes +# go with it and procd starts the whole thing again. Leaving rules behind with nothing at the other end is what +# made sing-box's crashes look like a dead modem (routing_cleanup), so every way out of here goes through down(). +run_xray() { + xray_routes_down + gen_xray + # Xray's output goes through a reader that passes it on and notes a pin mismatch, so a renewed server + # certificate is noticed without polling the server + rm -f "$RUN/pin-mismatch" "$RUN/xray.out"; mkfifo "$RUN/xray.out" + while IFS= read -r l; do + case "$l" in *"peer cert is unrecognized (against pinnedPeerCertSha256)"*) : > "$RUN/pin-mismatch" ;; esac + case "$l" in *"[Info]"*|*"[Debug]"*) ;; *) printf '%s\n' "$l" ;; esac + done < "$RUN/xray.out" & + "$XRAY" run -c "$RUN/xray.json" > "$RUN/xray.out" 2>&1 & xpid=$! + hpid= + down() { + trap - EXIT INT TERM + [ -n "$hpid" ] && kill "$hpid" 2>/dev/null + kill "$xpid" 2>/dev/null + wait 2>/dev/null + xray_routes_down + } + trap 'down; exit 0' INT TERM + trap down EXIT + n=0 + until listening "$SOCKS_PORT"; do + kill -0 "$xpid" 2>/dev/null || { echo "xray exited during start" >&2; exit 1; } + n=$((n + 1)); [ "$n" -lt 15 ] || { echo "xray did not open its SOCKS port" >&2; exit 1; } + sleep 1 + done + "$HEV" "$RUN/hev.yml" & hpid=$! + n=0 + until ip link show "$TUN" >/dev/null 2>&1; do + kill -0 "$hpid" 2>/dev/null || { echo "hev-socks5-tunnel exited during start" >&2; exit 1; } + n=$((n + 1)); [ "$n" -lt 15 ] || { echo "$TUN did not appear" >&2; exit 1; } + sleep 1 + done + ip link set "$TUN" up + xray_routes_up + echo "tunnel up on $TUN (xray $xpid, hev $hpid)" + # whichever exits first ends the service + while kill -0 "$xpid" 2>/dev/null && kill -0 "$hpid" 2>/dev/null; do + sleep 2 + [ -e "$RUN/pin-mismatch" ] && pin_managed || continue + rm -f "$RUN/pin-mismatch" + new=$(fetch_pin) || { sleep 30; continue; } + [ "$new" = "$PIN" ] && { sleep 30; continue; } + save_pin "$new" + echo "the server's certificate changed; pinned the new one and restarting" >&2 + exit 1 + done + echo "$( kill -0 "$xpid" 2>/dev/null && echo hev-socks5-tunnel || echo xray ) exited, tearing the tunnel down" >&2 + exit 1 +} + +gen() { case "$ENGINE" in xray) gen_xray ;; *) gen_singbox ;; esac; } + killswitch_on() { nft -f - </dev/null 2>&1 && return 0 + pgrep -f '[s]ing-box run|[x]ray run|[h]ev-socks5-tunnel' >/dev/null 2>&1 && return 0 ip link show "$TUN" >/dev/null 2>&1 && return 0 n=0 for pref in 9000 9001 9002 9003 9010; do while ip rule del pref "$pref" 2>/dev/null; do n=$((n + 1)); done done ip route flush table 2022 2>/dev/null || true - [ "$n" -gt 0 ] && echo "removed $n stale routing rule(s) left by sing-box" + nft delete table ip mu300_vpn_dns 2>/dev/null || true + [ "$n" -gt 0 ] && echo "removed $n stale routing rule(s) left by a VPN engine" return 0 } @@ -184,13 +406,14 @@ case "${1:-status}" in gen) gen ;; run) [ "$ENABLE" = 1 ] || { echo "VPN disabled (ENABLE=0 in $CONF)"; killswitch_off; exit 0; } - gen >/dev/null + [ "$ENGINE" = xray ] || gen >/dev/null ensure_firewall_zone if [ "$KILL_SWITCH" = 1 ]; then killswitch_on; else killswitch_off; fi + [ "$ENGINE" = xray ] && run_xray exec "$BIN" run -c "$RUN/config.json" ;; off) killswitch_off; echo "kill switch removed"; routing_cleanup ;; status) - echo "enabled: $ENABLE kill switch: $KILL_SWITCH ($(nft list table inet mu300_vpn >/dev/null 2>&1 && echo active || echo inactive))" + echo "engine: $ENGINE enabled: $ENABLE kill switch: $KILL_SWITCH ($(nft list table inet mu300_vpn >/dev/null 2>&1 && echo active || echo inactive))" ip -br addr show "$TUN" 2>/dev/null || echo "$TUN: down" if ip link show "$TUN" >/dev/null 2>&1; then printf 'exit IP: '; (wget -qO- -T 8 http://api.ipify.org 2>/dev/null || curl -s -m 8 http://api.ipify.org 2>/dev/null || echo unreachable); echo diff --git a/tools/fetch-xray.sh b/tools/fetch-xray.sh new file mode 100755 index 00000000..1ee009f7 --- /dev/null +++ b/tools/fetch-xray.sh @@ -0,0 +1,24 @@ +#!/bin/sh +# Download the pinned Xray-core and hev-socks5-tunnel releases (static arm64) used by mu300-vpn's xray engine and +# verify them. Xray speaks VLESS (it is the reference implementation); hev-socks5-tunnel turns a kernel TUN +# device into connections on Xray's local SOCKS port. +# tools/fetch-xray.sh [OUTDIR] (default: .; writes OUTDIR/xray and OUTDIR/hev-socks5-tunnel) +set -eu +XRAY_VER=26.3.27 +XRAY_SHA256=4d30283ae614e3057f730f67cd088a42be6fdf91f8639d82cb69e48cde80413c +HEV_VER=2.17.1 +HEV_SHA256=958206dcebcdc390cdc4d5b88c8504ec81483e2a04b46d37c835a179830c86ba +OUT=${1:-.} +tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT +sha() { s=$(shasum -a 256 "$1" 2>/dev/null || sha256sum "$1"); printf '%s' "${s%% *}"; } + +curl -fsSL -o "$tmp/xray.zip" "https://github.com/XTLS/Xray-core/releases/download/v$XRAY_VER/Xray-linux-arm64-v8a.zip" +[ "$(sha "$tmp/xray.zip")" = "$XRAY_SHA256" ] || { echo "checksum mismatch for Xray $XRAY_VER" >&2; exit 1; } +unzip -q -o "$tmp/xray.zip" xray -d "$tmp" +install -m 755 "$tmp/xray" "$OUT/xray" + +curl -fsSL -o "$tmp/hev" "https://github.com/heiher/hev-socks5-tunnel/releases/download/$HEV_VER/hev-socks5-tunnel-linux-arm64" +[ "$(sha "$tmp/hev")" = "$HEV_SHA256" ] || { echo "checksum mismatch for hev-socks5-tunnel $HEV_VER" >&2; exit 1; } +install -m 755 "$tmp/hev" "$OUT/hev-socks5-tunnel" + +echo "xray $XRAY_VER, hev-socks5-tunnel $HEV_VER -> $OUT" diff --git a/tools/make-release.sh b/tools/make-release.sh index a6263492..1aacd376 100755 --- a/tools/make-release.sh +++ b/tools/make-release.sh @@ -29,6 +29,7 @@ docker run --rm -v "$TOP/tools":/src:ro -v "$IN/tools":/o mu300-kbuild sh -c ' # cltest links against Android's libraries at build time only; use a local build when there is one [ -f "$TOP/tools/gpu/cltest" ] && cp "$TOP/tools/gpu/cltest" "$IN/tools/gpu/cltest" sh "$TOP/tools/fetch-sing-box.sh" "$IN/sing-box" +sh "$TOP/tools/fetch-xray.sh" "$IN" echo "==> kernel bundle" K=$D/kernel && mkdir -p "$K" @@ -44,7 +45,7 @@ cid=$(docker create mu300-ubuntu:24.04 /bin/true); docker export "$cid" > "$B/ba cltest=""; [ -f "$IN/tools/gpu/cltest" ] && cltest="-v $IN/tools/gpu/cltest:/cltest:ro" # shellcheck disable=SC2086 docker run --rm -v "$B":/w -v "$IN/out/modules":/kmods:ro -v "$IN/out":/kout:ro -v "$IN/tools/logdw/logdw":/logdw:ro \ - -v "$IN/tools/bt-init/mu300-bt-init":/bt-init:ro -v "$IN/sing-box":/sing-box:ro $cltest \ + -v "$IN/tools/bt-init/mu300-bt-init":/bt-init:ro -v "$IN/sing-box":/sing-box:ro -v "$IN/xray":/xray:ro -v "$IN/hev-socks5-tunnel":/hev-socks5-tunnel:ro $cltest \ -e MU300_VERSION="$TAG" mu300-ubuntu:24.04 bash /w/assemble.sh >/dev/null mv "$B/mu300-ubuntu-24.04-rootfs.tar.gz" "$D/mu300-ubuntu-rootfs.tar.gz"; rm -rf "$B" @@ -91,7 +92,8 @@ Built from $REPO@$commit with \`kernel/build-all.sh\` and \`tools/make-release.s Corresponding source (GPL): kernel https://github.com/Enceka/android_kernel_zte_ums9620_mifi_u30air/tree/$kernel_rev , Wi-Fi/Bluetooth/Mali modules https://github.com/realme-kernel-opensource/realme_C51_C53_Narzo-N53-AndroidT-kernel-source/tree/$modules_rev , patches in \`kernel/patches\`. Ubuntu, OpenWrt and busybox packages come from their distributions' archives; -sing-box from https://github.com/SagerNet/sing-box/releases. +sing-box from https://github.com/SagerNet/sing-box/releases, Xray from https://github.com/XTLS/Xray-core/releases, +hev-socks5-tunnel from https://github.com/heiher/hev-socks5-tunnel/releases. EOF if gh release view "$TAG" -R "$REPO" >/dev/null 2>&1; then gh release upload "$TAG" -R "$REPO" --clobber "$D"/*.tar.gz "$D/SHA256SUMS"