From 7b8ea15e743127ea92b94d8199b45fe96cbf409f Mon Sep 17 00:00:00 2001 From: yiguodev <147401898+yiguodev@users.noreply.github.com> Date: Tue, 29 Sep 2026 11:26:43 +0800 Subject: [PATCH] feat: add ShadowTLS v3, UoT v2, TUIC v5, and HTTPUpgrade (#2) * test: prepare protocol-completion validation * feat: support ShadowTLS v3 for Shadowsocks 2022 * feat: add UoT v2 to Shadowsocks 2022 * feat: support TUIC v5 TCP and UDP * feat: add HTTPUpgrade to VMess and Trojan Reuse the existing raw upgrade stream with typed normal/fast-open options and strict early-data configuration. Reject an expired setup before ready IO can write any prefix. Add isolated official-peer data, UDP, authentication, fingerprint, close and legacy-transport gates. * test: validate extended proxy chains and lifecycle * build: freeze release dependencies for protocol completion * fix: enforce HTTPUpgrade deadline on resumed IO Recheck the absolute setup deadline before each handshake poll and before accepting success, without retaining a timer on established streams. Cover ready late responses, blocked prefix writes, and post-setup IO in both normal and fast-open modes. --- AGENTS.md | 6 +- Cargo.toml | 8 +- README.md | 4 +- docs/acceptance.md | 29 +- docs/config.yaml | 45 +- docs/invoke-api.md | 4 +- docs/outbounds.md | 109 +- docs/runtime-resource-policy.md | 7 +- docs/tls-client-fingerprint.md | 5 +- docs/tls-dependencies.md | 25 +- docs/vless.md | 2 +- readme/README.ru.md | 4 +- readme/README.zh_CN.md | 4 +- scripts/README.md | 53 +- scripts/fixtures/platform_abi.c | 4 +- scripts/src/vcore_scripts/builds.py | 4 +- scripts/src/vcore_scripts/cli.py | 11 + .../container_protocol_client.py | 110 ++ .../vcore_scripts/container_restart_peer.py | 63 + .../container_shadowtls_fault.py | 203 +++ .../vcore_scripts/container_shadowtls_peer.py | 70 ++ .../src/vcore_scripts/container_udp_origin.py | 9 +- .../src/vcore_scripts/container_uot_watch.py | 67 + scripts/src/vcore_scripts/core_checks.py | 23 +- scripts/src/vcore_scripts/native_release.py | 9 +- .../src/vcore_scripts/protocol_catalogs.py | 4 + .../protocol_completion_peers.py | 366 ++++++ .../src/vcore_scripts/protocol_evidence.py | 47 +- .../protocol_fingerprint_shape.py | 7 +- scripts/src/vcore_scripts/protocol_harness.py | 54 +- .../src/vcore_scripts/protocol_httpupgrade.py | 554 ++++++++ .../protocol_httpupgrade_acceptance.py | 253 ++++ .../protocol_httpupgrade_catalog.py | 174 +++ .../protocol_integration_acceptance.py | 40 +- .../protocol_integration_catalog.py | 26 +- .../protocol_integration_checks.py | 3 + .../protocol_integration_coupled.py | 41 + .../protocol_integration_local.py | 11 +- .../protocol_integration_metrics.py | 35 +- .../protocol_integration_native.py | 73 +- .../protocol_integration_profiles.py | 66 + .../protocol_integration_suite.py | 32 +- .../src/vcore_scripts/protocol_shadowtls.py | 568 +++++++++ .../protocol_shadowtls_acceptance.py | 376 ++++++ .../protocol_shadowtls_catalog.py | 179 +++ .../protocol_shadowtls_native.py | 306 +++++ scripts/src/vcore_scripts/protocol_tuic.py | 543 ++++++++ .../vcore_scripts/protocol_tuic_acceptance.py | 230 ++++ .../vcore_scripts/protocol_tuic_catalog.py | 183 +++ scripts/src/vcore_scripts/protocol_uot.py | 439 +++++++ .../vcore_scripts/protocol_uot_acceptance.py | 247 ++++ .../src/vcore_scripts/protocol_uot_catalog.py | 149 +++ .../vcore_scripts/protocol_vmess_container.py | 9 +- scripts/tests/test_native_release.py | 24 + scripts/tests/test_platform_delivery.py | 4 +- .../tests/test_protocol_completion_peers.py | 70 ++ scripts/tests/test_protocol_httpupgrade.py | 105 ++ scripts/tests/test_protocol_integration.py | 106 +- scripts/tests/test_protocol_shadowtls.py | 125 ++ scripts/tests/test_protocol_tuic.py | 145 +++ scripts/tests/test_protocol_uot.py | 81 ++ src/config/mod.rs | 60 +- src/config/shadowsocks.rs | 123 ++ src/config/trojan.rs | 55 +- src/config/tuic.rs | 165 +++ src/config/vless.rs | 4 + src/config/vmess.rs | 21 +- src/lib.rs | 12 +- src/limits.rs | 10 + src/outbound/anytls/client.rs | 6 +- src/outbound/anytls/mod.rs | 3 +- src/outbound/connector.rs | 3 +- src/outbound/mod.rs | 7 +- src/outbound/shadowsocks/mod.rs | 56 +- src/outbound/shadowsocks/tests.rs | 2 + src/outbound/shadowsocks/uot.rs | 265 ++++ src/outbound/tuic/activity.rs | 43 + src/outbound/tuic/datagram.rs | 532 ++++++++ src/outbound/tuic/mod.rs | 12 + src/outbound/tuic/outbound.rs | 363 ++++++ src/outbound/tuic/stream.rs | 108 ++ src/outbound/tuic/wire.rs | 307 +++++ src/outbound/{anytls => }/uot.rs | 107 +- src/resources/observation.rs | 8 +- src/runtime.rs | 67 +- src/security/boring.rs | 21 +- src/security/mod.rs | 6 + src/security/shadow_tls.rs | 454 +++++++ src/security/shadow_tls_tests.rs | 570 +++++++++ src/security/tls.rs | 6 +- src/transport/ws.rs | 39 +- tests/README.md | 18 + tests/datagram_foundations.rs | 2 + tests/feature_foundations.rs | 4 +- tests/httpupgrade_config.rs | 149 +++ tests/httpupgrade_memory.rs | 311 +++++ tests/limit_foundations.rs | 16 + tests/protocols/limits.json | 108 ++ tests/shadowsocks_backpressure.rs | 4 + tests/shadowsocks_uot.rs | 505 ++++++++ tests/shadowtls_config.rs | 227 ++++ tests/shadowtls_stream.rs | 103 ++ tests/trojan_config.rs | 2 +- tests/tuic_config.rs | 168 +++ tests/tuic_memory.rs | 1119 +++++++++++++++++ tests/uot_config.rs | 86 ++ tests/vless_public.rs | 54 +- tests/vless_public/httpupgrade.rs | 247 ++++ tests/vless_public/integration/connector.rs | 72 +- tests/vless_public/integration/lifecycle.rs | 38 +- tests/vless_public/integration/mod.rs | 60 +- tests/vless_public/integration/pressure.rs | 73 +- tests/vless_public/integration/shadowsocks.rs | 4 +- tests/vless_public/runtime.rs | 12 +- tests/vless_public/shadowtls.rs | 257 ++++ tests/vless_public/tuic.rs | 292 +++++ tests/vless_public/uot.rs | 186 +++ tests/vmess_lifecycle.rs | 23 +- tests/xray_interop.rs | 2 +- 119 files changed, 13884 insertions(+), 246 deletions(-) create mode 100644 scripts/src/vcore_scripts/container_protocol_client.py create mode 100644 scripts/src/vcore_scripts/container_restart_peer.py create mode 100644 scripts/src/vcore_scripts/container_shadowtls_fault.py create mode 100644 scripts/src/vcore_scripts/container_shadowtls_peer.py create mode 100644 scripts/src/vcore_scripts/container_uot_watch.py create mode 100644 scripts/src/vcore_scripts/protocol_completion_peers.py create mode 100644 scripts/src/vcore_scripts/protocol_httpupgrade.py create mode 100644 scripts/src/vcore_scripts/protocol_httpupgrade_acceptance.py create mode 100644 scripts/src/vcore_scripts/protocol_httpupgrade_catalog.py create mode 100644 scripts/src/vcore_scripts/protocol_integration_coupled.py create mode 100644 scripts/src/vcore_scripts/protocol_integration_profiles.py create mode 100644 scripts/src/vcore_scripts/protocol_shadowtls.py create mode 100644 scripts/src/vcore_scripts/protocol_shadowtls_acceptance.py create mode 100644 scripts/src/vcore_scripts/protocol_shadowtls_catalog.py create mode 100644 scripts/src/vcore_scripts/protocol_shadowtls_native.py create mode 100644 scripts/src/vcore_scripts/protocol_tuic.py create mode 100644 scripts/src/vcore_scripts/protocol_tuic_acceptance.py create mode 100644 scripts/src/vcore_scripts/protocol_tuic_catalog.py create mode 100644 scripts/src/vcore_scripts/protocol_uot.py create mode 100644 scripts/src/vcore_scripts/protocol_uot_acceptance.py create mode 100644 scripts/src/vcore_scripts/protocol_uot_catalog.py create mode 100644 scripts/tests/test_protocol_completion_peers.py create mode 100644 scripts/tests/test_protocol_httpupgrade.py create mode 100644 scripts/tests/test_protocol_shadowtls.py create mode 100644 scripts/tests/test_protocol_tuic.py create mode 100644 scripts/tests/test_protocol_uot.py create mode 100644 src/config/tuic.rs create mode 100644 src/outbound/shadowsocks/uot.rs create mode 100644 src/outbound/tuic/activity.rs create mode 100644 src/outbound/tuic/datagram.rs create mode 100644 src/outbound/tuic/mod.rs create mode 100644 src/outbound/tuic/outbound.rs create mode 100644 src/outbound/tuic/stream.rs create mode 100644 src/outbound/tuic/wire.rs rename src/outbound/{anytls => }/uot.rs (83%) create mode 100644 src/security/shadow_tls.rs create mode 100644 src/security/shadow_tls_tests.rs create mode 100644 tests/httpupgrade_config.rs create mode 100644 tests/httpupgrade_memory.rs create mode 100644 tests/shadowsocks_uot.rs create mode 100644 tests/shadowtls_config.rs create mode 100644 tests/shadowtls_stream.rs create mode 100644 tests/tuic_config.rs create mode 100644 tests/tuic_memory.rs create mode 100644 tests/uot_config.rs create mode 100644 tests/vless_public/httpupgrade.rs create mode 100644 tests/vless_public/shadowtls.rs create mode 100644 tests/vless_public/tuic.rs create mode 100644 tests/vless_public/uot.rs diff --git a/AGENTS.md b/AGENTS.md index 2bd8ab5..74f40f3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # Project Overview -VCore is a standalone Rust proxy core. The current public contract is Invoke API v5 with internal schema revision 27. Runtime configuration uses the strict schema documented in `docs/config.yaml` and is passed inline as `configYaml` / `configYamls`; YAML contains neither `configVersion` nor `default-proxy`. Public lifecycle state is runtime-local and single-instance. +VCore is a standalone Rust proxy core. The current public contract is Invoke API v5 with internal schema revision 31. Runtime configuration uses the strict schema documented in `docs/config.yaml` and is passed inline as `configYaml` / `configYamls`; YAML contains neither `configVersion` nor `default-proxy`. Public lifecycle state is runtime-local and single-instance. Apple and Android use host-owned TUN fds through the Unix `rust-tun` adapter. Windows uses `windows-rs` / `Windows.Networking.Vpn`; the packaged ARM64 foreground, AppContainer provider, per-session full-trust runtime, lifecycle, pressure, and packet-channel gates pass on Windows 11. Windows 10, native x64, physical IPv6, WACK, and Store publishing remain release gates. Linux remains unsupported. @@ -13,12 +13,12 @@ Read the relevant document completely before changing that area: - FFI, lifecycle, Android protect, or config delivery: `docs/invoke-api.md` and `src/ffi/`. - YAML, proxy graph, proxy groups, DNS, rules, or sniffer: `docs/config.yaml`, `docs/tun-icmp-dns.md`, and `src/config/`. - HTTP/SOCKS5 inbound, authentication, or listeners: `docs/inbounds.md` and `src/inbound/`. -- SOCKS5, AnyTLS, Trojan, VMess, Hysteria2 or SS 2022: `docs/outbounds.md`. +- SOCKS5, AnyTLS, Trojan, VMess, Hysteria2, TUIC v5 or SS 2022: `docs/outbounds.md`. - VLESS, Vision, Encryption, JLS or static ECH: `docs/vless.md`. - XHTTP request fields, download legs, H1/H2/H3 or sing-mux: `docs/xhttp.md`. - Runtime Controller, proxy-group selection, or TUN traffic metrics: `docs/controller-api.md` and `src/controller.rs`. - GeoData: `docs/geodata.md`. -- TLS profiles, certificate policy or TLS dependencies: `docs/tls-client-fingerprint.md` and `docs/tls-dependencies.md`; REALITY also requires `docs/reality-wire-protocol.md`. +- TLS profiles, certificate policy or TLS dependencies: `docs/tls-client-fingerprint.md` and `docs/tls-dependencies.md`; REALITY also requires `docs/reality-wire-protocol.md`. Before local boring development or opening/updating a PR, follow the dependency-source workflow in `docs/tls-dependencies.md`. - Unix TUN fd ownership or packet I/O: `docs/tun-platform.md`. - Windows VPN/TUN, outbound binding, AppContainer packet buffers, or package lifecycle: `docs/windows-vpn.md` and `docs/tun-platform.md`. - Build, validation, or interoperability tooling: `scripts/README.md`, `tests/README.md`, and the unified `vcore-scripts` interface. diff --git a/Cargo.toml b/Cargo.toml index 1b95f67..3018839 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,6 +39,8 @@ default = [ "outbound-vmess", "outbound-vless", "outbound-hysteria2", + "outbound-tuic", + "shadow-tls-v3", ] inbound-http = [] inbound-socks5 = [] @@ -49,7 +51,9 @@ outbound-vless = ["tls-fingerprint", "boring/reality", "boring/jls", "boring/mlk outbound-trojan = ["stream-transport", "tls-fingerprint"] outbound-vmess = ["stream-transport", "tls-fingerprint", "dep:aes", "dep:crc32fast", "dep:md-5", "dep:ring", "dep:shake"] tls-fingerprint = ["dep:boring", "dep:tokio-boring"] +shadow-tls-v3 = ["tls-fingerprint", "boring/shadow-tls-v3", "dep:ring", "dep:zeroize"] outbound-hysteria2 = ["quic-transport", "dep:quinn-proto", "dep:h3", "dep:h3-quinn", "dep:blake2"] +outbound-tuic = ["quic-transport"] stream-transport = ["dep:tokio-tungstenite", "dep:httparse", "dep:log"] quic-transport = ["dep:quinn"] # Enables local interoperability-only trust-root injection. Release build @@ -68,6 +72,8 @@ tun = [ "outbound-vmess", "outbound-vless", "outbound-hysteria2", + "outbound-tuic", + "shadow-tls-v3", ] [dependencies] @@ -161,7 +167,7 @@ windows-collections = { version = "=0.3.2", optional = true } windows-core = { version = "=0.62.2", optional = true } [dev-dependencies] -# Native peer controls for bounded in-memory ALPS tests; same published fork. +# Native peer controls for bounded in-memory ALPS tests; same source as boring. boring-sys = { git = "https://github.com/OneXray/boring", branch = "release", version = "=5.2.0" } foreign-types = "=0.5.0" tokio = { version = "1", features = ["test-util"] } diff --git a/README.md b/README.md index 343b8ee..4f50639 100644 --- a/README.md +++ b/README.md @@ -4,10 +4,12 @@ English · 简体中文 · Русский

-VCore is a standalone, host-agnostic Rust client proxy core. It provides proxy graphs, static `select` proxy groups, DNS, routing rules, GeoData, HTTP/SOCKS5 listeners, a TUN data plane, and a loopback Controller through strict YAML configuration and Invoke API v5. The internal configuration schema revision is 27; the revision appears only in the `version` response and `buildIdentity`, not in YAML. +VCore is a standalone, host-agnostic Rust client proxy core. It provides proxy graphs, static `select` proxy groups, DNS, routing rules, GeoData, HTTP/SOCKS5 listeners, a TUN data plane, and a loopback Controller through strict YAML configuration and Invoke API v5. The internal configuration schema revision is 31; the revision appears only in the `version` response and `buildIdentity`, not in YAML. ## Features +SS2022 additionally supports [strict ShadowTLS v3](docs/outbounds.md#shadowtls-v3) TCP wrapping and UoT v2; native UDP remains separate. [TUIC v5](docs/outbounds.md#tuic-v5) supports TCP and native/quic UDP over controlled QUIC. + - Outbounds: [VLESS TCP/WS/gRPC/HTTP/H2/XHTTP, TLS/REALITY and Vision](docs/vless.md), SOCKS5 CONNECT/UDP ASSOCIATE, AnyTLS TCP/UoT, Shadowsocks 2022, [Trojan TCP/UDP over TLS/WS/gRPC](docs/outbounds.md#trojan), [VMess AEAD over TCP/WS/gRPC/HTTP/H2](docs/outbounds.md#vmess-aead), [Hysteria2 TCP/UDP, bandwidth, Salamander and port hopping](docs/outbounds.md#hysteria2), and DIRECT. SS supports three standard 2022 algorithms and AES identity chains; see its [upstream risks and acceptance boundaries](docs/outbounds.md#shadowsocks-2022). - Proxy chains: `dialer-proxy` forms a directed acyclic graph of arbitrary length. If node A points to B, the physical path is `client -> B -> A -> target`. - Proxy groups: static `select` groups keep ordered members, including concrete nodes, nested groups, `DIRECT`, and `REJECT`; their current-session selection can be changed live through the Controller. `dialer-proxy` may reference nodes or groups; DIRECT in an upstream group connects the current node's prepared server. diff --git a/docs/acceptance.md b/docs/acceptance.md index 237b652..4c9b429 100644 --- a/docs/acceptance.md +++ b/docs/acceptance.md @@ -9,7 +9,7 @@ | --- | --- | --- | | 离线 / 纯内存 | 严格配置与 feature、DAG/组快照、协议向量、TLS 身份/签名/pin、取消与局部上限、FFI 所有权 | 网络互通、设备 | | 容器互通 | 公开配置和消费者、真实认证及负例、传输关闭、UDP 来源与边界、受控 DNS/上游 | 任意字段组合或公网服务 | -| 集成 / 压力 | 七出站的有序两跳、运行时切组、Stop/回滚/测速、重建、持续流量与静默窗口 | 无扰动吞吐基准或整机内存保证 | +| 集成 / 压力 | 八出站 64 有序两跳、SS v3/UoT/TUIC 强耦合链、运行时切组、Stop/回滚/测速、混合重建与长测 | 无扰动吞吐基准或整机内存保证 | | 平台构建 / ABI | 同一锁文件、产物架构/身份/hash、原生 C/Swift 消费者与打包依赖 | 物理 TUN、签名安装 | | 设备 / 发布 | 真机网络、protect/物理绑定、正式宿主生命周期、签名安装及商店门禁 | 其他平台或后续 revision | @@ -17,6 +17,15 @@ HY2 已完成分片 ID 重用等确定性回归。单纯复用实现生成期望值、声明字段数量或找到 PASS 文本,不能替代行为验证。ignored、未运行、基础设施失败和清理失败均不得计为通过。 +integration 另含 TUIC 双模式到 SS v3 三算法的六条链,复跑 TCP-only SOCKS5 到 +SS UoT/v3、SS UoT 到 TUIC 等既有消费者。100 次生命周期覆盖基础协议及扩展组合; +100 轮重建和至少 1800 秒长测每轮保持 20 TCP + 20 UDP,TCP 使用 SOCKS5、SS v3、 +TUIC、HTTPUpgrade 四组,UDP 使用 SS UoT、SS UoT+v3、TUIC、HTTPUpgrade 四组, +每组五条并轮换算法/模式。原七协议和 HY2 连续跳端口回归仍保留。 +Stop 返回时资源必须归零、FD 回基线,后续五秒静默不作清理宽限。预热五分钟后, +逐分钟独立记录堆、RSS、活对象和队列;后十分钟堆中位数增长上限为 max(1 MiB, 5%), +建链中位数上限为首次两倍。短 tracer 或单协议 suite 均不能替代整轮验收。 + ## 对端与已知限制 - 所有协议端、原站、DNS 和提供入口的对照客户端遵守[隔离规则](testing-isolation.md)。 @@ -30,10 +39,24 @@ HY2 已完成分片 ID 重用等确定性回归。单纯复用实现生成期望 - 官方 Hysteria 回包缓冲包含协议头;V2Ray 部分 VMess 返回路径也有更小缓冲。 原生夹具上限不改变 VCore 的协议预算。 - SS 原样上游 padding 未初始化风险及空首包随机零 padding 被严格服务端拒绝的限制 - 仍未修补。codec 级刷新回归不证明 server-first 互通。官方 ssserver 单层 EIH 终结与自有 + 仍未修补。裸 SS、EIH 与 SS v3 TCP 的空首包/server-first 明确不在必过正例内, + 不计作互通成功;保留确定性拒绝负例。TCP 改验非空首段的 client-first,仍须三地址族、 + 双向各 10 MiB 摘要、认证和关闭;其他协议的 server-first 与 SS UoT 首写门控不变。 + codec 级刷新回归不证明 server-first 互通。官方 ssserver 单层 EIH 终结与自有 1/2 层身份中继是不同证据,不能据此宣称任意多层原生 EIH。详见[出站](outbounds.md#shadowsocks-2022)。 +- ShadowTLS 只支持 SS2022 的 strict v3/TLS1.3 TCP 包装,原生 UDP 单独验证。 + 主对端为 Mihomo,官方 ShadowTLS + 原样 ssserver 为补充对照;内存中的 cover + server-first 不代表官方 SS 空首包限制已解决,额外四字节记录特征仍存在。 +- SS UoT 仅 v2,裸流/v3 与三算法分别验证 TCP-only Mihomo listener,包含 + TCP-only SOCKS5 上游、切组、零长度包与 UDP 旁路观测。当前 Mihomo 的 UoT 接收 + 缓冲为 16 KiB;原样 ssserver 只作不支持 UoT 的负例。VCore u16 codec 边界、 + 调用方双向预算和该对端实际包上限分别取证,不相互替代。 - 静态 ECH、JLS、Encryption 与混合 REALITY 是选定能力集;动态 ECH、Restls、 - ShadowTLS、WireGuard 不在当前范围。JLS 内部使用 fork hook 不构成 ShadowTLS 支持。 + ShadowTLS v1/v2、WireGuard 不在当前范围。 +- TUIC v5 的 native/quic、三算法、身份拒绝、三地址族与上游组合对 Mihomo 验证; + 认证没有 ACK,不以本地 SOCKS 成功当作密码通过。独立内存 QUIC 验 u16、分片/ID + 退役、credit、窗口和同步 Stop,网络包大小以实际链路为准。TUIC suite 包含 + Hysteria2 和 XHTTP H3 受影响回归,不代表新的八协议完整压力或设备验收。 ## 当前证据如何使用 diff --git a/docs/config.yaml b/docs/config.yaml index f0f8e6a..1a7b76e 100644 --- a/docs/config.yaml +++ b/docs/config.yaml @@ -1,6 +1,6 @@ -# VCore 配置修订版 27 的完整示例。 +# VCore 配置修订版 31 的完整示例。 # -# `version.configVersion` 返回的 27 是二进制报告值,不是 YAML 字段。配置只接受 +# `version.configVersion` 返回的 31 是二进制报告值,不是 YAML 字段。配置只接受 # 本文列出的结构;未知字段、anchor、alias 和自定义 tag 都会失败。 # # 宿主先通过 Invoke API v5 调用 initialize({dataDir}),再通过 configYaml 内联 @@ -130,6 +130,24 @@ sniffer: # 下方 vless-edge 通过 upstream-select 当前选择的 socks-hop 建链: # 客户端 -> socks-hop -> vless-edge -> 目标。 proxies: + # TUIC v5:固定 QUIC/TLS1.3;必填 UUID 和原样 password(可空,最多 65535 UTF-8 字节)。 + # 不接受 v4、token、0-RTT、client-fingerprint、mTLS、ECH 或其他 TLS 后端选项。 + - name: tuic-edge + type: tuic + server: tuic.example.com + port: 443 + uuid: 00000000-0000-4000-8000-000000000004 + password: "synthetic-tuic-password" + sni: tuic.example.com # 缺省 server + alpn: [h3] # 缺省 h3;显式 [] 拒绝,保持非空列表顺序 + skip-cert-verify: false + # fingerprint: "" + # name-cert-verify: verified.example.com + congestion-controller: cubic # cubic(默认)/new_reno/bbr + udp: true # 缺省 false;只控制业务 UDP,QUIC 首跳始终需要数据报 + udp-relay-mode: native # native(默认)/quic + # dialer-proxy: upstream-select # 所选上游必须实际支持双向至少 1200 字节数据报 + # Hysteria2:固定 QUIC/TLS1.3,外层总是需要 UDP;业务 UDP 默认关闭。 # 完整字段/预算及开发验收边界见 outbounds.md#hysteria2。标准 TLS 证书策略与其他协议共用。 - name: hysteria2-edge @@ -212,8 +230,11 @@ proxies: # headers: {Host: cover.example:443, X-Custom: value} # max-early-data: 2048 # 0–2048,默认 0 # early-data-header-name: Sec-WebSocket-Protocol + # v2ray-http-upgrade: true # 默认 false;原始流,不发送 WebSocket 帧 + # v2ray-http-upgrade-fast-open: false # 仅 upgrade=true 可开启 # W04>0 时头名缺省为 Sec-WebSocket-Protocol;可显式自定义头,或空字符串 # 使用路径后缀(此时 path 不可含 query)。禁用 ED 时不接受无效的头名选项。 + # HTTPUpgrade 仅支持默认 ED 头,不接受自定义头或路径 ED;VMess 同样适用。 # 不接受保留握手头、重复大小写头、CR/LF、userinfo 或超限 HTTP 头。 # network: grpc # grpc-opts: @@ -333,6 +354,21 @@ proxies: cipher: 2022-blake3-aes-128-gcm password: "BwcHBwcHBwcHBwcHBwcHBw==" udp: true + # 可选 TCP 包装,两字段必须成对。仅 strict ShadowTLS v3 / TLS1.3。 + # UoT 默认关闭。开启须 udp: true,UDP 经 SS TCP(含可选插件),不回退原生 UDP。 + # udp-over-tcp: true + # udp-over-tcp-version: 2 # 开启时省略或整数 2;关闭时不得配置版本 + # 未启用 UoT 时,原生 SS UDP 仍单独发送,不经插件。 + # plugin: shadow-tls + # plugin-opts: + # version: 3 # 必填整数,仅 3 + # host: cover.example.com # 必填 DNS 名/IP,不是 SS 拨号地址 + # password: "independent-shadowtls-password" # 必填 1–65535 UTF-8 字节,不 trim + # alpn: [h2, http/1.1] # 缺省同此,[] 不发送;每项 1–255 字节 + # skip-cert-verify: false + # fingerprint: "" + # name-cert-verify: verified.example.com # 可选独立证书验证名 + # client-fingerprint: chrome # 仅有插件时允许;共享七值,缺省/none/空串关闭命名模板 # 可选的静态 `select` 代理组。字段外形是严格 Mihomo 子集:每组只接受 name、 # type、proxies 和可选 default-selected,type 只能是 select,proxies 至少一项。 @@ -352,8 +388,9 @@ proxies: # 当前节点的服务器而不是业务目标,REJECT 在建链时失败且不回退。单次建链对每个组 # 只读一次选择,SOCKS5 UDP 控制流与 relay 路径共用该快照和期限;不同组没有原子 # 快照保证。复用旧 AnyTLS 会话的新业务流仍沿用该会话路径,只有新建底层 transport -# 才读取新选择。已认证 Hysteria2 会话的新逻辑流和跳端口 socket 同样沿用初始上游 -# 快照,只有新建认证会话读取新选择。业务节点的 udp 开关不阻止上游通过 TCP 承载封装后的 UDP。 +# 才读取新选择。Hysteria2/TUIC 已建立会话的新逻辑流、Hysteria2 跳端口 socket +# 同样沿用初始上游快照,只有新建物理会话读取新选择。业务节点的 udp 开关不阻止 +# 上游通过 TCP 承载封装后的 UDP,也不替代 TUIC/Hysteria2 首跳的数据报能力检查。 proxy-groups: - name: upstream-select type: select diff --git a/docs/invoke-api.md b/docs/invoke-api.md index a4e5295..4087403 100644 --- a/docs/invoke-api.md +++ b/docs/invoke-api.md @@ -108,8 +108,8 @@ stopped -> preparing -> prepared -> starting -> running ```json { "apiVersion": 5, - "buildIdentity": "VCore;engine=rust;coreVersion=0.1.0;invokeApiVersion=5;configVersion=27", - "configVersion": 27, + "buildIdentity": "VCore;engine=rust;coreVersion=0.1.0;invokeApiVersion=5;configVersion=31", + "configVersion": 31, "engine": "rust", "version": "0.1.0" } diff --git a/docs/outbounds.md b/docs/outbounds.md index c8dd581..5973606 100644 --- a/docs/outbounds.md +++ b/docs/outbounds.md @@ -55,7 +55,8 @@ begin_shutdown 同步禁止新流、清空空闲并取消所有会话;shutdown ## Trojan -固定 TLS,network 为 tcp/标准 ws/grpc,默认 tcp。密码为非空原始 UTF-8,不 trim, +固定 TLS,network 为 tcp/ws/grpc,默认 tcp。ws 可选标准 WebSocket 或 HTTPUpgrade。 +密码为非空原始 UTF-8,不 trim, 认证为 SHA-224 小写十六进制。无认证 ACK:本地建链成功不代表密码通过,负例须检查 原站零业务字节。 @@ -65,6 +66,14 @@ WS http/1.1、gRPC h2,显式列表及实际协商均须满足传输,不能 WS path 默认 /,可带 query;头字段不得覆盖握手保留头或大小写重复。early-data 0–2048 字节,启用时默认 Sec-WebSocket-Protocol,可自定义;空头名表示路径后缀, 此时禁止 query。禁用时不能附 ED 头名。首请求头与剩余数据只按序发送一次。 +`ws-opts.v2ray-http-upgrade:true` 使用原始 HTTPUpgrade 流,不发送 WebSocket 帧。 +普通模式在有效 101 后发送剩余认证前缀;`v2ray-http-upgrade-fast-open:true` 提前 +发送该前缀,但仍须在原建链期限内收到有效 101 才返回成功。握手每次从等待恢复时 +先复核原期限,即使响应或写入已就绪也不能绕过;建立后的读写不再受该期限限制。 +fast-open 需要 upgrade。 +Upgrade 的 ED 仅允许默认 Sec-WebSocket-Protocol 头(大小写不敏感),不支持 +自定义头或路径 ED。101/头限额/截断失败不重放前缀,响应头后的字节保留给协议。 +这些选项同样适用于 VMess 的明文和标准 TLS;不改变各协议认证、UDP 编码或关闭责任。 gRPC service-name 必填,普通名映射 /name/Tun,以 / 开头则为完整路径;不开放池参数。 TCP 保留半关闭;gRPC duplex 发送 END_STREAM,不用 RST_STREAM 提前结束读侧。 @@ -72,6 +81,9 @@ UDP 使用同一已认证流上的地址/长度/CRLF 帧,无额外 socket/读 payload 最多 8192 字节,待解析最多 8455 字节,并与调用方收发预算分别取交集。 非法/截断帧关闭,合法超接收预算整包丢弃;取消读取保留进度,部分发送取消使关联失效。 运行时先取消并 join 入站所有者,再等待节点 gRPC 驱动。 +Mihomo 的 Trojan listener 仅支持 IP 形式的 UDP 目标;域名互通另用原生 Xray。 +Mihomo IP 路径可传空包;Xray 不转发空包,且域名回复的 8192 字节总帧预算需扣除 +地址和帧头。这些是对端限制,不降低 VCore 的独立帧解析上限。 ## VMess AEAD @@ -84,7 +96,7 @@ network 默认 tcp,另支持 ws/grpc/http/h2;均可明文或标准 TLS。tls 关闭时禁止 TLS 字段,即便空串、空列表或 false。认证名依次为 servername、WS Host 去端口、server;HTTP 伪装 Host/H2 authority 不替代认证名。WS 需 http/1.1,gRPC/H2 需 h2。 -- WS ED/路径/头约束同 Trojan。 +- WS ED/路径/头及 HTTPUpgrade 普通/fast-open 约束同 Trojan。 - gRPC service-name 必填,普通名/完整路径规则同 Trojan,无额外池调度器。 - http 是 TCP 首包伪装:method 默认 GET,path 列表省略/空为 /,按 URL.Path 转义; 头为字符串列表,每次握手独立选择路径/头值,Host 默认物理 server authority。 @@ -106,6 +118,7 @@ UDP packet-encoding 默认空串(raw),外层仍 TCP: UDP body 最多 15,000 字节;packetaddr 另扣 IPv4 7 / IPv6 19 字节,未解析域名按 19 预检;超限一字节即写前失败,不拆业务包。对端可能更小,V2Ray 部分返回路径总缓冲 仅 2048 字节,不能当作 VCore 上限。body wire 解析最多 16 KiB,响应头/XUDP 元数据有界。 +三种 UDP 编码均不接受零长度业务包;HTTPUpgrade 不改变这个边界。 TCP 写块最多 4 KiB 以适配 Mihomo 拷贝边界;UDP 不按此切块。16 位帧计数耗尽前关闭, 不重复 nonce。半帧发送取消关闭,接收取消保留进度;认证/地址/标签错误使关联失效。 gRPC/H2 driver 由节点跟踪并同步退出,无全局会话额度或历史表。 @@ -151,6 +164,43 @@ pacer;这是混淆不是认证,错误密钥由 QUIC 拒绝,短包有界丢 官方 Hysteria 已验证版本的 4096 字节回包缓冲包含头,更大回包可能在分片前丢弃。 原生测试记录实际版本和限制,VCore 完整 4096 字节另对 Mihomo 验证,不修改第三方。 +## TUIC v5 + +固定 QUIC/TLS 1.3,复用官方 Quinn、rustls/ring 与共享受控数据报适配器。 +仅 v5;必填标准 UUID 与原样 UTF-8 password,后者可空、最长 65,535 字节。 +SNI 缺省 server,ALPN 缺省 h3;显式空列表拒绝,非空有序列表必须实际协商命中。 +使用共享 pin/skip/独立验证名;无命名 TCP 指纹、mTLS、ECH、0-RTT 或跨节点恢复。 +拥塞使用官方 Quinn cubic(默认)、new_reno 或 bbr,不承诺与其他实现的吞吐相同。 + +认证使用当前真实 TLS 会话 exporter,UUID 为 label,原样 password 为 context。 +Authenticate 与 Connect 没有成功 ACK;本地 open 成功不是密码通过证明,错误身份 +必须由最终拒绝和原站零业务验证。Connect 为双向 QUIC 流,不引入 HTTP/3 请求。 +流关闭结束该逻辑双向通道,与 Mihomo 对齐,不影响兄弟流。 + +业务 udp 默认 false,但外层 QUIC 始终需要有效双向至少 1200 字节的数据报路径。 +未开放 DATAGRAM、预算不足、protect 失败或只支持 TCP 的上游均失败,不回退 TCP +或 DIRECT。`udp` 业务路由开关不替代上游实际数据报能力和预算检查。 +SS UoT、AnyTLS 与支持 UDP ASSOCIATE 的 SOCKS5 可作为上游;组快照绑定物理会话。 + +`udp-relay-mode` 为 native(默认)或 quic。native 使用 DATAGRAM,按实际容量拆为 +最多 255 片;quic 每包使用一条单向流,不受单 DATAGRAM MTU 限制,也不是 UoT。 +两者逐包携带 IPv4/IPv6/域名,业务负载取 u16 和调用方双向预算交集,超限不截断。 +未知关联不分配状态;每关联最多 64 个未完成包、256 KiB 分片负载、TTL 5 秒和 +32 项完成包交付队列。重复相同片忽略、冲突片丢弃;完成后释放 Packet ID,可回绕, +不做业务去重。发送过的关联关闭时发送有界 Dissociate,未发包关闭不创建对端状态。 + +每节点按需共享物理会话,流 credit 等待沿用调用方原期限。关联 ID 在同一物理会话 +不重用;65,536 个 ID 用尽后新业务新建会话,旧流继续,最后一个旧所有者退出即回收。 +TCP shutdown 立即完成逻辑关闭,发送所有权保留到 FIN/数据确认或最多 5 秒,防止 +退役池提前丢弃已接受的末尾上传;该等待归节点所有,Stop 直接取消并 join。 +切组不迁移已有池;故障后只有新业务可创建新池,已发送业务不自动重放。 + +每流接收窗口 256 KiB,连接收发各 1 MiB,DATAGRAM 收发各 256 KiB;最多 32 条 +入站单向控制流,半条控制流最长 5 秒;拒绝服务端主动双向流。QUIC payload 最大 +1400 并取路径预算交集,PMTUD 关闭。保活/Heartbeat 每 10 秒,空闲 30 秒;两种 +UDP 模式的 Heartbeat 均用 DATAGRAM。Stop 等待认证、收发、重组、心跳及上游释放, +关闭交换最多一秒;这些都是局部结构限制,不是全局业务会话额度。 + ## Shadowsocks 2022 原样复用官方 shadowsocks-rust,仅三算法: @@ -164,11 +214,53 @@ pacer;这是混淆不是认证,错误密钥由 QUIC 拒绝,短包有界丢 标准 Base64 可省末尾 padding;空段/非法编码/长度错误拒绝,凭据不 trim。 官方库只包装已有 TCP 流,UDP codec 单包有界交接,不调用其 socket 工厂。 -- TCP 每次最多交付 16 KiB;读或关闭先于首次写时,完成并刷新官方空首写以支持 - server-first/半关闭。Pending 继续同次握手,已有首写不重复目标头。 +### ShadowTLS v3 + +SS 三算法的 TCP 可配置 `plugin: shadow-tls` 与完整 `plugin-opts`,不是新的代理类型。 +仅整数 version 3,始终 strict/TLS 1.3;不提供 v1/v2、弱认证或版本回退。 +host 为独立 cover DNS 名/IP,不参与拨号或业务解析;password 保留原始 UTF-8。 +ALPN 缺省 `[h2, http/1.1]`、空列表不发送;共享 pin/skip/name-cert-verify 与 +节点 client-fingerprint 只影响 cover,不能替代 ShadowTLS 密码。 + +顺序为受控上游流 → 原生完整 TLS 握手与 relay 认证 → v3 记录流 → 官方 SS2022。 +借用原建链期限、取消和组快照,握手失败不发送 SS 目标或业务;pin/skip 不绕过 +CertificateVerify 或 Finished。独立 TLS 策略,不恢复 cover 会话。 +记录增量认证、未认证内容不交付;每次写最多 16 KiB,背压最多保留一条记录。 +flush 排空,关闭最多五秒,不在已切换的 SS 通道中发送 TLS close_notify。 + +原生 SS UDP 仍走独立受控 UDP 路径,**不经过 ShadowTLS**;TCP-only v3 服务端不会 +自动得到 UDP 或 UoT。裸 SS 拒绝 client-fingerprint。默认与 TUN 构建启用 +shadow-tls-v3,精简构建可单独移除;无 feature 的插件配置在 IO 前拒绝。 +v3 的额外四字节记录特征仍存在,完整认证和互通不等于不可识别。 + +### UDP over TCP v2 + +`udp-over-tcp` 默认 false;true 要求 `udp: true`,三算法均可用于裸 SS 或 +ShadowTLS v3。开启时 `udp-over-tcp-version` 省略或整数 2 均固定使用 v2; +关闭时不得提供版本,不支持 v1、协商或原生 UDP 降级。无 SS feature 在 IO 前拒绝。 + +每个关联独占一条既有 SS TCP 路径,支持 TCP-only SOCKS5 上游与 select 组。 +目标固定为 `sp.v2.udp-over-tcp.arpa:0`;v2 non-connect 请求只发送一次,之后每包 +携带地址和 u16 长度。业务域名先经过受控 `ResolutionContext` 转为 IP,magic 不参与 +DNS 或路由。AnyTLS 复用同一有界 codec,但保留自己的域名与会话/FIN 所有权。 + +SS 首包写入并 flush 成功前阻止后台读取;零长度 UDP 仍有非空 UoT 帧。 +延迟首包沿用原建链 deadline,成功建立后的业务不再使用旧期限。未发包关闭直接释放 +底层 IO,不触发官方空 SS 握手;半帧写取消使关联失效,不重发。每关联最多一个读取 +任务、一个排队响应及一个正在解析/等待入队的响应;接收取消不丢 parser 状态,超接收 +预算完整排空该包再读下一包。Stop 取消并等待读任务,释放流;不跨关联池化。 + +编码负载上限为 65,535 字节,发送/接收各自受调用方预算约束。当前官方 Mihomo +UoT 对端使用 16 KiB 接收缓冲;容器数据验收覆盖该实际边界与多一字节负例,不将 +内存中的 u16 上限宣称为端到端 UDP 能力。原样 ssserver 不支持 UoT,仅作拒绝负例。 + +### 共享 SS 流与数据报行为 + +- TCP 每次最多交付 16 KiB;读或关闭先于首次写时,完成并刷新官方空首写, + 但受下述空首包限制影响,不承诺可靠 server-first。Pending 继续同次握手,已有首写不重复目标头。 - 背压适配最多暂存一个 16 KiB 原文块并立即报告接受;后续保持同缓冲完成写入, 避免官方重试长度误计。flush/关闭排空,读取也推进待写但不被写背压阻塞。 -- UDP 取消前预留 packet ID,底层实际发送后才成功;Pending 不重编码,无后台发送队列。 +- 原生 UDP 取消前预留 packet ID,底层实际发送后才成功;Pending 不重编码,无后台发送队列。 接收验证来源、认证、关联与完整负载,外层 wire 最大 65,507。 - 每关联随机 client session ID、递增 packet ID,最多两个 server session 的 8128 包 重放窗口;旧 session 一分钟仍有有效包时不替换,ID 将溢出时换 client ID 并清空窗口。 @@ -183,8 +275,11 @@ shadowsocks-crypto 链使用,TLS/REALITY 不消费它,详见[TLS 依赖](tls **已知风险:**原样上游空 TCP 首写/空 UDP padding 路径扩展长度而未显式初始化, 存在把残留缓冲传给可解密对端的风险;普通 echo 或自有背压修复不代表此风险已解决。 官方空 TCP 首写还可能随机生成零 padding,被其严格服务端拒绝;VCore 不修改或重试 -该上游行为。内存回归分别验证适配器刷新与确定性的零 padding 拒绝,不将 codec -级回复算作 server-first 互通通过。 +该上游行为。裸 SS、EIH 和外包 ShadowTLS v3 的 TCP 均受影响;入站转发先轮询读取时, +即使业务计划随后发送请求,也可能触发空首写。TCP 数据验收使用已提交非空首段的 +client-first 路径,server-first/空首包列为已知限制,不计成功;其他协议的 server-first +要求不变。内存回归分别验证适配器刷新与确定性的零 padding 拒绝,不将 codec +级回复算作 server-first 互通通过。SS UoT 的非空请求帧与专用读取门控独立验证。 首次固定头不够单次读取时,上游按探测防护拒绝,不改成 read_exact。 Mihomo 仅提供单 PSK;原样 ssserver 验证 AES 单层 EIH 多用户 TCP/UDP 终结及错误身份。 MTU1500 大包夹具显式启用官方双向 IP 分片。自有 1/2 层身份中继不是原生任意多层证明。 diff --git a/docs/runtime-resource-policy.md b/docs/runtime-resource-policy.md index 1c39586..ac1bcd0 100644 --- a/docs/runtime-resource-policy.md +++ b/docs/runtime-resource-policy.md @@ -74,7 +74,7 @@ XUDP现在只拥有已认证流上的帧编码;VLESS响应头由VLESS包装层 ### 定向数据报预算与受控 QUIC -`DatagramBudget` 分别表达当前层的发送和接收 payload 上限。嵌套协议先为下层申请有界 envelope 空间,再按实际协议/地址族开销扣除下层能力,与调用方预算取交集;不能把接收上限直接当作发送能力。DIRECT、SOCKS5、SS 2022、AnyTLS UoT 和 VLESS XUDP 保留原来对端/地址校验。超出发送预算在写入前失败,超出接收预算丢当前包并有界让出执行权,close 后不能恢复收发。 +`DatagramBudget` 分别表达当前层的发送和接收 payload 上限。嵌套协议先为下层申请有界 envelope 空间,再按实际协议/地址族开销扣除下层能力,与调用方预算取交集;不能把接收上限直接当作发送能力。DIRECT、SOCKS5、SS 2022、SS/AnyTLS UoT 和 VLESS XUDP 保留对端/地址校验。超出发送预算在写入前失败,超出接收预算丢当前包并有界让出执行权,close 后不能恢复收发。UoT 的流头不从 UDP payload 预算扣除;SS 首包门控、读取任务与单响应队列的局部上限见[出站](outbounds.md#udp-over-tcp-v2)。 `quic-transport` 只把已有 `DatagramTransport` 适配成 Quinn 的受控 UDP 接口,没有内部 bind、DNS 或 DIRECT 回落。每个连接双向各最多32个排队数据报,另允许一个正在发送的包;TX满返回WouldBlock,RX满暂停读取。接收等待不会持有发送队列锁;Pending发送不会重复提交。单逻辑peer/物理peer映射和来源校验独立保留,不接受未请求的目标、GSO或源地址覆盖。物理 socket 仍只能来自 Dialer。 @@ -82,6 +82,11 @@ QUIC双向可用payload至少1,200字节;endpoint必须显式把QUIC MTU限制 QUIC owner.stop先取消并等待驱动,再关闭并释放上游;上游close最多1秒。Driver Drop仅为取消/abort兜底,不能作为同步Stop验收。队列容量是单连接局部界限,不是全局QUIC连接准入数。 +TUIC 与 Hysteria2 共用这一接点;TUIC 的独立会话、关联 ID 退役、控制流、分片负载 +及交付队列边界见 [TUIC v5](outbounds.md#tuic-v5)。旧池的待建流也持有所有权, +不能在等待 credit 时被当成空闲池回收。TUIC 业务 UDP 队列使用独立观测类别, +旧七协议压力 fixture 中该类别为零不代表 TUIC 压力通过。 + ## DNS - 不设置固定的活动请求或活动传输总许可数。 diff --git a/docs/tls-client-fingerprint.md b/docs/tls-client-fingerprint.md index b1abb7d..48f1aa3 100644 --- a/docs/tls-client-fingerprint.md +++ b/docs/tls-client-fingerprint.md @@ -23,7 +23,8 @@ AnyTLS、Trojan、VMess + TLS、VLESS + TLS/REALITY/JLS 使用同一共享连接器。 TCP、WS、gRPC、HTTP 首包伪装、legacy H2、Vision、XHTTP H1/H2 仍遵守各自的协议约束。 -关闭 TLS 时不能携带该字段。SOCKS5、SS 2022 不接入 TLS 指纹。 +关闭 TLS 时不能携带该字段。SS2022 + ShadowTLS v3 复用上述模板,作用于 cover +握手并强制 TLS1.3;其未命名握手也由 boring 执行。SOCKS5 和裸 SS 不接入 TLS 指纹。 XHTTP `download-settings.client-fingerprint` 缺省继承主腿,显式名称覆盖,`none` / 空串清除。 下载腿即使与主腿使用同一服务器,也拥有独立的 TLS 策略、身份和缓存。 @@ -42,7 +43,7 @@ client-fingerprint: chrome 不再要求公共根、名称或有效期;匹配非叶证书时将其作为信任锚,仍验证叶链、名称和有效期。 skip 只跳过常规验证,不能覆盖不匹配的 pin;所有策略仍验证握手签名。 - 未启用指纹的标准 TLS 和 QUIC 使用 crates.io 官方 rustls + ring,不依赖 rustls fork。 -- 命名指纹的标准 TLS,以及所有 REALITY/JLS,使用 release 分支并由 lockfile 锁定的自有 boring fork。 +- 命名指纹的标准 TLS,以及所有 REALITY/JLS,使用自有 boring fork;开发及 PR/发布的来源规则见 [TLS 依赖](tls-dependencies.md)。 - 普通 TLS 两条路径共用同一个 WebPKI 证书验证器和发布信任根;叶 pin、非叶信任锚、 独立验证名、skip 优先级不变。TLS 握手签名仍由各自后端强制验证。 - VLESS mTLS 继续使用配对的内联 PEM,密钥匹配在使用 IO 前检查;profile 不修改身份。 diff --git a/docs/tls-dependencies.md b/docs/tls-dependencies.md index b4abacd..61d545e 100644 --- a/docs/tls-dependencies.md +++ b/docs/tls-dependencies.md @@ -1,26 +1,37 @@ # TLS 依赖与发布 版本、完整 Git revision 和 registry 校验值以 Cargo.toml/Cargo.lock 为准, -由 `check tls-dependencies` 审核,不在文档复制一份易失效的包清单。 +PR/发布前由 `check tls-dependencies` 审核,不在文档复制一份易失效的包清单。 ## 来源与后端 | 用途 | 来源 / 约束 | | --- | --- | | 普通无指纹 TLS、QUIC、共享 WebPKI | crates.io 官方 rustls/tokio-rustls,仅 ring | -| 命名 ClientHello、REALITY、JLS | 自有 OneXray/boring 的 release 分支,由 lockfile 固定完整已发布 revision | +| 命名 ClientHello、REALITY、JLS、ShadowTLS v3 | 自有 OneXray/boring;开发用本地路径,PR/发布用 release 分支并由 lockfile 固定完整 revision | | SS 2022 | crates.io shadowsocks 版本依赖,原样官方库,仅 aead-cipher-2022 | | Encryption 原语 | 同一 boring 的公共 X25519、ML-KEM、AEAD、AES-CTR;官方 blake3 | | 静态 ECH | 官方 hpke,经 rustls 公开 HPKE trait;命名模板使用 boring 既有 ECH 接口 | -boring/tokio-boring/测试用 boring-sys 必须同源、同分支、同 revision;审计拒绝混合提交、 -未批准 revision、其他分支及本机 path/references/rustls Git patch。 +boring/tokio-boring/测试用 boring-sys 必须同源:开发时来自同一个本地 fork checkout, +PR/发布时来自同一个 release revision。PR/发布审计拒绝混合提交、未批准 revision、 +其他分支及本机 path/references/rustls Git patch。 旧 rustls fork 已退役,不是回退或重建来源。分支前移不会自动改变 locked 构建。 AWS-LC 只允许 shadowsocks → shadowsocks-crypto → aws-lc-rs → aws-lc-sys 链; 不能供 TLS/REALITY 使用。禁止额外消费者、FIPS 和 2022-extra。 SS 日志抑制与未修补风险见[出站](outbounds.md#shadowsocks-2022)。 +### 开发与 PR 的依赖切换 + +1. 本地开发将三个 crate 一起改为自有 fork checkout 的相对 `path` 依赖;保留版本和 + feature 约束,更新 Cargo.lock 后执行 locked 构建与相关测试,不混用本地和 Git 来源。 +2. 发起或更新 VCore PR 前,先将所需 fork 改动发布至 OneXray/boring 的 `release`, + 再将三个 crate 一起切回 `git = "https://github.com/OneXray/boring", branch = "release"`。 + 更新 Cargo.lock;若 revision 前移,同步依赖审计中的批准 revision。 +3. 在不依赖本地 fork 的 checkout 通过 `check tls-dependencies` 和相关验证后再提交 PR。 + 该命令是 PR/发布门禁,本地 path 开发态不要求通过,也不为开发态放宽来源检查。 + ## 身份与原生接口 VCore 负责策略和受控 IO,BoringSSL 拥有握手字节、认证状态和临时秘密。 @@ -30,7 +41,8 @@ REALITY 使用同一 X25519 临时密钥生成 share、ECDH 和 session ID;连 模板与 ALPS 限制见[TLS 指纹](tls-client-fingerprint.md),线格式见[REALITY](reality-wire-protocol.md)。 JLS hook 认证真正的 hello,保留 TLS 签名/Finished/记录保护;不可重试失败前清零, -非阻塞重试保留必要材料。其内部 ShadowTLS hook 依赖不等于支持 ShadowTLS。 +非阻塞重试保留必要材料。ShadowTLS v3 复用原生 ClientHello hook 和完整 TLS1.3 +认证,VCore 只包装受控 IO 的 relay 记录;未命名 cover 同样由 boring 执行。 Restls 不支持。所有 fork 补丁由 feature 控制,原始 BoringSSL 子模块不直接改写。 Encryption 的固定文本 context 使用官方 Rust blake3;二进制 context 使用 @@ -57,7 +69,8 @@ boring MIT/Apache-2.0、BoringSSL 随源通知及 Android C++ runtime,不能 ## 升级与回退 1. 选择官方最新稳定依赖;fork 同步上游并先完成普通 TLS 回归。 -2. fork 变更先发布至 release;同次修改 manifest、lockfile 和依赖审计的批准 revision。 +2. 本地按上述流程验证 fork 变更;PR 前发布至 release,同次修改 manifest、lockfile + 和依赖审计的批准 revision。 3. 重跑确定性向量、ClientHello/share/证书/签名、恢复/取消/期限及受影响容器数据面; 分别验证 AnyTLS 标准 TLS 和 REALITY/JLS,不能互相抵扣。 4. 在没有相邻 fork 目录的干净 checkout 执行 locked fetch、离线测试、相关平台构建和 diff --git a/docs/vless.md b/docs/vless.md index 58fbcc7..014c0c5 100644 --- a/docs/vless.md +++ b/docs/vless.md @@ -179,6 +179,6 @@ HTTP/H2/扩展 WS 可用 Xray TLS 网关 → V2Ray transport;需 UDP/Encryptio Mihomo 解码。网关使用官方 XRAY_BUF_SPLICE=disable,避免下行 raw splice 绕过 TLS; 不代表 V2Ray 直接支持 ECH。无指纹 JLS/gRPC 及 Safari ECH/gRPC 的官方对照缺口采用 明确标注的 Chrome 关闭参照;VCore 原配置的数据面单独验证,不声称同配置差分。 -动态 ECH、ShadowTLS、Restls 不支持,配置严格拒绝。 +VLESS 不接受动态 ECH、ShadowTLS 或 Restls 配置;ShadowTLS v3 仅用于 SS2022 插件。 WS + REALITY(普通 WS、HTTPUpgrade、fast-open)的数据及认证使用真实 Mihomo listener;关闭验证采用明确标注的分层参照。当前 Mihomo WS 客户端分支未接入 REALITY,不能作为同组合对照,因此使用标准 TLS 的同种传输客户端关闭基线,并独立验证 REALITY。不得将该结果写成 Mihomo WS + REALITY 客户端互通或同组合差分通过。 diff --git a/readme/README.ru.md b/readme/README.ru.md index 619942f..a97e7bc 100644 --- a/readme/README.ru.md +++ b/readme/README.ru.md @@ -4,10 +4,12 @@ English · 简体中文 · Русский

-VCore — независимое клиентское прокси-ядро на Rust, не привязанное к конкретному хост-приложению. Через строгую YAML-конфигурацию и Invoke API v5 оно предоставляет граф прокси, статические группы `select`, DNS, правила маршрутизации, GeoData, HTTP/SOCKS5 listeners, плоскость данных TUN и loopback Controller. Внутренняя ревизия схемы конфигурации — 27; она присутствует только в ответе `version` и `buildIdentity`, но не записывается в YAML. +VCore — независимое клиентское прокси-ядро на Rust, не привязанное к конкретному хост-приложению. Через строгую YAML-конфигурацию и Invoke API v5 оно предоставляет граф прокси, статические группы `select`, DNS, правила маршрутизации, GeoData, HTTP/SOCKS5 listeners, плоскость данных TUN и loopback Controller. Внутренняя ревизия схемы конфигурации — 28; она присутствует только в ответе `version` и `buildIdentity`, но не записывается в YAML. ## Возможности +SS2022 также поддерживает [strict ShadowTLS v3](../docs/outbounds.md#shadowtls-v3) для TCP; нативный UDP использует отдельный путь. + - Исходящие подключения: [VLESS TCP/WS/gRPC/HTTP/H2/XHTTP, TLS/REALITY и Vision](../docs/vless.md), SOCKS5 CONNECT/UDP ASSOCIATE, AnyTLS TCP/UoT, Shadowsocks 2022, [Trojan TCP/UDP через TLS/WS/gRPC](../docs/outbounds.md#trojan), [VMess AEAD через TCP/WS/gRPC/HTTP/H2](../docs/outbounds.md#vmess-aead), [Hysteria2 TCP/UDP, управление скоростью, Salamander и смена портов](../docs/outbounds.md#hysteria2) и DIRECT. - Цепочки прокси: `dialer-proxy` образует ориентированный ациклический граф произвольной длины. Если узел A указывает на B, физический путь имеет вид `client -> B -> A -> target`. - Группы прокси: статические группы `select` сохраняют порядок участников; участниками могут быть конкретные узлы, вложенные группы, `DIRECT` и `REJECT`. Выбор текущей session можно менять через Controller. `dialer-proxy` принимает узел или группу; DIRECT в группе верхнего уровня подключается к заранее разрешённому серверу текущего узла. diff --git a/readme/README.zh_CN.md b/readme/README.zh_CN.md index 334dab0..befa405 100644 --- a/readme/README.zh_CN.md +++ b/readme/README.zh_CN.md @@ -4,10 +4,12 @@ English · 简体中文 · Русский

-VCore 是独立且不绑定特定宿主应用的 Rust 客户端代理 core。它通过严格 YAML 配置和 Invoke API v5 提供代理图、静态 `select` 代理组、DNS、规则、GeoData、HTTP/SOCKS5 listener、TUN 数据面与回环 Controller。内部配置 schema revision 为 27;revision 只出现在 `version` 响应和 `buildIdentity` 中,不写入 YAML。 +VCore 是独立且不绑定特定宿主应用的 Rust 客户端代理 core。它通过严格 YAML 配置和 Invoke API v5 提供代理图、静态 `select` 代理组、DNS、规则、GeoData、HTTP/SOCKS5 listener、TUN 数据面与回环 Controller。内部配置 schema revision 为 28;revision 只出现在 `version` 响应和 `buildIdentity` 中,不写入 YAML。 ## 能力 +SS2022 另支持 [strict ShadowTLS v3](../docs/outbounds.md#shadowtls-v3) TCP 包装;原生 UDP 仍走独立路径。 + - Outbound:[VLESS TCP/WS/gRPC/HTTP/H2/XHTTP、TLS/REALITY 与 Vision](../docs/vless.md)、SOCKS5 CONNECT/UDP ASSOCIATE、AnyTLS TCP/UoT、Shadowsocks 2022、[Trojan TCP/UDP(TLS/WS/gRPC)](../docs/outbounds.md#trojan)、[VMess AEAD(TCP/WS/gRPC/HTTP/H2)](../docs/outbounds.md#vmess-aead)、[Hysteria2 TCP/UDP、带宽、Salamander 与端口跳跃](../docs/outbounds.md#hysteria2)、DIRECT。 - 代理链:`dialer-proxy` 组成任意长度的有向无环图;节点 A 指向 B 时,物理路径为 `client -> B -> A -> target`。 - 代理组:静态 `select` 组保留有序成员,可包含具体节点、嵌套组、`DIRECT` 与 `REJECT`;当前 session 的选择可通过 Controller 实时修改。`dialer-proxy` 可引用节点或组;上游组的 DIRECT 连接当前节点预解析的服务器。 diff --git a/scripts/README.md b/scripts/README.md index 35c00bc..d547a48 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -14,6 +14,7 @@ cargo fmt --all -- --check uv run --project scripts --locked ruff check scripts uv run --project scripts --locked ruff format --check scripts uv run --project scripts --locked vcore-scripts check c-header +# PR/发布来源门禁;本地 boring path 开发态不执行。 uv run --project scripts --locked vcore-scripts check tls-dependencies ``` @@ -44,7 +45,7 @@ uv run --project scripts --locked vcore-scripts check protocol-coverage --suite uv run --project scripts --locked vcore-scripts check protocol-coverage --catalog-only ``` -可执行容器 suite:vmess、vless、xhttp、hysteria2、security、integration。 +可执行容器 suite:vmess、vless、xhttp、hysteria2、security、integration、shadowtls、uot、tuic、httpupgrade。 `--case` 可重复、`--protocol` 可筛选;子集只证明实际执行的项目,不能签收整套。 foundations/trojan 保留基础用例和断言,其旧服务端编排尚未全容器化,不能执行; 需要 Trojan 互通时用 integration 中的真实容器路径。 @@ -62,6 +63,56 @@ SECURITY-ECH-CHROME;不再提供阶段编号或 --stage 别名。旧报告保 目录并清理,不进入报告。Stop 时和后续静默窗口分别采样;短 tracer 不代替完整长测。 容器不可用即 BLOCKED,不能退回宿主。完整规则见[测试隔离](../docs/testing-isolation.md)。 +shadowtls 包含配置/feature、真实 TLS 内存负例、三算法与五种握手模式、ALPN/HRR、 +记录故障、Stop/测速期限和原生 UDP 分流;主对端为 Mihomo,官方 ShadowTLS + +原样 ssserver 另作 TCP 对照。裸 SS、共享 TLS/REALITY/JLS、独立指纹 golden 与 +Apple/Android 编译是同轮必需组;不签收 UoT、实机或旧 SS 空首包风险。 + +uot 验证 SS v2 三算法 × 裸流/v3 的六组合,分别经直连、TCP-only SOCKS5 和 +嵌套 select;覆盖零包、三地址族、交替原站、16 KiB Mihomo 边界/超限和零原生 UDP +旁路。错误密钥/v3 身份及原样 ssserver 不支持是独立负例。内存检查另验 u16 上限、 +预算、首包门控、DNS、取消与 Stop;AnyTLS、裸 SS、精简 feature 和 Apple/Android +是同轮必需回归。使用 protocol-interop / check protocol-coverage 的 `--suite uot`。 + +tuic 覆盖 v5 的双向 TCP、native/quic UDP、三种官方拥塞算法、认证/TLS 负例和 +SOCKS5/SS UoT/AnyTLS 六种上游组合。服务端与上游分容器,避免触发 Mihomo 的 +同进程回环检测;不关闭对端检测或修改其源码。会话重用/重建、嵌套组、node-only 测速、 +回滚与 Stop 独立取证;本轮包含 HY2/H3 共享回归及 Apple/Android 构建。 +内存 u16 上限不当成对端端到端容量,旧七协议压力结果不替代 TUIC 混合压力。 + +httpupgrade 覆盖 VMess 明文/TLS、Trojan TLS × 普通/fast-open 六种模式; +包含双向数据、既有 UDP 编码、ED、身份负例、四个命名 TLS 模板及 Mihomo 关闭对照。 +域名 Trojan UDP 用原生 Xray 补验;VMess 与 Xray 的空包限制分别记录,不把超限 +回复截断计为成功。共享配置/内存握手、VLESS Upgrade/WS、其他 VMess/Trojan +传输、精简 feature 和 Apple/Android 构建均为同轮必需组。 +使用 `protocol-interop` / `protocol-coverage` 的 `--suite httpupgrade`。 + +integration 保留 64 个八协议有序配对,另加 TUIC 双模式 → SS v3 三算法六条链, +复跑 UoT 的 TCP-only 上游/嵌套组及 TUIC 上游消费者。公开入站/TUN、DNS/测速、 +回滚和 100 次生命周期与 100 轮 40-flow 重建、1800 秒混合长测属于同一完整门禁。 +TCP 为 SOCKS5/SS v3/TUIC/HTTPUpgrade 各五条,UDP 为 SS UoT/SS UoT+v3/ +TUIC/HTTPUpgrade 各五条,轮换算法与模式;独立核对逐轮实际配置、资源和静默证据。 +Debug/Release、精简 feature、脚本、netstack、HY2 跳端口和共享安全/传输回归同源重跑。 +integration 可在获准的本地 boring 开发态执行,不替代 release 来源审计;PR/交付候选 +仍须切回 release 分支,在干净 checkout 单独通过 `check tls-dependencies` 并重跑集成。 +SS TCP 数据用客户端预先提交的非空首段验证;SS 叶节点的配对记录明确包含 +`server_first:false` 和上游空首包限制,其他叶节点仍须 server-first。此范围调整不 +减小双向数据量、不移除确定性空首包拒绝回归,也不通过重试取得成功。 + +### 新协议对端能力预检 + +```sh +uv run --project scripts --locked vcore-scripts check protocol-peers --run-dir target/interop/runs/ +``` + +独立的原站/cover、Mihomo 服务端与 Mihomo 对照客户端都在容器中。当前检查 SS2022 +三算法的 v3/原生 UDP、裸流及 v3 上的 UoT v2、TUIC v5 双 UDP 模式、六种 +VMess/Trojan HTTPUpgrade 承载和 SOCKS5 上游;UoT 对照显式选择 v2,关闭服务端原生 UDP。 +`--case` 可选单项,语义 ID 由 `protocol_completion_peers.py` 生成。 +每项必须实际完成 TCP 回传与原站观测的 UDP 请求/回复;记录来源、官方版本/hash、 +原始观测及清理。该工具只证明对端能力,**VCore 新协议行为始终记 NOT RUN**, +不更新生产配置、不代替协议 suite、负例/边界、压力或发布验收。 + ### 对端下载 ```sh diff --git a/scripts/fixtures/platform_abi.c b/scripts/fixtures/platform_abi.c index e2c05b8..f9f947c 100644 --- a/scripts/fixtures/platform_abi.c +++ b/scripts/fixtures/platform_abi.c @@ -30,8 +30,8 @@ int main(int argc, char **argv) { char *response = invoke("{\"apiVersion\":5,\"method\":\"version\",\"payload\":{}}"); int valid = response && strstr(response, "\"success\":true") && strstr(response, "\"apiVersion\":5") - && strstr(response, "\"configVersion\":27") - && strstr(response, "VCore;engine=rust;coreVersion=0.1.0;invokeApiVersion=5;configVersion=27"); + && strstr(response, "\"configVersion\":31") + && strstr(response, "VCore;engine=rust;coreVersion=0.1.0;invokeApiVersion=5;configVersion=31"); release(response); if (!valid) return 20; } diff --git a/scripts/src/vcore_scripts/builds.py b/scripts/src/vcore_scripts/builds.py index b75c758..f60b511 100644 --- a/scripts/src/vcore_scripts/builds.py +++ b/scripts/src/vcore_scripts/builds.py @@ -13,12 +13,12 @@ from pathlib import Path CORE_DIR = Path(__file__).resolve().parents[3] EXPECTED_IDENTITY = ( - b"VCore;engine=rust;coreVersion=0.1.0;invokeApiVersion=5;configVersion=27" + b"VCore;engine=rust;coreVersion=0.1.0;invokeApiVersion=5;configVersion=31" ) DEFAULT_FEATURES = ( "ffi,tun,inbound-http,inbound-socks5,outbound-anytls," "outbound-socks5,outbound-shadowsocks,outbound-trojan,outbound-vmess,outbound-vless," - "outbound-hysteria2" + "outbound-hysteria2,outbound-tuic,shadow-tls-v3" ) diff --git a/scripts/src/vcore_scripts/cli.py b/scripts/src/vcore_scripts/cli.py index e1f0deb..9b0934e 100644 --- a/scripts/src/vcore_scripts/cli.py +++ b/scripts/src/vcore_scripts/cli.py @@ -82,6 +82,12 @@ def _parser() -> argparse.ArgumentParser: action="store_true", help="probe real download-leg client-identity enforcement only", ) + peers = checks.add_parser( + "protocol-peers", + help="verify isolated official peer capabilities, not VCore acceptance", + ) + peers.add_argument("--run-dir", type=Path, required=True) + peers.add_argument("--case", dest="identifiers", action="append") gateway = checks.add_parser( "xhttp-gateway", help="build xcaddy and test isolated H3/mTLS native topology", @@ -127,6 +133,7 @@ def _parser() -> argparse.ArgumentParser: "vmess", "vless", "hysteria2", + "tuic", ], ) modes = protocol.add_mutually_exclusive_group() @@ -182,6 +189,10 @@ def main(argv: Sequence[str] | None = None) -> int: from .protocol_xhttp_peers import main as xhttp_peers return xhttp_peers(args.run_dir, identities_only=args.identities_only) + elif args.check == "protocol-peers": + from .protocol_completion_peers import run + + run(args.run_dir, identifiers=args.identifiers) elif args.check == "xhttp-gateway": from .protocol_xhttp_gateway import main as xhttp_gateway diff --git a/scripts/src/vcore_scripts/container_protocol_client.py b/scripts/src/vcore_scripts/container_protocol_client.py new file mode 100644 index 0000000..9d1dfe7 --- /dev/null +++ b/scripts/src/vcore_scripts/container_protocol_client.py @@ -0,0 +1,110 @@ +"""Container-only comparison client for matched official protocol peers.""" + +import json +import os +import socket +import struct +import sys +from pathlib import Path + + +def exact(stream, size): + data = bytearray() + while len(data) < size: + part = stream.recv(size - len(data)) + if not part: + raise ValueError("truncated peer response") + data.extend(part) + return bytes(data) + + +def socks(stream, command, host, port): + stream.sendall(b"\x05\x01\x00") + if exact(stream, 2) != b"\x05\x00": + raise ValueError("SOCKS authentication failed") + stream.sendall( + bytes([5, command, 0, 1]) + socket.inet_aton(host) + struct.pack("!H", port) + ) + header = exact(stream, 4) + if header[:3] != b"\x05\x00\x00": + raise ValueError("SOCKS request failed") + if header[3] == 1: + address = socket.inet_ntop(socket.AF_INET, exact(stream, 4)) + elif header[3] == 4: + address = socket.inet_ntop(socket.AF_INET6, exact(stream, 16)) + else: + raise ValueError("unexpected SOCKS bound address") + return address, struct.unpack("!H", exact(stream, 2))[0] + + +def probe(option, origin): + """One real TCP exchange and two origin-observed UDP exchanges, no retry.""" + ingress = (option["socks_host"], option["socks_port"]) + payload = bytes(range(256)) * 4 + with socket.create_connection((origin, 24000), timeout=10) as control: + control.sendall(b"\x0d") + port = struct.unpack("!H", exact(control, 2))[0] + with socket.create_connection(ingress, timeout=10) as stream: + socks(stream, 1, origin, port) + stream.sendall(payload) + if exact(control, 1) != b"A" or exact(stream, len(payload)) != payload: + raise ValueError("TCP origin exchange differs") + with ( + socket.create_connection((origin, 24000), timeout=10) as control, + socket.create_connection(ingress, timeout=10) as association, + socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as udp, + ): + control.sendall(b"\x04") + port = struct.unpack("!H", exact(control, 2))[0] + relay = socks(association, 3, "0.0.0.0", 0) + # The ingress explicitly listens on IPv4, so no host/system DNS is used. + if relay[0] == "0.0.0.0": + relay = (option["socks_host"], relay[1]) + udp.settimeout(10) + udp.connect(relay) + header = ( + b"\x00\x00\x00\x01" + socket.inet_aton(origin) + struct.pack("!H", port) + ) + for size in (64, 1200): + payload = bytes(index % 251 for index in range(size)) + if udp.send(header + payload) != len(header) + size: + raise ValueError("partial UDP submission") + observed, _source = struct.unpack("!HH", exact(control, 4)) + if observed != size or exact(control, observed) != payload: + raise ValueError("UDP origin exchange differs") + if udp.recv(65536) != header + payload: + raise ValueError("UDP reply differs") + return dict( + case_id=option["case_id"], + status="PASS", + tcp_bytes_each_direction=1024, + udp_origin_packets=2, + udp_reply_packets=2, + udp_sizes=[64, 1200], + ) + + +def main(): + if sys.platform != "linux" or os.environ.get("VCORE_ISOLATED_CLIENT") != "1": + raise SystemExit("isolated container harness required") + fixture = json.loads(Path(sys.argv[1]).read_text()) + for option in fixture["cases"]: + try: + record = probe(option, fixture["origin"]) + except (OSError, ValueError) as error: + print( + json.dumps( + dict( + case_id=option["case_id"], + status="FAIL", + error=type(error).__name__, + ) + ), + flush=True, + ) + raise SystemExit(1) from None + print(json.dumps(record), flush=True) + + +if __name__ == "__main__": + main() diff --git a/scripts/src/vcore_scripts/container_restart_peer.py b/scripts/src/vcore_scripts/container_restart_peer.py new file mode 100644 index 0000000..5eef0a9 --- /dev/null +++ b/scripts/src/vcore_scripts/container_restart_peer.py @@ -0,0 +1,63 @@ +"""Restart only this guest's owned, unmodified protocol child on a fixture command.""" + +from __future__ import annotations + +import os +import select +import socket +import subprocess +import sys +import time + + +def terminate(peer): + peer.terminate() + try: + peer.wait(timeout=3) + except subprocess.TimeoutExpired: + peer.kill() + peer.wait(timeout=3) + + +def start(argv): + peer = subprocess.Popen(argv) + try: + until = time.monotonic() + 10 + while peer.poll() is None and time.monotonic() < until: + try: + with socket.create_connection(("127.0.0.1", 23999), timeout=0.1): + return peer + except OSError: + time.sleep(0.05) + raise RuntimeError("owned protocol child not ready") + except BaseException: + terminate(peer) + raise + + +def main(): + if sys.platform != "linux" or os.environ.get("VCORE_ISOLATED_ORIGIN") != "1": + raise SystemExit("isolated restart peer required") + peer = start(sys.argv[1:]) + try: + with socket.socket() as control: + control.bind(("0.0.0.0", 23998)) + control.listen(4) + while peer.poll() is None: + ready, _, _ = select.select([control], [], [], 0.1) + if not ready: + continue + client, _ = control.accept() + with client: + client.settimeout(2) + if client.recv(1) == b"R": + terminate(peer) + peer = start(sys.argv[1:]) + client.sendall(b"R") + raise RuntimeError("owned protocol child exited") + finally: + terminate(peer) + + +if __name__ == "__main__": + main() diff --git a/scripts/src/vcore_scripts/container_shadowtls_fault.py b/scripts/src/vcore_scripts/container_shadowtls_fault.py new file mode 100644 index 0000000..990b219 --- /dev/null +++ b/scripts/src/vcore_scripts/container_shadowtls_fault.py @@ -0,0 +1,203 @@ +"""Bounded container TCP fault relay around an unmodified official ShadowTLS peer. + +Only observes record framing/tags to locate faults; never terminates TLS or SS. +""" + +from __future__ import annotations + +import contextlib +import hashlib +import hmac +import json +import os +import socket +import sys +import threading +from pathlib import Path + +ROOT = Path("/data/fixture") +EVENTS = Path("/data/fault-events.jsonl") +LOCK = threading.Lock() +SLOTS = threading.BoundedSemaphore(16) +STALL = {"hello_seen": 0, "client_closed": 0} +PASSWORD = b"synthetic-shadowtls-fixture" +HRR = "cf21ad74e59a6111be1d8c021e65b891c2a211167abb8c5e079e09e2c8a8339c" + + +def emit(mode, **fields): + with LOCK, EVENTS.open("a") as output: + output.write(json.dumps(dict(mode=mode, **fields)) + "\n") + if mode == "stall": + for key in STALL: + STALL[key] += fields.get(key) is True + + +def observe(): + with socket.socket(socket.AF_INET) as listener: + listener.bind(("0.0.0.0", 23998)) + listener.listen(4) + while True: + client, _ = listener.accept() + with client: + client.settimeout(2) + try: + if client.recv(1) == b"?": + with LOCK: + data = json.dumps(STALL).encode() + client.sendall(data) + except OSError: + pass + + +def exact(raw, count): + data = bytearray() + while len(data) < count: + part = raw.recv(count - len(data)) + if not part: + if data: + raise EOFError("truncated fixture record") + return None + data.extend(part) + return bytes(data) + + +def record(raw): + header = exact(raw, 5) + if header is None: + return None + size = int.from_bytes(header[3:5], "big") + if not 0 < size <= 18436: + raise ValueError("record bound") + body = exact(raw, size) + if body is None: + raise EOFError("record body missing") + return header + body + + +def upload(client, upstream): + try: + while data := client.recv(16384): + upstream.sendall(data) + upstream.shutdown(socket.SHUT_WR) + except OSError: + pass + + +def serve(client, mode, target): + upstream = None + worker = None + try: + with client: + client.settimeout(15) + if mode == "stall": + # Observe a real client hello, then await the client's deadline + # or Stop. No business or cover destination is contacted. + if record(client) is None: + return # Readiness probes are not real stalled handshakes. + emit(mode, hello_seen=True) + while client.recv(16384): + pass + emit(mode, client_closed=True) + return + upstream = socket.create_connection(target, timeout=10) + upstream.settimeout(15) + client.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + worker = threading.Thread(target=upload, args=(client, upstream)) + worker.start() + cover = business = None + count = 0 + mutated = False + while (data := record(upstream)) is not None: + count += 1 + if data[0] == 22 and cover is None: + if len(data) < 43 or data[5] != 2: + raise ValueError("expected ServerHello") + seed = data[11:43] + cover = hmac.new(PASSWORD, seed, hashlib.sha1) + business = hmac.new(PASSWORD, seed + b"S", hashlib.sha1) + if seed.hex() == HRR: + emit(mode, hrr_seen=True) + if data[0] == 23: + if len(data) < 9 or cover is None or business is None: + raise ValueError("authenticated record expected") + trial = cover.copy() + trial.update(data[9:]) + is_cover = hmac.compare_digest(trial.digest()[:4], data[5:9]) + if is_cover: + cover = trial + else: + trial = business.copy() + trial.update(data[9:]) + if not hmac.compare_digest(trial.digest()[:4], data[5:9]): + raise ValueError("unclassified official record") + trial.update(data[5:9]) + business = trial + if not mutated and ( + (mode == "cover-mac" and is_cover) + or ( + mode in {"business-mac", "business-truncated"} + and not is_cover + ) + ): + mutated = True + emit( + mode, + injected=True, + phase="cover" if is_cover else "business", + ) + if mode == "business-truncated": + client.sendall(data[:8]) + client.shutdown(socket.SHUT_WR) + break + changed = bytearray(data) + changed[5] ^= 1 + data = bytes(changed) + if mode == "fragment" and count <= 8: + # The same authenticated records, with split headers and + # short writes; afterwards data remain bulk, not 10M syscalls. + for begin, end in ((0, 1), (1, 3), (3, 5), (5, 9), (9, len(data))): + if end > begin: + client.sendall(data[begin:end]) + emit(mode, split_record=True) + else: + client.sendall(data) + except (OSError, EOFError, ValueError): + pass + finally: + for raw in (client, upstream): + if raw is not None: + with contextlib.suppress(OSError): + raw.shutdown(socket.SHUT_RDWR) + raw.close() + if worker is not None: + worker.join(timeout=2) + if worker.is_alive(): + emit(mode, upload_join_failed=True) + SLOTS.release() + + +def listen(item): + with socket.socket(socket.AF_INET) as listener: + listener.bind(("0.0.0.0", item["port"])) + listener.listen(16) + while True: + client, _ = listener.accept() + if not SLOTS.acquire(blocking=False): + client.close() + continue + threading.Thread( + target=serve, + args=(client, item["mode"], (item["server"], item["server_port"])), + daemon=True, + ).start() + + +if __name__ == "__main__": + if sys.platform != "linux" or os.environ.get("VCORE_ISOLATED_ORIGIN") != "1": + raise SystemExit("isolated fault relay required") + EVENTS.touch() + threading.Thread(target=observe, daemon=True).start() + items = json.loads((ROOT / "config.json").read_text()) + for item in items[1:]: + threading.Thread(target=listen, args=(item,), daemon=True).start() + listen(items[0]) diff --git a/scripts/src/vcore_scripts/container_shadowtls_peer.py b/scripts/src/vcore_scripts/container_shadowtls_peer.py new file mode 100644 index 0000000..535ff08 --- /dev/null +++ b/scripts/src/vcore_scripts/container_shadowtls_peer.py @@ -0,0 +1,70 @@ +"""Container-only ShadowTLS cover variations; no proxy protocol implementation.""" + +from __future__ import annotations + +import json +import os +import socket +import ssl +import sys +import threading +from pathlib import Path + +import origin + +EVENTS = Path("/data/cover-events.jsonl") +LOCK = threading.Lock() +SLOTS = threading.BoundedSemaphore(16) + + +def event(**value): + with LOCK, EVENTS.open("a") as output: + output.write(json.dumps(value) + "\n") + + +def handle(raw, context, port): + try: + with raw: + raw.settimeout(5) + with context.wrap_socket(raw, server_side=True) as tls: + event( + port=port, version=tls.version(), alpn=tls.selected_alpn_protocol() + ) + tls.recv(1) + except OSError: + pass + finally: + SLOTS.release() + + +def cover(port, version, curve): + context = origin.tls_context(version) + context.set_ecdh_curve(curve) + context.set_alpn_protocols(["h2", "http/1.1", "fixture-custom"]) + with socket.socket(socket.AF_INET) as listener: + listener.bind(("0.0.0.0", port)) + listener.listen(16) + while True: + raw, _ = listener.accept() + if not SLOTS.acquire(blocking=False): + raw.close() + continue + threading.Thread( + target=handle, args=(raw, context, port), daemon=True + ).start() + + +if __name__ == "__main__": + if sys.platform != "linux" or os.environ.get("VCORE_ISOLATED_ORIGIN") != "1": + raise SystemExit("isolated ShadowTLS fixture required") + EVENTS.touch() + for port, version, curve in ( + (24001, ssl.TLSVersion.TLSv1_3, "X25519"), + (24002, ssl.TLSVersion.TLSv1_3, "secp384r1"), + (24003, ssl.TLSVersion.TLSv1_2, "X25519"), + ): + threading.Thread(target=cover, args=(port, version, curve), daemon=True).start() + # This fixture owns the cover workers; the shared origin still owns its + # independent TCP/UDP control channel and business-byte observations. + origin.camouflage = lambda: None + origin.main() diff --git a/scripts/src/vcore_scripts/container_udp_origin.py b/scripts/src/vcore_scripts/container_udp_origin.py index 27d4a85..fae46ba 100644 --- a/scripts/src/vcore_scripts/container_udp_origin.py +++ b/scripts/src/vcore_scripts/container_udp_origin.py @@ -37,7 +37,7 @@ def receive_exact(stream, size): def serve_tcp(control, mode, ipv6=False): - """10=bulk/server-first, 11=close differential, 12=identity probe. + """10=bulk/server-first, 22=bulk/client-first, 11=close, 12=identity probe. Observer A proves an actual accept; D proves exact request bytes and normal completion. Rejected identities must produce neither. No host-side server. @@ -112,8 +112,9 @@ def serve_tcp(control, mode, ipv6=False): raise ValueError("identity probe data") stream.sendall(b"ok") else: - stream.sendall(b"hello") - if mode in (10, 16, 18): + if mode != 22: + stream.sendall(b"hello") + if mode in (10, 16, 18, 22): data = receive_exact(stream, 10 * 1024 * 1024) if data != b"\x5a" * len(data): raise ValueError("bulk data") @@ -138,7 +139,7 @@ def serve(control): control.settimeout(15) control.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) family = control.recv(1) - if family and (family[0] & 0x7F) in (*range(10, 17), 18, 21): + if family and (family[0] & 0x7F) in (*range(10, 17), 18, 21, 22): serve_tcp(control, family[0] & 0x7F, bool(family[0] & 0x80)) return if family not in (b"\x04", b"\x06", b"\x11", b"\x13", b"\x14"): diff --git a/scripts/src/vcore_scripts/container_uot_watch.py b/scripts/src/vcore_scripts/container_uot_watch.py new file mode 100644 index 0000000..7997cfb --- /dev/null +++ b/scripts/src/vcore_scripts/container_uot_watch.py @@ -0,0 +1,67 @@ +"""Run an unmodified peer with a bounded UDP-side-channel observer in its guest. + +The official server still owns every TCP listener. These otherwise unused UDP +ports detect accidental native SS fallback; the observer never replies to UDP. +""" + +from __future__ import annotations + +import contextlib +import json +import os +import select +import socket +import subprocess +import sys +from pathlib import Path + + +def main(): + if sys.platform != "linux" or os.environ.get("VCORE_ISOLATED_ORIGIN") != "1": + raise SystemExit("isolated UoT peer required") + config = json.loads(Path("/data/fixture/config.json").read_text()) + native = "servers" in config + ports = [ + item["server_port" if native else "port"] + for item in config["servers" if native else "listeners"] + ] + if not 1 <= len(ports) <= 32 or len(ports) != len(set(ports)): + raise ValueError("bounded unique peer ports required") + with contextlib.ExitStack() as stack: + watchers = [] + for port in ports: + udp = stack.enter_context(socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)) + udp.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0) + udp.bind(("::", port)) + watchers.append(udp) + observer = stack.enter_context(socket.socket()) + observer.bind(("0.0.0.0", 23998)) + observer.listen(4) + counts = dict(ports=ports, native_udp_packets=0) + with subprocess.Popen(sys.argv[1:]) as peer: + try: + while peer.poll() is None: + ready, _, _ = select.select([*watchers, observer], [], [], 0.1) + # Drain UDP before answering a snapshot in the same cycle. + for udp in watchers: + if udp in ready: + udp.recvfrom(65536) + counts["native_udp_packets"] += 1 + if observer in ready: + client, _ = observer.accept() + with client: + client.settimeout(1) + if client.recv(1) == b"?": + client.sendall(json.dumps(counts).encode()) + raise RuntimeError("official UoT peer exited") + finally: + peer.terminate() + try: + peer.wait(timeout=3) + except subprocess.TimeoutExpired: + peer.kill() + peer.wait(timeout=3) + + +if __name__ == "__main__": + main() diff --git a/scripts/src/vcore_scripts/core_checks.py b/scripts/src/vcore_scripts/core_checks.py index 199fbcd..31211f2 100644 --- a/scripts/src/vcore_scripts/core_checks.py +++ b/scripts/src/vcore_scripts/core_checks.py @@ -14,7 +14,16 @@ from .protocol_peers import run_command FEATURE_TEST = ( "runtime::tests::integration_feature_admission_is_explicit_without_opening_sockets" ) -PROTOCOLS = ("socks5", "anytls", "shadowsocks", "trojan", "vmess", "vless", "hysteria2") +PROTOCOLS = ( + "socks5", + "anytls", + "shadowsocks", + "trojan", + "vmess", + "vless", + "hysteria2", + "tuic", +) TARGETS = ( "ech_config", "ech_tls", @@ -39,7 +48,16 @@ TARGETS = ( "hysteria2_paths", "hysteria2_config", "shadowsocks_backpressure", + "shadowtls_config", + "shadowtls_stream", + "uot_config", + "shadowsocks_uot", "hysteria2_packet_ids", + "tuic_config", + "tuic_memory", + "httpupgrade_config", + "httpupgrade_memory", + "vmess_lifecycle", ) LIB_FILTERS = ( "security::", @@ -48,6 +66,8 @@ LIB_FILTERS = ( "outbound::hysteria2::", "outbound::shadowsocks::tests::official_tcp_", "outbound::anytls::", + "outbound::uot::", + "outbound::tuic::", "transport::h2_write::tests::", "transport::sing_mux::smux_driver::tests::", "transport::sing_mux::tests::", @@ -91,6 +111,7 @@ def commands(profile: str) -> list[list[str]]: *features, "stream-transport", "quic-transport", + "shadow-tls-v3", "tun", "ffi", ] diff --git a/scripts/src/vcore_scripts/native_release.py b/scripts/src/vcore_scripts/native_release.py index a2b5852..b838af5 100644 --- a/scripts/src/vcore_scripts/native_release.py +++ b/scripts/src/vcore_scripts/native_release.py @@ -62,6 +62,11 @@ def _download_native( ) target = f"{platform.system().lower()}-{architecture}" assets = { + "ST": ( + "ihciah/shadow-tls", + "shadow-tls", + {"linux-arm64": "shadow-tls-aarch64-unknown-linux-musl"}, + ), "SS": ( "shadowsocks/shadowsocks-rust", "ssserver", @@ -136,7 +141,7 @@ def _download_native( ): _https_response(response) archive_hash = _copy_and_hash(response, output, MAX_ARCHIVE_BYTES) - if kind == "H": + if kind in {"H", "ST"}: with archive.open("rb") as source, executable.open("wb") as output: binary_hash = _copy_and_hash(source, output, MAX_BINARY_BYTES) elif kind == "SS": @@ -149,7 +154,7 @@ def _download_native( version = None if not defer_version: result = run_command( - [str(executable), "--version" if kind == "SS" else "version"], + [str(executable), "--version" if kind in {"SS", "ST"} else "version"], timeout=10, limit=4096, ) diff --git a/scripts/src/vcore_scripts/protocol_catalogs.py b/scripts/src/vcore_scripts/protocol_catalogs.py index fa73c08..247731f 100644 --- a/scripts/src/vcore_scripts/protocol_catalogs.py +++ b/scripts/src/vcore_scripts/protocol_catalogs.py @@ -25,6 +25,10 @@ SUITES = { "HYSTERIA2": ("tcp", "udp", "bandwidth", "salamander", "hopping", "acceptance"), "SECURITY": ("encryption", "reality", "ech", "jls", "acceptance"), "INTEGRATION": ("routing", "lifecycle", "pressure", "regression"), + "SHADOWTLS": ("configuration", "stream", "interop", "regression"), + "UOT": ("configuration", "datagrams", "interop", "regression"), + "TUIC": ("configuration", "datagrams", "interop", "regression"), + "HTTPUPGRADE": ("configuration", "stream", "interop", "regression"), } CATEGORIES = { f"{suite}.{category}" diff --git a/scripts/src/vcore_scripts/protocol_completion_peers.py b/scripts/src/vcore_scripts/protocol_completion_peers.py new file mode 100644 index 0000000..fd69510 --- /dev/null +++ b/scripts/src/vcore_scripts/protocol_completion_peers.py @@ -0,0 +1,366 @@ +"""Official peer capability fixtures, never VCore protocol acceptance.""" + +from __future__ import annotations + +import base64 +import contextlib +import json +import shutil +import tempfile +from dataclasses import dataclass +from pathlib import Path + +from .builds import CORE_DIR +from .mihomo_isolation import exclusive_run +from .mihomo_release import download_mihomo +from .protocol_containers import ContainerLab, frozen_image +from .protocol_fixtures import certificates +from .protocol_hysteria2_hop import guest +from .protocol_inputs import redact, same_source, source_identity + + +@dataclass(frozen=True) +class PeerCase: + identifier: str + protocol: str + cipher: str = "" + shadow_tls: bool = False + uot: bool = False + tls: bool = False + fast_open: bool = False + udp_mode: str = "" + + +CASES = ( + tuple( + PeerCase( + f"ss-{algorithm}-{mode}", + "ss", + f"2022-blake3-{algorithm}", + shadow_tls=shadow_tls, + uot=uot, + ) + for algorithm in ("aes-128-gcm", "aes-256-gcm", "chacha20-poly1305") + for mode, shadow_tls, uot in ( + ("shadowtls", True, False), + ("uot-v2", False, True), + ("shadowtls-uot-v2", True, True), + ) + ) + + tuple( + PeerCase(f"tuic-v5-{mode}", "tuic", tls=True, udp_mode=mode) + for mode in ("native", "quic") + ) + + tuple( + PeerCase( + f"{protocol}-upgrade-{'tls' if tls else 'plain'}" + f"-{'fast' if fast else 'normal'}", + protocol, + tls=tls, + fast_open=fast, + ) + for protocol, tls in (("vmess", False), ("vmess", True), ("trojan", True)) + for fast in (False, True) + ) + + (PeerCase("socks5-upstream", "socks5"),) +) + + +def peer_configuration(case, *, server, cover, port, certificate): + """Build matched Mihomo endpoints with explicit latest-only wire choices.""" + cert, key, pin = certificate + if case.protocol != "ss": + password = "synthetic-protocol-fixture" + identity = "07070707-0707-0707-0707-070707070707" + listener = dict( + name=case.identifier, type=case.protocol, listen="::", port=port + ) + node = dict( + name=case.identifier, type=case.protocol, server=server, port=port, udp=True + ) + if case.tls: + listener.update( + certificate=f"/data/fixture/{cert.name}", + **{"private-key": f"/data/fixture/{key.name}"}, + ) + node.update(fingerprint=pin) + if case.protocol == "socks5": + listener.update(type="socks", udp=True) + elif case.protocol == "tuic": + listener.update(users={identity: password}, alpn=["h3"]) + node.update(uuid=identity, password=password, sni="localhost", alpn=["h3"]) + node["udp-relay-mode"] = case.udp_mode + else: + if case.protocol == "vmess": + listener["users"] = [dict(username="fixture", uuid=identity, alterId=0)] + node.update(uuid=identity, alterId=0, cipher="auto", tls=case.tls) + node["packet-encoding"] = "xudp" + if case.tls: + node["servername"] = "localhost" + elif case.protocol == "trojan": + listener["users"] = [dict(username="fixture", password=password)] + node.update(password=password, sni="localhost") + else: + raise ValueError("unsupported peer capability") + listener["ws-path"] = "/protocol-upgrade" + node["network"] = "ws" + node["ws-opts"] = { + "path": "/protocol-upgrade", + "headers": {"Host": "localhost"}, + "v2ray-http-upgrade": True, + "v2ray-http-upgrade-fast-open": case.fast_open, + } + return node, listener + password = base64.b64encode( + bytes([7]) * (16 if case.cipher == "2022-blake3-aes-128-gcm" else 32) + ).decode() + listener = dict( + name=case.identifier, + type="shadowsocks", + listen="::", + port=port, + cipher=case.cipher, + password=password, + udp=not case.uot, + ) + node = dict( + name=case.identifier, + type="ss", + server=server, + port=port, + cipher=case.cipher, + password=password, + udp=True, + ) + if case.uot: + node.update({"udp-over-tcp": True, "udp-over-tcp-version": 2}) + if case.shadow_tls: + credential = "synthetic-shadowtls-fixture" + listener["shadow-tls"] = { + "enable": True, + "version": 3, + "users": [dict(name="fixture", password=credential)], + "handshake": dict(dest=cover), + "strict-mode": True, + } + node["plugin"] = "shadow-tls" + node["plugin-opts"] = dict( + host="localhost", password=credential, version=3, fingerprint=pin + ) + return node, listener + + +def run(output, *, identifiers=None): + output = output.resolve() + if not output.is_relative_to((CORE_DIR / "target/interop/runs").resolve()): + raise ValueError("peer evidence must stay inside target/interop/runs") + selected = ( + CASES + if identifiers is None + else tuple(case for case in CASES if case.identifier in identifiers) + ) + if not selected or ( + identifiers is not None + and ( + len(identifiers) != len(set(identifiers)) + or len(selected) != len(identifiers) + ) + ): + raise ValueError("unknown or repeated peer capability selection") + report = dict( + scope="official-peer-capability-only", + vcore_behavior="NOT RUN", + status="NOT RUN", + source=source_identity(), + peer={}, + isolation={}, + selected=[case.identifier for case in selected], + cases=[], + cleanup=False, + ) + output.mkdir(parents=True, exist_ok=False) + try: + with exclusive_run(), frozen_image(output / "image-pull.log") as image: + report["container_image"] = image + binary = download_mihomo( + "linux-arm64", directory=output / "binary", identity=report["peer"] + ) + lab = ContainerLab(report["isolation"], mtu=1500) + with tempfile.TemporaryDirectory( + prefix="private-", dir=output + ) as temporary: + root = Path(temporary) + directories, peers = {}, {} + try: + with contextlib.ExitStack() as stack: + for role in ("origin", "server", "client"): + directory = root / role + directory.mkdir() + directories[role] = directory + if role == "origin": + shutil.copy2( + Path(__file__).with_name("container_udp_origin.py"), + directory / "origin.py", + ) + argv = [ + "env", + "VCORE_ISOLATED_ORIGIN=1", + "VCORE_ORIGIN_CERT=/data/fixture/cert.pem", + "VCORE_ORIGIN_KEY=/data/fixture/key.pem", + "python", + "-B", + "/data/fixture/origin.py", + ] + else: + shutil.copy2(binary, directory / "mihomo") + argv = [ + "/data/fixture/mihomo", + "-d", + "/data", + "-f", + "/data/fixture/config.json", + ] + peers[role] = lab.start(stack, directory, role, argv) + origin, server, client = ( + peers[r] for r in ("origin", "server", "client") + ) + report["peer"]["version"] = guest( + server, "/data/fixture/mihomo", "-v" + ).strip() + for peer in (server, client): + if ( + guest( + peer, "sha256sum", "/data/fixture/mihomo" + ).split()[0] + != report["peer"]["binary_sha256"] + ): + raise RuntimeError( + "container peer differs from official download" + ) + certificate = certificates(directories["server"]) + for path, name in zip( + certificate[:2], ("cert.pem", "key.pem"), strict=True + ): + shutil.copy2(path, directories["origin"] / name) + nodes, listeners, ingresses, options = [], [], [], [] + for index, case in enumerate(selected): + node, listener = peer_configuration( + case, + server=server.ipv4, + cover=f"{origin.ipv4}:24001", + port=23000 + index, + certificate=certificate, + ) + nodes.append(node) + listeners.append(listener) + ingresses.append( + dict( + name=case.identifier, + type="socks", + listen=client.ipv4, + port=25000 + index, + udp=True, + proxy=case.identifier, + ) + ) + options.append( + dict( + case_id=case.identifier, + socks_host=client.ipv4, + socks_port=25000 + index, + ) + ) + server_config = { + "socks-port": 23999, + "allow-lan": True, + "bind-address": "*", + "ipv6": True, + "log-level": "warning", + "listeners": listeners, + "rules": ["MATCH,DIRECT"], + } + client_config = { + "ipv6": True, + "log-level": "warning", + "proxies": nodes, + "listeners": ingresses, + "rules": ["MATCH,REJECT"], + } + for role, configuration in ( + ("server", server_config), + ("client", client_config), + ): + (directories[role] / "config.json").write_text( + json.dumps(configuration) + ) + shutil.copy2( + Path(__file__).with_name("container_protocol_client.py"), + directories["client"] / "probe.py", + ) + (directories["client"] / "fixture.json").write_text( + json.dumps(dict(origin=origin.ipv4, cases=options)) + ) + for peer in peers.values(): + peer.release() + origin.wait_tcp(24000) + origin.wait_tcp(24001) + server.wait_tcp(23999) + client.wait_tcp(25000) + raw = guest( + client, + "env", + "VCORE_ISOLATED_CLIENT=1", + "python", + "-B", + "/data/fixture/probe.py", + "/data/fixture/fixture.json", + timeout=30 * len(selected), + ) + (output / "observations.jsonl").write_text(raw) + rows = [ + json.loads(line) + for line in raw.splitlines() + if line.strip() + ] + expected = [ + dict( + case_id=case.identifier, + status="PASS", + tcp_bytes_each_direction=1024, + udp_origin_packets=2, + udp_reply_packets=2, + udp_sizes=[64, 1200], + ) + for case in selected + ] + if rows != expected: + raise RuntimeError( + "official peer data evidence is incomplete" + ) + report["cases"] = rows + finally: + # A failed start may already own a VM/log before returning + # its peer. ExitStack has joined it; preserve that log too. + for role, directory in directories.items(): + log = directory / "peer.log" + if log.is_file(): + (output / f"{role}.log").write_text( + redact(log.read_text(errors="replace")) + ) + report["status"] = "PASS" + except BaseException as error: + report["status"] = "FAIL" + report["failure_kind"] = type(error).__name__ + (output / "failure.log").write_text(redact(str(error))) + raise + finally: + report["cleanup"] = all( + peer.get("joined") is True for peer in report["isolation"].get("peers", []) + ) + report["source_unchanged"] = same_source(report["source"], source_identity()) + if not report["cleanup"] or not report["source_unchanged"]: + report["status"] = "FAIL" + (output / "report.json").write_text(json.dumps(report, indent=2) + "\n") + if report["status"] != "PASS": + raise RuntimeError("peer capability ownership or source evidence failed") + print(f"Official peer capabilities: {len(selected)} PASS; VCore behavior: NOT RUN") diff --git a/scripts/src/vcore_scripts/protocol_evidence.py b/scripts/src/vcore_scripts/protocol_evidence.py index b93d29a..03df3c5 100644 --- a/scripts/src/vcore_scripts/protocol_evidence.py +++ b/scripts/src/vcore_scripts/protocol_evidence.py @@ -91,9 +91,13 @@ def read_json(path: Path): def executable_cases() -> list[dict]: """Single source: retained foundation fixtures plus current protocol catalogs.""" + from .protocol_httpupgrade_catalog import definitions as httpupgrade from .protocol_hysteria2_catalog import definitions as hysteria2 from .protocol_integration_catalog import definitions as integration from .protocol_security_catalog import definitions as security + from .protocol_shadowtls_catalog import definitions as shadowtls + from .protocol_tuic_catalog import definitions as tuic + from .protocol_uot_catalog import definitions as uot from .protocol_vless_acceptance import definitions as vless from .protocol_vmess_acceptance import definitions as vmess from .protocol_xhttp_acceptance import definitions as xhttp @@ -101,7 +105,18 @@ def executable_cases() -> list[dict]: foundation = read_json(CATALOG_DIR / "foundation-cases.json")["cases"] return foundation + [ case - for define in (vmess, vless, xhttp, hysteria2, security, integration) + for define in ( + vmess, + vless, + xhttp, + hysteria2, + security, + integration, + shadowtls, + uot, + tuic, + httpupgrade, + ) for case in define() ] @@ -311,6 +326,10 @@ def validate_results(required: list[dict], results: list[dict]) -> None: "HYSTERIA2", "SECURITY", "INTEGRATION", + "SHADOWTLS", + "UOT", + "TUIC", + "HTTPUPGRADE", } else "foundation-only" ) @@ -358,7 +377,19 @@ def new_result(case: dict) -> dict: "peer_kind": case["peer_kind"], "scope": "protocol-consumer" if case["stage"] - in {"TROJAN", "VMESS", "VLESS", "XHTTP", "HYSTERIA2", "SECURITY", "INTEGRATION"} + in { + "TROJAN", + "VMESS", + "VLESS", + "XHTTP", + "HYSTERIA2", + "SECURITY", + "INTEGRATION", + "SHADOWTLS", + "UOT", + "TUIC", + "HTTPUPGRADE", + } else "foundation-only", "status": "NOT RUN", "assertions": {}, @@ -420,6 +451,10 @@ def check_run(run_dir: Path, stage: str, manifest: Path | None = None) -> None: "HYSTERIA2", "SECURITY", "INTEGRATION", + "SHADOWTLS", + "UOT", + "TUIC", + "HTTPUPGRADE", }: if stage == "TROJAN": from .protocol_trojan_acceptance import check @@ -433,6 +468,14 @@ def check_run(run_dir: Path, stage: str, manifest: Path | None = None) -> None: from .protocol_hysteria2_acceptance import check elif stage == "SECURITY": from .protocol_security_acceptance import check + elif stage == "SHADOWTLS": + from .protocol_shadowtls_acceptance import check + elif stage == "UOT": + from .protocol_uot_acceptance import check + elif stage == "TUIC": + from .protocol_tuic_acceptance import check + elif stage == "HTTPUPGRADE": + from .protocol_httpupgrade_acceptance import check else: from .protocol_integration_acceptance import check diff --git a/scripts/src/vcore_scripts/protocol_fingerprint_shape.py b/scripts/src/vcore_scripts/protocol_fingerprint_shape.py index af053a1..3f24944 100644 --- a/scripts/src/vcore_scripts/protocol_fingerprint_shape.py +++ b/scripts/src/vcore_scripts/protocol_fingerprint_shape.py @@ -178,9 +178,10 @@ def check_warm_captures(rows): def run(output): - if output.parent != CORE_DIR / "target/interop/runs": - raise ValueError("use a fresh directory directly under target/interop/runs") - output.mkdir(exist_ok=False) + output = output.resolve() + if not output.is_relative_to((CORE_DIR / "target/interop/runs").resolve()): + raise ValueError("use a fresh directory under target/interop/runs") + output.mkdir(parents=True, exist_ok=False) report = dict( stage="FINGERPRINT-WIRE", scope="memory-clienthello-structure", diff --git a/scripts/src/vcore_scripts/protocol_harness.py b/scripts/src/vcore_scripts/protocol_harness.py index 31eb25a..5606b4c 100644 --- a/scripts/src/vcore_scripts/protocol_harness.py +++ b/scripts/src/vcore_scripts/protocol_harness.py @@ -459,7 +459,27 @@ def run_protocol_interop( try: run.update(run_identity(stage, selected, preflight_only)) with exclusive_run(), deadline(run["suite_timeout_seconds"]): - if preflight_only and stage == "INTEGRATION": + if preflight_only and stage == "HTTPUPGRADE": + from .protocol_httpupgrade_acceptance import ( + preflight as upgrade_preflight, + ) + + upgrade_preflight(output) + elif preflight_only and stage == "TUIC": + from .protocol_tuic_acceptance import preflight as tuic_preflight + + tuic_preflight(output) + elif preflight_only and stage == "UOT": + from .protocol_uot_acceptance import preflight as uot_preflight + + uot_preflight(output) + elif preflight_only and stage == "SHADOWTLS": + from .protocol_shadowtls_acceptance import ( + preflight as shadowtls_preflight, + ) + + shadowtls_preflight(output) + elif preflight_only and stage == "INTEGRATION": from .protocol_integration_acceptance import ( preflight as integration_preflight, ) @@ -542,6 +562,22 @@ def run_protocol_interop( elif stage == "INTEGRATION": from .protocol_integration_acceptance import execute + execute(selected, run, output, records) + elif stage == "SHADOWTLS": + from .protocol_shadowtls_acceptance import execute + + execute(selected, run, output, records) + elif stage == "UOT": + from .protocol_uot_acceptance import execute + + execute(selected, run, output, records) + elif stage == "TUIC": + from .protocol_tuic_acceptance import execute + + execute(selected, run, output, records) + elif stage == "HTTPUPGRADE": + from .protocol_httpupgrade_acceptance import execute + execute(selected, run, output, records) else: _execute(selected, run, output, records) @@ -616,6 +652,22 @@ def run_protocol_interop( else "Seven-protocol integration; container-only peers. " "Partial selections do not sign off lifecycle or soak gates.\n\n" if stage == "INTEGRATION" + else "SS2022 ShadowTLS v3; official Mihomo and native peers " + "in isolated containers. " + "UoT and device delivery remain separate gates.\n\n" + if stage == "SHADOWTLS" + else "SS2022 UoT v2; TCP-only official peers in isolated containers. " + "Native unsupported peers are negative cases; " + "devices remain separate.\n\n" + if stage == "UOT" + else "TUIC v5 TCP/native UDP/quic UDP; isolated official Mihomo. " + "Shared Hysteria2 and XHTTP H3 regressions included; " + "devices remain separate.\n\n" + if stage == "TUIC" + else "VMess/Trojan HTTPUpgrade normal/fast-open; " + "official isolated peers and existing transport regressions. " + "Device delivery is separate.\n\n" + if stage == "HTTPUPGRADE" else "Foundation-only evidence; " "production protocol field consumers remain NOT RUN.\n\n" ) diff --git a/scripts/src/vcore_scripts/protocol_httpupgrade.py b/scripts/src/vcore_scripts/protocol_httpupgrade.py new file mode 100644 index 0000000..c95dcf8 --- /dev/null +++ b/scripts/src/vcore_scripts/protocol_httpupgrade.py @@ -0,0 +1,554 @@ +"""Public HTTPUpgrade consumers against owned official release containers.""" + +from __future__ import annotations + +import contextlib +import json +import os +import shutil +import tempfile +from pathlib import Path + +from .builds import CORE_DIR +from .mihomo_isolation import exclusive_run +from .mihomo_release import download_mihomo +from .native_release import download_native +from .protocol_completion_peers import CASES, peer_configuration +from .protocol_containers import ContainerLab, command, frozen_image +from .protocol_evidence import read_events +from .protocol_fixtures import certificates +from .protocol_hysteria2_catalog import assertions_pass +from .protocol_inputs import redact, same_source, source_identity +from .protocol_peers import run_command +from .protocol_security_acceptance import rust_command + +CHECKS = ("tcp", "udp", "udp-domain", "early-data", "profiles", "negative", "close") + + +def selection(checks): + rows = [] + for case in CASES: + if case.protocol not in {"vmess", "trojan"}: + continue + if checks == "udp-domain" and case.protocol != "trojan": + continue + if checks == "profiles" and not case.tls: + continue + variants = ( + ("raw", "xudp", "packetaddr") + if checks == "udp" and case.protocol == "vmess" + else ("raw",) + if checks == "udp" + else ("domain",) + if checks == "udp-domain" + else ("ed1", "ed2048") + if checks == "early-data" + else ("chrome", "chrome120", "firefox", "safari") + if checks == "profiles" + else ("identity", "path") + (("certificate",) if case.tls else ()) + if checks == "negative" + else ("",) + ) + for variant in variants: + consumer = ( + "udp" + if checks.startswith("udp") + else "echo_and_stop" + if checks in {"early-data", "profiles"} + else "rejected" + if checks == "negative" + else checks + ) + rows.append( + ( + case.identifier + ("-" + variant if variant else ""), + case, + variant, + consumer, + ) + ) + return rows + + +def configure(node, checks, variant): + if checks == "udp" and node["type"] == "vmess": + node["packet-encoding"] = "" if variant == "raw" else variant + elif checks == "early-data": + node["ws-opts"].update( + {"max-early-data": int(variant[2:]), "path": "/protocol-upgrade?probe=once"} + ) + elif checks == "profiles": + node["client-fingerprint"] = variant + elif checks == "negative": + if variant == "identity": + node["uuid" if node["type"] == "vmess" else "password"] = ( + "08080808-0808-0808-0808-080808080808" + ) + elif variant == "certificate": + node["fingerprint"] = "00" * 32 + elif variant == "path": + node["ws-opts"]["path"] = "/wrong" + + +def families(node, kind): + return ( + ["domain"] + if kind == "XR" + else ["ipv4", "ipv6"] + if node["type"] == "trojan" + else ["ipv4", "ipv6", "domain"] + ) + + +def expected_observation(consumer, node=None, kind="M"): + if consumer == "echo_and_stop": + return dict(authenticated_echo=True, live_stream_cancelled=True, stop_idle=True) + if consumer == "rejected": + return dict(origin_connected=False, received_business_bytes=0, stop_idle=True) + if consumer == "tcp": + return dict( + families=["ipv4", "ipv6", "domain"], + tcp_bytes_each_family_each_direction=10 * 1024 * 1024, + server_first=True, + client_first=True, + stop_idle=True, + ) + if consumer == "udp": + vmess = node["type"] == "vmess" + rows = [] + for family in families(node, kind): + cap = ( + 15000 + - ( + (7 if family == "ipv4" else 19) + if node.get("packet-encoding") == "packetaddr" + else 0 + ) + if vmess + else 8166 + if kind == "XR" + else 8192 + ) + sizes = ([] if vmess or kind == "XR" else [0]) + [1, 64, 512, 1200, cap] + rows.append(dict(family=family, sizes=sizes, packets=len(sizes) * 100)) + return dict( + udp=rows, + zero_no_delivery=vmess or kind == "XR", + oversize_rejected=True, + tcp_sibling=True, + stop_idle=True, + ) + raise ValueError("unknown HTTPUpgrade consumer") + + +def measure_close(lab, root, output, binary, origin, node, name): + directory = root / (name + "-reference") + directory.mkdir() + shutil.copy2(binary, directory / "peer") + reference = dict(node, name="reference") + (directory / "config.json").write_text( + json.dumps( + { + "socks-port": 23002, + "allow-lan": True, + "bind-address": "*", + "ipv6": True, + "log-level": "warning", + "proxies": [reference], + "rules": ["MATCH,reference"], + } + ) + ) + with contextlib.ExitStack() as stack: + peer = lab.start( + stack, + directory, + name + "-reference", + ["/data/fixture/peer", "-d", "/data", "-f", "/data/fixture/config.json"], + ) + peer.release() + peer.wait_tcp(23002) + measured = run_command( + [ + "container", + "exec", + origin.name, + "env", + "VCORE_ISOLATED_ORIGIN=1", + "python", + "-B", + "/data/fixture/close.py", + peer.ipv4, + origin.ipv4, + ], + timeout=30, + ) + (output / (name + "-close-command.log")).write_text( + redact(measured.stdout.decode(errors="replace")) + ) + if measured.returncode or not measured.cleanup: + raise RuntimeError("official HTTPUpgrade close comparison failed") + value = json.loads(measured.stdout) + if ( + set(value) != {"tail_hex", "terminated", "variant"} + or value["terminated"] is not True + or value["variant"] != "plain" + ): + raise RuntimeError("invalid official close observation") + (output / (name + "-reference.log")).write_text( + redact((directory / "peer.log").read_text(errors="replace")) + ) + (output / (name + "-close-reference.json")).write_text(json.dumps(value) + "\n") + return value + + +def events_pass(events, consumer): + expected = {("HTTPUPGRADE-PUBLIC", consumer): 1} + if consumer == "tcp": + expected[("HTTPUPGRADE-BASE", "tcp_10mib_both_directions")] = 3 + return assertions_pass(events, expected) + + +def native_configuration(rows, certificate, origin): + cert, key, _ = certificate + return dict( + log={"loglevel": "warning"}, + dns={"hosts": {"vcore-fixture.test": origin}}, + inbounds=[ + dict( + listen="::", + port=node["port"], + protocol="trojan", + settings={"clients": [{"password": node["password"]}]}, + streamSettings={ + "network": "httpupgrade", + "security": "tls", + "tlsSettings": { + "alpn": ["http/1.1"], + "certificates": [ + { + "certificateFile": "/data/fixture/" + cert.name, + "keyFile": "/data/fixture/" + key.name, + } + ], + }, + "httpupgradeSettings": { + "path": "/protocol-upgrade", + "host": "localhost", + }, + }, + ) + for _, node, _, _ in rows + ], + outbounds=[dict(protocol="freedom", settings={"domainStrategy": "UseIPv4"})], + ) + + +def run(output, *, checks="tcp", selected=None, supplied=None, image=None): + if checks not in CHECKS: + raise ValueError("unknown HTTPUpgrade check") + kind = "XR" if checks == "udp-domain" else "M" + output = output.resolve() + if not output.is_relative_to((CORE_DIR / "target/interop/runs").resolve()): + raise ValueError("HTTPUpgrade evidence must stay in target/interop/runs") + cases = selection(checks) + if selected is not None: + if ( + not selected + or len(set(selected)) != len(selected) + or not set(selected) <= {c[0] for c in cases} + ): + raise ValueError("unknown or repeated HTTPUpgrade selection") + cases = [c for c in cases if c[0] in selected] + output.mkdir(parents=True, exist_ok=False) + report = dict( + source=source_identity(), + status="NOT RUN", + peer={}, + peer_kind=kind, + isolation={}, + cases=[], + ) + try: + with ( + exclusive_run() if supplied is None else contextlib.nullcontext(), + frozen_image(output / "image-pull.log") + if image is None + else contextlib.nullcontext(image) as image, + ): + report["container_image"] = image + if supplied is None and kind == "M": + binary = download_mihomo( + "linux-arm64", directory=output / "binary", identity=report["peer"] + ) + elif supplied is None: + artifact = download_native( + kind, output / "binary", "linux-arm64", defer_version=True + ) + binary, report["peer"] = artifact.binary, artifact.identity + else: + binary, report["peer"] = supplied + built = run_command( + [ + "cargo", + "test", + "--locked", + "--all-features", + "--test", + "vless_public", + "--no-run", + ], + cwd=CORE_DIR, + timeout=180, + ) + (output / "build.log").write_text( + redact(built.stdout.decode(errors="replace")) + ) + if built.returncode or not built.cleanup: + raise RuntimeError("HTTPUpgrade consumer build failed") + lab = ContainerLab(report["isolation"], mtu=1500) + with tempfile.TemporaryDirectory(prefix="private-", dir=output) as tmp: + root = Path(tmp) + directories = {role: root / role for role in ("origin", "server")} + for directory in directories.values(): + directory.mkdir() + certificate = certificates(directories["server"]) + shutil.copy2(binary, directories["server"] / "peer") + shutil.copy2( + Path(__file__).with_name("container_udp_origin.py"), + directories["origin"] / "origin.py", + ) + shutil.copy2( + Path(__file__).with_name("container_close_client.py"), + directories["origin"] / "close.py", + ) + try: + with contextlib.ExitStack() as stack: + origin = lab.start( + stack, + directories["origin"], + "origin", + [ + "env", + "VCORE_ISOLATED_ORIGIN=1", + "python", + "-B", + "/data/fixture/origin.py", + ], + ) + server = lab.start( + stack, + directories["server"], + "server", + [ + "/data/fixture/peer", + "-d", + "/data", + "-f", + "/data/fixture/config.json", + ] + if kind == "M" + else [ + "/data/fixture/peer", + "run", + "-c", + "/data/fixture/config.json", + ], + ) + report["peer"]["version"] = command( + "exec", + server.name, + "/data/fixture/peer", + "-v" if kind == "M" else "version", + ).strip() + if ( + command( + "exec", server.name, "sha256sum", "/data/fixture/peer" + ).split()[0] + != report["peer"]["binary_sha256"] + ): + raise RuntimeError("HTTPUpgrade peer identity mismatch") + rows = [] + for i, (name, case, variant, consumer) in enumerate(cases): + node, listener = peer_configuration( + case, + server=server.ipv4, + cover="", + port=23000 + i, + certificate=certificate, + ) + node["name"] = "peer" + listener["name"] = name + configure(node, checks, variant) + rows.append( + ( + name, + node, + listener, + consumer, + ) + ) + (directories["server"] / "config.json").write_text( + json.dumps( + { + "socks-port": 23999, + "allow-lan": True, + "bind-address": "*", + "ipv6": True, + "log-level": "warning", + "hosts": {"vcore-fixture.test": origin.ipv4}, + "listeners": [r[2] for r in rows], + "rules": ["MATCH,DIRECT"], + } + if kind == "M" + else native_configuration( + rows, certificate, origin.ipv4 + ) + ) + ) + checked = run_command( + [ + "container", + "exec", + server.name, + "/data/fixture/peer", + "-t", + "-d", + "/data", + "-f", + "/data/fixture/config.json", + ] + if kind == "M" + else [ + "container", + "exec", + server.name, + "/data/fixture/peer", + "run", + "-test", + "-c", + "/data/fixture/config.json", + ], + timeout=30, + ) + (output / "peer-config.log").write_text( + redact(checked.stdout.decode(errors="replace")) + ) + if checked.returncode or not checked.cleanup: + raise RuntimeError("HTTPUpgrade peer configuration failed") + origin.release() + origin.wait_tcp(24000) + server.release() + server.wait_tcp(23999 if kind == "M" else rows[0][1]["port"]) + for name, node, _, consumer in rows: + reference = ( + measure_close( + lab, root, output, binary, origin, node, name + ) + if consumer == "close" + else None + ) + fixture = root / "fixture.json" + fixture.write_text( + json.dumps( + dict( + isolation="containers", + node=node, + peer_kind=kind, + families=families(node, kind), + origin_ipv4=origin.ipv4, + origin_ipv6=origin.ipv6, + origin_control=f"{origin.ipv4}:24000", + data_dir=str(root / "data"), + close_reference=reference, + ) + ) + ) + observations = output / (name + "-observations.json") + events = output / (name + "-events.jsonl") + argv = rust_command( + "vless_public", "httpupgrade::" + consumer + ) + result = run_command( + argv, + cwd=CORE_DIR, + timeout=240, + env=dict( + os.environ, + VCORE_VLESS_INPUT=str(fixture), + VCORE_HTTPUPGRADE_OBSERVATIONS=str(observations), + VCORE_PROTOCOL_STAGE="HTTPUPGRADE", + VCORE_CASE_EVENTS=str(events), + ), + ) + (output / (name + ".log")).write_text( + redact(result.stdout.decode(errors="replace")) + ) + observed = ( + json.loads(observations.read_text()) + if observations.is_file() + else None + ) + good = ( + result.returncode == 0 + and result.cleanup + and observed + == ( + dict( + tail_hex=reference["tail_hex"], + terminated=True, + stop_idle=True, + ) + if consumer == "close" + else expected_observation(consumer, node, kind) + ) + and events_pass(read_events(events), consumer) + ) + report["cases"].append( + dict( + case_id=name, + command=argv, + exit_code=result.returncode, + command_cleanup=result.cleanup, + observations=observed, + status="PASS" if good else "FAIL", + ) + ) + print(name + (": PASS" if good else ": FAIL"), flush=True) + if not good: + raise RuntimeError("HTTPUpgrade consumer failed") + finally: + for role, directory in directories.items(): + if (directory / "peer.log").is_file(): + (output / (role + ".log")).write_text( + redact( + (directory / "peer.log").read_text(errors="replace") + ) + ) + report["status"] = "PASS" + except BaseException as error: + report["status"] = "FAIL" + (output / "failure.log").write_text(redact(str(error))) + raise + finally: + report["cleanup"] = all( + p.get("joined") is True for p in report["isolation"].get("peers", []) + ) + report["source_unchanged"] = same_source(report["source"], source_identity()) + if not report["cleanup"] or not report["source_unchanged"]: + report["status"] = "FAIL" + (output / "report.json").write_text(json.dumps(report, indent=2) + "\n") + if report["status"] != "PASS": + raise RuntimeError("HTTPUpgrade source or cleanup failed") + return report + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("output", type=Path) + parser.add_argument("--case", action="append") + parser.add_argument("--checks", choices=CHECKS, default="tcp") + args = parser.parse_args() + run(args.output, checks=args.checks, selected=args.case) diff --git a/scripts/src/vcore_scripts/protocol_httpupgrade_acceptance.py b/scripts/src/vcore_scripts/protocol_httpupgrade_acceptance.py new file mode 100644 index 0000000..b6e4a17 --- /dev/null +++ b/scripts/src/vcore_scripts/protocol_httpupgrade_acceptance.py @@ -0,0 +1,253 @@ +"""Run HTTPUpgrade gates and independently reconstruct persisted acceptance.""" + +from __future__ import annotations + +import json + +from .core_checks import validate_execution +from .protocol_evidence import read_events, read_json +from .protocol_httpupgrade import events_pass, expected_observation +from .protocol_httpupgrade_catalog import ( + LOCAL, + REGRESSION, + UNIT, + WIRE, + commands, + wire_cases, +) +from .protocol_hysteria2_catalog import assertions_pass +from .protocol_inputs import redact +from .protocol_integration_checks import envelope +from .protocol_security_acceptance import result, rust_command +from .protocol_shadowtls_acceptance import source + + +def wire_pass(name, directory, report): + expected = wire_cases(name) + rows = report.get("cases", []) + if [r.get("case_id") for r in rows] != [r[0] for r in expected]: + return False + for row, (identifier, consumer) in zip(rows, expected, strict=True): + observed = read_json(directory / (identifier + "-observations.json")) + if consumer == "close": + reference = read_json(directory / (identifier + "-close-reference.json")) + raw = json.loads( + (directory / (identifier + "-close-command.log")).read_text() + ) + if ( + reference != raw + or raw.get("terminated") is not True + or raw.get("variant") != "plain" + ): + return False + wanted = dict(tail_hex=raw["tail_hex"], terminated=True, stop_idle=True) + else: + node = dict(type="vmess" if identifier.startswith("vmess") else "trojan") + node["packet-encoding"] = identifier.rsplit("-", 1)[-1] + wanted = expected_observation( + consumer, node, "XR" if name == "UDP-DOMAIN" else "M" + ) + if not ( + row.get("command") + == rust_command("vless_public", "httpupgrade::" + consumer) + and type(row.get("exit_code")) is int + and row["exit_code"] == 0 + and row.get("command_cleanup") is True + and observed == row.get("observations") == wanted + and events_pass( + read_events(directory / (identifier + "-events.jsonl")), consumer + ) + ): + return False + return True + + +def local_pass(name, directory, run): + rows = [ + r for r in run["commands"] if r["name"].startswith("HTTPUPGRADE-" + name + "-") + ] + expected = commands(name) + if len(rows) != len(expected): + return False + events = [] + for i, (row, argv) in enumerate(zip(rows, expected, strict=True)): + label = f"HTTPUPGRADE-{name}-{i}" + if row["name"] != label or row["command"] != [redact(v) for v in argv]: + return False + validate_execution( + row["command"], + (directory / row["log"]).read_text(), + row["exit_code"], + row["cleanup"], + ) + path = directory / (label + "-events.jsonl") + if path.exists(): + events += read_events(path) + return name not in {"MEMORY", "FEATURES"} or assertions_pass( + [e for e in events if e.get("suite", "").startswith("HTTPUPGRADE-")], + {("HTTPUPGRADE-UNIT", n): 1 if name == "MEMORY" else 2 for n in UNIT}, + ) + + +def regression_pass(name, directory, report): + from .protocol_vless_public import PUBLIC + from .protocol_vless_public import events_pass as vless_events + from .protocol_vmess_public import CASES + from .protocol_vmess_public import events_pass as vmess_events + + selected = REGRESSION[name] + rows = report.get("cases", []) + if [r.get("case_id") for r in rows] != selected: + return False + for row in rows: + identifier = row["case_id"] + kind, mode, _, consumer = (PUBLIC if name == "VLESS" else CASES)[identifier] + observed = read_events(directory / (identifier + "-events.jsonl")) + if not ( + row.get("peer_kind") == kind + and row.get("command") == rust_command(name.lower() + "_public", consumer) + and type(row.get("exit_code")) is int + and row["exit_code"] == 0 + and row.get("command_cleanup") is True + and row.get("cleanup") is True + and ( + vless_events(observed, consumer, mode) + if name == "VLESS" + else vmess_events(observed, consumer) + ) + ): + return False + return True + + +def group_pass(name, directory, run, peers): + if name in LOCAL: + return local_pass(name, directory, run) + root = directory / name.lower() + report = read_json( + root / ("report.json" if name in WIRE else name.lower() + "-results.json") + ) + return envelope( + report, + peers, + source(run), + run["container_image"]["digest"], + single=("XR" if name == "UDP-DOMAIN" else "M") if name in WIRE else None, + ) and ( + wire_pass(name, root, report) + if name in WIRE + else regression_pass(name, root, report) + ) + + +def execute(cases, run, output, results): + from .protocol_containers import frozen_image + from .protocol_harness import _command + from .protocol_httpupgrade import run as upgrade + from .protocol_hysteria2_acceptance import prepare + from .protocol_vless_container import run as vless + from .protocol_vmess_container import run as vmess + + selected = {c["case_id"].removeprefix("HTTPUPGRADE-"): c for c in cases} + peers = {} + + def save(name): + good = group_pass(name, output, run, peers) + case = selected[name] + results[case["case_id"]] = result(case, good, good) + print(case["case_id"] + (": PASS" if good else ": FAIL"), flush=True) + if not good: + raise RuntimeError("HTTPUpgrade gate failed: " + name) + + try: + for name in selected: + if name not in LOCAL: + continue + for i, argv in enumerate(commands(name)): + label = f"HTTPUPGRADE-{name}-{i}" + completed = _command( + run, + output, + label, + argv, + 3600, + events=output / (label + "-events.jsonl"), + ) + validate_execution( + argv, + completed.stdout.decode(errors="replace"), + completed.returncode, + completed.cleanup, + ) + save(name) + if set(selected) <= LOCAL: + return + with frozen_image(output / "image-pull.log") as image: + run["container_image"] = image + kinds = ( + {"M"} + | ({"XR"} if "UDP-DOMAIN" in selected else set()) + | ({"V2"} if "VMESS" in selected else set()) + ) + supplied = prepare(output, kinds) + peers.update({k: v[1] for k, v in supplied.items()}) + for name in selected: + if name in LOCAL: + continue + root = output / name.lower() + if name in WIRE: + upgrade( + root, + checks=name.lower(), + supplied=supplied["XR" if name == "UDP-DOMAIN" else "M"], + image=image, + ) + elif name == "VLESS": + vless(root, selected=REGRESSION[name], supplied=supplied) + elif name == "VMESS": + vmess(root, selected=REGRESSION[name], supplied=supplied) + save(name) + finally: + (output / "peers.json").write_text(json.dumps(peers, indent=2) + "\n") + + +def check(directory, cases, run, results, peers, paths): + if not {"cases.json", "peers.json", "resources.jsonl", "summary.md"} <= set(paths): + raise ValueError("missing HTTPUpgrade evidence") + expected = [ + f"{c['case_id']}-{i}" + for c in cases + for i, _ in enumerate(commands(c["case_id"].removeprefix("HTTPUPGRADE-"))) + ] + actual = [r["name"] for r in run["commands"]] + if ( + len(actual) != len(set(actual)) + or set(actual) != set(expected) + or set(peers) != {"M", "XR", "V2"} + ): + raise ValueError("HTTPUpgrade command or peer selection differs") + for case in cases: + name = case["case_id"].removeprefix("HTTPUPGRADE-") + if not group_pass(name, directory, run, peers): + raise ValueError("HTTPUpgrade raw evidence failed: " + name) + print("HTTPUpgrade coverage: PASS (all required groups; device delivery separate)") + + +def preflight(output): + from .protocol_containers import command, frozen_image + from .protocol_hysteria2_acceptance import prepare + + command("system", "status") + with frozen_image(output / "image-pull.log"): + supplied = prepare(output, {"M", "XR", "V2"}) + (output / "peers.json").write_text( + json.dumps( + dict( + scope="download-only", + wire_acceptance="NOT RUN", + peers={k: v[1] for k, v in supplied.items()}, + ), + indent=2, + ) + + "\n" + ) diff --git a/scripts/src/vcore_scripts/protocol_httpupgrade_catalog.py b/scripts/src/vcore_scripts/protocol_httpupgrade_catalog.py new file mode 100644 index 0000000..9e73659 --- /dev/null +++ b/scripts/src/vcore_scripts/protocol_httpupgrade_catalog.py @@ -0,0 +1,174 @@ +"""Independent required HTTPUpgrade consumers and regression selection.""" + +from .protocol_shadowtls_catalog import commands as shared_commands + +LOCAL = {"MEMORY", "FEATURES", "QUALITY", "PLATFORMS"} +WIRE = ("TCP", "UDP", "UDP-DOMAIN", "EARLY-DATA", "PROFILES", "NEGATIVE", "CLOSE") +GATES = ("MEMORY", "FEATURES", "QUALITY", "PLATFORMS", *WIRE, "VLESS", "VMESS") +BASES = tuple( + f"{protocol}-upgrade-{security}-{mode}" + for protocol, security in (("vmess", "plain"), ("vmess", "tls"), ("trojan", "tls")) + for mode in ("normal", "fast") +) +UNIT = ( + "config_dispatch", + "config_bounds", + "early_data", + "invalid_response", + "deadline_cancel", + "expired_deadline", + "late_response", + "late_write", + "established_io", +) +REGRESSION = { + "VLESS": [ + "VLESS-" + mode + "-BASE" + for mode in ( + "WS", + "WS-TLS", + "UPGRADE", + "UPGRADE-FAST", + "UPGRADE-TLS", + "UPGRADE-FAST-TLS", + ) + ] + + [ + "VLESS-REGRESSION-" + protocol + "-" + network + for protocol in ("VMESS", "TROJAN") + for network in ("TCP", "WS", "GRPC") + ], + "VMESS": ["VMESS-PUBLIC-" + mode + "-TLS-BASE" for mode in ("HTTP", "H2")], +} + + +def wire_cases(name): + rows = [] + for base in BASES: + if name == "UDP-DOMAIN" and not base.startswith("trojan"): + continue + if name == "PROFILES" and "-plain-" in base: + continue + variants = { + "TCP": ("",), + "CLOSE": ("",), + "UDP": ("raw", "xudp", "packetaddr") + if base.startswith("vmess") + else ("raw",), + "UDP-DOMAIN": ("domain",), + "EARLY-DATA": ("ed1", "ed2048"), + "PROFILES": ("chrome", "chrome120", "firefox", "safari"), + "NEGATIVE": ("identity", "path") + + (("certificate",) if "-tls-" in base else ()), + }[name] + consumer = { + "TCP": "tcp", + "CLOSE": "close", + "UDP": "udp", + "UDP-DOMAIN": "udp", + "EARLY-DATA": "echo_and_stop", + "PROFILES": "echo_and_stop", + "NEGATIVE": "rejected", + }[name] + rows += [(base + ("-" + v if v else ""), consumer) for v in variants] + return rows + + +def definitions(): + return [ + dict( + case_id="HTTPUPGRADE-" + name, + stage="HTTPUPGRADE", + substage="HTTPUPGRADE." + + ( + "configuration" + if name == "FEATURES" + else "stream" + if name == "MEMORY" + else "interop" + if name in WIRE + else "regression" + ), + required=True, + row_ids=[], + protocol="vmess/trojan", + network="httpupgrade", + security="plain/tls", + udp_codec="raw/xudp/packetaddr/trojan", + field_values={}, + outer_family="IPv4", + inner_family="IPv4/IPv6/domain", + target_type="memory-only/build" if name in LOCAL else "isolated origin", + upstream_graph="existing connector", + peer_kind="unit" + if name in LOCAL + else "XR" + if name == "UDP-DOMAIN" + else "V2" + if name == "VMESS" + else "M", + peer_config={"group": name}, + gap_source=None, + expected_observation=["HTTPUPGRADE-" + name], + required_evidence=["command", "structured-assertions", "cleanup"] + + ([] if name in LOCAL else ["peer-identity", "isolated-origins"]), + prerequisites=["rust-toolchain"] + if name in LOCAL + else ["owned-host-only-container-network", "official-latest-peer"], + runner="httpupgrade-gate", + timeout_seconds=3600, + ) + for name in GATES + ] + + +def commands(name): + cargo = ["cargo", "test", "--locked", "--all-features"] + if name == "MEMORY": + return [ + cargo + + [ + arg + for t in ( + "httpupgrade_config", + "httpupgrade_memory", + "vmess_lifecycle", + "vmess_config", + "trojan", + "trojan_config", + "vless_config", + "vless_lifecycle", + "stream_foundations", + "stream_shutdown", + ) + for arg in ("--test", t) + ] + ] + if name == "FEATURES": + return ( + [ + ["cargo", "check", "--locked", "--no-default-features"] + + (["--features", f] if f else []) + for f in ("", "stream-transport", "outbound-vmess", "outbound-trojan") + ] + + [ + [ + "cargo", + "test", + "--locked", + "--no-default-features", + "--features", + f + ",interop-test", + "--test", + "httpupgrade_config", + "--test", + "httpupgrade_memory", + ] + for f in ("outbound-vmess", "outbound-trojan") + ] + + [ + ["cargo", "test", "--locked", "--test", "feature_foundations"], + cargo + ["--all-targets", "--no-run"], + ] + ) + return shared_commands(name) if name in {"QUALITY", "PLATFORMS"} else [] diff --git a/scripts/src/vcore_scripts/protocol_integration_acceptance.py b/scripts/src/vcore_scripts/protocol_integration_acceptance.py index 7f48640..f294d8e 100644 --- a/scripts/src/vcore_scripts/protocol_integration_acceptance.py +++ b/scripts/src/vcore_scripts/protocol_integration_acceptance.py @@ -6,7 +6,7 @@ import json from .protocol_evidence import read_events, read_json from .protocol_hysteria2_catalog import assertions_pass -from .protocol_integration_catalog import LOCAL, PAIRS, definitions +from .protocol_integration_catalog import CHAINS, LOCAL, ORDERED, PAIRS, definitions from .protocol_integration_checks import envelope, runtime_pass from .protocol_integration_local import commands, passed from .protocol_integration_shared import hops_pass, shared_pass @@ -16,7 +16,7 @@ from .protocol_security_acceptance import result def pair_pass(identifier, record, directory): from .protocol_integration_native import rust_command - first, last = PAIRS[identifier] + first, last = ORDERED[identifier] targets = 2 if last == "trojan" else 3 events = read_events(directory / (identifier + "-events.jsonl")) observation = read_json(directory / (identifier + "-observations.json")) @@ -29,9 +29,14 @@ def pair_pass(identifier, record, directory): udp_target_kinds=targets, udp_packets=targets * 400, udp_sizes=[1, 64, 512, 1200], - server_first=True, + server_first=last != "ss", client_first=True, ports_rebound=True, + **( + {"server_first_limitation": "official-ss2022-empty-first-write"} + if last == "ss" + else {} + ), ) for v6 in (False, True) for group in (False, True) @@ -78,10 +83,11 @@ def pair_pass(identifier, record, directory): ), carrier_capability=dict( upstream_datagrams="rejected", - tcp_allowed=last != "hysteria2", - udp_allowed=last not in {"ss", "socks5", "hysteria2"}, + tcp_allowed=last not in {"hysteria2", "tuic"}, + udp_allowed=last not in {"ss", "socks5", "hysteria2", "tuic"}, no_bypass=True, ), + **({"variant": CHAINS[identifier]} if identifier in CHAINS else {}), ) and assertions_pass( events, @@ -105,6 +111,8 @@ def execute(cases, run, output, results): from .protocol_containers import frozen_image from .protocol_harness import _command from .protocol_hysteria2_acceptance import prepare + from .protocol_integration_coupled import passed as coupled_pass + from .protocol_integration_coupled import run as coupled_run from .protocol_integration_native import run as run_pairs from .protocol_integration_shared import hops_run, shared_run from .protocol_integration_suite import CONSUMERS @@ -160,7 +168,7 @@ def execute(cases, run, output, results): kinds = {"M"} if "INTEGRATION-SHARED" in by_id: kinds |= {"XR", "V2"} - if any(PAIRS[i][1] == "trojan" for i in by_id.keys() & PAIRS.keys()): + if any(ORDERED[i][1] == "trojan" for i in by_id.keys() & ORDERED.keys()): kinds.add("XR") if "INTEGRATION-HY2-HOP" in by_id: kinds.add("H") @@ -169,7 +177,7 @@ def execute(cases, run, output, results): digest = snapshot["digest"] # Each group is rerun from this source/image/peer scope. Historical # reports are never imported into results. - selected = sorted(by_id.keys() & PAIRS.keys()) + selected = sorted(by_id.keys() & ORDERED.keys()) if selected: directory = output / "pairs" report = run_pairs( @@ -188,6 +196,12 @@ def execute(cases, run, output, results): and pair_pass(identifier, record, directory), report["cleanup"], ) + if "INTEGRATION-COUPLED" in by_id: + coupled_run(output / "coupled", supplied["M"], snapshot) + save( + "INTEGRATION-COUPLED", + coupled_pass(output / "coupled", peers, source, digest), + ) selected = sorted( by_id.keys() & CONSUMERS.keys(), key=lambda k: (k == "INTEGRATION-SOAK", k), @@ -229,6 +243,7 @@ def check(run_dir, cases, run, results, peers, paths): from .protocol_containers import IMAGE from .protocol_evidence import HEX from .protocol_inputs import redact + from .protocol_integration_coupled import passed as coupled_pass from .protocol_integration_suite import CONSUMERS observed_paths = { @@ -285,7 +300,7 @@ def check(run_dir, cases, run, results, peers, paths): key=lambda k: (k == "INTEGRATION-SOAK", k), ) if ( - [r.get("case_id") for r in pair_report.get("cases", [])] != sorted(PAIRS) + [r.get("case_id") for r in pair_report.get("cases", [])] != sorted(ORDERED) or [r.get("case_id") for r in runtime_report.get("cases", [])] != expected_runtime or set(pair_report.get("peers", {})) != {"M", "XR"} @@ -325,8 +340,8 @@ def check(run_dir, cases, run, results, peers, paths): if identifier == "INTEGRATION-SCRIPTS" else None, ) - elif identifier in PAIRS or identifier in CONSUMERS: - pair = identifier in PAIRS + elif identifier in ORDERED or identifier in CONSUMERS: + pair = identifier in ORDERED report = pair_report if pair else runtime_report record = next(r for r in report["cases"] if r["case_id"] == identifier) directory = run_dir / ("pairs" if pair else "runtime") @@ -335,12 +350,15 @@ def check(run_dir, cases, run, results, peers, paths): )(identifier, record, directory) elif identifier == "INTEGRATION-HY2-HOP": good = hops_pass(run_dir / "hop", peers, source, digest) + elif identifier == "INTEGRATION-COUPLED": + good = coupled_pass(run_dir / "coupled", peers, source, digest) else: good = shared_pass(run_dir / "shared", peers, source, digest) if not good or result(case, good, True) != actual[identifier]: raise ValueError("INTEGRATION raw evidence does not pass: " + identifier) print( - f"INTEGRATION: PASS ({len(cases)} required gates; 49 pairs, " + f"INTEGRATION: PASS ({len(cases)} required gates; {len(PAIRS)} pairs, " + f"{len(CHAINS)} TUIC/ShadowTLS chains, retained UoT/TUIC chains, " "100 lifetimes, 100 rebuilds, 1800-second soak)" ) diff --git a/scripts/src/vcore_scripts/protocol_integration_catalog.py b/scripts/src/vcore_scripts/protocol_integration_catalog.py index e62b336..ea97420 100644 --- a/scripts/src/vcore_scripts/protocol_integration_catalog.py +++ b/scripts/src/vcore_scripts/protocol_integration_catalog.py @@ -2,12 +2,21 @@ from __future__ import annotations -PROTOCOLS = ("socks5", "anytls", "ss", "trojan", "vmess", "vless", "hysteria2") +PROTOCOLS = ("socks5", "anytls", "ss", "trojan", "vmess", "vless", "hysteria2", "tuic") PAIRS = { f"INTEGRATION-PAIR-{first.upper()}-{last.upper()}": (first, last) for first in PROTOCOLS for last in PROTOCOLS } +CHAINS = { + f"INTEGRATION-CHAIN-TUIC-{mode.upper()}-SS-V3-{cipher.upper()}": { + "udp_mode": mode, + "cipher": "2022-blake3-" + cipher, + } + for mode in ("native", "quic") + for cipher in ("aes-128-gcm", "aes-256-gcm", "chacha20-poly1305") +} +ORDERED = PAIRS | dict.fromkeys(CHAINS, ("tuic", "ss")) GATES = { "INTEGRATION-ENTRYPOINTS": "routing", "INTEGRATION-GRAPH": "routing", @@ -25,6 +34,7 @@ GATES = { "INTEGRATION-FEATURES": "regression", "INTEGRATION-SCRIPTS": "regression", "INTEGRATION-SHARED": "regression", + "INTEGRATION-COUPLED": "routing", } LOCAL = { "INTEGRATION-DEBUG", @@ -37,8 +47,8 @@ LOCAL = { def definitions(): result = [] - for identifier in sorted(PAIRS.keys() | GATES.keys()): - pair = PAIRS.get(identifier) + for identifier in sorted(ORDERED.keys() | GATES.keys()): + pair = ORDERED.get(identifier) local = identifier in LOCAL result.append( dict( @@ -48,10 +58,16 @@ def definitions(): required=True, row_ids=["C06"] if pair else [], protocol="integration", - network="seven-protocol-graph", + network="eight-protocol-graph", security="per-frozen-consumer", udp_codec="per-protocol", - field_values={"first": pair[0], "last": pair[1]} if pair else {}, + field_values={ + "first": pair[0], + "last": pair[1], + **CHAINS.get(identifier, {}), + } + if pair + else {}, outer_family="IPv4/IPv6", inner_family="IPv4/IPv6/domain", target_type="memory-only/build" if local else "isolated origin", diff --git a/scripts/src/vcore_scripts/protocol_integration_checks.py b/scripts/src/vcore_scripts/protocol_integration_checks.py index f53e801..8a82a35 100644 --- a/scripts/src/vcore_scripts/protocol_integration_checks.py +++ b/scripts/src/vcore_scripts/protocol_integration_checks.py @@ -19,6 +19,7 @@ def envelope(report, peers, source, digest, *, single=None): "XR": "XTLS/Xray-core", "V2": "v2fly/v2ray-core", "SS": "shadowsocks/shadowsocks-rust", + "ST": "ihciah/shadow-tls", "H": "HyNetworks/hysteria", } return bool( @@ -113,8 +114,10 @@ def runtime_pass(identifier, record, directory): "vmess", "vless", "hysteria2", + "tuic", ], source_and_oversize_isolated=protocols, + tuic_transmit_budget=dict(limit=128, rejected=129, following_roundtrip=128), cancel_preserves_sibling=protocols, no_origin_bytes=True, stop_idle=True, diff --git a/scripts/src/vcore_scripts/protocol_integration_coupled.py b/scripts/src/vcore_scripts/protocol_integration_coupled.py new file mode 100644 index 0000000..d1d0c65 --- /dev/null +++ b/scripts/src/vcore_scripts/protocol_integration_coupled.py @@ -0,0 +1,41 @@ +"""Rerun the retained UoT/TUIC chain consumers in one integration source scope.""" + +from .protocol_evidence import read_json +from .protocol_integration_checks import envelope + +GROUPS = ("MIHOMO-SOCKS5", "MIHOMO-GROUPS", "MIHOMO-PATHS") + + +def run(directory, supplied, image): + from .protocol_tuic import run as tuic + from .protocol_uot import run as uot + + for name in GROUPS: + print("INTEGRATION coupled: " + name, flush=True) + root = directory / name + if name == "MIHOMO-PATHS": + tuic(root, checks="paths", supplied=supplied, image=image) + else: + uot( + root, + checks="group" if name == "MIHOMO-GROUPS" else "data", + via_socks5=True, + supplied=supplied, + image=image, + ) + + +def passed(directory, peers, source, digest): + from .protocol_tuic_acceptance import wire_pass as tuic + from .protocol_uot_acceptance import wire_pass as uot + + for name in GROUPS: + root = directory / name + report = read_json(root / "report.json") + checker = tuic if name == "MIHOMO-PATHS" else uot + if not ( + envelope(report, peers, source, digest, single="M") + and checker(name, root, report) + ): + return False + return True diff --git a/scripts/src/vcore_scripts/protocol_integration_local.py b/scripts/src/vcore_scripts/protocol_integration_local.py index 3d91d8f..9d625eb 100644 --- a/scripts/src/vcore_scripts/protocol_integration_local.py +++ b/scripts/src/vcore_scripts/protocol_integration_local.py @@ -16,7 +16,13 @@ def commands(identifier): }: return core_commands(identifier.removeprefix("INTEGRATION-").lower()) if identifier == "INTEGRATION-QUALITY": - return hysteria2_commands("HYSTERIA2-QUALITY") + [ + # Behavioral integration also runs with the approved local boring fork. + # Strict release-source audit remains a separate mandatory PR/delivery gate. + return [ + row + for row in hysteria2_commands("HYSTERIA2-QUALITY") + if row != ["vcore-scripts", "check", "tls-dependencies"] + ] + [ ["vcore-scripts", "check", "protocol-coverage", "--catalog-only"], ["vcore-scripts", "build", "apple"], ["vcore-scripts", "build", "android"], @@ -74,7 +80,7 @@ def passed(identifier, records, events, script=None): if identifier == "INTEGRATION-FEATURES": good &= assertions_pass( [e for e in events if e.get("suite") == "INTEGRATION-FEATURE"], - {("INTEGRATION-FEATURE", p): 7 for p in PROTOCOLS}, + {("INTEGRATION-FEATURE", p): 8 for p in PROTOCOLS}, ) if identifier == "INTEGRATION-SCRIPTS": rows = (script or {}).get("cases", []) @@ -87,6 +93,7 @@ def passed(identifier, records, events, script=None): "test_list_contains_all_ordered_pairs_and_remaining_gates", "test_pressure_evidence_is_recomputed_not_inferred", "test_native_source_identity_and_cleanup_are_required", + "test_integration_quality_separates_release_source_policy", ) } good &= ( diff --git a/scripts/src/vcore_scripts/protocol_integration_metrics.py b/scripts/src/vcore_scripts/protocol_integration_metrics.py index c0b5e26..347ce52 100644 --- a/scripts/src/vcore_scripts/protocol_integration_metrics.py +++ b/scripts/src/vcore_scripts/protocol_integration_metrics.py @@ -6,11 +6,18 @@ from math import isfinite from statistics import median from .protocol_evidence import RESOURCE_KINDS, idle_resources +from .protocol_integration_profiles import ( + LIFETIME_GROUPS, + TCP_GROUPS, + UDP_GROUPS, + expected_flows, + selected, +) -NEW = ["trojan", "vmess", "vless", "hysteria2"] QUEUES = { "socks_udp": 16, - "hysteria2_udp": 32, + "hysteria2_udp": 0, + "tuic_udp": 32, "quic_incoming": 32, "quic_outgoing": 32, } @@ -44,10 +51,12 @@ def sample(value, *, active=True): and integer(value.get("rss_kib"), 1) and integer(value.get("fd"), 1) and resources(value.get("resources", {}), active=active) - and len(queues) == 4 + and len(queues) == len(QUEUES) and {q.get("kind"): q.get("capacity") for q in queues} == QUEUES and all( - integer(q.get("peak"), 1) and q["peak"] <= q["capacity"] for q in queues + integer(q.get("peak"), int(q["capacity"] > 0)) + and q["peak"] <= q["capacity"] + for q in queues ) ) @@ -61,10 +70,13 @@ def lifetimes(value, events): stop = row.get("after_stop", {}) checkpoints = event.get("checkpoints", []) mode = index % 5 + group = LIFETIME_GROUPS[(index // 5) % len(LIFETIME_GROUPS)] retained = {0: 0, 1: 10, 2: 1, 3: 0, 4: 8}[mode] if not ( row.get("cycle") == index - and row.get("protocol") == NEW[(index // 5) % 4] + and row.get("group") == group + and row.get("profile") + == selected(group, index // (5 * len(LIFETIME_GROUPS))) and row.get("mode") == mode and integer(row.get("baseline_fd"), 1) and row.get("retained_fixture_fd") == retained @@ -130,13 +142,15 @@ def rebuild(value, event): return ( value.get("count") == 100 and value.get("same_running_session") is True - and value.get("protocols") == NEW + and value.get("tcp_groups") == list(TCP_GROUPS) + and value.get("udp_groups") == list(UDP_GROUPS) and len(rows) == 100 and stopped(value, event) and all( row.get("generation") == i and row.get("tcp") == row.get("udp") == 20 - and row.get("per_protocol_tcp") == row.get("per_protocol_udp") == 5 + and row.get("per_group_tcp") == row.get("per_group_udp") == 5 + and row.get("flow_profiles") == expected_flows(i) and sample(row.get("active", {})) and sample(row.get("after_clients", {}), active=False) and setup(row.get("setup_us")) @@ -156,9 +170,12 @@ def soak(value, event, curve): if not ( value.get("requested_seconds") == 1800 and 1800 <= value.get("seconds", 0) < 1860 - and value.get("protocols") == NEW + and value.get("tcp_groups") == list(TCP_GROUPS) + and value.get("udp_groups") == list(UDP_GROUPS) and value.get("tcp") == value.get("udp") == 20 - and value.get("per_protocol_tcp") == value.get("per_protocol_udp") == 5 + and value.get("per_group_tcp") == value.get("per_group_udp") == 5 + and value.get("first_profiles") == expected_flows(0) + and value.get("last_profiles") == expected_flows(len(faults)) and integer(value.get("waves"), 1) and value.get("normal_verified_bytes") == value["waves"] * 20 * 2 * 2 * 257 and all( diff --git a/scripts/src/vcore_scripts/protocol_integration_native.py b/scripts/src/vcore_scripts/protocol_integration_native.py index e74f5d0..48b3fe3 100644 --- a/scripts/src/vcore_scripts/protocol_integration_native.py +++ b/scripts/src/vcore_scripts/protocol_integration_native.py @@ -1,4 +1,4 @@ -"""Seven-protocol integration with owned official peers and container origins.""" +"""Eight-protocol integration with owned official peers and container origins.""" from __future__ import annotations @@ -18,7 +18,7 @@ from .native_release import download_native from .protocol_containers import ContainerLab, command, frozen_image from .protocol_fixtures import certificates from .protocol_inputs import redact, sha256, source_identity -from .protocol_integration_catalog import PAIRS +from .protocol_integration_catalog import CHAINS, ORDERED from .protocol_peers import run_command @@ -38,6 +38,16 @@ def peer_configuration(protocol, server, origin, directory, *, certificate=None) cipher = "2022-blake3-aes-128-gcm" listener.update(type="shadowsocks", udp=True, cipher=cipher, password=password) node.update(cipher=cipher, password=password) + elif protocol == "tuic": + listener.update(users={identity: password}, alpn=["h3"]) + node.update( + uuid=identity, + password=password, + sni="localhost", + fingerprint=pin, + alpn=["h3"], + **{"udp-relay-mode": "native"}, + ) elif protocol in {"trojan", "anytls", "hysteria2"}: node.update(password=password, sni="localhost", fingerprint=pin) listener["users"] = ( @@ -91,7 +101,7 @@ def run( if ( not selected or len(selected) != len(set(selected)) - or not set(selected) <= PAIRS.keys() + or not set(selected) <= ORDERED.keys() ): raise ValueError("invalid INTEGRATION pair selection") output = output.resolve() @@ -120,7 +130,7 @@ def run( if sha256(binary) != identity["binary_sha256"]: raise RuntimeError("INTEGRATION native peer identity mismatch") report["peers"]["M"] = identity - if any(PAIRS[key][1] == "trojan" for key in selected): + if any(ORDERED[key][1] == "trojan" for key in selected): if domain_peer is None: artifact = download_native( "XR", output / "binary-xray", "linux-arm64", defer_version=True @@ -131,7 +141,8 @@ def run( report["peers"]["XR"] = domain_peer[1] lab = ContainerLab(report["isolation"], mtu=1500) for index, identifier in enumerate(selected): - first_kind, last_kind = PAIRS[identifier] + first_kind, last_kind = ORDERED[identifier] + variant = CHAINS.get(identifier) print(f"INTEGRATION: {identifier}", flush=True) with tempfile.TemporaryDirectory( prefix="private-", dir=output @@ -144,20 +155,35 @@ def run( Path(__file__).with_name("container_udp_origin.py"), origin_dir / "origin.py", ) + origin_command = ["env", "VCORE_ISOLATED_ORIGIN=1"] + cover_certificate = None + if variant: + cover_certificate = certificates(origin_dir) + shutil.copyfile( + Path(__file__).with_name("container_shadowtls_peer.py"), + origin_dir / "cover.py", + ) + origin_command += [ + "VCORE_ORIGIN_CERT=/data/fixture/cert.pem", + "VCORE_ORIGIN_KEY=/data/fixture/key.pem", + ] + origin_command += [ + "python", + "-B", + "/data/fixture/cover.py" + if variant + else "/data/fixture/origin.py", + ] origin = lab.start( stack, origin_dir, f"{index}-origin", - [ - "env", - "VCORE_ISOLATED_ORIGIN=1", - "python", - "-B", - "/data/fixture/origin.py", - ], + origin_command, ) origin.release() origin.wait_tcp(24000) + if variant: + origin.wait_tcp(24001) fixture = dict( isolation="containers", origin_control=f"{origin.ipv4}:24000", @@ -165,6 +191,8 @@ def run( origin_ipv6=origin.ipv6, data_dir=str(root / "core"), ) + if variant: + fixture["variant"] = variant for role, protocol in (("first", first_kind), ("last", last_kind)): directory = root / role directory.mkdir() @@ -196,6 +224,25 @@ def run( node, config = peer_configuration( protocol, peer.ipv4, origin.ipv4, directory ) + if variant and role == "first": + node["udp-relay-mode"] = variant["udp_mode"] + elif variant: + from .protocol_completion_peers import PeerCase + from .protocol_completion_peers import ( + peer_configuration as profile, + ) + + node, listener = profile( + PeerCase( + identifier, "ss", variant["cipher"], shadow_tls=True + ), + server=peer.ipv4, + cover=f"{origin.ipv4}:24001", + port=23000, + certificate=cover_certificate, + ) + node["name"] = "peer" + config["listeners"] = [listener] (directory / "config.json").write_text(json.dumps(config)) fixture[role], fixture[role + "_ipv6"] = node, peer.ipv6 peer.release() @@ -302,4 +349,4 @@ def run( if __name__ == "__main__": output = Path(sys.argv[1]).resolve() with exclusive_run(), frozen_image(None): - run(output, sys.argv[2:] or list(PAIRS)) + run(output, sys.argv[2:] or list(ORDERED)) diff --git a/scripts/src/vcore_scripts/protocol_integration_profiles.py b/scripts/src/vcore_scripts/protocol_integration_profiles.py new file mode 100644 index 0000000..f5abe40 --- /dev/null +++ b/scripts/src/vcore_scripts/protocol_integration_profiles.py @@ -0,0 +1,66 @@ +"""Mixed-load profiles built from the implemented protocol peer fixtures.""" + +from .protocol_completion_peers import CASES, peer_configuration + +TCP_GROUPS = ("socks5", "ss-v3", "tuic", "httpupgrade") +UDP_GROUPS = ("ss-uot", "ss-uot-v3", "tuic", "httpupgrade") +LIFETIME_GROUPS = ( + "socks5", + "anytls", + "ss", + "trojan", + "vmess", + "vless", + "hysteria2", + "tuic", + "ss-v3", + "ss-uot", + "ss-uot-v3", + "httpupgrade", +) + + +def group(case): + if case.protocol == "ss": + return ( + "ss-uot-v3" + if case.uot and case.shadow_tls + else "ss-uot" + if case.uot + else "ss-v3" + ) + return "tuic" if case.protocol == "tuic" else "httpupgrade" + + +PROFILE_IDS = { + name: [c.identifier for c in CASES if c.protocol != "socks5" and group(c) == name] + for name in ("ss-v3", "ss-uot", "ss-uot-v3", "tuic", "httpupgrade") +} + + +def configuration(server, cover, certificate): + nodes, listeners = {}, [] + for i, case in enumerate(c for c in CASES if c.protocol != "socks5"): + node, listener = peer_configuration( + case, server=server, cover=cover, port=23100 + i, certificate=certificate + ) + node["name"] = "peer" + nodes[case.identifier] = node + listeners.append(listener) + return nodes, listeners + + +def selected(group_name, generation, slot=0): + options = PROFILE_IDS.get(group_name, [group_name]) + return options[(generation + slot) % len(options)] + + +def expected_flows(generation): + return { + kind: [ + selected(group_name, generation, slot) + for group_name in groups + for slot in range(5) + ] + for kind, groups in (("tcp", TCP_GROUPS), ("udp", UDP_GROUPS)) + } diff --git a/scripts/src/vcore_scripts/protocol_integration_suite.py b/scripts/src/vcore_scripts/protocol_integration_suite.py index c7e99ea..3f93bc0 100644 --- a/scripts/src/vcore_scripts/protocol_integration_suite.py +++ b/scripts/src/vcore_scripts/protocol_integration_suite.py @@ -1,4 +1,4 @@ -"""INTEGRATION public-runtime gates against seven listeners in an owned native peer.""" +"""INTEGRATION public-runtime and mixed-profile gates in owned native peers.""" from __future__ import annotations @@ -21,6 +21,8 @@ from .protocol_fixtures import certificates from .protocol_inputs import redact, sha256, source_identity from .protocol_integration_catalog import PROTOCOLS from .protocol_integration_native import peer_configuration, rust_command +from .protocol_integration_profiles import PROFILE_IDS +from .protocol_integration_profiles import configuration as profiles from .protocol_peers import run_command CONSUMERS = { @@ -79,10 +81,15 @@ def run(output: Path, selected, *, supplied=None): with contextlib.ExitStack() as stack: origin_dir = root / "origin" origin_dir.mkdir() + certificate = certificates(origin_dir) shutil.copyfile( Path(__file__).with_name("container_udp_origin.py"), origin_dir / "origin.py", ) + shutil.copyfile( + Path(__file__).with_name("container_shadowtls_peer.py"), + origin_dir / "cover.py", + ) origin = lab.start( stack, origin_dir, @@ -91,13 +98,16 @@ def run(output: Path, selected, *, supplied=None): "env", "VCORE_ISOLATED_ORIGIN=1", "VCORE_ORIGIN_PROFILE=INTEGRATION", + "VCORE_ORIGIN_CERT=/data/fixture/cert.pem", + "VCORE_ORIGIN_KEY=/data/fixture/key.pem", "python", "-B", - "/data/fixture/origin.py", + "/data/fixture/cover.py", ], ) origin.release() origin.wait_tcp(24000) + origin.wait_tcp(24001) upstream_dir = root / "upstream" upstream_dir.mkdir() shutil.copy2(binary, upstream_dir / "peer") @@ -156,7 +166,8 @@ def run(output: Path, selected, *, supplied=None): raise RuntimeError( "INTEGRATION container binary differs from download" ) - certificate = certificates(directory) + for path in certificate[:2]: + shutil.copy2(path, directory / path.name) nodes, listeners = {}, [] config = None for index, protocol in enumerate(PROTOCOLS): @@ -195,6 +206,11 @@ def run(output: Path, selected, *, supplied=None): ) ) ss_nodes.append(node) + extra_nodes, extra_listeners = profiles( + peer.ipv4, f"{origin.ipv4}:24001", certificate + ) + nodes.update(extra_nodes) + listeners.extend(extra_listeners) config.update( listeners=listeners, **{ @@ -211,6 +227,16 @@ def run(output: Path, selected, *, supplied=None): origin_ipv4=origin.ipv4, origin_ipv6=origin.ipv6, nodes=nodes, + profile_groups={ + name: PROFILE_IDS.get(name, [name]) + for name in ( + *PROTOCOLS, + "ss-v3", + "ss-uot", + "ss-uot-v3", + "httpupgrade", + ) + }, ss_nodes=ss_nodes, hop=hop, server_ipv6=peer.ipv6, diff --git a/scripts/src/vcore_scripts/protocol_shadowtls.py b/scripts/src/vcore_scripts/protocol_shadowtls.py new file mode 100644 index 0000000..b20bf90 --- /dev/null +++ b/scripts/src/vcore_scripts/protocol_shadowtls.py @@ -0,0 +1,568 @@ +"""SS2022 ShadowTLS v3 through public consumers and isolated official peers.""" + +from __future__ import annotations + +import contextlib +import copy +import json +import os +import shutil +import tempfile +from pathlib import Path + +from .builds import CORE_DIR +from .mihomo_isolation import exclusive_run +from .mihomo_release import download_mihomo +from .protocol_completion_peers import CASES, peer_configuration +from .protocol_containers import ContainerLab, command, frozen_image +from .protocol_fixtures import certificates +from .protocol_inputs import redact, same_source, source_identity +from .protocol_peers import run_command + +PROFILES = ("none", "chrome120", "chrome", "firefox", "safari") +POLICIES = ( + "alpn-default", + "alpn-empty", + "alpn-custom", + "hrr", + "wrong-password", + "wrong-pin", + "wrong-pin-with-skip", + "untrusted", + "tls12", +) + + +def policy_inputs(node, listener): + for index, policy in enumerate(POLICIES): + client, peer = copy.deepcopy(node), copy.deepcopy(listener) + client["port"] = peer["port"] = 23500 + index + peer["name"] += "-" + policy + port, alpn = 24001, "h2" + if policy == "alpn-empty": + client["plugin-opts"]["alpn"] = [] + alpn = None + elif policy == "alpn-custom": + client["plugin-opts"]["alpn"] = ["fixture-custom"] + alpn = "fixture-custom" + elif policy == "hrr": + port = 24002 + elif policy == "wrong-password": + client["plugin-opts"]["password"] = "wrong-synthetic-password" + elif policy.startswith("wrong-pin"): + client["plugin-opts"]["fingerprint"] = "07" * 32 + client["plugin-opts"]["skip-cert-verify"] = policy.endswith("skip") + elif policy == "untrusted": + del client["plugin-opts"]["fingerprint"] + elif policy == "tls12": + port = 24003 + host = peer["shadow-tls"]["handshake"]["dest"].rsplit(":", 1)[0] + peer["shadow-tls"]["handshake"]["dest"] = f"{host}:{port}" + yield ( + policy, + client, + peer, + policy.startswith("alpn-") or policy == "hrr", + port, + alpn, + ) + + +def run( + output: Path, + *, + profiles=("none",), + selected=None, + checks="data", + supplied=None, + image=None, +): + output = output.resolve() + if not output.is_relative_to((CORE_DIR / "target/interop/runs").resolve()): + raise ValueError("ShadowTLS evidence must stay inside target/interop/runs") + cases = tuple(c for c in CASES if c.shadow_tls and not c.uot) + if ( + checks not in {"data", "policy", "fault"} + or not profiles + or len(set(profiles)) != len(profiles) + or not set(profiles) <= set(PROFILES) + ): + raise ValueError("invalid ShadowTLS checks or profiles") + if selected is not None: + if len(set(selected)) != len(selected) or not set(selected) <= { + c.identifier for c in cases + }: + raise ValueError("unknown or duplicate ShadowTLS case") + cases = tuple(c for c in cases if c.identifier in selected) + if checks != "data": + cases = cases[:1] + if not cases: + raise ValueError("empty ShadowTLS selection") + report = dict( + source=source_identity(), status="NOT RUN", peer={}, isolation={}, cases=[] + ) + output.mkdir(parents=True, exist_ok=False) + try: + with ( + exclusive_run() if supplied is None else contextlib.nullcontext(), + ( + frozen_image(output / "image-pull.log") + if image is None + else contextlib.nullcontext(image) + ) as image, + ): + report["container_image"] = image + if supplied is None: + binary = download_mihomo( + "linux-arm64", directory=output / "binary", identity=report["peer"] + ) + else: + binary, report["peer"] = supplied + built = run_command( + [ + "cargo", + "test", + "--locked", + "--all-features", + "--test", + "vless_public", + "--no-run", + ], + cwd=CORE_DIR, + timeout=180, + ) + (output / "build.log").write_text( + redact(built.stdout.decode(errors="replace")) + ) + if built.returncode or not built.cleanup: + raise RuntimeError("ShadowTLS consumer build failed") + lab = ContainerLab(report["isolation"], mtu=1500) + with tempfile.TemporaryDirectory(prefix="private-", dir=output) as temp: + root = Path(temp) + directories = {} + try: + with contextlib.ExitStack() as stack: + for role in ("origin", "server"): + directory = root / role + directory.mkdir() + directories[role] = directory + cert = certificates(directories["server"]) + for source, name in zip( + cert[:2], ("cert.pem", "key.pem"), strict=True + ): + shutil.copy2(source, directories["origin"] / name) + shutil.copy2( + Path(__file__).with_name("container_udp_origin.py"), + directories["origin"] / "origin.py", + ) + shutil.copy2( + Path(__file__).with_name("container_shadowtls_peer.py"), + directories["origin"] / "peer.py", + ) + origin = lab.start( + stack, + directories["origin"], + "origin", + [ + "env", + "VCORE_ISOLATED_ORIGIN=1", + "VCORE_ORIGIN_CERT=/data/fixture/cert.pem", + "VCORE_ORIGIN_KEY=/data/fixture/key.pem", + "python", + "-B", + "/data/fixture/peer.py", + ], + ) + shutil.copy2(binary, directories["server"] / "mihomo") + server = lab.start( + stack, + directories["server"], + "server", + [ + "/data/fixture/mihomo", + "-d", + "/data", + "-f", + "/data/fixture/config.json", + ], + ) + report["peer"]["version"] = command( + "exec", server.name, "/data/fixture/mihomo", "-v" + ).strip() + if ( + command( + "exec", server.name, "sha256sum", "/data/fixture/mihomo" + ).split()[0] + != report["peer"]["binary_sha256"] + ): + raise RuntimeError("ShadowTLS peer identity mismatch") + nodes, listeners = [], [] + for index, case in enumerate(cases): + node, listener = peer_configuration( + case, + server=server.ipv4, + cover=f"{origin.ipv4}:24001", + port=23000 + index, + certificate=cert, + ) + node["name"] = "peer" + if checks == "data": + nodes.append((case.identifier, node, True, 24001, "h2")) + listeners.append(listener) + elif checks == "policy": + for ( + label, + client, + peer, + success, + port, + alpn, + ) in policy_inputs(node, listener): + nodes.append((label, client, success, port, alpn)) + listeners.append(peer) + else: + listeners.append(listener) + hrr = copy.deepcopy(listener) + hrr["name"] += "-hrr" + hrr["port"] = 23001 + hrr["shadow-tls"]["handshake"]["dest"] = ( + f"{origin.ipv4}:24002" + ) + listeners.append(hrr) + directory = root / "fault" + directory.mkdir() + directories["fault"] = directory + shutil.copy2( + Path(__file__).with_name( + "container_shadowtls_fault.py" + ), + directory / "fault.py", + ) + fault = lab.start( + stack, + directory, + "fault", + [ + "env", + "VCORE_ISOLATED_ORIGIN=1", + "python", + "-B", + "/data/fixture/fault.py", + ], + ) + routes = [] + for index, label in enumerate( + ( + "fragment", + "hrr-wire", + "cover-mac", + "business-mac", + "business-truncated", + "stall", + "native-udp-disabled", + ) + ): + port = 23600 + index + routes.append( + dict( + port=port, + mode="fragment" + if label == "hrr-wire" + else label, + server=server.ipv4, + server_port=23001 + if label == "hrr-wire" + else 23000, + ) + ) + client = copy.deepcopy(node) + client.update(server=fault.ipv4, port=port) + nodes.append( + ( + label, + client, + label not in {"cover-mac", "stall"}, + 24002 if label == "hrr-wire" else 24001, + "h2", + ) + ) + (directory / "config.json").write_text( + json.dumps(routes) + ) + (directories["server"] / "config.json").write_text( + json.dumps( + { + "socks-port": 23999, + "allow-lan": True, + "bind-address": "*", + "ipv6": True, + "log-level": "warning", + "listeners": listeners, + "rules": ["MATCH,DIRECT"], + } + ) + ) + origin.release() + server.release() + origin.wait_tcp(24000) + origin.wait_tcp(24001) + origin.wait_tcp(24002) + origin.wait_tcp(24003) + server.wait_tcp(23999) + if checks == "fault": + fault.release() + fault.wait_tcp(23998) + for route in routes: + fault.wait_tcp(route["port"]) + for label, node, success, cover_port, alpn in nodes: + for profile in profiles: + identifier = f"{label}-{profile}" + before = len( + command( + "exec", + origin.name, + "cat", + "/data/cover-events.jsonl", + ).splitlines() + ) + fault_before = ( + len( + command( + "exec", + fault.name, + "cat", + "/data/fault-events.jsonl", + ).splitlines() + ) + if checks == "fault" + else 0 + ) + consumer = ( + checks + if checks != "fault" + else { + "fragment": "native_tcp", + "hrr-wire": "native_tcp", + "cover-mac": "policy", + "stall": "stall", + "native-udp-disabled": "native_udp_disabled", + }.get(label, "corrupt") + ) + node["client-fingerprint"] = profile + fixture = root / "fixture.json" + fixture.write_text( + json.dumps( + dict( + isolation="containers", + node=node, + origin_ipv4=origin.ipv4, + origin_ipv6=origin.ipv6, + origin_control=f"{origin.ipv4}:24000", + data_dir=str(root / "data"), + expected_success=success, + fault_control=f"{fault.ipv4}:23998" + if checks == "fault" + else None, + ) + ) + ) + observations = ( + output / f"{identifier}-observations.json" + ) + argv = [ + "cargo", + "test", + "--locked", + "--all-features", + "--test", + "vless_public", + f"shadowtls::{consumer}", + "--", + "--ignored", + "--exact", + "--nocapture", + ] + result = run_command( + argv, + cwd=CORE_DIR, + timeout=240, + env=dict( + os.environ, + VCORE_VLESS_INPUT=str(fixture), + VCORE_SHADOWTLS_OBSERVATIONS=str(observations), + VCORE_CASE_EVENTS=str( + output / f"{identifier}-events.jsonl" + ), + ), + ) + (output / f"{identifier}.log").write_text( + redact(result.stdout.decode(errors="replace")) + ) + observed = ( + json.loads(observations.read_text()) + if observations.is_file() + else None + ) + expected = ( + dict( + tcp_bytes_each_direction=10 * 1024 * 1024, + udp_packets=500 if consumer == "data" else 0, + udp_sizes=[1, 64, 512, 1200, 4096] + if consumer == "data" + else [], + stop_idle=True, + ) + if consumer in {"data", "native_tcp"} + else dict( + origin_connected=True, + delivered_bytes=0, + stop_idle=True, + ) + if consumer == "corrupt" + else dict( + stop_idle=True, + stop_handshake_cancelled=True, + measure_deadline=True, + origin_connected=False, + closed_handshakes=2, + ) + if consumer == "stall" + else dict( + tcp_accepted=True, + udp_delivered=False, + stop_idle=True, + ) + if consumer == "native_udp_disabled" + else dict( + accepted=success, + origin_connected=success, + stop_idle=True, + ) + ) + cover = [ + json.loads(line) + for line in command( + "exec", + origin.name, + "cat", + "/data/cover-events.jsonl", + ).splitlines()[before:] + ] + cover_pass = ( + not success + or dict( + port=cover_port, version="TLSv1.3", alpn=alpn + ) + in cover + ) + fault_events = ( + [ + json.loads(line) + for line in command( + "exec", + fault.name, + "cat", + "/data/fault-events.jsonl", + ).splitlines()[fault_before:] + ] + if checks == "fault" + else [] + ) + fault_pass = True + if checks == "fault": + required = ( + "split_record" + if label == "fragment" + else "hrr_seen" + if label == "hrr-wire" + else "injected" + ) + fault_pass = any( + event.get(required) is True + for event in fault_events + ) and not any( + event.get("upload_join_failed") + for event in fault_events + ) + if label == "stall": + fault_pass = not cover and all( + sum( + event.get(key) is True + for event in fault_events + ) + == 2 + for key in ("hello_seen", "client_closed") + ) + elif label == "native-udp-disabled": + fault_pass = not any( + event.get("upload_join_failed") + for event in fault_events + ) + passed = ( + result.returncode == 0 + and result.cleanup + and observed == expected + and cover_pass + and fault_pass + ) + report["cases"].append( + dict( + case_id=identifier, + status="PASS" if passed else "FAIL", + command=argv, + exit_code=result.returncode, + command_cleanup=result.cleanup, + observations=observed, + cover=cover, + fault=fault_events, + ) + ) + print( + f"{identifier}: {'PASS' if passed else 'FAIL'}", + flush=True, + ) + if not passed: + raise RuntimeError( + "ShadowTLS public data validation failed" + ) + finally: + for role, directory in directories.items(): + if (directory / "peer.log").is_file(): + (output / f"{role}.log").write_text( + redact( + (directory / "peer.log").read_text(errors="replace") + ) + ) + report["status"] = "PASS" + except BaseException as error: + report["status"] = "FAIL" + (output / "failure.log").write_text(redact(str(error))) + raise + finally: + report["cleanup"] = all( + p.get("joined") is True for p in report["isolation"].get("peers", []) + ) + report["source_unchanged"] = same_source(report["source"], source_identity()) + if not report["cleanup"] or not report["source_unchanged"]: + report["status"] = "FAIL" + (output / "report.json").write_text(json.dumps(report, indent=2) + "\n") + if report["status"] != "PASS": + raise RuntimeError("ShadowTLS source or cleanup validation failed") + return report + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("output", type=Path) + parser.add_argument("--profile", action="append") + parser.add_argument("--case", action="append") + parser.add_argument("--checks", choices=("data", "policy", "fault"), default="data") + args = parser.parse_args() + run( + args.output, + profiles=args.profile or ["none"], + selected=args.case, + checks=args.checks, + ) diff --git a/scripts/src/vcore_scripts/protocol_shadowtls_acceptance.py b/scripts/src/vcore_scripts/protocol_shadowtls_acceptance.py new file mode 100644 index 0000000..6b72720 --- /dev/null +++ b/scripts/src/vcore_scripts/protocol_shadowtls_acceptance.py @@ -0,0 +1,376 @@ +"""ShadowTLS execution and reconstruction from raw, source-bound evidence.""" + +from __future__ import annotations + +import json + +from .core_checks import validate_execution +from .protocol_evidence import read_events, read_json +from .protocol_hysteria2_catalog import assertions_pass +from .protocol_inputs import redact +from .protocol_integration_checks import envelope, runtime_pass +from .protocol_security_acceptance import REPORTS, result, rust_command, vless_pass +from .protocol_shadowtls import POLICIES, PROFILES +from .protocol_shadowtls_catalog import ( + FAULTS, + LOCAL, + MEMORY_EVENTS, + SHARED, + SS_CASES, + commands, +) + + +def expected_observation(consumer, success): + if consumer in {"data", "native_tcp"}: + return dict( + tcp_bytes_each_direction=10 * 1024 * 1024, + udp_packets=500 if consumer == "data" else 0, + udp_sizes=[1, 64, 512, 1200, 4096] if consumer == "data" else [], + stop_idle=True, + ) + if consumer == "policy": + return dict(accepted=success, origin_connected=success, stop_idle=True) + if consumer == "corrupt": + return dict(origin_connected=True, delivered_bytes=0, stop_idle=True) + if consumer == "stall": + return dict( + stop_idle=True, + stop_handshake_cancelled=True, + measure_deadline=True, + origin_connected=False, + closed_handshakes=2, + ) + if consumer == "native_udp_disabled": + return dict(tcp_accepted=True, udp_delivered=False, stop_idle=True) + raise ValueError("unknown ShadowTLS consumer") + + +def fault_pass(label, events, cover): + if any(e.get("upload_join_failed") for e in events): + return False + if label == "stall": + return not cover and all( + sum(e.get(key) is True for e in events) == 2 + for key in ("hello_seen", "client_closed") + ) + if label == "native-udp-disabled": + return True + required = ( + "split_record" + if label == "fragment" + else "hrr_seen" + if label == "hrr-wire" + else "injected" + ) + return any(e.get(required) is True for e in events) + + +def wire_pass(name, directory, report): + if name == "MIHOMO-DATA": + labels = [ + (f"{c}-{p}", "data", True, 24001, "h2", None) + for c in SS_CASES + for p in PROFILES + ] + elif name == "MIHOMO-POLICY": + labels = [ + ( + f"{p}-chrome", + "policy", + p.startswith("alpn-") or p == "hrr", + 24002 if p == "hrr" else 24003 if p == "tls12" else 24001, + None + if p == "alpn-empty" + else "fixture-custom" + if p == "alpn-custom" + else "h2", + None, + ) + for p in POLICIES + ] + elif name == "MIHOMO-FAULT": + consumers = { + "fragment": "native_tcp", + "hrr-wire": "native_tcp", + "cover-mac": "policy", + "stall": "stall", + "native-udp-disabled": "native_udp_disabled", + } + labels = [ + ( + f"{f}-chrome", + consumers.get(f, "corrupt"), + f not in {"cover-mac", "stall"}, + 24002 if f == "hrr-wire" else 24001, + "h2", + f, + ) + for f in FAULTS + ] + elif name == "NATIVE": + labels = [(c, "native_tcp", True, None, None, None) for c in SS_CASES] + else: + raise ValueError("unknown wire group") + rows = report.get("cases", []) + if [r.get("case_id") for r in rows] != [item[0] for item in labels]: + return False + for row, (identifier, consumer, success, port, alpn, fault) in zip( + rows, labels, strict=True + ): + observed = read_json(directory / (identifier + "-observations.json")) + events = read_events(directory / (identifier + "-events.jsonl")) + if not ( + row.get("command") == rust_command("vless_public", "shadowtls::" + consumer) + and type(row.get("exit_code")) is int + and row["exit_code"] == 0 + and row.get("command_cleanup") is True + and observed + == row.get("observations") + == expected_observation(consumer, success) + and assertions_pass(events, {("SHADOWTLS", consumer): 1}) + ): + return False + cover = row.get("cover", []) + if ( + port is not None + and success + and dict(port=port, version="TLSv1.3", alpn=alpn) not in cover + ): + return False + if fault is not None and not fault_pass(fault, row.get("fault", []), cover): + return False + return True + + +def local_pass(name, directory, run): + expected = commands(name) + records = [ + r for r in run["commands"] if r["name"].startswith("SHADOWTLS-" + name + "-") + ] + if len(records) != len(expected): + return False + events = [] + for i, (row, argv) in enumerate(zip(records, expected, strict=True)): + label = f"SHADOWTLS-{name}-{i}" + if row["name"] != label or row["command"] != [ + redact(v.replace("{output}", str(directory))) for v in argv + ]: + return False + validate_execution( + row["command"], + (directory / row["log"]).read_text(), + row["exit_code"], + row["cleanup"], + ) + path = directory / (label + "-events.jsonl") + if path.exists(): + events += read_events(path) + if name == "MEMORY": + return assertions_pass( + [e for e in events if e.get("suite", "").startswith("SHADOWTLS-")], + MEMORY_EVENTS, + ) + if name == "FEATURES": + return assertions_pass( + [e for e in events if e.get("suite") == "SHADOWTLS-CFG"], + {("SHADOWTLS-CFG", "feature"): 1}, + ) + if name == "FINGERPRINT": + from .protocol_fingerprint_shape import check_captures, check_warm_captures + + root = directory / "fingerprint" + report = read_json(root / "shape-results.json") + return ( + report.get("source") == source(run) + and report.get("source_unchanged") is True + and report.get("cleanup") is True + and report.get("cases") == check_captures(read_json(root / "captures.json")) + and report.get("warm_cases") + == check_warm_captures(read_json(root / "warm.json")) + ) + return True + + +def source(run): + return { + k: run[k] + for k in ( + "parent_commit", + "source_tree_sha256", + "dirty_patch_sha256", + "lock_sha256", + ) + } + + +def group_pass(name, directory, run, peers): + if name in LOCAL: + return local_pass(name, directory, run) + root = directory / name.lower() + digest = run["container_image"]["digest"] + if name == "SHARED": + return all( + envelope( + report := read_json(root / label / REPORTS["vless"]), + peers, + source(run), + digest, + ) + and vless_pass(group, report, root / label) + for label, group in SHARED.items() + ) + if name == "BARE-SS": + report = read_json(root / "integration-suite.json") + rows = report.get("cases", []) + return ( + envelope(report, peers, source(run), digest) + and len(rows) == 1 + and runtime_pass("INTEGRATION-SS-ALGORITHMS", rows[0], root) + ) + report = read_json(root / "report.json") + identities = report.get("peers") if name == "NATIVE" else {"M": report.get("peer")} + return ( + set(identities) == ({"SS", "ST"} if name == "NATIVE" else {"M"}) + and envelope( + report, peers, source(run), digest, single=None if name == "NATIVE" else "M" + ) + and wire_pass(name, root, report) + ) + + +def prepare(output, *, native): + from .native_release import download_native + from .protocol_hysteria2_acceptance import prepare as prepare_mihomo + + supplied = prepare_mihomo(output, {"M"}) + artifacts = ( + { + kind: download_native( + kind, output / "binaries" / kind, "linux-arm64", defer_version=True + ) + for kind in ("ST", "SS") + } + if native + else {} + ) + return supplied, artifacts + + +def execute(cases, run, output, results): + from .protocol_containers import frozen_image + from .protocol_harness import _command + from .protocol_integration_suite import run as integration + from .protocol_shadowtls import run as mihomo + from .protocol_shadowtls_native import run as native + from .protocol_vless_container import run as vless + + selected = {c["case_id"].removeprefix("SHADOWTLS-"): c for c in cases} + peers = {} + + def save(name): + good = group_pass(name, output, run, peers) + case = selected[name] + results[case["case_id"]] = result(case, good, good) + print(case["case_id"] + (": PASS" if good else ": FAIL"), flush=True) + if not good: + raise RuntimeError("ShadowTLS gate failed: " + name) + + try: + for name in selected: + if name not in LOCAL: + continue + for i, argv in enumerate(commands(name)): + label = f"SHADOWTLS-{name}-{i}" + command = _command( + run, + output, + label, + [v.replace("{output}", str(output)) for v in argv], + 3600, + events=output / (label + "-events.jsonl"), + ) + validate_execution( + argv, + command.stdout.decode(errors="replace"), + command.returncode, + command.cleanup, + ) + save(name) + if set(selected) <= LOCAL: + return + with frozen_image(output / "image-pull.log") as image: + run["container_image"] = image + supplied, artifacts = prepare(output, native="NATIVE" in selected) + peers.update({k: v[1] for k, v in supplied.items()}) + peers.update({k: v.identity for k, v in artifacts.items()}) + for name in selected: + if name in LOCAL: + continue + root = output / name.lower() + if name.startswith("MIHOMO-"): + mihomo( + root, + profiles=PROFILES if name == "MIHOMO-DATA" else ("chrome",), + checks=name.removeprefix("MIHOMO-").lower(), + supplied=supplied["M"], + image=image, + ) + elif name == "NATIVE": + native(root, supplied=artifacts, image=image) + elif name == "SHARED": + for label, group in SHARED.items(): + vless(root / label, supplied=supplied, **group) + elif name == "BARE-SS": + integration( + root, ["INTEGRATION-SS-ALGORITHMS"], supplied=supplied["M"] + ) + else: + raise ValueError("unknown ShadowTLS gate") + save(name) + finally: + (output / "peers.json").write_text(json.dumps(peers, indent=2) + "\n") + + +def check(directory, cases, run, results, peers, paths): + if not {"cases.json", "peers.json", "resources.jsonl", "summary.md"} <= set(paths): + raise ValueError("missing ShadowTLS evidence files") + expected_commands = [ + f"SHADOWTLS-{c['case_id'].removeprefix('SHADOWTLS-')}-{i}" + for c in cases + for i, _ in enumerate(commands(c["case_id"].removeprefix("SHADOWTLS-"))) + ] + actual = [r["name"] for r in run["commands"]] + if ( + len(actual) != len(set(actual)) + or set(actual) != set(expected_commands) + or set(peers) != {"M", "SS", "ST"} + ): + raise ValueError("ShadowTLS command or peer selection differs") + for case in cases: + name = case["case_id"].removeprefix("SHADOWTLS-") + if not group_pass(name, directory, run, peers): + raise ValueError("ShadowTLS raw evidence failed: " + name) + print("SHADOWTLS coverage: PASS (all required groups; device delivery separate)") + + +def preflight(output): + from .protocol_containers import command, frozen_image + + command("system", "status") + with frozen_image(output / "image-pull.log"): + supplied, artifacts = prepare(output, native=True) + (output / "peers.json").write_text( + json.dumps( + dict( + scope="download-only", + wire_acceptance="NOT RUN", + peers={ + **{k: v[1] for k, v in supplied.items()}, + **{k: v.identity for k, v in artifacts.items()}, + }, + ), + indent=2, + ) + + "\n" + ) diff --git a/scripts/src/vcore_scripts/protocol_shadowtls_catalog.py b/scripts/src/vcore_scripts/protocol_shadowtls_catalog.py new file mode 100644 index 0000000..da9701a --- /dev/null +++ b/scripts/src/vcore_scripts/protocol_shadowtls_catalog.py @@ -0,0 +1,179 @@ +"""Frozen ShadowTLS v3 acceptance groups, not a duplicate field matrix.""" + +from __future__ import annotations + +import sys + +from .protocol_completion_peers import CASES + +SS_CASES = tuple(c.identifier for c in CASES if c.shadow_tls and not c.uot) +FAULTS = ( + "fragment", + "hrr-wire", + "cover-mac", + "business-mac", + "business-truncated", + "stall", + "native-udp-disabled", +) +GATES = { + "MEMORY": "stream", + "FEATURES": "configuration", + "QUALITY": "regression", + "PLATFORMS": "regression", + "FINGERPRINT": "regression", + "MIHOMO-DATA": "interop", + "MIHOMO-POLICY": "interop", + "MIHOMO-FAULT": "interop", + "NATIVE": "interop", + "SHARED": "regression", + "BARE-SS": "regression", +} +LOCAL = {"MEMORY", "FEATURES", "QUALITY", "PLATFORMS", "FINGERPRINT"} +SHARED = { + **{ + p: dict( + client_fingerprint=p, + selected=[ + "VLESS-TCP-TLS-BASE", + "VLESS-TCP-TLS-NEG", + "VLESS-TCP-REALITY-BASE", + "VLESS-TCP-REALITY-NEG", + "FINGERPRINT-ANYTLS", + ], + ) + for p in ("none", "chrome") + }, + "jls": dict( + jls=True, + client_fingerprint="chrome", + selected=["SECURITY-JLS-TCP-BASE", "SECURITY-JLS-TCP-AUTH"], + ), +} +MEMORY_EVENTS = { + **{("SHADOWTLS-CFG", n): 1 for n in ("policy", "reject", "feature")}, + **{("SHADOWTLS-STREAM", n): 1 for n in ("cancelled_hello", "invalid_record")}, + **{ + ("SHADOWTLS-UNIT", n): 1 + for n in ( + "native_signature", + "native_finished", + "stream_io", + "read_cancel", + "close_deadline", + ) + }, +} + + +def definitions(): + return [ + dict( + case_id="SHADOWTLS-" + name, + stage="SHADOWTLS", + substage="SHADOWTLS." + category, + required=True, + row_ids=[], + protocol="ss", + network="tcp/native-udp", + security="shadowtls-v3", + udp_codec="ss2022", + field_values={}, + outer_family="IPv4", + inner_family="IPv4/IPv6/domain", + target_type="memory-only/build" if name in LOCAL else "isolated origin", + upstream_graph="existing-controlled-connector", + peer_kind="unit" if name in LOCAL else "SS" if name == "NATIVE" else "M", + peer_config={"group": name}, + gap_source=None, + expected_observation=["SHADOWTLS-" + name], + required_evidence=["command", "structured-assertions", "cleanup"] + + ([] if name in LOCAL else ["peer-identity", "isolated-origins"]), + prerequisites=["rust-toolchain"] + if name in LOCAL + else ["owned-host-only-container-network", "official-latest-peer"], + runner="shadowtls-gate", + timeout_seconds=3600, + ) + for name, category in GATES.items() + ] + + +def commands(name): + cargo = ["cargo", "test", "--locked", "--all-features"] + if name == "MEMORY": + return [ + cargo + + [ + arg + for target in ( + "shadowtls_config", + "shadowtls_stream", + "shadowsocks_backpressure", + "jls_config", + "reality_config", + ) + for arg in ("--test", target) + ], + cargo + ["--lib", "security::shadow_tls_tests::"], + cargo + ["--lib", "security::tls::tests::"], + ] + if name == "FEATURES": + return [ + [ + "cargo", + "check", + "--locked", + "--no-default-features", + "--features", + features, + ] + for features in ( + "outbound-shadowsocks", + "shadow-tls-v3", + "outbound-shadowsocks,shadow-tls-v3", + ) + ] + [ + [ + "cargo", + "test", + "--locked", + "--no-default-features", + "--features", + "outbound-shadowsocks,interop-test", + "--test", + "shadowtls_config", + ], + ["cargo", "test", "--locked", "--test", "feature_foundations"], + cargo + ["--all-targets", "--no-run"], + ] + if name == "QUALITY": + return [ + ["cargo", "fmt", "--all", "--", "--check"], + [ + "cargo", + "clippy", + "--locked", + "--all-features", + "--all-targets", + "--", + "-D", + "warnings", + ], + [sys.executable, "-m", "unittest", "discover", "-s", "scripts/tests"], + ["ruff", "check", "scripts"], + ["ruff", "format", "--check", "scripts"], + ["git", "diff", "--check"], + ] + if name == "PLATFORMS": + return [["vcore-scripts", "build", target] for target in ("apple", "android")] + if name == "FINGERPRINT": + return [ + [ + sys.executable, + "-m", + "vcore_scripts.protocol_fingerprint_shape", + "{output}/fingerprint", + ] + ] + return [] diff --git a/scripts/src/vcore_scripts/protocol_shadowtls_native.py b/scripts/src/vcore_scripts/protocol_shadowtls_native.py new file mode 100644 index 0000000..ecf34a3 --- /dev/null +++ b/scripts/src/vcore_scripts/protocol_shadowtls_native.py @@ -0,0 +1,306 @@ +"""Supplementary native ShadowTLS + unmodified ssserver TCP acceptance.""" + +from __future__ import annotations + +import contextlib +import json +import os +import shutil +import tempfile +from pathlib import Path + +from .builds import CORE_DIR +from .mihomo_isolation import exclusive_run +from .native_release import download_native +from .protocol_completion_peers import CASES, peer_configuration +from .protocol_containers import ContainerLab, command, frozen_image +from .protocol_fixtures import certificates +from .protocol_inputs import redact, same_source, source_identity +from .protocol_peers import run_command + + +def run(output: Path, *, supplied=None, image=None): + output = output.resolve() + if not output.is_relative_to((CORE_DIR / "target/interop/runs").resolve()): + raise ValueError("native ShadowTLS evidence must stay in the owned run root") + output.mkdir(parents=True, exist_ok=False) + report = dict( + source=source_identity(), status="NOT RUN", peers={}, isolation={}, cases=[] + ) + directories = {} + try: + with ( + exclusive_run() if supplied is None else contextlib.nullcontext(), + ( + frozen_image(output / "image-pull.log") + if image is None + else contextlib.nullcontext(image) + ) as image, + ): + report["container_image"] = image + artifacts = supplied or { + kind: download_native( + kind, output / kind, "linux-arm64", defer_version=True + ) + for kind in ("ST", "SS") + } + for kind, artifact in artifacts.items(): + report["peers"][kind] = artifact.identity + built = run_command( + [ + "cargo", + "test", + "--locked", + "--all-features", + "--test", + "vless_public", + "--no-run", + ], + cwd=CORE_DIR, + timeout=180, + ) + (output / "build.log").write_text( + redact(built.stdout.decode(errors="replace")) + ) + if built.returncode or not built.cleanup: + raise RuntimeError("native ShadowTLS consumer build failed") + lab = ContainerLab(report["isolation"], mtu=1500) + with tempfile.TemporaryDirectory(prefix="private-", dir=output) as temp: + root = Path(temp) + try: + with contextlib.ExitStack() as stack: + for role in ( + "origin", + "ssserver", + "shadow0", + "shadow1", + "shadow2", + ): + directories[role] = root / role + directories[role].mkdir() + cert = certificates(directories["origin"]) + shutil.copy2( + Path(__file__).with_name("container_udp_origin.py"), + directories["origin"] / "origin.py", + ) + origin = lab.start( + stack, + directories["origin"], + "origin", + [ + "env", + "VCORE_ISOLATED_ORIGIN=1", + "VCORE_ORIGIN_CERT=/data/fixture/cert.pem", + "VCORE_ORIGIN_KEY=/data/fixture/key.pem", + "python", + "-B", + "/data/fixture/origin.py", + ], + ) + shutil.copy2( + artifacts["SS"].binary, directories["ssserver"] / "ssserver" + ) + ss = lab.start( + stack, + directories["ssserver"], + "ssserver", + [ + "/data/fixture/ssserver", + "-c", + "/data/fixture/config.json", + ], + ) + peers = {"SS": ss} + servers, nodes, relays = [], [], [] + for index, case in enumerate( + c for c in CASES if c.shadow_tls and not c.uot + ): + directory = directories[f"shadow{index}"] + shutil.copy2( + artifacts["ST"].binary, directory / "shadow-tls" + ) + relay = lab.start( + stack, + directory, + f"shadow{index}", + [ + "env", + "RUST_LOG=error", + "/data/fixture/shadow-tls", + "--threads", + "1", + "--v3", + "--strict", + "server", + "--listen", + "0.0.0.0:23000", + "--server", + f"{ss.ipv4}:{23100 + index}", + "--tls", + f"{origin.ipv4}:24001", + "--password", + "synthetic-shadowtls-fixture", + ], + ) + peers.setdefault("ST", relay) + node, _ = peer_configuration( + case, + server=relay.ipv4, + cover=f"{origin.ipv4}:24001", + port=23000, + certificate=cert, + ) + node.update(name="peer", udp=False) + node["client-fingerprint"] = "chrome" + nodes.append((case.identifier, node)) + relays.append(relay) + servers.append( + dict( + server="::", + server_port=23100 + index, + method=node["cipher"], + password=node["password"], + mode="tcp_only", + ) + ) + for kind, peer in peers.items(): + name = artifacts[kind].binary.name + identity = report["peers"][kind] + identity["version"] = command( + "exec", peer.name, f"/data/fixture/{name}", "--version" + ).strip() + if ( + not identity["version"] + or command( + "exec", + peer.name, + "sha256sum", + f"/data/fixture/{name}", + ).split()[0] + != identity["binary_sha256"] + ): + raise RuntimeError( + "native ShadowTLS peer identity mismatch" + ) + (directories["ssserver"] / "config.json").write_text( + json.dumps(dict(servers=servers)) + ) + origin.release() + origin.wait_tcp(24000) + origin.wait_tcp(24001) + ss.release() + for index in range(3): + ss.wait_tcp(23100 + index) + for relay in relays: + relay.release() + relay.wait_tcp(23000) + for identifier, node in nodes: + fixture = root / "fixture.json" + fixture.write_text( + json.dumps( + dict( + isolation="containers", + node=node, + origin_ipv4=origin.ipv4, + origin_ipv6=origin.ipv6, + origin_control=f"{origin.ipv4}:24000", + data_dir=str(root / "data"), + ) + ) + ) + observations = output / f"{identifier}-observations.json" + argv = [ + "cargo", + "test", + "--locked", + "--all-features", + "--test", + "vless_public", + "shadowtls::native_tcp", + "--", + "--ignored", + "--exact", + "--nocapture", + ] + result = run_command( + argv, + cwd=CORE_DIR, + timeout=240, + env=dict( + os.environ, + VCORE_VLESS_INPUT=str(fixture), + VCORE_SHADOWTLS_OBSERVATIONS=str(observations), + VCORE_CASE_EVENTS=str( + output / f"{identifier}-events.jsonl" + ), + ), + ) + (output / f"{identifier}.log").write_text( + redact(result.stdout.decode(errors="replace")) + ) + observed = ( + json.loads(observations.read_text()) + if observations.is_file() + else None + ) + passed = ( + result.returncode == 0 + and result.cleanup + and observed + == dict( + tcp_bytes_each_direction=10 * 1024 * 1024, + udp_packets=0, + udp_sizes=[], + stop_idle=True, + ) + ) + report["cases"].append( + dict( + case_id=identifier, + status="PASS" if passed else "FAIL", + command=argv, + exit_code=result.returncode, + command_cleanup=result.cleanup, + observations=observed, + ) + ) + print( + f"{identifier}: {'PASS' if passed else 'FAIL'}", + flush=True, + ) + if not passed: + raise RuntimeError( + "native ShadowTLS TCP validation failed" + ) + finally: + for role, directory in directories.items(): + if (directory / "peer.log").is_file(): + (output / f"{role}.log").write_text( + redact( + (directory / "peer.log").read_text(errors="replace") + ) + ) + report["status"] = "PASS" + except BaseException as error: + report["status"] = "FAIL" + (output / "failure.log").write_text(redact(str(error))) + raise + finally: + report["cleanup"] = all( + p.get("joined") is True for p in report["isolation"].get("peers", []) + ) + report["source_unchanged"] = same_source(report["source"], source_identity()) + if not report["cleanup"] or not report["source_unchanged"]: + report["status"] = "FAIL" + (output / "report.json").write_text(json.dumps(report, indent=2) + "\n") + if report["status"] != "PASS": + raise RuntimeError("native ShadowTLS source or cleanup gate failed") + return report + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("output", type=Path) + run(parser.parse_args().output) diff --git a/scripts/src/vcore_scripts/protocol_tuic.py b/scripts/src/vcore_scripts/protocol_tuic.py new file mode 100644 index 0000000..21a2596 --- /dev/null +++ b/scripts/src/vcore_scripts/protocol_tuic.py @@ -0,0 +1,543 @@ +"""TUIC v5 public consumers against freshly downloaded, isolated Mihomo.""" + +from __future__ import annotations + +import contextlib +import copy +import json +import os +import shutil +import tempfile +from pathlib import Path + +from .builds import CORE_DIR +from .mihomo_isolation import exclusive_run +from .mihomo_release import download_mihomo +from .protocol_completion_peers import CASES, peer_configuration +from .protocol_containers import ContainerLab, command, frozen_image +from .protocol_fixtures import certificate_chain +from .protocol_inputs import redact, same_source, source_identity +from .protocol_peers import run_command +from .protocol_security_acceptance import rust_command + + +def expected_observation(consumer): + if consumer == "udp_disabled": + return dict(udp_packets=0, tcp_works=True, stop_idle=True) + if consumer == "group": + return dict( + nested_select=True, + pooled_path_retained=True, + explicit_rebuild=True, + reject_no_fallback=True, + new_direct=True, + node_measure=True, + group_measure_rejected=True, + rollback=True, + stop_idle=True, + ) + if consumer == "udp": + return dict( + udp_packets=2100, + udp_sizes=[0, 1, 64, 512, 1200, 4096, 16384], + families=["ipv4", "ipv6", "domain"], + alternating_origins=True, + tcp_sibling=True, + stop_idle=True, + ) + if consumer == "tcp": + return dict( + families=["ipv4", "ipv6", "domain"], + tcp_bytes_each_family_each_direction=10 * 1024 * 1024, + sibling_survives=True, + stop_idle=True, + ) + if consumer == "rejected": + return dict(origin_connected=False, received_business_bytes=0, stop_idle=True) + raise ValueError("unknown TUIC consumer") + + +def inputs(node, listener, checks): + if checks == "negative": + for index, (kind, mode) in enumerate( + (kind, mode) + for kind in ("udp-disabled", "socks5-tcp-only") + for mode in ("native", "quic") + ): + client, peer = copy.deepcopy(node), copy.deepcopy(listener) + client["udp-relay-mode"] = mode + client["udp"] = kind != "udp-disabled" + client["port"] = peer["port"] = 23000 + index + peer["name"] = kind + "-" + mode + yield ( + peer["name"], + client, + peer, + ("udp_disabled" if kind == "udp-disabled" else "rejected"), + ) + return + if checks == "paths": + for index, (upstream, mode) in enumerate( + (upstream, mode) + for upstream in ("socks5", "ss-uot", "anytls") + for mode in ("native", "quic") + ): + client, peer = copy.deepcopy(node), copy.deepcopy(listener) + client["udp-relay-mode"] = mode + client["port"] = peer["port"] = 23000 + index + peer["name"] = upstream + "-" + mode + yield peer["name"], client, peer, "group" + return + if checks == "udp": + for index, mode in enumerate(("native", "quic")): + client, peer = copy.deepcopy(node), copy.deepcopy(listener) + client["udp-relay-mode"] = mode + client["port"] = peer["port"] = 23000 + index + peer["name"] = "udp-" + mode + yield peer["name"], client, peer, "udp" + return + names = ( + ("tcp-cubic", "tcp-new_reno", "tcp-bbr") + if checks == "tcp" + else ( + "alpn-default", + "alpn-custom", + "empty-password", + "raw-password", + "skip", + "verify-name", + "wrong-uuid", + "wrong-password", + "wrong-pin", + "wrong-pin-skip", + "untrusted", + "wrong-name-skip", + "wrong-alpn", + ) + ) + for index, name in enumerate(names): + client, peer = copy.deepcopy(node), copy.deepcopy(listener) + client["udp"] = False + client.pop("udp-relay-mode") + client["port"] = peer["port"] = 23000 + index + peer["name"] = name + if name.startswith("tcp-"): + client["congestion-controller"] = name.removeprefix("tcp-") + elif name == "alpn-default": + del client["alpn"] + elif name == "alpn-custom": + client["alpn"] = ["not-selected", "fixture-custom"] + peer["alpn"] = ["fixture-custom"] + elif name in {"empty-password", "raw-password"}: + client["password"] = ( + "" if name == "empty-password" else " synthetic-原样\t\0 " + ) + peer["users"] = {client["uuid"]: client["password"]} + elif name == "skip": + del client["fingerprint"] + client["skip-cert-verify"] = True + elif name == "verify-name": + client["sni"] = "unrelated.invalid" + client["name-cert-verify"] = "localhost" + elif name == "wrong-uuid": + client["uuid"] = "09090909-0909-0909-0909-090909090909" + elif name == "wrong-password": + client["password"] = "incorrect-synthetic-auth" + elif name.startswith("wrong-pin"): + client["fingerprint"] = "09" * 32 + client["skip-cert-verify"] = name.endswith("skip") + elif name == "untrusted": + del client["fingerprint"] + elif name == "wrong-name-skip": + client["name-cert-verify"] = "unrelated.invalid" + client["skip-cert-verify"] = True + elif name == "wrong-alpn": + client["alpn"] = ["unrelated"] + yield ( + name, + client, + peer, + "rejected" if name.startswith("wrong-") or name == "untrusted" else "tcp", + ) + + +def upstream_pair(name, node, certificate, index): + cert, key, pin = certificate + base = dict(name="hop", server=node["server"], port=23100 + index, udp=True) + listener = dict(name="hop-" + str(index), listen="::", port=base["port"]) + if name.startswith("socks5-"): + return dict(base, type="socks5"), dict(listener, type="socks", udp=True) + if name.startswith("ss-uot-"): + keytext = "BwcHBwcHBwcHBwcHBwcHBw==" + return dict( + base, + type="ss", + cipher="2022-blake3-aes-128-gcm", + password=keytext, + **{"udp-over-tcp": True}, + ), dict( + listener, + type="shadowsocks", + cipher="2022-blake3-aes-128-gcm", + password=keytext, + udp=False, + ) + if name.startswith("anytls-"): + password = "synthetic-hop" + return dict( + base, type="anytls", password=password, sni="localhost", fingerprint=pin + ), dict( + listener, + type="anytls", + users={"fixture": password}, + certificate="/data/fixture/" + cert.name, + **{"private-key": "/data/fixture/" + key.name}, + ) + raise ValueError("unknown TUIC upstream") + + +def run(output, *, checks="tcp", selected=None, supplied=None, image=None): + if checks not in {"tcp", "policy", "udp", "paths", "negative"}: + raise ValueError("unknown TUIC check") + output = output.resolve() + if not output.is_relative_to((CORE_DIR / "target/interop/runs").resolve()): + raise ValueError("TUIC evidence must stay in target/interop/runs") + output.mkdir(parents=True, exist_ok=False) + report = dict( + source=source_identity(), status="NOT RUN", peer={}, isolation={}, cases=[] + ) + try: + with ( + exclusive_run() if supplied is None else contextlib.nullcontext(), + frozen_image(output / "image-pull.log") + if image is None + else contextlib.nullcontext(image) as image, + ): + report["container_image"] = image + if supplied is None: + binary = download_mihomo( + "linux-arm64", directory=output / "binary", identity=report["peer"] + ) + else: + binary, report["peer"] = supplied + built = run_command( + [ + "cargo", + "test", + "--locked", + "--all-features", + "--test", + "vless_public", + "--no-run", + ], + cwd=CORE_DIR, + timeout=180, + ) + (output / "build.log").write_text( + redact(built.stdout.decode(errors="replace")) + ) + if built.returncode or not built.cleanup: + raise RuntimeError("TUIC consumer build failed") + lab = ContainerLab(report["isolation"], mtu=1500) + with tempfile.TemporaryDirectory(prefix="private-", dir=output) as tmp: + root = Path(tmp) + directories = { + role: root / role + for role in ( + "origin", + "server", + *(["upstream"] if checks in {"paths", "negative"} else []), + ) + } + for d in directories.values(): + d.mkdir() + cert = certificate_chain(directories["server"]) + shutil.copy2(binary, directories["server"] / "mihomo") + if checks in {"paths", "negative"}: + for asset in (binary, *cert[:2]): + shutil.copy2( + asset, + directories["upstream"] + / ("mihomo" if asset == binary else asset.name), + ) + shutil.copy2( + Path(__file__).with_name("container_restart_peer.py"), + directories["server"] / "restart.py", + ) + shutil.copy2( + Path(__file__).with_name("container_udp_origin.py"), + directories["origin"] / "origin.py", + ) + try: + with contextlib.ExitStack() as stack: + origin = lab.start( + stack, + directories["origin"], + "origin", + [ + "env", + "VCORE_ISOLATED_ORIGIN=1", + "python", + "-B", + "/data/fixture/origin.py", + ], + ) + server = lab.start( + stack, + directories["server"], + "server", + [ + *( + [ + "env", + "VCORE_ISOLATED_ORIGIN=1", + "python", + "-B", + "/data/fixture/restart.py", + ] + if checks == "paths" + else [] + ), + "/data/fixture/mihomo", + "-d", + "/data", + "-f", + "/data/fixture/config.json", + ], + ) + upstream = ( + lab.start( + stack, + directories["upstream"], + "upstream", + [ + "/data/fixture/mihomo", + "-d", + "/data", + "-f", + "/data/fixture/config.json", + ], + ) + if checks in {"paths", "negative"} + else None + ) + report["peer"]["version"] = command( + "exec", server.name, "/data/fixture/mihomo", "-v" + ).strip() + if ( + command( + "exec", server.name, "sha256sum", "/data/fixture/mihomo" + ).split()[0] + != report["peer"]["binary_sha256"] + ): + raise RuntimeError("TUIC peer binary identity mismatch") + case = next( + c for c in CASES if c.identifier == "tuic-v5-native" + ) + node, listener = peer_configuration( + case, + server=server.ipv4, + cover="", + port=23000, + certificate=cert, + ) + node["name"] = "peer" + rows = list(inputs(node, listener, checks)) + if selected is not None: + if len(set(selected)) != len(selected) or not set( + selected + ) <= {r[0] for r in rows}: + raise ValueError("unknown or repeated TUIC case") + rows = [r for r in rows if r[0] in selected] + if not rows: + raise ValueError("empty TUIC selection") + upstreams = ( + { + r[0]: upstream_pair( + r[0], dict(r[1], server=upstream.ipv4), cert, i + ) + for i, r in enumerate(rows) + if checks == "paths" or r[0].startswith("socks5-") + } + if checks in {"paths", "negative"} + else {} + ) + if checks == "negative": + for client, peer in upstreams.values(): + client["udp"] = peer["udp"] = False + (directories["server"] / "config.json").write_text( + json.dumps( + { + "socks-port": 23999, + "allow-lan": True, + "bind-address": "*", + "ipv6": True, + "log-level": "warning", + "hosts": {"vcore-fixture.test": origin.ipv4}, + "listeners": [r[2] for r in rows], + "rules": ["MATCH,DIRECT"], + } + ) + ) + if upstream is not None: + (directories["upstream"] / "config.json").write_text( + json.dumps( + { + "socks-port": 23999, + "allow-lan": True, + "bind-address": "*", + "ipv6": True, + "log-level": "warning", + "listeners": [r[1] for r in upstreams.values()], + "rules": ["MATCH,DIRECT"], + } + ) + ) + if ( + command( + "exec", + upstream.name, + "sha256sum", + "/data/fixture/mihomo", + ).split()[0] + != report["peer"]["binary_sha256"] + or command( + "exec", upstream.name, "/data/fixture/mihomo", "-v" + ).strip() + != report["peer"]["version"] + ): + raise RuntimeError("TUIC upstream identity mismatch") + upstream.release() + upstream.wait_tcp(23999) + origin.release() + origin.wait_tcp(24000) + checked = run_command( + [ + "container", + "exec", + server.name, + "/data/fixture/mihomo", + "-t", + "-d", + "/data", + "-f", + "/data/fixture/config.json", + ], + timeout=30, + ) + (output / "peer-config.log").write_text( + redact(checked.stdout.decode(errors="replace")) + ) + if checked.returncode or not checked.cleanup: + raise RuntimeError( + "TUIC isolated peer configuration rejected" + ) + server.release() + server.wait_tcp(23999) + if checks == "paths": + server.wait_tcp(23998) + for name, node, _, consumer in rows: + fixture = root / "fixture.json" + fixture.write_text( + json.dumps( + dict( + isolation="containers", + node=node, + origin_ipv4=origin.ipv4, + origin_ipv6=origin.ipv6, + origin_control=f"{origin.ipv4}:24000", + data_dir=str(root / "data"), + **( + dict(upstream=upstreams[name][0]) + if name in upstreams + else {} + ), + **( + dict(restart_control=f"{server.ipv4}:23998") + if checks == "paths" + else {} + ), + ) + ) + ) + observations = output / (name + "-observations.json") + events = output / (name + "-events.jsonl") + argv = rust_command("vless_public", "tuic::" + consumer) + result = run_command( + argv, + cwd=CORE_DIR, + timeout=240, + env=dict( + os.environ, + VCORE_VLESS_INPUT=str(fixture), + VCORE_TUIC_OBSERVATIONS=str(observations), + VCORE_CASE_EVENTS=str(events), + ), + ) + (output / (name + ".log")).write_text( + redact(result.stdout.decode(errors="replace")) + ) + observed = ( + json.loads(observations.read_text()) + if observations.is_file() + else None + ) + from .protocol_evidence import read_events + from .protocol_hysteria2_catalog import assertions_pass + + good = ( + result.returncode == 0 + and result.cleanup + and observed == expected_observation(consumer) + and assertions_pass( + read_events(events), {("TUIC-PUBLIC", consumer): 1} + ) + ) + report["cases"].append( + dict( + case_id=name, + command=argv, + exit_code=result.returncode, + command_cleanup=result.cleanup, + observations=observed, + status="PASS" if good else "FAIL", + ) + ) + print(name + (": PASS" if good else ": FAIL"), flush=True) + if not good: + raise RuntimeError("TUIC public consumer failed") + finally: + for role, d in directories.items(): + if (d / "peer.log").is_file(): + (output / (role + ".log")).write_text( + redact((d / "peer.log").read_text(errors="replace")) + ) + report["status"] = "PASS" + except BaseException as error: + report["status"] = "FAIL" + (output / "failure.log").write_text(redact(str(error))) + raise + finally: + report["cleanup"] = all( + p.get("joined") is True for p in report["isolation"].get("peers", []) + ) + report["source_unchanged"] = same_source(report["source"], source_identity()) + if not report["cleanup"] or not report["source_unchanged"]: + report["status"] = "FAIL" + (output / "report.json").write_text(json.dumps(report, indent=2) + "\n") + if report["status"] != "PASS": + raise RuntimeError("TUIC source or cleanup failed") + return report + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("output", type=Path) + parser.add_argument( + "--checks", choices=("tcp", "policy", "udp", "paths", "negative"), default="tcp" + ) + parser.add_argument("--case", action="append") + args = parser.parse_args() + run(args.output, checks=args.checks, selected=args.case) diff --git a/scripts/src/vcore_scripts/protocol_tuic_acceptance.py b/scripts/src/vcore_scripts/protocol_tuic_acceptance.py new file mode 100644 index 0000000..cfc939d --- /dev/null +++ b/scripts/src/vcore_scripts/protocol_tuic_acceptance.py @@ -0,0 +1,230 @@ +"""Execute TUIC gates; reconstruct acceptance from raw local and container evidence.""" + +from __future__ import annotations + +import json + +from .core_checks import validate_execution +from .protocol_evidence import read_events, read_json +from .protocol_hysteria2_catalog import M, assertions_pass +from .protocol_hysteria2_catalog import definitions as hy2_definitions +from .protocol_inputs import redact +from .protocol_integration_checks import envelope +from .protocol_security_acceptance import result, rust_command +from .protocol_shadowtls_acceptance import source +from .protocol_tuic import expected_observation +from .protocol_tuic_catalog import ( + CFG_EVENTS, + LOCAL, + MEMORY_EVENTS, + commands, + wire_cases, +) + + +def wire_pass(name, directory, report): + selected = wire_cases(name) + rows = report.get("cases", []) + if [r.get("case_id") for r in rows] != [c[0] for c in selected]: + return False + for row, (identifier, consumer) in zip(rows, selected, strict=True): + if not ( + row.get("command") == rust_command("vless_public", "tuic::" + consumer) + and type(row.get("exit_code")) is int + and row["exit_code"] == 0 + and row.get("command_cleanup") is True + and row.get("observations") + == read_json(directory / (identifier + "-observations.json")) + == expected_observation(consumer) + and assertions_pass( + read_events(directory / (identifier + "-events.jsonl")), + {("TUIC-PUBLIC", consumer): 1}, + ) + ): + return False + return True + + +def local_pass(name, directory, run): + expected = commands(name) + rows = [r for r in run["commands"] if r["name"].startswith("TUIC-" + name + "-")] + if len(rows) != len(expected): + return False + events = [] + for index, (row, argv) in enumerate(zip(rows, expected, strict=True)): + label = f"TUIC-{name}-{index}" + if row["name"] != label or row["command"] != [redact(v) for v in argv]: + return False + validate_execution( + row["command"], + (directory / row["log"]).read_text(), + row["exit_code"], + row["cleanup"], + ) + path = directory / (label + "-events.jsonl") + if path.exists(): + events += read_events(path) + if name in {"MEMORY", "FEATURES"}: + required = ( + MEMORY_EVENTS + if name == "MEMORY" + else { + **{ + key: value + for key, value in MEMORY_EVENTS.items() + if key[1] + not in {"reassembly_order", "reassembly_limits", "delivery_limits"} + }, + **{ + key: 2 if key[1] in {"identity", "redaction"} else value + for key, value in CFG_EVENTS.items() + }, + } + ) + return assertions_pass( + [e for e in events if e.get("suite", "").startswith("TUIC-")], required + ) + return True + + +def group_pass(name, directory, run, peers): + from .protocol_hysteria2_acceptance import h3_result, native_result + + if name in LOCAL: + return local_pass(name, directory, run) + root = directory / name.lower() + digest = run["container_image"]["digest"] + if name.startswith("MIHOMO-"): + report = read_json(root / "report.json") + return envelope(report, peers, source(run), digest, single="M") and wire_pass( + name, root, report + ) + if name.startswith("HYSTERIA2-"): + case = next(c for c in hy2_definitions() if c["case_id"] == name) + report = read_json(root / "report.json") + return ( + envelope(report, peers, source(run), digest) + and native_result(case, report, root)["status"] == "PASS" + ) + if name == "XHTTP-H3": + from .protocol_hysteria2_catalog import H3 + + case = next(c for c in hy2_definitions() if c["case_id"] == H3) + report = read_json(root / "xhttp-fields-results.json") + return ( + envelope(report, peers, source(run), digest) + and h3_result(case, report, root)["status"] == "PASS" + ) + raise ValueError("unknown TUIC gate") + + +def execute(cases, run, output, results): + from .protocol_containers import frozen_image + from .protocol_harness import _command + from .protocol_hysteria2 import run as hysteria2 + from .protocol_hysteria2_acceptance import h3_jobs, prepare + from .protocol_tuic import run as tuic + from .protocol_xhttp_fields import run as h3 + + selected = {c["case_id"].removeprefix("TUIC-"): c for c in cases} + peers = {} + + def save(name): + good = group_pass(name, output, run, peers) + case = selected[name] + results[case["case_id"]] = result(case, good, good) + print(case["case_id"] + (": PASS" if good else ": FAIL"), flush=True) + if not good: + raise RuntimeError("TUIC gate failed: " + name) + + try: + for name in selected: + if name not in LOCAL: + continue + for i, argv in enumerate(commands(name)): + label = f"TUIC-{name}-{i}" + completed = _command( + run, + output, + label, + argv, + 3600, + events=output / (label + "-events.jsonl"), + ) + validate_execution( + argv, + completed.stdout.decode(errors="replace"), + completed.returncode, + completed.cleanup, + ) + save(name) + if set(selected) <= LOCAL: + return + with frozen_image(output / "image-pull.log") as image: + run["container_image"] = image + supplied = prepare(output, {"M", "XR"} if "XHTTP-H3" in selected else {"M"}) + peers.update({k: v[1] for k, v in supplied.items()}) + for name in selected: + if name in LOCAL: + continue + root = output / name.lower() + if name.startswith("MIHOMO-"): + tuic( + root, + checks=name.removeprefix("MIHOMO-").lower(), + supplied=supplied["M"], + image=image, + ) + elif name in M: + test, obfs, _ = M[name] + hysteria2(root, test, obfs=obfs, supplied=supplied["M"]) + elif name == "XHTTP-H3": + jobs = h3_jobs() + h3(root, list(jobs), jobs=jobs, supplied=supplied) + else: + raise ValueError("unknown TUIC group") + save(name) + finally: + (output / "peers.json").write_text(json.dumps(peers, indent=2) + "\n") + + +def check(directory, cases, run, results, peers, paths): + if not {"cases.json", "peers.json", "resources.jsonl", "summary.md"} <= set(paths): + raise ValueError("missing TUIC evidence") + expected = [ + f"{c['case_id']}-{i}" + for c in cases + for i, _ in enumerate(commands(c["case_id"].removeprefix("TUIC-"))) + ] + actual = [r["name"] for r in run["commands"]] + if ( + len(actual) != len(set(actual)) + or set(actual) != set(expected) + or set(peers) != {"M", "XR"} + ): + raise ValueError("TUIC command or peer selection differs") + for case in cases: + name = case["case_id"].removeprefix("TUIC-") + if not group_pass(name, directory, run, peers): + raise ValueError("TUIC raw evidence failed: " + name) + print("TUIC coverage: PASS (all required groups; device delivery separate)") + + +def preflight(output): + from .protocol_containers import command, frozen_image + from .protocol_hysteria2_acceptance import prepare + + command("system", "status") + with frozen_image(output / "image-pull.log"): + supplied = prepare(output, {"M", "XR"}) + (output / "peers.json").write_text( + json.dumps( + dict( + scope="download-only", + wire_acceptance="NOT RUN", + peers={k: v[1] for k, v in supplied.items()}, + ), + indent=2, + ) + + "\n" + ) diff --git a/scripts/src/vcore_scripts/protocol_tuic_catalog.py b/scripts/src/vcore_scripts/protocol_tuic_catalog.py new file mode 100644 index 0000000..acaab1b --- /dev/null +++ b/scripts/src/vcore_scripts/protocol_tuic_catalog.py @@ -0,0 +1,183 @@ +"""TUIC v5 required groups and independently enumerated wire consumers.""" + +from .protocol_shadowtls_catalog import commands as shared_commands + +LOCAL = {"MEMORY", "FEATURES", "QUALITY", "PLATFORMS", "SHARED-QUIC"} +HY2 = ("TCP", "UDP", "SECURITY", "OWNED", "DEADLINE") +GATES = { + "MEMORY": "datagrams", + "FEATURES": "configuration", + "QUALITY": "regression", + "PLATFORMS": "regression", + "SHARED-QUIC": "regression", + **{ + "MIHOMO-" + name: "interop" + for name in ("TCP", "POLICY", "UDP", "PATHS", "NEGATIVE") + }, + **{"HYSTERIA2-" + name: "regression" for name in HY2}, + "XHTTP-H3": "regression", +} +CFG_EVENTS = {("TUIC-CFG", n): 1 for n in ("identity", "redaction", "udp", "bounds")} +MEMORY_EVENTS = CFG_EVENTS | { + ("TUIC-UNIT", n): 1 + for n in ( + "tcp_owner", + "credit_deadline", + "path_requirements", + "handshake_stop", + "udp_wire", + "unused_association", + "session_retirement", + "partial_control_expiry", + "udp_credit_cancel", + "protect_fail_closed", + "heartbeat_full_queue_stop", + "receive_windows", + "send_buffers", + "reassembly_order", + "reassembly_limits", + "delivery_limits", + ) +} + + +def definitions(): + return [ + dict( + case_id="TUIC-" + name, + stage="TUIC", + substage="TUIC." + category, + required=True, + row_ids=[], + protocol="tuic", + network="quic", + security="tls13", + udp_codec="native/quic", + field_values={}, + outer_family="IPv4", + inner_family="IPv4/IPv6/domain", + target_type="memory-only/build" if name in LOCAL else "isolated origin", + upstream_graph="controlled-datagrams/optional-nested-select", + peer_kind="unit" if name in LOCAL else "M", + peer_config={"group": name}, + gap_source=None, + expected_observation=["TUIC-" + name], + required_evidence=["command", "structured-assertions", "cleanup"] + + ([] if name in LOCAL else ["peer-identity", "isolated-origins"]), + prerequisites=["rust-toolchain"] + if name in LOCAL + else ["owned-host-only-container-network", "official-latest-peer"], + runner="tuic-gate", + timeout_seconds=3600, + ) + for name, category in GATES.items() + ] + + +def wire_cases(name): + if name == "MIHOMO-TCP": + return [("tcp-" + n, "tcp") for n in ("cubic", "new_reno", "bbr")] + if name == "MIHOMO-POLICY": + return [ + (n, "tcp" if i < 6 else "rejected") + for i, n in enumerate( + ( + "alpn-default", + "alpn-custom", + "empty-password", + "raw-password", + "skip", + "verify-name", + "wrong-uuid", + "wrong-password", + "wrong-pin", + "wrong-pin-skip", + "untrusted", + "wrong-name-skip", + "wrong-alpn", + ) + ) + ] + if name == "MIHOMO-UDP": + return [("udp-" + mode, "udp") for mode in ("native", "quic")] + if name == "MIHOMO-PATHS": + return [ + (hop + "-" + mode, "group") + for hop in ("socks5", "ss-uot", "anytls") + for mode in ("native", "quic") + ] + if name == "MIHOMO-NEGATIVE": + return [ + ( + kind + "-" + mode, + "udp_disabled" if kind == "udp-disabled" else "rejected", + ) + for kind in ("udp-disabled", "socks5-tcp-only") + for mode in ("native", "quic") + ] + raise ValueError("unknown TUIC wire group") + + +def commands(name): + cargo = ["cargo", "test", "--locked", "--all-features"] + if name == "MEMORY": + return [ + cargo + ["--test", "tuic_config", "--test", "tuic_memory"], + cargo + ["--lib", "outbound::tuic::"], + ] + if name == "FEATURES": + return [ + ["cargo", "check", "--locked", "--no-default-features"] + + (["--features", f] if f else []) + for f in ("", "outbound-tuic", "quic-transport") + ] + [ + [ + "cargo", + "test", + "--locked", + "--no-default-features", + "--features", + "interop-test", + "--test", + "tuic_config", + ], + [ + "cargo", + "test", + "--locked", + "--no-default-features", + "--features", + "outbound-tuic,interop-test", + "--test", + "tuic_config", + "--test", + "tuic_memory", + ], + ["cargo", "test", "--locked", "--test", "feature_foundations"], + cargo + ["--all-targets", "--no-run"], + ] + if name == "SHARED-QUIC": + return [ + cargo + + [ + "--test", + "hysteria2_paths", + "--test", + "hysteria2_packet_ids", + "--test", + "xhttp_h3_shutdown", + "--test", + "limit_foundations", + ], + cargo + + [ + "--test", + "quic_datagram_foundations", + "pending_send_is_not_restarted_and_stop_cancels_without_waiting_for_writable", + "--", + "--exact", + ], + cargo + ["--lib", "outbound::hysteria2::"], + cargo + ["--lib", "security::tls::tests::"], + ] + return shared_commands(name) if name in {"QUALITY", "PLATFORMS"} else [] diff --git a/scripts/src/vcore_scripts/protocol_uot.py b/scripts/src/vcore_scripts/protocol_uot.py new file mode 100644 index 0000000..07aa629 --- /dev/null +++ b/scripts/src/vcore_scripts/protocol_uot.py @@ -0,0 +1,439 @@ +"""SS UoT v2 public consumers against unmodified TCP-only Mihomo listeners.""" + +from __future__ import annotations + +import base64 +import contextlib +import copy +import json +import os +import shutil +import tempfile +from pathlib import Path + +from .builds import CORE_DIR +from .mihomo_isolation import exclusive_run +from .mihomo_release import download_mihomo +from .protocol_completion_peers import CASES, peer_configuration +from .protocol_containers import ContainerLab, command, frozen_image +from .protocol_fixtures import certificates +from .protocol_inputs import redact, same_source, source_identity +from .protocol_peers import run_command +from .protocol_security_acceptance import rust_command + + +def expected_observation(consumer, via_socks5=False): + if consumer == "group": + return dict( + nested_select=True, + old_association_snapshot=True, + new_direct=True, + reject_no_fallback=True, + native_udp_packets=0, + stop_idle=True, + ) + if consumer == "rejected": + return dict( + origin_packets=0, received_packets=0, native_udp_packets=0, stop_idle=True + ) + if consumer != "data": + raise ValueError("unknown UoT consumer") + return dict( + udp_packets=2100, + udp_sizes=[0, 1, 64, 512, 1200, 4096, 16384], + families=["ipv4", "ipv6", "domain"], + alternating_origins=True, + controlled_dns=True, + tcp_regression=True, + stop_idle=True, + tcp_only_upstream=via_socks5, + peer_oversize_rejected=True, + native_udp_packets=0, + ) + + +def run( + output, + *, + selected=None, + via_socks5=False, + supplied=None, + image=None, + checks="data", + native=False, +): + if ( + checks not in {"data", "negative", "group"} + or (checks == "group" and not via_socks5) + or (native and (checks != "negative" or via_socks5)) + ): + raise ValueError("unsupported UoT peer checks") + output = output.resolve() + if not output.is_relative_to((CORE_DIR / "target/interop/runs").resolve()): + raise ValueError("UoT evidence must stay inside target/interop/runs") + cases = tuple(c for c in CASES if c.uot and (not native or not c.shadow_tls)) + if selected is not None: + if len(set(selected)) != len(selected) or not set(selected) <= { + c.identifier for c in cases + }: + raise ValueError("unknown or duplicate UoT selection") + cases = tuple(c for c in cases if c.identifier in selected) + if not cases: + raise ValueError("empty UoT selection") + output.mkdir(parents=True, exist_ok=False) + report = dict( + source=source_identity(), + status="NOT RUN", + peer={}, + isolation={}, + cases=[], + tcp_only_upstream=via_socks5, + ) + try: + with ( + exclusive_run() if supplied is None else contextlib.nullcontext(), + ( + frozen_image(output / "image-pull.log") + if image is None + else contextlib.nullcontext(image) + ) as image, + ): + report["container_image"] = image + if supplied is None: + if native: + from .native_release import download_native + + artifact = download_native( + "SS", output / "binary", "linux-arm64", defer_version=True + ) + binary, report["peer"] = artifact.binary, artifact.identity + else: + binary = download_mihomo( + "linux-arm64", + directory=output / "binary", + identity=report["peer"], + ) + else: + binary, report["peer"] = supplied + built = run_command( + [ + "cargo", + "test", + "--locked", + "--all-features", + "--test", + "vless_public", + "--no-run", + ], + cwd=CORE_DIR, + timeout=180, + ) + (output / "build.log").write_text( + redact(built.stdout.decode(errors="replace")) + ) + if built.returncode or not built.cleanup: + raise RuntimeError("UoT public consumer build failed") + lab = ContainerLab(report["isolation"], mtu=1500) + with tempfile.TemporaryDirectory(prefix="private-", dir=output) as temp: + root = Path(temp) + directories = { + role: root / role + for role in ( + "origin", + "server", + *(["upstream"] if via_socks5 else []), + ) + } + for d in directories.values(): + d.mkdir() + certificate = certificates(directories["server"]) + for source, name in zip( + certificate[:2], ("cert.pem", "key.pem"), strict=True + ): + shutil.copy2(source, directories["origin"] / name) + for source, target in ( + ("container_udp_origin.py", "origin.py"), + ("container_shadowtls_peer.py", "peer.py"), + ): + shutil.copy2( + Path(__file__).with_name(source), directories["origin"] / target + ) + try: + with contextlib.ExitStack() as stack: + origin = lab.start( + stack, + directories["origin"], + "origin", + [ + "env", + "VCORE_ISOLATED_ORIGIN=1", + "VCORE_ORIGIN_CERT=/data/fixture/cert.pem", + "VCORE_ORIGIN_KEY=/data/fixture/key.pem", + "python", + "-B", + "/data/fixture/peer.py", + ], + ) + peers = {} + peer_name = "ssserver" if native else "mihomo" + for role in ("server", *(["upstream"] if via_socks5 else [])): + shutil.copy2(binary, directories[role] / peer_name) + shutil.copy2( + Path(__file__).with_name("container_uot_watch.py"), + directories[role] / "watch.py", + ) + peer_argv = ( + [ + f"/data/fixture/{peer_name}", + "-c", + "/data/fixture/config.json", + ] + if native + else [ + "/data/fixture/mihomo", + "-d", + "/data", + "-f", + "/data/fixture/config.json", + ] + ) + peers[role] = lab.start( + stack, + directories[role], + role, + [ + "env", + "VCORE_ISOLATED_ORIGIN=1", + "python", + "-B", + "/data/fixture/watch.py", + *peer_argv, + ], + ) + if ( + command( + "exec", + peers[role].name, + "sha256sum", + f"/data/fixture/{peer_name}", + ).split()[0] + != report["peer"]["binary_sha256"] + ): + raise RuntimeError( + "UoT peer identity differs from official download" + ) + server = peers["server"] + report["peer"]["version"] = command( + "exec", + server.name, + f"/data/fixture/{peer_name}", + "--version" if native else "-v", + ).strip() + nodes, listeners = [], [] + for index, case in enumerate(cases): + node, listener = peer_configuration( + case, + server=server.ipv4, + cover=f"{origin.ipv4}:24001", + port=23000 + index, + certificate=certificate, + ) + node["name"] = "peer" + if case.shadow_tls: + node["client-fingerprint"] = "chrome" + else: + del node["udp-over-tcp-version"] + assert listener["udp"] is False + if native: + nodes.append((case.identifier + "-unsupported", node)) + elif checks == "negative": + bad_key = copy.deepcopy(node) + bad_key["password"] = base64.b64encode( + bytes([9]) + * (16 if "aes-128" in node["cipher"] else 32) + ).decode() + nodes.append((case.identifier + "-key", bad_key)) + if case.shadow_tls: + bad_cover = copy.deepcopy(node) + bad_cover["plugin-opts"]["password"] = ( + "incorrect-synthetic-cover" + ) + nodes.append( + (case.identifier + "-identity", bad_cover) + ) + else: + nodes.append((case.identifier, node)) + listeners.append( + dict( + server="::", + server_port=node["port"], + method=node["cipher"], + password=node["password"], + mode="tcp_only", + ) + if native + else listener + ) + + def configuration(listeners): + return { + "socks-port": 23999, + "allow-lan": True, + "bind-address": "*", + "ipv6": True, + "log-level": "warning", + "listeners": listeners, + "rules": ["MATCH,DIRECT"], + } + + (directories["server"] / "config.json").write_text( + json.dumps( + dict(servers=listeners) + if native + else configuration(listeners) + ) + ) + upstream = None + if via_socks5: + upstream = dict( + name="hop", + type="socks5", + server=peers["upstream"].ipv4, + port=23050, + udp=False, + ) + (directories["upstream"] / "config.json").write_text( + json.dumps( + configuration( + [ + dict( + name="hop", + type="socks", + listen="::", + port=23050, + udp=False, + ) + ] + ) + ) + ) + origin.release() + origin.wait_tcp(24000) + origin.wait_tcp(24001) + for peer in peers.values(): + peer.release() + peer.wait_tcp(23998) + peer.wait_tcp(23000 if native else 23999) + for identifier, node in nodes: + fixture = root / "fixture.json" + value = dict( + isolation="containers", + node=node, + origin_ipv4=origin.ipv4, + origin_ipv6=origin.ipv6, + origin_control=f"{origin.ipv4}:24000", + udp_observer=f"{server.ipv4}:23998", + data_dir=str(root / "data"), + ) + if upstream is not None: + value["upstream"] = upstream + fixture.write_text(json.dumps(value)) + observations = output / (identifier + "-observations.json") + consumer = "rejected" if checks == "negative" else checks + argv = rust_command("vless_public", "uot::" + consumer) + result = run_command( + argv, + cwd=CORE_DIR, + timeout=240, + env=dict( + os.environ, + VCORE_VLESS_INPUT=str(fixture), + VCORE_UOT_OBSERVATIONS=str(observations), + VCORE_CASE_EVENTS=str( + output / (identifier + "-events.jsonl") + ), + ), + ) + (output / (identifier + ".log")).write_text( + redact(result.stdout.decode(errors="replace")) + ) + observed = ( + json.loads(observations.read_text()) + if observations.is_file() + else None + ) + expected = expected_observation(consumer, via_socks5) + from .protocol_evidence import read_events + from .protocol_hysteria2_catalog import assertions_pass + + good = ( + result.returncode == 0 + and result.cleanup + and observed == expected + and assertions_pass( + read_events( + output / (identifier + "-events.jsonl") + ), + {("UOT-PUBLIC", consumer): 1}, + ) + ) + report["cases"].append( + dict( + case_id=identifier, + command=argv, + exit_code=result.returncode, + command_cleanup=result.cleanup, + observations=observed, + listener_native_udp=False, + status="PASS" if good else "FAIL", + ) + ) + print( + identifier + (": PASS" if good else ": FAIL"), + flush=True, + ) + if not good: + raise RuntimeError("UoT public data failed") + finally: + for role, d in directories.items(): + if (d / "peer.log").is_file(): + (output / (role + ".log")).write_text( + redact((d / "peer.log").read_text(errors="replace")) + ) + report["status"] = "PASS" + except BaseException as error: + report["status"] = "FAIL" + (output / "failure.log").write_text(redact(str(error))) + raise + finally: + report["cleanup"] = all( + p.get("joined") is True for p in report["isolation"].get("peers", []) + ) + report["source_unchanged"] = same_source(report["source"], source_identity()) + if not report["cleanup"] or not report["source_unchanged"]: + report["status"] = "FAIL" + (output / "report.json").write_text(json.dumps(report, indent=2) + "\n") + if report["status"] != "PASS": + raise RuntimeError("UoT source or cleanup failed") + return report + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("output", type=Path) + parser.add_argument("--case", action="append") + parser.add_argument("--via-socks5", action="store_true") + parser.add_argument( + "--checks", choices=("data", "negative", "group"), default="data" + ) + parser.add_argument("--native", action="store_true") + args = parser.parse_args() + run( + args.output, + selected=args.case, + via_socks5=args.via_socks5, + checks=args.checks, + native=args.native, + ) diff --git a/scripts/src/vcore_scripts/protocol_uot_acceptance.py b/scripts/src/vcore_scripts/protocol_uot_acceptance.py new file mode 100644 index 0000000..9dbafd8 --- /dev/null +++ b/scripts/src/vcore_scripts/protocol_uot_acceptance.py @@ -0,0 +1,247 @@ +"""Execute UoT gates and independently verify their raw evidence.""" + +from __future__ import annotations + +import json + +from .core_checks import validate_execution +from .protocol_evidence import read_events, read_json +from .protocol_hysteria2_catalog import assertions_pass +from .protocol_inputs import redact +from .protocol_integration_checks import envelope, runtime_pass +from .protocol_security_acceptance import REPORTS, result, rust_command, vless_pass +from .protocol_shadowtls_acceptance import source +from .protocol_uot import expected_observation +from .protocol_uot_catalog import LOCAL, MEMORY_EVENTS, commands, wire_cases + + +def wire_pass(name, directory, report): + selected = wire_cases(name) + rows = report.get("cases", []) + if [r.get("case_id") for r in rows] != [c[0] for c in selected]: + return False + via_socks5 = name in {"MIHOMO-SOCKS5", "MIHOMO-GROUPS"} + if report.get("tcp_only_upstream") is not via_socks5: + return False + for row, (identifier, consumer) in zip(rows, selected, strict=True): + if not ( + row.get("command") == rust_command("vless_public", "uot::" + consumer) + and type(row.get("exit_code")) is int + and row["exit_code"] == 0 + and row.get("command_cleanup") is True + and row.get("listener_native_udp") is False + and row.get("observations") + == read_json(directory / (identifier + "-observations.json")) + == expected_observation(consumer, via_socks5) + and assertions_pass( + read_events(directory / (identifier + "-events.jsonl")), + {("UOT-PUBLIC", consumer): 1}, + ) + ): + return False + return True + + +def local_pass(name, directory, run): + expected = commands(name) + rows = [r for r in run["commands"] if r["name"].startswith("UOT-" + name + "-")] + if len(rows) != len(expected): + return False + events = [] + for index, (row, argv) in enumerate(zip(rows, expected, strict=True)): + label = f"UOT-{name}-{index}" + if row["name"] != label or row["command"] != [redact(v) for v in argv]: + return False + validate_execution( + row["command"], + (directory / row["log"]).read_text(), + row["exit_code"], + row["cleanup"], + ) + path = directory / (label + "-events.jsonl") + if path.exists(): + events += read_events(path) + if name == "MEMORY": + return assertions_pass( + [e for e in events if e.get("suite", "").startswith("UOT-")], MEMORY_EVENTS + ) + if name == "FEATURES": + return assertions_pass( + [e for e in events if e.get("suite", "").startswith("UOT-")], + MEMORY_EVENTS | {("UOT-CFG", "strict_v2"): 2}, + ) + return True + + +ANYTLS = dict(selected=["FINGERPRINT-ANYTLS"], client_fingerprint="none") + + +def group_pass(name, directory, run, peers): + if name in LOCAL: + return local_pass(name, directory, run) + root = directory / name.lower() + digest = run["container_image"]["digest"] + if name == "ANYTLS": + report = read_json(root / REPORTS["vless"]) + return envelope(report, peers, source(run), digest) and vless_pass( + ANYTLS, report, root + ) + if name == "BARE-SS": + report = read_json(root / "integration-suite.json") + rows = report.get("cases", []) + return ( + envelope(report, peers, source(run), digest) + and len(rows) == 1 + and runtime_pass("INTEGRATION-SS-ALGORITHMS", rows[0], root) + ) + report = read_json(root / "report.json") + return envelope( + report, + peers, + source(run), + digest, + single="SS" if name == "NATIVE-UNSUPPORTED" else "M", + ) and wire_pass(name, root, report) + + +def prepare(output, *, native): + from .native_release import download_native + from .protocol_hysteria2_acceptance import prepare as mihomo + + supplied = mihomo(output, {"M"}) + artifact = ( + download_native("SS", output / "binaries/SS", "linux-arm64", defer_version=True) + if native + else None + ) + return supplied, artifact + + +def execute(cases, run, output, results): + from .protocol_containers import frozen_image + from .protocol_harness import _command + from .protocol_integration_suite import run as integration + from .protocol_uot import run as uot + from .protocol_vless_container import run as vless + + selected = {c["case_id"].removeprefix("UOT-"): c for c in cases} + peers = {} + + def save(name): + good = group_pass(name, output, run, peers) + case = selected[name] + results[case["case_id"]] = result(case, good, good) + print(case["case_id"] + (": PASS" if good else ": FAIL"), flush=True) + if not good: + raise RuntimeError("UoT gate failed: " + name) + + try: + for name in selected: + if name not in LOCAL: + continue + for i, argv in enumerate(commands(name)): + label = f"UOT-{name}-{i}" + completed = _command( + run, + output, + label, + argv, + 3600, + events=output / (label + "-events.jsonl"), + ) + validate_execution( + argv, + completed.stdout.decode(errors="replace"), + completed.returncode, + completed.cleanup, + ) + save(name) + if set(selected) <= LOCAL: + return + with frozen_image(output / "image-pull.log") as image: + run["container_image"] = image + supplied, artifact = prepare( + output, native="NATIVE-UNSUPPORTED" in selected + ) + peers.update({k: v[1] for k, v in supplied.items()}) + if artifact is not None: + peers["SS"] = artifact.identity + for name in selected: + if name in LOCAL: + continue + root = output / name.lower() + if name.startswith("MIHOMO-"): + uot( + root, + via_socks5=name in {"MIHOMO-SOCKS5", "MIHOMO-GROUPS"}, + checks="negative" + if name == "MIHOMO-NEGATIVE" + else "group" + if name == "MIHOMO-GROUPS" + else "data", + supplied=supplied["M"], + image=image, + ) + elif name == "NATIVE-UNSUPPORTED": + uot( + root, + native=True, + checks="negative", + supplied=(artifact.binary, artifact.identity), + image=image, + ) + elif name == "ANYTLS": + vless(root, supplied=supplied, **ANYTLS) + elif name == "BARE-SS": + integration( + root, ["INTEGRATION-SS-ALGORITHMS"], supplied=supplied["M"] + ) + else: + raise ValueError("unknown UoT gate") + save(name) + finally: + (output / "peers.json").write_text(json.dumps(peers, indent=2) + "\n") + + +def check(directory, cases, run, results, peers, paths): + if not {"cases.json", "peers.json", "resources.jsonl", "summary.md"} <= set(paths): + raise ValueError("missing UoT evidence") + expected = [ + f"UOT-{c['case_id'].removeprefix('UOT-')}-{i}" + for c in cases + for i, _ in enumerate(commands(c["case_id"].removeprefix("UOT-"))) + ] + actual = [r["name"] for r in run["commands"]] + if ( + len(actual) != len(set(actual)) + or set(actual) != set(expected) + or set(peers) != {"M", "SS"} + ): + raise ValueError("UoT command or peer selection differs") + for case in cases: + name = case["case_id"].removeprefix("UOT-") + if not group_pass(name, directory, run, peers): + raise ValueError("UoT raw evidence failed: " + name) + print("UOT coverage: PASS (all required groups; device delivery separate)") + + +def preflight(output): + from .protocol_containers import command, frozen_image + + command("system", "status") + with frozen_image(output / "image-pull.log"): + supplied, artifact = prepare(output, native=True) + (output / "peers.json").write_text( + json.dumps( + dict( + scope="download-only", + wire_acceptance="NOT RUN", + peers={ + **{k: v[1] for k, v in supplied.items()}, + "SS": artifact.identity, + }, + ), + indent=2, + ) + + "\n" + ) diff --git a/scripts/src/vcore_scripts/protocol_uot_catalog.py b/scripts/src/vcore_scripts/protocol_uot_catalog.py new file mode 100644 index 0000000..19f8b55 --- /dev/null +++ b/scripts/src/vcore_scripts/protocol_uot_catalog.py @@ -0,0 +1,149 @@ +"""SS UoT v2 gates, reconstructed from existing runner evidence conventions.""" + +from .protocol_completion_peers import CASES +from .protocol_shadowtls_catalog import commands as shared_commands + +UOT_CASES = tuple(c for c in CASES if c.uot) +GATES = { + "MEMORY": "datagrams", + "FEATURES": "configuration", + "QUALITY": "regression", + "PLATFORMS": "regression", + "MIHOMO-DIRECT": "interop", + "MIHOMO-SOCKS5": "interop", + "MIHOMO-GROUPS": "interop", + "MIHOMO-NEGATIVE": "interop", + "NATIVE-UNSUPPORTED": "interop", + "ANYTLS": "regression", + "BARE-SS": "regression", +} +LOCAL = {"MEMORY", "FEATURES", "QUALITY", "PLATFORMS"} +MEMORY_EVENTS = { + ("UOT-CFG", "strict_v2"): 1, + **{ + ("UOT-SS", n): 1 + for n in ( + "first_packet", + "never_sent", + "deadline", + "cancel_write", + "budget_read_cancel", + "dns", + "stop_full_queue", + ) + }, +} + + +def definitions(): + return [ + dict( + case_id="UOT-" + name, + stage="UOT", + substage="UOT." + category, + required=True, + row_ids=[], + protocol="ss", + network="tcp", + security="ss2022/optional-v3", + udp_codec="uot-v2", + field_values={}, + outer_family="IPv4", + inner_family="IPv4/IPv6/domain", + target_type="memory-only/build" if name in LOCAL else "isolated origin", + upstream_graph="controlled-stream/optional-socks5-or-select", + peer_kind="unit" + if name in LOCAL + else "SS" + if name == "NATIVE-UNSUPPORTED" + else "M", + peer_config={"group": name}, + gap_source=None, + expected_observation=["UOT-" + name], + required_evidence=["command", "structured-assertions", "cleanup"] + + ([] if name in LOCAL else ["peer-identity", "isolated-origins"]), + prerequisites=["rust-toolchain"] + if name in LOCAL + else ["owned-host-only-container-network", "official-latest-peer"], + runner="uot-gate", + timeout_seconds=3600, + ) + for name, category in GATES.items() + ] + + +def wire_cases(name): + if name in {"MIHOMO-DIRECT", "MIHOMO-SOCKS5", "MIHOMO-GROUPS"}: + return [ + (c.identifier, "group" if name == "MIHOMO-GROUPS" else "data") + for c in UOT_CASES + ] + if name == "NATIVE-UNSUPPORTED": + return [ + (c.identifier + "-unsupported", "rejected") + for c in UOT_CASES + if not c.shadow_tls + ] + if name == "MIHOMO-NEGATIVE": + return [ + (c.identifier + "-" + failure, "rejected") + for c in UOT_CASES + for failure in (("key", "identity") if c.shadow_tls else ("key",)) + ] + raise ValueError("unknown UoT wire group") + + +def commands(name): + cargo = ["cargo", "test", "--locked", "--all-features"] + if name == "MEMORY": + return [ + cargo + + [ + arg + for target in ( + "uot_config", + "shadowsocks_uot", + "shadowsocks_backpressure", + ) + for arg in ("--test", target) + ], + cargo + ["--lib", "outbound::uot::"], + cargo + ["--lib", "outbound::anytls::"], + ] + if name == "FEATURES": + return [ + ["cargo", "check", "--locked", "--no-default-features"] + + (["--features", feature] if feature else []) + for feature in ( + "", + "outbound-shadowsocks", + "outbound-anytls", + "outbound-shadowsocks,shadow-tls-v3", + ) + ] + [ + [ + "cargo", + "test", + "--locked", + "--no-default-features", + "--features", + "interop-test", + "--test", + "uot_config", + ], + [ + "cargo", + "test", + "--locked", + "--no-default-features", + "--features", + "outbound-shadowsocks,interop-test", + "--test", + "uot_config", + "--test", + "shadowsocks_uot", + ], + ["cargo", "test", "--locked", "--test", "feature_foundations"], + cargo + ["--all-targets", "--no-run"], + ] + return shared_commands(name) if name in {"QUALITY", "PLATFORMS"} else [] diff --git a/scripts/src/vcore_scripts/protocol_vmess_container.py b/scripts/src/vcore_scripts/protocol_vmess_container.py index dd3203d..501cda7 100644 --- a/scripts/src/vcore_scripts/protocol_vmess_container.py +++ b/scripts/src/vcore_scripts/protocol_vmess_container.py @@ -24,7 +24,7 @@ from .protocol_vmess_public import events_pass, node_config ALL_CASES = CASES | PUBLIC_CASES -def run(output: Path, selected=None, *, preflight_only=False): +def run(output: Path, selected=None, *, preflight_only=False, supplied=None): selected = list(ALL_CASES) if selected is None else selected if ( not selected @@ -54,7 +54,10 @@ def run(output: Path, selected=None, *, preflight_only=False): artifacts = {} for kind in sorted({ALL_CASES[case][0] for case in selected} | {"M"}): directory = output / "binaries" / kind - if kind == "M": + if supplied is not None and kind in supplied: + binary, identity = supplied[kind] + artifacts[kind] = PeerArtifact(binary, identity) + elif kind == "M": identity = {} binary = download_mihomo( "linux-arm64", directory=directory, identity=identity @@ -65,7 +68,7 @@ def run(output: Path, selected=None, *, preflight_only=False): kind, directory, "linux-arm64", defer_version=True ) report["peers"][kind] = artifacts[kind].identity - lab = ContainerLab(report["isolation"]) + lab = ContainerLab(report["isolation"], mtu=1500) report["phase"] = "build" built = run_command( [ diff --git a/scripts/tests/test_native_release.py b/scripts/tests/test_native_release.py index af7c1a7..9e958e4 100644 --- a/scripts/tests/test_native_release.py +++ b/scripts/tests/test_native_release.py @@ -19,6 +19,30 @@ class Response(io.BytesIO): class NativeReleaseTest(unittest.TestCase): + def test_shadowtls_uses_latest_unmodified_binary_with_deferred_guest_version(self): + with ( + tempfile.TemporaryDirectory() as directory, + patch( + "urllib.request.urlopen", return_value=Response(b"official-st-binary") + ) as request, + patch("vcore_scripts.native_release.run_command") as run, + ): + peer = native_release.download_native( + "ST", Path(directory), "linux-arm64", defer_version=True + ) + self.assertEqual( + request.call_args.args[0].full_url, + "https://github.com/ihciah/shadow-tls/releases/latest/download/shadow-tls-aarch64-unknown-linux-musl", + ) + self.assertEqual(peer.binary.name, "shadow-tls") + self.assertEqual(peer.binary.read_bytes(), b"official-st-binary") + self.assertEqual( + peer.identity["binary_sha256"], + hashlib.sha256(b"official-st-binary").hexdigest(), + ) + self.assertIsNone(peer.identity["version"]) + run.assert_not_called() + def test_ss_tar_is_bounded_named_only_and_rejects_links(self): def archive(unsafe=False): data = io.BytesIO() diff --git a/scripts/tests/test_platform_delivery.py b/scripts/tests/test_platform_delivery.py index f5c1c6f..c0c2a3f 100644 --- a/scripts/tests/test_platform_delivery.py +++ b/scripts/tests/test_platform_delivery.py @@ -182,7 +182,7 @@ class PlatformDeliveryTest(unittest.TestCase): artifacts = [] identity = ( "VCore;engine=rust;coreVersion=0.1.0;" - "invokeApiVersion=5;configVersion=27" + "invokeApiVersion=5;configVersion=31" ) for abi, machine in [("arm64-v8a", 183), ("x86_64", 62)]: for name in ("libvcore.so", "libc++_shared.so"): @@ -228,6 +228,8 @@ class PlatformDeliveryTest(unittest.TestCase): "outbound-vmess", "outbound-vless", "outbound-hysteria2", + "outbound-tuic", + "shadow-tls-v3", ], "host": {"os": "Linux", "architecture": "x86_64"}, "toolchain": { diff --git a/scripts/tests/test_protocol_completion_peers.py b/scripts/tests/test_protocol_completion_peers.py new file mode 100644 index 0000000..6dd5a1c --- /dev/null +++ b/scripts/tests/test_protocol_completion_peers.py @@ -0,0 +1,70 @@ +"""Fixture contracts; real peer traffic is checked only in owned containers.""" + +import unittest +from pathlib import Path +from unittest.mock import patch + +from vcore_scripts.protocol_completion_peers import CASES, peer_configuration + + +class CompletionPeerTests(unittest.TestCase): + def test_comparison_client_refuses_host_network_io(self): + from vcore_scripts.container_protocol_client import main + + with ( + patch.dict("os.environ", {}, clear=True), + self.assertRaisesRegex(SystemExit, "container harness"), + ): + main() + + def test_tuic_v5_and_upgrade_fixtures_select_real_wire_modes(self): + tuic = [case for case in CASES if case.protocol == "tuic"] + upgrades = [case for case in CASES if case.protocol in {"vmess", "trojan"}] + self.assertEqual({case.udp_mode for case in tuic}, {"native", "quic"}) + self.assertEqual(len(upgrades), 6) + for case in tuic + upgrades: + with self.subTest(case=case.identifier): + node, listener = peer_configuration( + case, + server="192.0.2.2", + cover="192.0.2.3:24001", + port=23000, + certificate=(Path("cert.pem"), Path("key.pem"), "a" * 64), + ) + if case.protocol == "tuic": + self.assertNotIn("token", node) + self.assertEqual(listener["users"][node["uuid"]], node["password"]) + self.assertEqual(node["udp-relay-mode"], case.udp_mode) + else: + self.assertEqual(node["network"], "ws") + self.assertIs(node["ws-opts"]["v2ray-http-upgrade"], True) + self.assertEqual( + node["ws-opts"]["v2ray-http-upgrade-fast-open"], case.fast_open + ) + self.assertEqual(node["ws-opts"]["path"], listener["ws-path"]) + self.assertEqual("certificate" in listener, case.tls) + + def test_uot_fixtures_force_v2_and_do_not_offer_native_udp(self): + selected = [case for case in CASES if case.uot] + self.assertEqual(len(selected), 6) + for case in selected: + with self.subTest(case=case.identifier): + node, listener = peer_configuration( + case, + server="192.0.2.2", + cover="192.0.2.3:24001", + port=23000, + certificate=(Path("cert.pem"), Path("key.pem"), "a" * 64), + ) + self.assertEqual(node["type"], "ss") + self.assertIs(node["udp-over-tcp"], True) + self.assertEqual(node["udp-over-tcp-version"], 2) + self.assertIs(listener["udp"], False) + if case.shadow_tls: + self.assertEqual(node["plugin"], "shadow-tls") + self.assertEqual(node["plugin-opts"]["version"], 3) + self.assertIs(listener["shadow-tls"]["strict-mode"], True) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_protocol_httpupgrade.py b/scripts/tests/test_protocol_httpupgrade.py new file mode 100644 index 0000000..b30f5f3 --- /dev/null +++ b/scripts/tests/test_protocol_httpupgrade.py @@ -0,0 +1,105 @@ +import copy +import json +import tempfile +import unittest +from pathlib import Path + +from vcore_scripts.protocol_evidence import load_manifest, validate_results +from vcore_scripts.protocol_httpupgrade import expected_observation, selection +from vcore_scripts.protocol_httpupgrade_acceptance import wire_pass +from vcore_scripts.protocol_httpupgrade_catalog import WIRE, definitions, wire_cases +from vcore_scripts.protocol_security_acceptance import result, rust_command + + +class HttpUpgradeAcceptanceTest(unittest.TestCase): + def test_required_groups_are_registered_and_cannot_be_omitted(self): + cases = definitions() + self.assertEqual(len(cases), 13) + self.assertEqual( + cases, [c for c in load_manifest() if c["stage"] == "HTTPUPGRADE"] + ) + rows = [result(c, True, True) for c in cases] + validate_results(cases, rows) + with self.assertRaises(ValueError): + validate_results(cases, rows[:-1]) + rows[0]["assertions"] = {} + with self.assertRaises(ValueError): + validate_results(cases, rows) + + def test_runner_matches_independent_six_mode_wire_matrix(self): + counts = [6, 14, 2, 12, 16, 16, 6] + for name, count in zip(WIRE, counts, strict=True): + self.assertEqual(len(wire_cases(name)), count) + self.assertEqual( + [(r[0], r[3]) for r in selection(name.lower())], wire_cases(name) + ) + + def test_raw_evidence_rejects_missing_cases_forged_bytes_and_wrong_consumer(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + for name in WIRE: + rows = [] + for identifier, consumer in wire_cases(name): + node = dict( + type="vmess" if identifier.startswith("vmess") else "trojan" + ) + node["packet-encoding"] = identifier.rsplit("-", 1)[-1] + if consumer == "close": + reference = dict(tail_hex="", terminated=True, variant="plain") + for suffix in ("-close-reference.json", "-close-command.log"): + (root / (identifier + suffix)).write_text( + json.dumps(reference) + ) + observed = dict(tail_hex="", terminated=True, stop_idle=True) + else: + observed = expected_observation( + consumer, node, "XR" if name == "UDP-DOMAIN" else "M" + ) + (root / (identifier + "-observations.json")).write_text( + json.dumps(observed) + ) + events = [] + for suite, assertion in [("HTTPUPGRADE-PUBLIC", consumer)] + ( + [("HTTPUPGRADE-BASE", "tcp_10mib_both_directions")] * 3 + if consumer == "tcp" + else [] + ): + events += [ + dict( + schema_version=1, + suite=suite, + assertion=assertion, + status=s, + ) + for s in ("BEGIN", "PASS") + ] + (root / (identifier + "-events.jsonl")).write_text( + "".join(json.dumps(e) + "\n" for e in events) + ) + rows.append( + dict( + case_id=identifier, + command=rust_command( + "vless_public", "httpupgrade::" + consumer + ), + exit_code=0, + command_cleanup=True, + observations=observed, + ) + ) + report = dict(cases=rows) + self.assertTrue(wire_pass(name, root, report)) + self.assertFalse(wire_pass(name, root, dict(cases=rows[:-1]))) + for key, value in ( + ("exit_code", True), + ("command_cleanup", False), + ("observations", {}), + ("command", []), + ): + broken = copy.deepcopy(report) + broken["cases"][0][key] = value + self.assertFalse(wire_pass(name, root, broken)) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_protocol_integration.py b/scripts/tests/test_protocol_integration.py index 2edc642..64d3e19 100644 --- a/scripts/tests/test_protocol_integration.py +++ b/scripts/tests/test_protocol_integration.py @@ -12,6 +12,26 @@ from vcore_scripts import cli class IntegrationAcceptanceTest(unittest.TestCase): + def test_integration_quality_separates_release_source_policy(self): + from vcore_scripts.protocol_integration_local import commands + + rows = commands("INTEGRATION-QUALITY") + self.assertNotIn(["vcore-scripts", "check", "tls-dependencies"], rows) + self.assertIn(["vcore-scripts", "check", "c-header"], rows) + self.assertIn( + [ + "cargo", + "test", + "--locked", + "--manifest-path", + "crates/vcore-netstack/Cargo.toml", + "--all-targets", + ], + rows, + ) + self.assertIn(["vcore-scripts", "build", "apple"], rows) + self.assertIn(["vcore-scripts", "build", "android"], rows) + def test_native_source_identity_and_cleanup_are_required(self): from vcore_scripts.protocol_integration_checks import envelope @@ -63,12 +83,16 @@ class IntegrationAcceptanceTest(unittest.TestCase): def test_pressure_evidence_is_recomputed_not_inferred(self): from vcore_scripts.protocol_evidence import RESOURCE_KINDS from vcore_scripts.protocol_integration_metrics import ( - NEW, QUEUES, lifetimes, rebuild, soak, ) + from vcore_scripts.protocol_integration_profiles import ( + TCP_GROUPS, + UDP_GROUPS, + expected_flows, + ) def snapshot(current): return dict( @@ -84,7 +108,9 @@ class IntegrationAcceptanceTest(unittest.TestCase): rss_kib=50_000, fd=100 if active else 6, resources=snapshot(int(active)), - queues=[dict(kind=k, capacity=v, peak=1) for k, v in QUEUES.items()], + queues=[ + dict(kind=k, capacity=v, peak=int(v > 0)) for k, v in QUEUES.items() + ], ) event = dict(resources=snapshot(0)) @@ -100,8 +126,9 @@ class IntegrationAcceptanceTest(unittest.TestCase): generation=i, tcp=20, udp=20, - per_protocol_tcp=5, - per_protocol_udp=5, + per_group_tcp=5, + per_group_udp=5, + flow_profiles=expected_flows(i), active=sample(), setup_us=[1000] * 40, fault="owned-peer-connections-closed", @@ -113,7 +140,8 @@ class IntegrationAcceptanceTest(unittest.TestCase): value = dict( count=100, same_running_session=True, - protocols=NEW, + tcp_groups=list(TCP_GROUPS), + udp_groups=list(UDP_GROUPS), cold_fd=4, baseline_fd=6, cycles=rows, @@ -125,6 +153,8 @@ class IntegrationAcceptanceTest(unittest.TestCase): lambda d: d.update(same_running_session=False), lambda d: d["cycles"][0].update(tcp=0), lambda d: d["cycles"][0].update(setup_us=[]), + lambda d: d["cycles"][0]["flow_profiles"]["tcp"].pop(), + lambda d: d["cycles"][1].update(flow_profiles=expected_flows(0)), lambda d: d["stopped"].update(stop_ms=5001), lambda d: d["stopped"].update(quiet_seconds=0), lambda d: d["stopped"]["after_stop"].update(fd=7), @@ -140,11 +170,14 @@ class IntegrationAcceptanceTest(unittest.TestCase): value = dict( requested_seconds=1800, seconds=1800.2, - protocols=NEW, + tcp_groups=list(TCP_GROUPS), + udp_groups=list(UDP_GROUPS), tcp=20, udp=20, - per_protocol_tcp=5, - per_protocol_udp=5, + per_group_tcp=5, + per_group_udp=5, + first_profiles=expected_flows(0), + last_profiles=expected_flows(29), waves=1000, normal_verified_bytes=1000 * 20 * 2 * 2 * 257, normal_corruption=0, @@ -280,6 +313,10 @@ class IntegrationAcceptanceTest(unittest.TestCase): lambda d: d["paths"].append(d["paths"][0]), lambda d: d["paths"][0].update(udp_packets=799), lambda d: d["paths"][0].update(ports_rebound=False), + lambda d: d["paths"][0].update(server_first=False), + lambda d: d["paths"][0].update( + server_first_limitation="official-ss2022-empty-first-write" + ), lambda d: d.update(last="vmess"), lambda d: d["budgets"][0].update(packets=99), lambda d: d["carrier_capability"].update(no_bypass=False), @@ -291,6 +328,37 @@ class IntegrationAcceptanceTest(unittest.TestCase): data_path.write_text(json.dumps(observation)) event_path.write_text("".join(json.dumps(e) + "\n" for e in events[:-1])) self.assertFalse(pair_pass(identifier, record, root)) + identifier = "INTEGRATION-CHAIN-TUIC-QUIC-SS-V3-AES-256-GCM" + record["case_id"] = identifier + observation.update( + first="tuic", + last="ss", + variant=dict(udp_mode="quic", cipher="2022-blake3-aes-256-gcm"), + ) + observation["carrier_capability"]["udp_allowed"] = False + for path in observation["paths"]: + path.update( + server_first=False, + server_first_limitation="official-ss2022-empty-first-write", + ) + event_path = root / (identifier + "-events.jsonl") + data_path = root / (identifier + "-observations.json") + event_path.write_text("".join(json.dumps(e) + "\n" for e in events)) + data_path.write_text(json.dumps(observation)) + self.assertTrue(pair_pass(identifier, record, root)) + for mutate in ( + lambda d: d.pop("variant"), + lambda d: d["variant"].update(udp_mode="native"), + lambda d: d["variant"].update(cipher="2022-blake3-aes-128-gcm"), + lambda d: d["paths"][0].update(server_first=True), + lambda d: d["paths"][0].pop("server_first_limitation"), + lambda d: d["paths"][0].update(client_first=False), + lambda d: d["paths"][0].update(tcp_bytes_each_direction=1), + ): + broken = copy.deepcopy(observation) + mutate(broken) + data_path.write_text(json.dumps(broken)) + self.assertFalse(pair_pass(identifier, record, root)) def test_list_contains_all_ordered_pairs_and_remaining_gates(self): output = io.StringIO() @@ -302,14 +370,31 @@ class IntegrationAcceptanceTest(unittest.TestCase): 0, ) identifiers = [line.split("\t")[0] for line in output.getvalue().splitlines()] - protocols = {"SOCKS5", "ANYTLS", "SS", "TROJAN", "VMESS", "VLESS", "HYSTERIA2"} + protocols = { + "SOCKS5", + "ANYTLS", + "SS", + "TROJAN", + "VMESS", + "VLESS", + "HYSTERIA2", + "TUIC", + } expected = { f"INTEGRATION-PAIR-{first}-{last}" for first in protocols for last in protocols } - self.assertEqual(len(expected), 49) + self.assertEqual(len(expected), 64) self.assertEqual({key for key in identifiers if "-PAIR-" in key}, expected) + self.assertEqual( + {key for key in identifiers if "-CHAIN-" in key}, + { + f"INTEGRATION-CHAIN-TUIC-{mode}-SS-V3-{cipher}" + for mode in ("NATIVE", "QUIC") + for cipher in ("AES-128-GCM", "AES-256-GCM", "CHACHA20-POLY1305") + }, + ) self.assertEqual(len(identifiers), len(set(identifiers))) self.assertTrue( { @@ -329,6 +414,7 @@ class IntegrationAcceptanceTest(unittest.TestCase): "INTEGRATION-FEATURES", "INTEGRATION-SCRIPTS", "INTEGRATION-SHARED", + "INTEGRATION-COUPLED", } <= set(identifiers) ) diff --git a/scripts/tests/test_protocol_shadowtls.py b/scripts/tests/test_protocol_shadowtls.py new file mode 100644 index 0000000..942d2da --- /dev/null +++ b/scripts/tests/test_protocol_shadowtls.py @@ -0,0 +1,125 @@ +import copy +import json +import tempfile +import unittest +from pathlib import Path + +from vcore_scripts.protocol_evidence import load_manifest, validate_results +from vcore_scripts.protocol_inputs import redact +from vcore_scripts.protocol_security_acceptance import rust_command +from vcore_scripts.protocol_shadowtls_acceptance import ( + expected_observation, + fault_pass, + local_pass, + result, + wire_pass, +) +from vcore_scripts.protocol_shadowtls_catalog import SS_CASES, commands, definitions + + +class ShadowTlsAcceptanceTest(unittest.TestCase): + def test_local_command_identity_uses_the_same_redaction_as_the_runner(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + records = [] + for index, argv in enumerate(commands("QUALITY")): + name = f"SHADOWTLS-QUALITY-{index}" + (root / (name + ".log")).write_text("") + records.append( + dict( + name=name, + command=[redact(v) for v in argv], + exit_code=0, + cleanup=True, + log=name + ".log", + ) + ) + self.assertTrue(local_pass("QUALITY", root, {"commands": records})) + records[0]["command"] = ["true"] + self.assertFalse(local_pass("QUALITY", root, {"commands": records})) + + def test_wire_proof_requires_all_algorithms_raw_events_and_actual_counts(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + rows = [] + for name in SS_CASES: + observed = expected_observation("native_tcp", True) + (root / (name + "-observations.json")).write_text(json.dumps(observed)) + (root / (name + "-events.jsonl")).write_text( + "".join( + json.dumps( + dict( + schema_version=1, + suite="SHADOWTLS", + assertion="native_tcp", + status=status, + ) + ) + + "\n" + for status in ("BEGIN", "PASS") + ) + ) + rows.append( + dict( + case_id=name, + command=rust_command("vless_public", "shadowtls::native_tcp"), + exit_code=0, + command_cleanup=True, + observations=observed, + ) + ) + self.assertTrue(wire_pass("NATIVE", root, {"cases": rows})) + self.assertFalse(wire_pass("NATIVE", root, {"cases": rows[:-1]})) + observed = dict(rows[0]["observations"], tcp_bytes_each_direction=0) + rows[0]["observations"] = observed + (root / (SS_CASES[0] + "-observations.json")).write_text( + json.dumps(observed) + ) + self.assertFalse(wire_pass("NATIVE", root, {"cases": rows})) + + def test_suite_is_registered_and_cannot_accept_a_partial_or_forged_result(self): + cases = definitions() + self.assertEqual( + cases, [c for c in load_manifest() if c["stage"] == "SHADOWTLS"] + ) + self.assertEqual(len(cases), 11) + records = [] + for case in cases: + record = result(case, True, True) + self.assertEqual(record["scope"], "protocol-consumer") + records.append(record) + validate_results(cases, records) + with self.assertRaises(ValueError): + validate_results(cases, records[:-1]) + forged = copy.deepcopy(records) + forged[0]["assertions"] = {} + with self.assertRaises(ValueError): + validate_results(cases, forged) + + def test_fault_proof_requires_actual_injection_hrr_or_closed_handshakes(self): + for label, field in [ + ("fragment", "split_record"), + ("hrr-wire", "hrr_seen"), + ("business-mac", "injected"), + ("cover-mac", "injected"), + ]: + self.assertFalse(fault_pass(label, [], [])) + self.assertTrue(fault_pass(label, [{field: True}], [])) + self.assertFalse( + fault_pass(label, [{field: True, "upload_join_failed": True}], []) + ) + events = [{"hello_seen": True}, {"client_closed": True}] * 2 + self.assertTrue(fault_pass("stall", events, [])) + self.assertFalse(fault_pass("stall", events[:-1], [])) + self.assertFalse(fault_pass("stall", events, [{"version": "TLSv1.3"}])) + + def test_no_implicit_uot_and_authentication_evidence_are_distinct_from_bulk(self): + self.assertEqual(expected_observation("data", True)["udp_packets"], 500) + self.assertEqual(expected_observation("native_tcp", True)["udp_packets"], 0) + self.assertFalse(expected_observation("policy", False)["origin_connected"]) + self.assertEqual(expected_observation("corrupt", True)["delivered_bytes"], 0) + self.assertFalse( + expected_observation("native_udp_disabled", True)["udp_delivered"] + ) + with self.assertRaises(ValueError): + expected_observation("unknown", True) diff --git a/scripts/tests/test_protocol_tuic.py b/scripts/tests/test_protocol_tuic.py new file mode 100644 index 0000000..bba2f4f --- /dev/null +++ b/scripts/tests/test_protocol_tuic.py @@ -0,0 +1,145 @@ +import copy +import json +import tempfile +import unittest +from pathlib import Path + +from vcore_scripts.protocol_evidence import load_manifest, validate_results +from vcore_scripts.protocol_security_acceptance import result, rust_command +from vcore_scripts.protocol_tuic import expected_observation, inputs, upstream_pair +from vcore_scripts.protocol_tuic_acceptance import wire_pass +from vcore_scripts.protocol_tuic_catalog import definitions, wire_cases + + +class TuicAcceptanceTest(unittest.TestCase): + def test_registered_gates_cannot_omit_assertions_or_required_groups(self): + cases = definitions() + self.assertEqual(len(cases), 16) + self.assertEqual(cases, [c for c in load_manifest() if c["stage"] == "TUIC"]) + results = [result(c, True, True) for c in cases] + validate_results(cases, results) + with self.assertRaises(ValueError): + validate_results(cases, results[:-1]) + broken = copy.deepcopy(results) + broken[0]["assertions"] = {} + with self.assertRaises(ValueError): + validate_results(cases, broken) + + def test_runner_matches_independent_wire_matrix(self): + node = dict( + udp=True, + uuid="synthetic", + password="synthetic", + fingerprint="00" * 32, + alpn=["h3"], + **{"udp-relay-mode": "native"}, + ) + for name in ("TCP", "POLICY", "UDP", "PATHS", "NEGATIVE"): + rows = inputs(node, {}, name.lower()) + self.assertEqual([(r[0], r[3]) for r in rows], wire_cases("MIHOMO-" + name)) + + def test_raw_wire_evidence_rejects_truncation_forged_observation_and_wrong_consumer( + self, + ): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + for name in ( + "MIHOMO-TCP", + "MIHOMO-POLICY", + "MIHOMO-UDP", + "MIHOMO-PATHS", + "MIHOMO-NEGATIVE", + ): + rows = [] + for identifier, consumer in wire_cases(name): + observed = expected_observation(consumer) + (root / (identifier + "-observations.json")).write_text( + json.dumps(observed) + ) + (root / (identifier + "-events.jsonl")).write_text( + "".join( + json.dumps( + dict( + schema_version=1, + suite="TUIC-PUBLIC", + assertion=consumer, + status=status, + ) + ) + + "\n" + for status in ("BEGIN", "PASS") + ) + ) + rows.append( + dict( + case_id=identifier, + command=rust_command("vless_public", "tuic::" + consumer), + exit_code=0, + command_cleanup=True, + observations=observed, + ) + ) + report = dict(cases=rows) + self.assertTrue(wire_pass(name, root, report)) + self.assertFalse(wire_pass(name, root, dict(cases=rows[:-1]))) + for key, value in ( + ("observations", {}), + ("command_cleanup", False), + ("exit_code", True), + ( + "command", + rust_command( + "vless_public", + "tuic::tcp" + if rows[0]["command"] + != rust_command("vless_public", "tuic::tcp") + else "tuic::udp", + ), + ), + ): + broken = copy.deepcopy(report) + broken["cases"][0][key] = value + self.assertFalse(wire_pass(name, root, broken)) + + def test_mixed_pressure_requires_active_tuic_and_inactive_hysteria2(self): + from vcore_scripts.protocol_evidence import RESOURCE_KINDS + from vcore_scripts.protocol_integration_metrics import QUEUES, sample + + value = dict( + heap_in_use=1, + rss_kib=1, + fd=1, + resources=dict( + counts=[dict(kind=k, current=1, peak=1) for k in RESOURCE_KINDS] + ), + queues=[ + dict(kind=k, capacity=v, peak=int(v > 0)) for k, v in QUEUES.items() + ], + ) + self.assertTrue(sample(value)) + for kind, mutation in ( + ("tuic_udp", dict(capacity=0, peak=0)), + ("tuic_udp", dict(peak=33)), + ("hysteria2_udp", dict(capacity=32)), + ("hysteria2_udp", dict(peak=1)), + ("quic_incoming", dict(kind="unknown")), + ): + broken = copy.deepcopy(value) + next(q for q in broken["queues"] if q["kind"] == kind).update(mutation) + self.assertFalse(sample(broken)) + value["queues"].pop() + self.assertFalse(sample(value)) + + def test_anytls_fixture_uses_listener_password_map(self): + client, peer = upstream_pair( + "anytls-native", + {"server": "192.0.2.1"}, + (Path("cert.pem"), Path("key.pem"), "00" * 32), + 0, + ) + self.assertEqual(peer["users"], {"fixture": client["password"]}) + self.assertTrue(client["udp"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/tests/test_protocol_uot.py b/scripts/tests/test_protocol_uot.py new file mode 100644 index 0000000..0be33e0 --- /dev/null +++ b/scripts/tests/test_protocol_uot.py @@ -0,0 +1,81 @@ +import copy +import json +import tempfile +import unittest +from pathlib import Path + +from vcore_scripts.protocol_evidence import load_manifest, validate_results +from vcore_scripts.protocol_security_acceptance import result, rust_command +from vcore_scripts.protocol_uot import expected_observation +from vcore_scripts.protocol_uot_acceptance import wire_pass +from vcore_scripts.protocol_uot_catalog import definitions, wire_cases + + +class UotAcceptanceTest(unittest.TestCase): + def test_registered_groups_use_real_result_keys_and_require_every_group(self): + cases = definitions() + self.assertEqual(cases, [c for c in load_manifest() if c["stage"] == "UOT"]) + self.assertEqual(len(cases), 11) + results = [result(c, True, True) for c in cases] + validate_results(cases, results) + with self.assertRaises(ValueError): + validate_results(cases, results[:-1]) + forged = copy.deepcopy(results) + forged[0]["assertions"] = {} + with self.assertRaises(ValueError): + validate_results(cases, forged) + + def test_all_six_combinations_need_raw_packets_events_and_no_native_fallback(self): + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) + rows = [] + for identifier, consumer in wire_cases("MIHOMO-DIRECT"): + observation = expected_observation(consumer) + (root / (identifier + "-observations.json")).write_text( + json.dumps(observation) + ) + (root / (identifier + "-events.jsonl")).write_text( + "".join( + json.dumps( + dict( + schema_version=1, + suite="UOT-PUBLIC", + assertion=consumer, + status=status, + ) + ) + + "\n" + for status in ("BEGIN", "PASS") + ) + ) + rows.append( + dict( + case_id=identifier, + command=rust_command("vless_public", "uot::" + consumer), + exit_code=0, + command_cleanup=True, + observations=observation, + listener_native_udp=False, + ) + ) + report = dict(cases=rows, tcp_only_upstream=False) + self.assertEqual(len(rows), 6) + self.assertTrue(wire_pass("MIHOMO-DIRECT", root, report)) + self.assertFalse(wire_pass("MIHOMO-SOCKS5", root, report)) + self.assertFalse( + wire_pass("MIHOMO-DIRECT", root, dict(report, cases=rows[:-1])) + ) + rows[0]["listener_native_udp"] = True + self.assertFalse(wire_pass("MIHOMO-DIRECT", root, report)) + rows[0]["listener_native_udp"] = False + rows[0]["observations"]["native_udp_packets"] = 1 + self.assertFalse(wire_pass("MIHOMO-DIRECT", root, report)) + + def test_negative_and_group_cases_are_not_counted_as_data(self): + self.assertEqual(len(wire_cases("MIHOMO-NEGATIVE")), 9) + self.assertEqual(len(wire_cases("NATIVE-UNSUPPORTED")), 3) + self.assertTrue(all(test == "group" for _, test in wire_cases("MIHOMO-GROUPS"))) + self.assertEqual(expected_observation("rejected")["origin_packets"], 0) + self.assertEqual(expected_observation("data")["udp_sizes"][-1], 16384) + with self.assertRaises(ValueError): + expected_observation("unsupported") diff --git a/src/config/mod.rs b/src/config/mod.rs index bde6130..890b2de 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -23,12 +23,14 @@ mod ech; pub use ech::StaticEchConfig; mod hysteria2; pub use hysteria2::{Hysteria2Hopping, Hysteria2OutboundConfig}; +mod tuic; +pub use tuic::{TuicCongestion, TuicOutboundConfig, TuicUdpMode}; mod jls; pub use jls::JlsConfig; mod shadowsocks; -pub use shadowsocks::{ShadowsocksCipher, ShadowsocksOutboundConfig}; +pub use shadowsocks::{ShadowTlsConfig, ShadowsocksCipher, ShadowsocksOutboundConfig}; mod trojan; -pub use trojan::{TrojanOutboundConfig, TrojanTransport}; +pub use trojan::{TrojanOutboundConfig, TrojanTransport, WebSocketHandshake}; mod vless; pub use vless::{GrpcOptions, SingMuxConfig, SingMuxProtocol, VlessStreamOptions}; pub(crate) mod xhttp; @@ -301,6 +303,7 @@ pub struct ProxyConfig { #[derive(Debug, Clone, PartialEq, Eq)] pub enum ProxyProtocol { + Tuic(TuicOutboundConfig), Hysteria2(Hysteria2OutboundConfig), Vmess(VmessOutboundConfig), Trojan(TrojanOutboundConfig), @@ -314,6 +317,7 @@ impl ProxyConfig { #[must_use] pub fn address(&self) -> &str { match &self.protocol { + ProxyProtocol::Tuic(config) => &config.address, ProxyProtocol::Hysteria2(config) => &config.address, ProxyProtocol::Vmess(config) => &config.address, ProxyProtocol::Trojan(config) => &config.address, @@ -327,6 +331,7 @@ impl ProxyConfig { #[must_use] pub const fn port(&self) -> u16 { match &self.protocol { + ProxyProtocol::Tuic(config) => config.port, ProxyProtocol::Hysteria2(config) => config.port, ProxyProtocol::Vmess(config) => config.port, ProxyProtocol::Trojan(config) => config.port, @@ -863,6 +868,8 @@ where // protocol fields inline avoids extra heap allocations in the startup path. #[allow(clippy::large_enum_variant)] enum RawOutbound { + #[serde(rename = "tuic")] + Tuic(#[serde(deserialize_with = "tuic::deserialize")] tuic::RawTuic), #[serde(rename = "hysteria2")] Hysteria2(hysteria2::RawHysteria2), #[serde(rename = "vmess")] @@ -876,6 +883,28 @@ enum RawOutbound { port: u16, cipher: String, password: String, + #[serde(default, deserialize_with = "deserialize_present_option")] + plugin: Option, + #[serde( + rename = "plugin-opts", + default, + deserialize_with = "shadowsocks::deserialize_plugin" + )] + plugin_opts: Option, + #[serde( + rename = "client-fingerprint", + default, + deserialize_with = "deserialize_present_option" + )] + client_fingerprint: Option, + #[serde(rename = "udp-over-tcp", default)] + udp_over_tcp: bool, + #[serde( + rename = "udp-over-tcp-version", + default, + deserialize_with = "deserialize_present_option" + )] + udp_over_tcp_version: Option, #[serde(default)] udp: bool, #[serde( @@ -1936,6 +1965,7 @@ impl RawOutbound { fn normalize(self) -> Result { let (tag, dialer_proxy, udp, protocol) = match self { Self::Hysteria2(raw) => raw.normalize()?, + Self::Tuic(raw) => raw.normalize()?, Self::Vmess(raw) => raw.normalize()?, Self::Trojan(raw) => raw.normalize()?, Self::Shadowsocks { @@ -1944,14 +1974,28 @@ impl RawOutbound { port, cipher, password, + plugin, + plugin_opts, + client_fingerprint, + udp_over_tcp, + udp_over_tcp_version, udp, dialer_proxy, - } => ( - name, - dialer_proxy, - udp, - ProxyProtocol::Shadowsocks(shadowsocks::normalize(server, port, cipher, password)?), - ), + } => { + let mut config = shadowsocks::normalize(server, port, cipher, password)?; + config.shadow_tls = shadowsocks::plugin(plugin, plugin_opts, client_fingerprint)?; + if udp_over_tcp && !cfg!(feature = "outbound-shadowsocks") { + return invalid("Shadowsocks UoT support is not enabled in this build"); + } + if udp_over_tcp && !udp { + return invalid("Shadowsocks udp-over-tcp requires udp: true"); + } + if udp_over_tcp_version.is_some_and(|version| !udp_over_tcp || version != 2) { + return invalid("Shadowsocks udp-over-tcp-version requires enabled UoT v2"); + } + config.udp_over_tcp = udp_over_tcp; + (name, dialer_proxy, udp, ProxyProtocol::Shadowsocks(config)) + } Self::Vless(raw) => raw.normalize()?, Self::Socks5 { name, diff --git a/src/config/shadowsocks.rs b/src/config/shadowsocks.rs index 9337027..54cf884 100644 --- a/src/config/shadowsocks.rs +++ b/src/config/shadowsocks.rs @@ -5,6 +5,122 @@ use base64::{ use super::{invalid, validate_host, validate_port}; use crate::Result; +use serde::Deserialize; + +/// Fixed strict-v3 cover policy, independent of the SS payload credentials. +#[derive(Clone, PartialEq, Eq)] +pub struct ShadowTlsConfig { + pub server_name: String, + pub password: String, + pub alpn: Vec>, + pub certificate: super::TlsCertificatePolicy, + pub client_fingerprint: Option, +} + +impl std::fmt::Debug for ShadowTlsConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ShadowTlsConfig") + .field("client_fingerprint", &self.client_fingerprint) + .field("certificate", &self.certificate) + .finish_non_exhaustive() + } +} + +impl ShadowTlsConfig { + pub(crate) fn validate(&self) -> Result<()> { + if !cfg!(feature = "shadow-tls-v3") { + return invalid("ShadowTLS v3 is not compiled in"); + } + validate_host(&self.server_name, "ShadowTLS host")?; + if let Some(name) = &self.certificate.verification_name { + validate_host(name, "ShadowTLS verification name")?; + } + if !(1..=65_535).contains(&self.password.len()) { + return invalid("ShadowTLS password must contain 1..65535 UTF-8 bytes"); + } + if self + .alpn + .iter() + .any(|value| !(1..=255).contains(&value.len())) + || self.alpn.iter().map(|value| value.len() + 1).sum::() > 65_533 + { + return invalid("invalid ShadowTLS ALPN list"); + } + Ok(()) + } +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields, rename_all = "kebab-case")] +pub(super) struct RawShadowTls { + version: u8, + host: String, + password: String, + #[serde(default, deserialize_with = "super::deserialize_present_option")] + alpn: Option>, + #[serde(default)] + skip_cert_verify: bool, + #[serde(default, deserialize_with = "super::deserialize_present_option")] + fingerprint: Option, + #[serde(default, deserialize_with = "super::deserialize_present_option")] + name_cert_verify: Option, +} + +impl std::fmt::Debug for RawShadowTls { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RawShadowTls").finish_non_exhaustive() + } +} + +pub(super) fn deserialize_plugin<'de, D>( + deserializer: D, +) -> std::result::Result, D::Error> +where + D: serde::Deserializer<'de>, +{ + super::deserialize_present_map(deserializer) + .map_err(|_| serde::de::Error::custom("invalid ShadowTLS plugin policy")) +} + +pub(super) fn plugin( + name: Option, + options: Option, + fingerprint: Option, +) -> Result> { + let (name, raw) = match (name, options) { + (None, None) if fingerprint.is_none() => return Ok(None), + (Some(name), Some(raw)) => (name, raw), + _ => return invalid("ShadowTLS plugin and plugin-opts must be provided together"), + }; + if name != "shadow-tls" || raw.version != 3 { + return invalid("only explicit ShadowTLS v3 is supported"); + } + let config = ShadowTlsConfig { + server_name: raw.host, + password: raw.password, + alpn: raw + .alpn + .unwrap_or_else(|| vec!["h2".into(), "http/1.1".into()]) + .into_iter() + .map(String::into_bytes) + .collect(), + certificate: super::TlsCertificatePolicy { + verification_name: raw.name_cert_verify, + skip_cert_verify: raw.skip_cert_verify, + fingerprint: raw + .fingerprint + .as_deref() + .map(super::vless::parse_pin) + .transpose() + .map_err(|_| { + crate::VCoreError::InvalidConfig("invalid ShadowTLS certificate pin".into()) + })?, + }, + client_fingerprint: super::parse_client_fingerprint(fingerprint.as_deref())?, + }; + config.validate()?; + Ok(Some(config)) +} #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ShadowsocksCipher { @@ -41,6 +157,8 @@ pub struct ShadowsocksOutboundConfig { pub port: u16, pub cipher: ShadowsocksCipher, pub password: String, + pub shadow_tls: Option, + pub udp_over_tcp: bool, } impl std::fmt::Debug for ShadowsocksOutboundConfig { @@ -55,6 +173,9 @@ impl ShadowsocksOutboundConfig { pub(crate) fn validate(&self) -> Result<()> { validate_host(&self.address, "Shadowsocks server")?; validate_port(self.port, "Shadowsocks")?; + if let Some(shadow_tls) = &self.shadow_tls { + shadow_tls.validate()?; + } if !self.cipher.supports_eih() && self.password.contains(':') { return invalid("Shadowsocks identity chains require an AES 2022 cipher"); } @@ -94,6 +215,8 @@ pub(super) fn normalize( port, cipher, password, + shadow_tls: None, + udp_over_tcp: false, }; config.validate()?; Ok(config) diff --git a/src/config/trojan.rs b/src/config/trojan.rs index 7a16115..fb90376 100644 --- a/src/config/trojan.rs +++ b/src/config/trojan.rs @@ -25,12 +25,41 @@ pub enum TrojanTransport { headers: BTreeMap, max_early_data: u16, early_data_header_name: String, + handshake: WebSocketHandshake, }, Grpc { uri: String, }, } +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum WebSocketHandshake { + #[default] + WebSocket, + HttpUpgrade { + fast_open: bool, + }, +} + +pub(super) fn websocket_handshake( + upgrade: bool, + fast_open: bool, + early_header: Option<&str>, +) -> Result { + if (fast_open && !upgrade) + || (upgrade + && early_header + .is_some_and(|name| !name.eq_ignore_ascii_case("Sec-WebSocket-Protocol"))) + { + return invalid("invalid HTTPUpgrade options"); + } + Ok(if upgrade { + WebSocketHandshake::HttpUpgrade { fast_open } + } else { + WebSocketHandshake::WebSocket + }) +} + impl std::fmt::Debug for TrojanTransport { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(match self { @@ -57,11 +86,19 @@ impl TrojanTransport { headers, max_early_data, early_data_header_name, + handshake, } = self else { return Ok(None); }; - websocket_options(uri, headers, *max_early_data, early_data_header_name).map(Some) + websocket_options( + uri, + headers, + *max_early_data, + early_data_header_name, + *handshake, + ) + .map(Some) } } @@ -71,6 +108,7 @@ pub(super) fn websocket_options( headers: &BTreeMap, max_early_data: u16, early_data_header_name: &str, + handshake: WebSocketHandshake, ) -> std::io::Result { use crate::transport::{WebSocketEarlyData, WebSocketOptions}; let invalid = || { @@ -101,11 +139,19 @@ pub(super) fn websocket_options( max_bytes: usize::from(max_early_data), }) }; - WebSocketOptions::new(uri, map, early) + let options = WebSocketOptions::new(uri, map, early)?; + match handshake { + WebSocketHandshake::WebSocket => Ok(options), + WebSocketHandshake::HttpUpgrade { fast_open } => options.with_http_upgrade(fast_open), + } } #[derive(Default, Deserialize)] #[serde(deny_unknown_fields)] struct RawWebSocket { + #[serde(rename = "v2ray-http-upgrade", default)] + http_upgrade: bool, + #[serde(rename = "v2ray-http-upgrade-fast-open", default)] + fast_open: bool, #[serde(default, deserialize_with = "deserialize_present_option")] path: Option, #[serde(default)] @@ -227,6 +273,11 @@ impl RawTrojan { return invalid("invalid Trojan WebSocket early-data options"); } let transport = TrojanTransport::WebSocket { + handshake: websocket_handshake( + ws.http_upgrade, + ws.fast_open, + ws.early_data_header_name.as_deref(), + )?, uri: uri( "wss", &self.server, diff --git a/src/config/tuic.rs b/src/config/tuic.rs new file mode 100644 index 0000000..f11deab --- /dev/null +++ b/src/config/tuic.rs @@ -0,0 +1,165 @@ +use serde::Deserialize; +use uuid::Uuid; + +use super::{ + ProxyProtocol, TlsCertificatePolicy, TlsConfig, invalid, validate_host, validate_port, +}; +use crate::Result; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum TuicCongestion { + #[default] + Cubic, + NewReno, + Bbr, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum TuicUdpMode { + #[default] + Native, + Quic, +} + +#[derive(Clone, PartialEq, Eq)] +pub struct TuicOutboundConfig { + pub address: String, + pub port: u16, + pub uuid: Uuid, + pub password: String, + pub tls: TlsConfig, + pub congestion: TuicCongestion, + pub udp_mode: TuicUdpMode, +} + +impl std::fmt::Debug for TuicOutboundConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("TuicOutboundConfig") + .field("congestion", &self.congestion) + .finish_non_exhaustive() + } +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields, rename_all = "kebab-case")] +pub(super) struct RawTuic { + name: String, + server: String, + port: u16, + uuid: String, + password: String, + #[serde(default)] + udp: bool, + #[serde(default, deserialize_with = "super::deserialize_present_option")] + dialer_proxy: Option, + #[serde(default, deserialize_with = "super::deserialize_present_option")] + sni: Option, + #[serde(default, deserialize_with = "super::deserialize_present_option")] + alpn: Option>, + #[serde(default)] + skip_cert_verify: bool, + #[serde(default, deserialize_with = "super::deserialize_present_option")] + fingerprint: Option, + #[serde(default, deserialize_with = "super::deserialize_present_option")] + name_cert_verify: Option, + #[serde(default)] + congestion_controller: TuicCongestion, + #[serde(default)] + udp_relay_mode: TuicUdpMode, +} + +impl std::fmt::Debug for RawTuic { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RawTuic").finish_non_exhaustive() + } +} + +pub(super) fn deserialize<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> std::result::Result { + RawTuic::deserialize(deserializer) + .map_err(|_| serde::de::Error::custom("invalid TUIC configuration fields")) +} + +impl RawTuic { + pub(super) fn normalize(self) -> Result<(String, Option, bool, ProxyProtocol)> { + if !cfg!(feature = "outbound-tuic") { + return invalid("TUIC outbound support is disabled at build time"); + } + let uuid = super::parse_standard_uuid(&self.uuid).map_err(|_| { + crate::VCoreError::InvalidConfig("TUIC requires a standard hyphenated UUID".into()) + })?; + let config = TuicOutboundConfig { + address: self.server.clone(), + port: self.port, + uuid, + password: self.password, + congestion: self.congestion_controller, + udp_mode: self.udp_relay_mode, + tls: TlsConfig { + server_name: self.sni.unwrap_or(self.server), + alpn: self + .alpn + .unwrap_or_else(|| vec!["h3".into()]) + .into_iter() + .map(String::into_bytes) + .collect(), + tls13_only: true, + required_alpn: None, + identity: None, + ech: None, + client_fingerprint: None, + certificate: TlsCertificatePolicy { + skip_cert_verify: self.skip_cert_verify, + verification_name: self.name_cert_verify, + fingerprint: self + .fingerprint + .as_deref() + .map(super::vless::parse_pin) + .transpose() + .map_err(|_| { + crate::VCoreError::InvalidConfig("invalid TUIC certificate pin".into()) + })?, + }, + }, + }; + config.validate()?; + Ok(( + self.name, + self.dialer_proxy, + self.udp, + ProxyProtocol::Tuic(config), + )) + } +} + +impl TuicOutboundConfig { + pub(crate) fn validate(&self) -> Result<()> { + validate_host(&self.address, "TUIC server")?; + validate_port(self.port, "TUIC")?; + validate_host(&self.tls.server_name, "TUIC sni")?; + if let Some(name) = &self.tls.certificate.verification_name { + validate_host(name, "TUIC verification name")?; + } + if self.password.len() > 65_535 { + return invalid("TUIC password exceeds 65535 UTF-8 bytes"); + } + if self.tls.alpn.is_empty() + || self.tls.alpn.iter().any(|p| p.is_empty() || p.len() > 255) + || self.tls.alpn.iter().map(|p| p.len() + 1).sum::() > 65_533 + { + return invalid("invalid TUIC ALPN list"); + } + if !self.tls.tls13_only + || self.tls.ech.is_some() + || self.tls.identity.is_some() + || self.tls.client_fingerprint.is_some() + || self.tls.required_alpn.is_some() + { + return invalid("TUIC requires standard QUIC TLS 1.3"); + } + Ok(()) + } +} diff --git a/src/config/vless.rs b/src/config/vless.rs index 30796a9..d1d0a0d 100644 --- a/src/config/vless.rs +++ b/src/config/vless.rs @@ -278,6 +278,10 @@ impl RawVless { stream_options.http_upgrade = ws.http_upgrade; stream_options.fast_open = ws.fast_open; Ok(RawWs { + // VLESS also carries the mode alongside Encryption's + // initial-data choice; keep that existing ownership path. + http_upgrade: false, + fast_open: false, path: ws.path, headers: ws.headers, max_early_data: ws.max_early_data, diff --git a/src/config/vmess.rs b/src/config/vmess.rs index 8fd517d..003eaac 100644 --- a/src/config/vmess.rs +++ b/src/config/vmess.rs @@ -25,6 +25,7 @@ pub enum StreamTransport { headers: BTreeMap, max_early_data: u16, early_data_header_name: String, + handshake: super::WebSocketHandshake, }, Grpc { uri: String, @@ -64,12 +65,19 @@ impl StreamTransport { headers, max_early_data, early_data_header_name, + handshake, } = self else { return Ok(None); }; - super::trojan::websocket_options(uri, headers, *max_early_data, early_data_header_name) - .map(Some) + super::trojan::websocket_options( + uri, + headers, + *max_early_data, + early_data_header_name, + *handshake, + ) + .map(Some) } #[cfg(feature = "stream-transport")] pub fn http_options(&self) -> std::io::Result> { @@ -114,6 +122,10 @@ fn http_options<'a>( #[derive(Default, Deserialize)] #[serde(deny_unknown_fields)] pub(super) struct RawWs { + #[serde(rename = "v2ray-http-upgrade", default)] + pub(super) http_upgrade: bool, + #[serde(rename = "v2ray-http-upgrade-fast-open", default)] + pub(super) fast_open: bool, #[serde(default, deserialize_with = "deserialize_present_option")] pub(super) path: Option, #[serde(default)] @@ -426,6 +438,11 @@ pub(super) fn normalize_transport( } } let transport = StreamTransport::WebSocket { + handshake: super::trojan::websocket_handshake( + ws.http_upgrade, + ws.fast_open, + ws.early_data_header_name.as_deref(), + )?, uri: uri( if tls { "wss" } else { "ws" }, &authority, diff --git a/src/lib.rs b/src/lib.rs index e9ac738..7f9a646 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -33,7 +33,8 @@ pub mod routing; feature = "outbound-vless", feature = "outbound-trojan", feature = "outbound-vmess", - feature = "outbound-hysteria2" + feature = "outbound-hysteria2", + feature = "outbound-tuic" ), any(feature = "ffi", test) ))] @@ -42,13 +43,16 @@ mod runtime; feature = "outbound-anytls", feature = "outbound-vless", feature = "stream-transport", - feature = "outbound-hysteria2" + feature = "outbound-hysteria2", + feature = "outbound-tuic", + feature = "shadow-tls-v3" ))] pub mod security; pub mod session; #[cfg(any( feature = "inbound-socks5", feature = "outbound-anytls", + feature = "outbound-shadowsocks", feature = "outbound-socks5", feature = "outbound-trojan", feature = "outbound-vless" @@ -88,7 +92,7 @@ pub const INVOKE_API_VERSION: u32 = 5; /// Internal configuration schema revision reported through Invoke. /// /// The strict Mihomo YAML subset deliberately carries no version field. -pub const CONFIG_VERSION: u8 = 27; +pub const CONFIG_VERSION: u8 = 31; /// Stable implementation identifier returned by the version Invoke method. pub const ENGINE: &str = "rust"; @@ -100,5 +104,5 @@ pub const ENGINE: &str = "rust"; pub const BUILD_IDENTITY: &str = concat!( "VCore;engine=rust;coreVersion=", env!("CARGO_PKG_VERSION"), - ";invokeApiVersion=5;configVersion=27" + ";invokeApiVersion=5;configVersion=31" ); diff --git a/src/limits.rs b/src/limits.rs index bdc3482..fc6181f 100644 --- a/src/limits.rs +++ b/src/limits.rs @@ -54,6 +54,16 @@ pub const HY2_DATAGRAM_BUFFER: usize = 256 * 1024; pub const HY2_AUTH_HEADERS: usize = 16384; pub const HY2_RESPONSE_MESSAGE: usize = 2048; pub const HY2_RESPONSE_PADDING: usize = 4096; +pub const TUIC_QUIC_PAYLOAD: usize = 1400; +pub const TUIC_UNI_STREAMS: usize = 32; +pub const TUIC_STREAM_WINDOW: usize = 256 * 1024; +pub const TUIC_CONNECTION_WINDOW: usize = 1024 * 1024; +pub const TUIC_DATAGRAM_BUFFER: usize = 256 * 1024; +pub const TUIC_UDP_QUEUE: usize = 32; +pub const TUIC_PENDING_PACKETS: usize = 64; +pub const TUIC_PENDING_BYTES: usize = 256 * 1024; +pub const TUIC_FRAGMENT_TTL_SECONDS: usize = 5; +pub const TUIC_FIN_GRACE_SECONDS: usize = 5; /// Historical iOS TUN footprint target retained for best-effort telemetry. /// diff --git a/src/outbound/anytls/client.rs b/src/outbound/anytls/client.rs index 3f2cf61..2436607 100644 --- a/src/outbound/anytls/client.rs +++ b/src/outbound/anytls/client.rs @@ -23,8 +23,8 @@ use super::{ padding::PaddingScheme, session::{PreparedSession, Session}, stream::AnyTlsStream, - uot::UotTransport, }; +use crate::outbound::uot::UotTransport; const IDLE_CHECK_INTERVAL: Duration = Duration::from_secs(30); const IDLE_TIMEOUT: Duration = Duration::from_secs(30); @@ -201,8 +201,10 @@ impl AnyTlsClient { if state.closed { return Err(DispatchError::Other("AnyTLS client is closed".to_owned())); } + let (reader, writer) = tokio::io::split(stream); Ok(UotTransport::new( - stream, + reader, + writer, max_response_payload_size, self.cancellation.clone(), &self.tasks, diff --git a/src/outbound/anytls/mod.rs b/src/outbound/anytls/mod.rs index b28e6d3..689fcb5 100644 --- a/src/outbound/anytls/mod.rs +++ b/src/outbound/anytls/mod.rs @@ -3,7 +3,6 @@ mod frame; mod padding; mod session; mod stream; -mod uot; use std::{io, sync::Arc}; @@ -17,8 +16,8 @@ use crate::{ session::{Destination, StreamSession}, }; +use super::uot::magic_destination; use client::{AnyTlsClient, SessionDialer}; -use uot::magic_destination; pub use stream::AnyTlsStream; diff --git a/src/outbound/connector.rs b/src/outbound/connector.rs index f87b0f6..ac845ba 100644 --- a/src/outbound/connector.rs +++ b/src/outbound/connector.rs @@ -598,7 +598,8 @@ impl UpstreamPath { #[cfg(any( feature = "outbound-shadowsocks", feature = "outbound-vless", - feature = "outbound-hysteria2" + feature = "outbound-hysteria2", + feature = "outbound-tuic" ))] pub(crate) fn datagram_server( &self, diff --git a/src/outbound/mod.rs b/src/outbound/mod.rs index b43f560..6ee6396 100644 --- a/src/outbound/mod.rs +++ b/src/outbound/mod.rs @@ -11,6 +11,8 @@ mod anytls; mod connector; #[cfg(feature = "outbound-shadowsocks")] mod shadowsocks; +#[cfg(any(feature = "outbound-anytls", feature = "outbound-shadowsocks"))] +mod uot; #[cfg(feature = "outbound-shadowsocks")] pub use shadowsocks::ShadowsocksOutbound; mod direct; @@ -51,6 +53,9 @@ pub mod hysteria2; feature = "outbound-trojan", feature = "outbound-vmess", feature = "outbound-vless", - feature = "outbound-hysteria2" + feature = "outbound-hysteria2", + feature = "outbound-tuic" ))] mod owned_stream; +#[cfg(feature = "outbound-tuic")] +pub mod tuic; diff --git a/src/outbound/shadowsocks/mod.rs b/src/outbound/shadowsocks/mod.rs index c2969aa..2a89691 100644 --- a/src/outbound/shadowsocks/mod.rs +++ b/src/outbound/shadowsocks/mod.rs @@ -16,6 +16,7 @@ mod datagram; mod packet_io; mod packet_window; mod stream; +mod uot; #[derive(Clone)] pub struct ShadowsocksOutbound { @@ -23,6 +24,9 @@ pub struct ShadowsocksOutbound { config: Arc, context: shadowsocks::context::SharedContext, upstream: UpstreamPath, + uot: Option>, + #[cfg(feature = "shadow-tls-v3")] + shadow_tls: Option, } impl std::fmt::Debug for ShadowsocksOutbound { @@ -36,6 +40,19 @@ impl ShadowsocksOutbound { pub fn new_with_path( config: &ShadowsocksOutboundConfig, upstream: UpstreamPath, + ) -> io::Result { + Self::with_security( + config, + upstream, + #[cfg(feature = "shadow-tls-v3")] + None, + ) + } + + pub(crate) fn with_security( + config: &ShadowsocksOutboundConfig, + upstream: UpstreamPath, + #[cfg(feature = "shadow-tls-v3")] security: Option<&crate::security::SecurityContext>, ) -> io::Result { config.validate().map_err(|_| { io::Error::new( @@ -44,12 +61,22 @@ impl ShadowsocksOutbound { ) })?; let server = server_destination(&config.address, config.port)?; + #[cfg(feature = "shadow-tls-v3")] + let shadow_tls = config + .shadow_tls + .as_ref() + .map(|options| { + let context = security.cloned().unwrap_or_default(); + crate::security::ShadowTlsClient::new(&context, options) + }) + .transpose()?; let method = config.cipher.as_str().parse().map_err(|_| { io::Error::new( io::ErrorKind::InvalidInput, "unsupported Shadowsocks cipher", ) })?; + let uot = config.udp_over_tcp.then(|| Arc::new(uot::Owner::default())); let config = ServerConfig::new( (config.address.clone(), config.port), config.password.clone(), @@ -66,6 +93,9 @@ impl ShadowsocksOutbound { config: Arc::new(config), context: Context::new_shared(ServerType::Local), upstream, + uot, + #[cfg(feature = "shadow-tls-v3")] + shadow_tls, }) } } @@ -82,9 +112,18 @@ impl OutboundConnector for ShadowsocksOutbound { .upstream .connect_server(session, &self.server, context) .await?; + let io = connected.io; + #[cfg(feature = "shadow-tls-v3")] + let io = if let Some(shadow_tls) = &self.shadow_tls { + context + .run_io("Shadowsocks ShadowTLS handshake", shadow_tls.connect(io)) + .await? + } else { + io + }; let stream = shadowsocks::ProxyClientStream::from_stream( self.context.clone(), - connected.io, + io, &self.config, address(&target), ); @@ -99,6 +138,9 @@ impl OutboundConnector for ShadowsocksOutbound { request: DatagramRequest, context: &EstablishContext, ) -> Result, DispatchError> { + if let Some(uot) = &self.uot { + return uot.open(self, request, context).await; + } let server = self.upstream.datagram_server(&self.server, context)?; let maximum = request.max_response_payload_size(); let wire_maximum = maximum.saturating_add(datagram::MAX_RESPONSE_HEADER); @@ -124,6 +166,18 @@ impl OutboundConnector for ShadowsocksOutbound { request.budget(), )) } + + fn begin_shutdown(&self) { + if let Some(uot) = &self.uot { + uot.begin_shutdown(); + } + } + + async fn shutdown(&self) { + if let Some(uot) = &self.uot { + uot.shutdown().await; + } + } } #[async_trait] diff --git a/src/outbound/shadowsocks/tests.rs b/src/outbound/shadowsocks/tests.rs index 3c22765..b585d4f 100644 --- a/src/outbound/shadowsocks/tests.rs +++ b/src/outbound/shadowsocks/tests.rs @@ -87,6 +87,8 @@ fn config(cipher: ShadowsocksCipher) -> ShadowsocksOutboundConfig { port: 12345, cipher, password: STANDARD.encode(vec![7; cipher.key_len()]), + shadow_tls: None, + udp_over_tcp: false, } } diff --git a/src/outbound/shadowsocks/uot.rs b/src/outbound/shadowsocks/uot.rs new file mode 100644 index 0000000..70e0fb8 --- /dev/null +++ b/src/outbound/shadowsocks/uot.rs @@ -0,0 +1,265 @@ +//! SS-specific ownership around the shared v2 datagram module. A reader cannot +//! initialize SS, and ending that reader releases IO even if a caller keeps the +//! association after Stop. AnyTLS retains its separate stream/FIN ownership. +use std::{ + future::Future, + io, + pin::Pin, + sync::{Arc, Mutex}, + task::{Context, Poll, Waker, ready}, +}; + +use async_trait::async_trait; +use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; +use tokio::time::{Instant, Sleep}; +use tokio_util::{sync::CancellationToken, task::TaskTracker}; + +use super::ShadowsocksOutbound; +use crate::{ + dispatch::{BoxStream, DatagramTransport, DispatchError}, + dns::resolution::ResolutionContext, + outbound::{ + DEFAULT_ESTABLISH_TIMEOUT, DatagramRequest, EstablishContext, OutboundConnector, + uot::{UotTransport, magic_destination}, + }, + session::{Datagram, Destination, StreamSession}, +}; + +#[derive(Default)] +pub(super) struct Owner { + closed: Mutex, + cancellation: CancellationToken, + tasks: TaskTracker, +} + +impl Owner { + pub(super) async fn open( + &self, + outbound: &ShadowsocksOutbound, + request: DatagramRequest, + context: &EstablishContext, + ) -> Result, DispatchError> { + let stream = tokio::select! { + biased; + () = self.cancellation.cancelled() => return Err(DispatchError::NotAllowed), + result = outbound.connect_stream(StreamSession { + inbound: request.session.inbound, + source: request.session.source, + destination: magic_destination(), + sniffed_domain: None, + }, context) => result?.io, + }; + // Admission and task registration share Stop's lock. A completed TCP + // handshake racing Stop cannot introduce a new untracked read task. + let closed = self + .closed + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if *closed { + return Err(DispatchError::NotAllowed); + } + let io = Arc::new(Mutex::new(FirstWrite { + io: Some(stream), + deadline: Some(Box::pin(tokio::time::sleep_until(context.deadline()))), + written: false, + readable: false, + failure: io::ErrorKind::BrokenPipe, + reader: None, + writer: None, + })); + let transport = UotTransport::new( + Reader(io.clone()), + Writer(io), + request.max_response_payload_size(), + self.cancellation.clone(), + &self.tasks, + ); + Ok(crate::dispatch::bound_datagram( + Box::new(DatagramAdapter { + inner: transport, + resolution: context.resolution(), + first_deadline: Some(context.deadline()), + cancellation: self.cancellation.clone(), + }), + request.budget(), + )) + } + + pub(super) fn begin_shutdown(&self) { + *self + .closed + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = true; + self.cancellation.cancel(); + self.tasks.close(); + } + + pub(super) async fn shutdown(&self) { + self.begin_shutdown(); + self.tasks.wait().await; + } +} + +impl Drop for Owner { + fn drop(&mut self) { + self.cancellation.cancel(); + self.tasks.close(); + } +} + +struct DatagramAdapter { + inner: UotTransport, + resolution: ResolutionContext, + first_deadline: Option, + cancellation: CancellationToken, +} + +#[async_trait] +impl DatagramTransport for DatagramAdapter { + async fn send(&mut self, mut datagram: Datagram) -> Result<(), DispatchError> { + let deadline = self + .first_deadline + .unwrap_or_else(|| Instant::now() + DEFAULT_ESTABLISH_TIMEOUT); + datagram.remote = Destination::Ip(tokio::select! { + biased; + () = self.cancellation.cancelled() => return Err(DispatchError::NotAllowed), + result = self.resolution.resolve_ip(&datagram.remote, deadline) => result?, + }); + self.inner.send(datagram).await?; + self.first_deadline = None; + Ok(()) + } + + async fn receive(&mut self) -> Result { + self.inner.receive().await + } + + async fn close(&mut self) -> Result<(), DispatchError> { + self.inner.close().await + } +} + +struct FirstWrite { + io: Option, + deadline: Option>>, + written: bool, + readable: bool, + failure: io::ErrorKind, + reader: Option, + writer: Option, +} + +impl FirstWrite { + fn check(&mut self, cx: &mut Context<'_>) -> io::Result<()> { + if self + .deadline + .as_mut() + .is_some_and(|timer| timer.as_mut().poll(cx).is_ready()) + { + self.fail(io::ErrorKind::TimedOut); + } + if self.io.is_none() { + return Err(io::Error::new( + self.failure, + "Shadowsocks UoT stream is closed", + )); + } + Ok(()) + } + + fn fail(&mut self, kind: io::ErrorKind) { + if self.io.take().is_some() { + self.failure = kind; + } + self.deadline = None; + for waker in [self.reader.take(), self.writer.take()] + .into_iter() + .flatten() + { + waker.wake(); + } + } +} + +struct Reader(Arc>); +struct Writer(Arc>); + +impl Drop for Reader { + fn drop(&mut self) { + // Task completion (including cancellation/abort) releases the actual + // stream, not just one Tokio split handle. No shutdown/empty SS write. + self.0 + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .fail(io::ErrorKind::ConnectionAborted); + } +} + +impl AsyncRead for Reader { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + out: &mut ReadBuf<'_>, + ) -> Poll> { + if out.remaining() == 0 { + return Poll::Ready(Ok(())); + } + let mut state = self + .0 + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + state.check(cx)?; + if !state.readable { + state.reader = Some(cx.waker().clone()); + return Poll::Pending; + } + Pin::new(state.io.as_mut().unwrap()).poll_read(cx, out) + } +} + +impl AsyncWrite for Writer { + fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bytes: &[u8], + ) -> Poll> { + let mut state = self + .0 + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + state.check(cx)?; + if bytes.is_empty() { + return Poll::Ready(Ok(0)); + } + state.writer = Some(cx.waker().clone()); + state.written = true; + Pin::new(state.io.as_mut().unwrap()).poll_write(cx, bytes) + } + + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let mut state = self + .0 + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + state.check(cx)?; + state.writer = Some(cx.waker().clone()); + if !state.written { + return Poll::Ready(Ok(())); + } + ready!(Pin::new(state.io.as_mut().unwrap()).poll_flush(cx))?; + state.readable = true; + state.deadline = None; + if let Some(waker) = state.reader.take() { + waker.wake(); + } + Poll::Ready(Ok(())) + } + + fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { + self.0 + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .fail(io::ErrorKind::BrokenPipe); + Poll::Ready(Ok(())) + } +} diff --git a/src/outbound/tuic/activity.rs b/src/outbound/tuic/activity.rs new file mode 100644 index 0000000..2ca76ed --- /dev/null +++ b/src/outbound/tuic/activity.rs @@ -0,0 +1,43 @@ +//! Retired physical sessions outlive their existing logical owners, not forever. +use std::sync::{Arc, Mutex}; +use tokio::sync::Notify; + +#[derive(Default)] +pub(super) struct Activity { + state: Mutex, + changed: Notify, +} +#[derive(Default)] +struct State { + active: usize, + retired: bool, +} +pub(super) struct Lease(Arc); +impl Activity { + pub fn acquire(self: &Arc) -> Lease { + self.state.lock().unwrap().active += 1; + Lease(self.clone()) + } + pub fn retire(&self) { + self.state.lock().unwrap().retired = true; + self.changed.notify_one(); + } + pub async fn retired_and_idle(&self) { + loop { + let notified = self.changed.notified(); + { + let state = self.state.lock().unwrap(); + if state.retired && state.active == 0 { + return; + } + } + notified.await; + } + } +} +impl Drop for Lease { + fn drop(&mut self) { + self.0.state.lock().unwrap().active -= 1; + self.0.changed.notify_one(); + } +} diff --git a/src/outbound/tuic/datagram.rs b/src/outbound/tuic/datagram.rs new file mode 100644 index 0000000..8f5afc5 --- /dev/null +++ b/src/outbound/tuic/datagram.rs @@ -0,0 +1,532 @@ +//! Per-connection associations; bounded per-association reassembly and delivery. +use super::wire::{self, Fragment}; +use crate::{ + config::TuicUdpMode, + dispatch::{DatagramBudget, DatagramTransport, DispatchError}, + resources::observation::{self, ResourceKind}, + session::{Datagram, Destination}, + transport::quic::OwnedRuntime, +}; +use async_trait::async_trait; +use bytes::Bytes; +use futures_util::{StreamExt, stream::FuturesUnordered}; +use std::{ + collections::HashMap, + io, + sync::{Arc, Mutex}, + time::Duration, +}; +use tokio::{ + io::AsyncWriteExt, + sync::{mpsc, oneshot}, + time::Instant, +}; +use tokio_util::sync::CancellationToken; + +const TTL: Duration = Duration::from_secs(crate::limits::TUIC_FRAGMENT_TTL_SECONDS as u64); + +pub(super) struct Registry { + state: Mutex, + mode: TuicUdpMode, +} +#[derive(Default)] +struct State { + next: u32, + closed: bool, + entries: HashMap, +} +struct Registration { + _lease: super::activity::Lease, + sender: mpsc::Sender, + budget: u16, + pending: Reassembly, + _observation: observation::Guard, +} +impl Registry { + pub fn new(mode: TuicUdpMode) -> Self { + Self { + state: Mutex::new(State::default()), + mode, + } + } + pub fn open( + self: &Arc, + connection: quinn::Connection, + cancel: CancellationToken, + runtime: Arc, + budget: DatagramBudget, + lease: super::activity::Lease, + ) -> Result>, DispatchError> { + let mut state = self.state.lock().unwrap(); + if state.closed || cancel.is_cancelled() { + return Err(DispatchError::NotAllowed); + } + if state.next > u16::MAX as u32 { + return Ok(None); + } + let id = state.next as u16; + state.next += 1; + let (sender, receiver) = mpsc::channel(crate::limits::TUIC_UDP_QUEUE); + state.entries.insert( + id, + Registration { + _lease: lease, + sender, + budget: budget.receive(), + pending: Reassembly::default(), + _observation: observation::track(ResourceKind::Association), + }, + ); + Ok(Some(Box::new(Transport { + id, + packet: 0, + connection, + cancel, + runtime, + registry: self.clone(), + receiver, + budget, + sent: false, + closed: false, + closing: None, + }))) + } + pub fn exhausted(&self) -> bool { + self.state.lock().unwrap().next > u16::MAX as u32 + } + pub fn close(&self) { + let mut state = self.state.lock().unwrap(); + state.closed = true; + state.entries.clear(); + } + fn budget(&self, id: u16) -> Option { + self.state + .lock() + .unwrap() + .entries + .get(&id) + .map(|entry| entry.budget) + } + fn deliver(&self, fragment: Fragment) { + let mut state = self.state.lock().unwrap(); + if let Some(entry) = state.entries.get_mut(&fragment.association) + && let Some(datagram) = + entry + .pending + .push(fragment, Instant::now(), entry.budget as usize) + { + let _ = entry.sender.try_send(datagram); + observation::observe_queue( + observation::QueueKind::TuicUdp, + entry.sender.max_capacity() - entry.sender.capacity(), + crate::limits::TUIC_UDP_QUEUE, + ); + } + } + fn expire(&self) { + for entry in self.state.lock().unwrap().entries.values_mut() { + entry.pending.expire(Instant::now()); + } + } +} + +struct Transport { + id: u16, + packet: u16, + connection: quinn::Connection, + cancel: CancellationToken, + runtime: Arc, + registry: Arc, + receiver: mpsc::Receiver, + budget: DatagramBudget, + sent: bool, + closed: bool, + closing: Option>, +} + +impl Transport { + fn close_local(&mut self) { + if self.closed { + return; + } + self.closed = true; + let present = self + .registry + .state + .lock() + .unwrap() + .entries + .remove(&self.id) + .is_some(); + self.receiver.close(); + while self.receiver.try_recv().is_ok() {} + if present && self.sent && !self.cancel.is_cancelled() { + let connection = self.connection.clone(); + let id = self.id; + let (done, wait) = oneshot::channel(); + self.closing = Some(wait); + // Cancellation of close/Drop cannot orphan a control task. Quinn's + // owned runtime joins or cancels it during node Stop. + let _ = self.runtime.spawn_owned(async move { + let _ = tokio::time::timeout(crate::transport::quic::CLOSE_TIMEOUT, async { + let mut stream = connection.open_uni().await.map_err(super::failure)?; + let [hi, lo] = id.to_be_bytes(); + AsyncWriteExt::write_all(&mut stream, &[5, 3, hi, lo]).await?; + stream.finish().map_err(super::failure) + }) + .await; + let _ = done.send(()); + }); + } + } + fn message_limit(&self) -> usize { + match self.registry.mode { + TuicUdpMode::Native => self.connection.max_datagram_size().unwrap_or(0), + TuicUdpMode::Quic => u16::MAX as usize + 10 + 259, + } + } +} +impl Drop for Transport { + fn drop(&mut self) { + self.close_local(); + } +} + +#[async_trait] +impl DatagramTransport for Transport { + fn payload_budget(&self, peer: &Destination) -> DatagramBudget { + let mut address = Vec::new(); + let space = if wire::address(peer, &mut address).is_ok() { + self.message_limit().saturating_sub(10 + address.len()) + } else { + 0 + }; + DatagramBudget::new( + space.saturating_mul(255).min(u16::MAX as usize) as u16, + u16::MAX, + ) + .intersect(self.budget) + } + async fn send(&mut self, datagram: Datagram) -> Result<(), DispatchError> { + if self.closed || self.cancel.is_cancelled() { + return Err(DispatchError::NotAllowed); + } + if datagram.payload.len() > self.payload_budget(&datagram.remote).transmit() as usize { + return Err(io::Error::from(io::ErrorKind::InvalidInput).into()); + } + let packets = wire::packets( + self.id, + self.packet, + &datagram.remote, + &datagram.payload, + self.message_limit(), + )?; + // Consume the ID before the first await: cancelling a partial send + // never reuses that unfinished packet or replays its business bytes. + self.packet = self.packet.wrapping_add(1); + self.sent = true; + for (index, packet) in packets.into_iter().enumerate() { + tokio::select! { biased; + ()=self.cancel.cancelled()=>return Err(DispatchError::NotAllowed), + result=async { + match self.registry.mode { + TuicUdpMode::Native=>self.connection.send_datagram_wait(packet).await.map_err(super::failure), + TuicUdpMode::Quic=>{ + let stream=self.connection.open_uni().await.map_err(super::failure)?; + let mut stream=UniSend(Some(stream)); + AsyncWriteExt::write_all(stream.0.as_mut().unwrap(),&packet).await.map_err(super::failure)?; + stream.0.take().unwrap().finish().map_err(super::failure) + } + } + } => result?, + } + if (index + 1) % crate::limits::IO_POLL_BUDGET == 0 { + tokio::task::yield_now().await; + } + } + Ok(()) + } + async fn receive(&mut self) -> Result { + if self.closed { + return Err(DispatchError::NotAllowed); + } + tokio::select! { biased; + ()=self.cancel.cancelled()=>Err(DispatchError::NotAllowed), + packet=self.receiver.recv()=>packet.ok_or(DispatchError::ConnectionRefused), + } + } + async fn close(&mut self) -> Result<(), DispatchError> { + self.close_local(); + if let Some(wait) = self.closing.as_mut() { + let _ = wait.await; + } + self.closing = None; + Ok(()) + } +} +struct UniSend(Option); +impl Drop for UniSend { + fn drop(&mut self) { + if let Some(mut stream) = self.0.take() { + let _ = stream.reset(0_u8.into()); + } + } +} + +struct Pending { + peer: Option, + pieces: Vec>, + bytes: usize, + received: usize, + expires: Instant, + _observation: observation::Guard, +} +#[derive(Default)] +struct Reassembly { + packets: HashMap, + bytes: usize, +} +impl Reassembly { + fn remove(&mut self, id: u16) -> Option { + let p = self.packets.remove(&id)?; + self.bytes -= p.bytes; + Some(p) + } + fn expire(&mut self, now: Instant) { + self.packets.retain(|_, p| { + if p.expires <= now { + self.bytes -= p.bytes; + false + } else { + true + } + }); + } + fn push(&mut self, f: Fragment, now: Instant, budget: usize) -> Option { + self.expire(now); + if f.payload.len() > budget { + return None; + } + if f.count == 1 { + self.remove(f.packet); + return Some(Datagram { + remote: f.peer?, + payload: f.payload, + sniffed_domain: None, + }); + } + if !self.packets.contains_key(&f.packet) { + if self.packets.len() >= crate::limits::TUIC_PENDING_PACKETS { + return None; + } + self.packets.insert( + f.packet, + Pending { + peer: None, + pieces: vec![None; f.count as usize], + bytes: 0, + received: 0, + expires: now + TTL, + _observation: observation::track(ResourceKind::Reassembly), + }, + ); + } + let p = self.packets.get_mut(&f.packet).unwrap(); + if p.pieces.len() != f.count as usize + || (f.index == 0 && p.peer.is_some() && p.peer != f.peer) + { + self.remove(f.packet); + return None; + } + if let Some(previous) = &p.pieces[f.index as usize] { + if previous != &f.payload { + self.remove(f.packet); + } + return None; + } + if p.bytes + f.payload.len() > budget + || self.bytes + f.payload.len() > crate::limits::TUIC_PENDING_BYTES + { + self.remove(f.packet); + return None; + } + if f.index == 0 { + p.peer = f.peer; + } + p.bytes += f.payload.len(); + self.bytes += f.payload.len(); + p.received += 1; + p.pieces[f.index as usize] = Some(f.payload); + if p.received != p.pieces.len() { + return None; + } + let p = self.remove(f.packet).unwrap(); + let mut payload = Vec::with_capacity(p.bytes); + for piece in p.pieces { + payload.extend_from_slice(&piece.unwrap()); + } + Some(Datagram { + remote: p.peer?, + payload: payload.into(), + sniffed_domain: None, + }) + } +} + +pub(super) async fn receive( + connection: &quinn::Connection, + registry: &Registry, +) -> Result<(), DispatchError> { + let mut streams = FuturesUnordered::new(); + let mut expiry = tokio::time::interval(Duration::from_secs(1)); + expiry.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + let mut count = 0; + loop { + tokio::select! { + _=expiry.tick()=>registry.expire(), + result=connection.read_datagram()=>{ + let raw=result.map_err(|_|DispatchError::ConnectionRefused)?; + if registry.mode==TuicUdpMode::Native && let Ok(fragment)=wire::decode(raw) { registry.deliver(fragment); } + }, + stream=connection.accept_uni(),if streams.len(){ + let stream=stream.map_err(|_|DispatchError::ConnectionRefused)?; + if registry.mode==TuicUdpMode::Quic { + streams.push(tokio::time::timeout(TTL,wire::read_packet(stream,|id|registry.budget(id)))); + } + }, + Some(result)=streams.next(),if !streams.is_empty()=>{ + if let Ok(Ok(fragment))=result { registry.deliver(fragment); } + }, + } + count += 1; + if count % crate::limits::IO_POLL_BUDGET == 0 { + tokio::task::yield_now().await; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + fn fragment(id: u16, index: u8, payload: Bytes) -> Fragment { + Fragment { + association: 0, + packet: id, + count: 2, + index, + peer: if index == 0 { + Some(Destination::domain("x", 80).unwrap()) + } else { + None + }, + payload, + } + } + #[test] + fn reassembly_releases_completed_ids_and_orders_duplicates_without_cross_packet_mix() { + let _case = crate::resources::case_events::Case::new("TUIC-UNIT", "reassembly_order"); + let mut r = Reassembly::default(); + let now = Instant::now(); + for id in [65535, 0, 65535] { + assert!( + r.push(fragment(id, 1, Bytes::from_static(b"tail")), now, 8) + .is_none() + ); + assert!( + r.push(fragment(id, 1, Bytes::from_static(b"tail")), now, 8) + .is_none() + ); + assert_eq!(r.bytes, 4); + let packet = r + .push(fragment(id, 0, Bytes::from_static(b"head")), now, 8) + .unwrap(); + assert_eq!(packet.payload, b"headtail"[..]); + assert_eq!(packet.remote, Destination::domain("x", 80).unwrap()); + assert!(r.packets.is_empty()); + assert_eq!(r.bytes, 0); + } + r.push(fragment(0, 1, Bytes::from_static(b"a")), now, 8); + r.push(fragment(0, 1, Bytes::from_static(b"b")), now, 8); + assert!(r.packets.is_empty()); + } + #[test] + fn partial_packets_expire_and_both_resource_bounds_are_per_association() { + let _case = crate::resources::case_events::Case::new("TUIC-UNIT", "reassembly_limits"); + let now = Instant::now(); + let mut r = Reassembly::default(); + for id in 0..65 { + r.push(fragment(id, 1, Bytes::new()), now, 65535); + } + assert_eq!(r.packets.len(), 64); + assert_eq!(r.bytes, 0); + let mut other = Reassembly::default(); + other.push(fragment(64, 0, Bytes::new()), now, 65535); + assert_eq!(other.packets.len(), 1); + r.expire(now + TTL - Duration::from_nanos(1)); + assert_eq!(r.packets.len(), 64); + r.expire(now + TTL); + assert!(r.packets.is_empty()); + for id in 0..4 { + r.push(fragment(id, 1, vec![1; 65535].into()), now, 65535); + } + r.push(fragment(4, 1, Bytes::from_static(b"1234")), now, 65535); + assert_eq!(r.bytes, 256 * 1024); + r.push(fragment(5, 1, Bytes::from_static(b"x")), now, 65535); + assert_eq!(r.bytes, 256 * 1024); + assert!(!r.packets.contains_key(&5)); + // Packet-level budget is independent from the owner-wide byte cap. + other.push(fragment(3, 0, Bytes::from_static(b"ab")), now, 2); + assert!( + other + .push(fragment(3, 1, Bytes::from_static(b"x")), now, 2) + .is_none() + ); + assert!(!other.packets.contains_key(&3)); + r.expire(now + TTL); + assert_eq!(r.bytes, 0); + } + #[test] + fn unknown_associations_do_not_allocate_and_full_queues_drop_complete_packets() { + let _case = crate::resources::case_events::Case::new("TUIC-UNIT", "delivery_limits"); + let probe = observation::ResourceProbe::default(); + probe.scope_sync(|| { + let registry = Registry::new(TuicUdpMode::Native); + registry.deliver(fragment(0, 1, Bytes::from_static(b"x"))); + assert!(probe.snapshot().is_idle()); + let (sender, mut receiver) = mpsc::channel(crate::limits::TUIC_UDP_QUEUE); + registry.state.lock().unwrap().entries.insert( + 0, + Registration { + _lease: Arc::new(super::super::activity::Activity::default()).acquire(), + sender, + budget: 1, + pending: Reassembly::default(), + _observation: observation::track(ResourceKind::Association), + }, + ); + for byte in 0..33 { + let mut f = fragment(byte, 0, vec![byte as u8].into()); + f.count = 1; + registry.deliver(f); + } + let mut count = 0; + while let Ok(packet) = receiver.try_recv() { + assert_eq!(packet.payload, vec![count]); + count += 1; + } + assert_eq!(count, 32); + let mut f = fragment(0, 0, Bytes::from_static(b"xx")); + f.count = 1; + registry.deliver(f); + assert!(receiver.try_recv().is_err()); + registry.close(); + assert!(probe.snapshot().is_idle()); + let queue = probe + .queues() + .into_iter() + .find(|q| q.kind == observation::QueueKind::TuicUdp) + .unwrap(); + assert_eq!((queue.peak, queue.capacity), (32, 32)); + }); + } +} diff --git a/src/outbound/tuic/mod.rs b/src/outbound/tuic/mod.rs new file mode 100644 index 0000000..a309e49 --- /dev/null +++ b/src/outbound/tuic/mod.rs @@ -0,0 +1,12 @@ +//! TUIC v5 over the existing controlled QUIC seam. No socket or DNS factory. +mod activity; +mod datagram; +mod outbound; +mod stream; +mod wire; +pub use outbound::TuicOutbound; + +fn failure(_: E) -> std::io::Error { + // Peer close reasons and TLS errors may carry identities or destinations. + std::io::Error::other("TUIC exchange failed") +} diff --git a/src/outbound/tuic/outbound.rs b/src/outbound/tuic/outbound.rs new file mode 100644 index 0000000..36c0a36 --- /dev/null +++ b/src/outbound/tuic/outbound.rs @@ -0,0 +1,363 @@ +use super::{ + activity::{Activity, Lease}, + failure, + stream::Stream, + wire, +}; +use crate::{ + config::{TuicCongestion, TuicOutboundConfig}, + dispatch::{DatagramBudget, DatagramTransport, DispatchError}, + outbound::{ + ConnectedStream, DatagramRequest, EstablishContext, OutboundConnector, UpstreamPath, + owned_stream::OwnedStream, server_destination, + }, + resources::observation::{self, ResourceKind}, + security::{SecurityContext, StandardTlsClient, TlsClientOptions, TlsVersions}, + session::{DatagramSession, Destination, StreamSession}, + transport::quic::{self, OwnedRuntime}, +}; +use async_trait::async_trait; +use std::{ + io, + sync::{Arc, Mutex}, + time::Duration, +}; +use tokio::{ + io::AsyncWriteExt, + sync::{Mutex as AsyncMutex, oneshot}, +}; +use tokio_util::{sync::CancellationToken, task::TaskTracker}; + +pub struct TuicOutbound { + config: Arc, + server: Destination, + upstream: UpstreamPath, + tls: Arc, + current: AsyncMutex>>, + cancel: CancellationToken, + admission: Mutex<()>, + tasks: TaskTracker, +} + +struct Session { + connection: quinn::Connection, + cancel: CancellationToken, + datagrams: Arc, + runtime: Arc, + activity: Arc, +} + +impl std::fmt::Debug for TuicOutbound { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("TuicOutbound").finish_non_exhaustive() + } +} + +impl TuicOutbound { + /// Remaining actual Quinn datagram buffer, for bounded-backpressure checks. + #[cfg(feature = "interop-test")] + pub async fn datagram_buffer_space(&self) -> Option { + self.current + .lock() + .await + .as_ref() + .map(|s| s.connection.datagram_send_buffer_space()) + } + + /// Actual Quinn controller identity for acceptance; no peer or credential data. + #[cfg(feature = "interop-test")] + pub async fn congestion_observation(&self) -> Option { + let current = self.current.lock().await; + let controller = current.as_ref()?.connection.congestion_state().into_any(); + if controller.is::() { + Some(TuicCongestion::Cubic) + } else if controller.is::() { + Some(TuicCongestion::NewReno) + } else if controller.is::() { + Some(TuicCongestion::Bbr) + } else { + None + } + } + + pub fn new_with_path(config: &TuicOutboundConfig, upstream: UpstreamPath) -> io::Result { + Self::with_shared_security(config, upstream, &SecurityContext::new(), 64 * 1024) + } + + pub(crate) fn with_shared_security( + config: &TuicOutboundConfig, + upstream: UpstreamPath, + security: &SecurityContext, + buffer_limit: usize, + ) -> io::Result { + config.validate().map_err(failure)?; + let tls = StandardTlsClient::with_options( + security, + &config.tls.server_name, + TlsClientOptions { + versions: TlsVersions::Tls13, + alpn: config.tls.alpn.clone(), + certificate: config.tls.certificate.clone(), + ..Default::default() + }, + 0, + buffer_limit, + )? + .quic_config()? + .0; + Ok(Self { + config: Arc::new(config.clone()), + server: server_destination(&config.address, config.port)?, + upstream, + tls, + current: AsyncMutex::new(None), + cancel: CancellationToken::new(), + admission: Mutex::new(()), + tasks: TaskTracker::new(), + }) + } + + async fn session( + &self, + datagram: DatagramSession, + context: &EstablishContext, + ) -> Result<(Arc, Lease), DispatchError> { + if tokio::time::Instant::now() >= context.deadline() { + return Err(DispatchError::TimedOut); + } + let _waiter = observation::track(ResourceKind::Waiter); + tokio::select! { biased; + () = self.cancel.cancelled() => Err(DispatchError::NotAllowed), + result = context.run("TUIC session", async { + let mut current = self.current.lock().await; + if let Some(session) = current.as_ref().filter(|s| !s.cancel.is_cancelled() && s.connection.close_reason().is_none() && !s.datagrams.exhausted()) { + return Ok((session.clone(),session.activity.acquire())); + } + if let Some(previous)=current.take() { previous.activity.retire(); } + let cancel = self.cancel.child_token(); + let guard = cancel.clone().drop_guard(); + let (ready, reply) = oneshot::channel(); + { + let _admission = self.admission.lock().unwrap(); + if self.cancel.is_cancelled() { return Err(DispatchError::NotAllowed); } + let config = self.config.clone(); + let upstream = self.upstream.clone(); + let server = self.server.clone(); + let tls = self.tls.clone(); + let context = context.clone(); + let task = observation::track(ResourceKind::Task); + self.tasks.spawn(observation::bind(async move { + let _task = task; + drive(config, upstream, server, tls, datagram, context, cancel, ready).await; + })); + } + let session = reply.await.map_err(|_|DispatchError::ConnectionRefused)??; + guard.disarm(); + *current = Some(session.clone()); + let lease=session.activity.acquire(); + Ok((session,lease)) + }) => result, + } + } +} + +#[async_trait] +impl OutboundConnector for TuicOutbound { + async fn connect_stream( + &self, + session: StreamSession, + context: &EstablishContext, + ) -> Result { + let header = wire::connect(&session.destination)?; + let (shared, lease) = self + .session( + DatagramSession::new(session.inbound, session.source), + context, + ) + .await?; + tokio::select! { biased; + () = shared.cancel.cancelled() => Err(DispatchError::ConnectionRefused), + result = context.run_io("TUIC Connect", async { + let pair = shared.connection.open_bi().await.map_err(failure)?; + let mut stream = Stream::new(pair,lease,shared.runtime.clone()); + stream.write_all(&header).await?; + stream.flush().await?; + Ok(ConnectedStream { io: Box::new(OwnedStream::new(Box::new(stream), shared.cancel.child_token())), effective_peer:session.destination }) + }) => result, + } + } + + async fn open_datagram( + &self, + request: DatagramRequest, + context: &EstablishContext, + ) -> Result, DispatchError> { + loop { + let (shared, lease) = self.session(request.session.clone(), context).await?; + if let Some(transport) = shared.datagrams.open( + shared.connection.clone(), + shared.cancel.clone(), + shared.runtime.clone(), + request.budget(), + lease, + )? { + return Ok(transport); + } + // Another concurrent admission consumed the last ID. The next + // lookup retires this session under the same original deadline. + } + } + + fn begin_shutdown(&self) { + let _admission = self.admission.lock().unwrap(); + self.cancel.cancel(); + self.tasks.close(); + } + async fn shutdown(&self) { + self.begin_shutdown(); + self.tasks.wait().await; + self.current.lock().await.take(); + } +} +impl Drop for TuicOutbound { + fn drop(&mut self) { + self.cancel.cancel(); + } +} + +#[allow(clippy::too_many_arguments)] +async fn drive( + config: Arc, + upstream: UpstreamPath, + server: Destination, + tls: Arc, + datagram: DatagramSession, + context: EstablishContext, + cancel: CancellationToken, + ready: oneshot::Sender, DispatchError>>, +) { + let runtime = Arc::new(OwnedRuntime::new(CancellationToken::new())); + let mut ready = Some(ready); + let mut endpoint = None; + let mut driver = None; + let _pool = observation::track(ResourceKind::Pool); + let datagrams = Arc::new(super::datagram::Registry::new(config.udp_mode)); + let activity = Arc::new(Activity::default()); + let operation = async { + let handshake = observation::track(ResourceKind::Handshake); + let destination = upstream.datagram_server(&server, &context)?; + let peer = context.resolve_ip(&destination).await?; + let budget = DatagramBudget::new( + crate::limits::TUIC_QUIC_PAYLOAD as u16, + crate::limits::TUIC_QUIC_PAYLOAD as u16, + ); + let raw = upstream + .open_datagram(DatagramRequest::new(datagram).with_budget(budget), &context) + .await?; + let (socket, owned) = quic::attach(raw, peer, budget)?; + driver = Some(owned); + let mtu = socket.budget().quic_payload_limit()?; + let mut limits = quinn::TransportConfig::default(); + limits + .initial_mtu(mtu) + .min_mtu(mtu) + .mtu_discovery_config(None) + .max_concurrent_bidi_streams(0_u8.into()) + .max_concurrent_uni_streams((crate::limits::TUIC_UNI_STREAMS as u32).into()) + .stream_receive_window((crate::limits::TUIC_STREAM_WINDOW as u32).into()) + .receive_window((crate::limits::TUIC_CONNECTION_WINDOW as u32).into()) + .send_window(crate::limits::TUIC_CONNECTION_WINDOW as u64) + .datagram_receive_buffer_size(Some(crate::limits::TUIC_DATAGRAM_BUFFER)) + .datagram_send_buffer_size(crate::limits::TUIC_DATAGRAM_BUFFER) + .max_idle_timeout(Some(Duration::from_secs(30).try_into().map_err(failure)?)) + .keep_alive_interval(Some(Duration::from_secs(10))) + .congestion_controller_factory(match config.congestion { + TuicCongestion::Cubic => Arc::new(quinn::congestion::CubicConfig::default()), + TuicCongestion::NewReno => Arc::new(quinn::congestion::NewRenoConfig::default()), + TuicCongestion::Bbr => Arc::new(quinn::congestion::BbrConfig::default()), + }); + let crypto = quinn::crypto::rustls::QuicClientConfig::try_from(tls).map_err(failure)?; + let mut client = quinn::ClientConfig::new(Arc::new(crypto)); + client.transport_config(Arc::new(limits)); + let mut options = quinn::EndpointConfig::default(); + options.max_udp_payload_size(mtu).map_err(failure)?; + let mut ep = + quinn::Endpoint::new_with_abstract_socket(options, None, socket, runtime.clone())?; + ep.set_default_client_config(client); + endpoint = Some(ep); + let connection = endpoint + .as_ref() + .unwrap() + .connect(peer, &config.tls.server_name) + .map_err(failure)? + .await + .map_err(failure)?; + let alpn = connection + .handshake_data() + .and_then(|v| v.downcast::().ok()) + .and_then(|v| v.protocol); + if !alpn.is_some_and(|p| config.tls.alpn.contains(&p)) + || connection.max_datagram_size().is_none() + { + return Err(DispatchError::NotAllowed); + } + // Export from this established connection; no provider fork or token cache. + let mut auth = [0_u8; 50]; + auth[..2].copy_from_slice(&[5, 0]); + auth[2..18].copy_from_slice(config.uuid.as_bytes()); + connection + .export_keying_material( + &mut auth[18..], + config.uuid.as_bytes(), + config.password.as_bytes(), + ) + .map_err(failure)?; + let mut send = connection.open_uni().await.map_err(failure)?; + AsyncWriteExt::write_all(&mut send, &auth) + .await + .map_err(failure)?; + send.finish().map_err(failure)?; + auth.fill(0); + drop(handshake); + let session = Arc::new(Session { + connection: connection.clone(), + cancel: cancel.clone(), + datagrams: datagrams.clone(), + runtime: runtime.clone(), + activity: activity.clone(), + }); + ready + .take() + .unwrap() + .send(Ok(session)) + .map_err(|_| DispatchError::ConnectionRefused)?; + let mut beat = tokio::time::interval(Duration::from_secs(10)); + beat.tick().await; + tokio::select! { + _=connection.closed()=>{}, + ()=activity.retired_and_idle()=>{}, + result=super::datagram::receive(&connection,&datagrams)=>{ result?; }, + result=async { loop { beat.tick().await; connection.send_datagram(bytes::Bytes::from_static(&[5,4])).map_err(failure)?; } #[allow(unreachable_code)] Ok::<_,io::Error>(()) }=>{ result?; }, + } + Ok::<_, DispatchError>(()) + }; + let result = tokio::select! { biased; + () = cancel.cancelled() => Err(DispatchError::NotAllowed), + result = operation => result, + }; + cancel.cancel(); + datagrams.close(); + if let Some(ready) = ready { + let _ = ready.send(Err(result + .err() + .unwrap_or(DispatchError::ConnectionRefused))); + } + if let Some(ep) = endpoint { + ep.close(0_u8.into(), b""); + let _ = tokio::time::timeout(quic::CLOSE_TIMEOUT, ep.wait_idle()).await; + } + runtime.stop().await; + if let Some(driver) = driver { + let _ = driver.stop().await; + } +} diff --git a/src/outbound/tuic/stream.rs b/src/outbound/tuic/stream.rs new file mode 100644 index 0000000..2ef8794 --- /dev/null +++ b/src/outbound/tuic/stream.rs @@ -0,0 +1,108 @@ +use std::{ + io, + pin::Pin, + sync::Arc, + task::{Context, Poll}, + time::Duration, +}; +use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; + +/// A logical stream owns both directions. Cancellation resets only this stream; +/// application EOF follows Mihomo's close-both-directions wrapper semantics. +pub(super) struct Stream { + lease: Option, + runtime: Arc, + send: Option, + recv: Option, + reader: futures_util::task::AtomicWaker, +} + +impl Stream { + pub fn new( + (send, recv): (quinn::SendStream, quinn::RecvStream), + lease: super::activity::Lease, + runtime: Arc, + ) -> Self { + Self { + lease: Some(lease), + runtime, + send: Some(send), + recv: Some(recv), + reader: Default::default(), + } + } +} + +impl Drop for Stream { + fn drop(&mut self) { + if let Some(mut send) = self.send.take() { + let _ = send.reset(0_u8.into()); + } + self.recv.take(); + } +} + +impl AsyncRead for Stream { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + if buf.remaining() == 0 { + return Poll::Ready(Ok(())); + } + self.reader.register(cx.waker()); + let Some(recv) = &mut self.recv else { + return Poll::Ready(Err(io::ErrorKind::BrokenPipe.into())); + }; + Pin::new(recv) + .poll_read(cx, buf) + .map(|v| v.map_err(super::failure)) + } +} + +impl AsyncWrite for Stream { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { + let Some(send) = &mut self.send else { + return Poll::Ready(Err(io::ErrorKind::BrokenPipe.into())); + }; + AsyncWrite::poll_write(Pin::new(send), cx, buf).map(|v| v.map_err(super::failure)) + } + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let Some(send) = &mut self.send else { + return Poll::Ready(Err(io::ErrorKind::BrokenPipe.into())); + }; + Pin::new(send) + .poll_flush(cx) + .map(|v| v.map_err(super::failure)) + } + fn poll_shutdown(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { + self.recv.take(); + self.reader.wake(); + let lease = self.lease.take(); + let Some(mut send) = self.send.take() else { + return Poll::Ready(Ok(())); + }; + if let Err(error) = send.finish() { + return Poll::Ready(Err(super::failure(error))); + } + // finish queues a FIN; it is not peer acknowledgement. Keep the retired + // pool alive until FIN/data are acknowledged, or the bounded grace ends. + // Mihomo retains closed TCP stream owners for its five-second TCP + // timeout. Application shutdown remains immediate; node Stop cancels + // and joins this work rather than waiting out the grace. + let _ = self.runtime.spawn_owned(async move { + let _lease = lease; + let _ = tokio::time::timeout( + Duration::from_secs(crate::limits::TUIC_FIN_GRACE_SECONDS as u64), + send.stopped(), + ) + .await; + }); + Poll::Ready(Ok(())) + } +} diff --git a/src/outbound/tuic/wire.rs b/src/outbound/tuic/wire.rs new file mode 100644 index 0000000..d059eaa --- /dev/null +++ b/src/outbound/tuic/wire.rs @@ -0,0 +1,307 @@ +//! Minimal v5 command encoding. Crypto and QUIC remain in official libraries. +use crate::session::Destination; +use bytes::{Buf, Bytes}; +use std::io; +use tokio::io::{AsyncRead, AsyncReadExt}; + +pub(super) fn address(peer: &Destination, out: &mut Vec) -> io::Result<()> { + if peer.port() == 0 { + return Err(io::ErrorKind::InvalidInput.into()); + } + match peer { + Destination::Ip(peer) => match peer.ip() { + std::net::IpAddr::V4(ip) => { + out.push(1); + out.extend_from_slice(&ip.octets()); + } + std::net::IpAddr::V6(ip) => { + out.push(2); + out.extend_from_slice(&ip.octets()); + } + }, + Destination::Domain { host, .. } => { + if host.is_empty() || host.len() > 255 || host.bytes().any(|v| v.is_ascii_control()) { + return Err(io::ErrorKind::InvalidInput.into()); + } + out.extend_from_slice(&[0, host.len() as u8]); + out.extend_from_slice(host.as_bytes()); + } + } + out.extend_from_slice(&peer.port().to_be_bytes()); + Ok(()) +} + +pub(super) fn connect(peer: &Destination) -> io::Result> { + let mut bytes = vec![5, 1]; + address(peer, &mut bytes)?; + Ok(bytes) +} + +pub(super) fn packets( + association: u16, + packet: u16, + peer: &Destination, + payload: &[u8], + limit: usize, +) -> io::Result> { + if payload.len() > u16::MAX as usize { + return Err(io::ErrorKind::InvalidInput.into()); + } + let mut target = Vec::new(); + address(peer, &mut target)?; + let space = limit + .checked_sub(10 + target.len()) + .ok_or(io::ErrorKind::InvalidInput)?; + if space == 0 && !payload.is_empty() { + return Err(io::ErrorKind::InvalidInput.into()); + } + let count = payload.len().max(1).div_ceil(space.max(1)); + if count > 255 { + return Err(io::ErrorKind::InvalidInput.into()); + } + let mut out = Vec::with_capacity(count); + for index in 0..count { + let body = + &payload[(index * space).min(payload.len())..((index + 1) * space).min(payload.len())]; + let mut bytes = vec![5, 2]; + bytes.extend_from_slice(&association.to_be_bytes()); + bytes.extend_from_slice(&packet.to_be_bytes()); + bytes.extend_from_slice(&[count as u8, index as u8]); + bytes.extend_from_slice(&(body.len() as u16).to_be_bytes()); + if index == 0 { + bytes.extend_from_slice(&target); + } else { + bytes.push(255); + } + bytes.extend_from_slice(body); + out.push(bytes.into()); + } + Ok(out) +} + +pub(super) struct Fragment { + pub association: u16, + pub packet: u16, + pub count: u8, + pub index: u8, + pub peer: Option, + pub payload: Bytes, +} + +fn invalid() -> io::Error { + io::ErrorKind::InvalidData.into() +} + +fn take(bytes: &mut Bytes, count: usize) -> io::Result { + if bytes.len() < count { + return Err(invalid()); + } + Ok(bytes.split_to(count)) +} + +fn parse_address(bytes: &mut Bytes) -> io::Result> { + let kind = take(bytes, 1)?[0]; + if kind == 255 { + return Ok(None); + } + let host = match kind { + 0 => { + let n = take(bytes, 1)?[0] as usize; + take(bytes, n)? + } + 1 => take(bytes, 4)?, + 2 => take(bytes, 16)?, + _ => return Err(invalid()), + }; + let mut port = take(bytes, 2)?; + let port = port.get_u16(); + if port == 0 { + return Err(invalid()); + } + Ok(Some(match kind { + 0 => Destination::domain(std::str::from_utf8(&host).map_err(|_| invalid())?, port) + .map_err(|_| invalid())?, + 1 => Destination::Ip(std::net::SocketAddr::new( + std::net::Ipv4Addr::from(<[u8; 4]>::try_from(host.as_ref()).unwrap()).into(), + port, + )), + 2 => Destination::Ip(std::net::SocketAddr::new( + std::net::Ipv6Addr::from(<[u8; 16]>::try_from(host.as_ref()).unwrap()).into(), + port, + )), + _ => unreachable!(), + })) +} + +pub(super) fn decode(mut bytes: Bytes) -> io::Result { + let mut head = take(&mut bytes, 10)?; + if head.get_u8() != 5 || head.get_u8() != 2 { + return Err(invalid()); + } + let association = head.get_u16(); + let packet = head.get_u16(); + let count = head.get_u8(); + let index = head.get_u8(); + let size = head.get_u16(); + if count == 0 || index >= count { + return Err(invalid()); + } + let peer = parse_address(&mut bytes)?; + if (index == 0) != peer.is_some() || bytes.len() != size as usize { + return Err(invalid()); + } + Ok(Fragment { + association, + packet, + count, + index, + peer, + payload: bytes, + }) +} + +/// Validate the association/size before allocating payload storage. One command +/// per uni stream, bounded by the same receiver budget as DATAGRAM packets. +pub(super) async fn read_packet( + mut stream: impl AsyncRead + Unpin, + allowed: impl Fn(u16) -> Option, +) -> io::Result { + let mut head = [0; 10]; + stream.read_exact(&mut head).await?; + if head[..2] != [5, 2] || head[6] == 0 || head[7] >= head[6] { + return Err(invalid()); + } + let id = u16::from_be_bytes([head[2], head[3]]); + let budget = allowed(id).ok_or_else(invalid)?; + let size = u16::from_be_bytes([head[8], head[9]]) as usize; + if size > budget as usize { + return Err(invalid()); + } + let kind = stream.read_u8().await?; + let mut raw = head.to_vec(); + raw.push(kind); + let rest = match kind { + 0 => { + let len = stream.read_u8().await?; + raw.push(len); + len as usize + 2 + } + 1 => 6, + 2 => 18, + 255 => 0, + _ => return Err(invalid()), + }; + let start = raw.len(); + raw.resize(start + rest, 0); + stream.read_exact(&mut raw[start..]).await?; + // Address validity before payload allocation. + let target = parse_address(&mut Bytes::copy_from_slice(&raw[10..]))?; + if (head[7] == 0) != target.is_some() { + return Err(invalid()); + } + let start = raw.len(); + raw.resize(start + size, 0); + stream.read_exact(&mut raw[start..]).await?; + let mut extra = [0]; + if stream.read(&mut extra).await? != 0 { + return Err(invalid()); + } + decode(raw.into()) +} + +#[cfg(test)] +mod tests { + use super::*; + use tokio::io::AsyncWriteExt; + #[test] + fn native_packet_has_one_address_and_exact_fragment_lengths() { + let peer = Destination::Ip("192.0.2.1:53".parse().unwrap()); + let actual = packets(0x1234, 0xabcd, &peer, b"abcde", 19).unwrap(); + assert_eq!( + actual.iter().map(|b| b.as_ref()).collect::>(), + [ + &b"\x05\x02\x12\x34\xab\xcd\x03\x00\x00\x02\x01\xc0\x00\x02\x01\x00\x35ab"[..], + &b"\x05\x02\x12\x34\xab\xcd\x03\x01\x00\x02\xffcd"[..], + &b"\x05\x02\x12\x34\xab\xcd\x03\x02\x00\x01\xffe"[..], + ] + ); + } + + #[test] + fn address_and_packet_bounds_are_wire_exact_and_fail_closed() { + assert_eq!( + connect(&Destination::domain("x", 80).unwrap()).unwrap(), + b"\x05\x01\x00\x01x\x00\x50" + ); + let mut ipv6 = vec![5, 1, 2]; + ipv6.extend_from_slice(&[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 53]); + assert_eq!( + connect(&Destination::Ip("[::1]:53".parse().unwrap())).unwrap(), + ipv6 + ); + let peer = Destination::Ip("192.0.2.1:53".parse().unwrap()); + assert_eq!(packets(0, 0, &peer, &[], 17).unwrap()[0].len(), 17); + assert!(packets(0, 0, &peer, &[], 16).is_err()); + assert_eq!(packets(0, 0, &peer, &[1; 255], 18).unwrap().len(), 255); + assert!(packets(0, 0, &peer, &[1; 256], 18).is_err()); + assert!(packets(0, 0, &peer, &vec![1; 65536], 66000).is_err()); + let literal = &b"\x05\x02\x00\x00\xff\xff\x01\x00\x00\x01\x01\xc0\x00\x02\x01\x00\x35x"[..]; + assert_eq!( + decode(Bytes::copy_from_slice(literal)).unwrap().payload, + b"x"[..] + ); + for length in 0..literal.len() { + assert!(decode(Bytes::copy_from_slice(&literal[..length])).is_err()); + } + for (position, value) in [(0, 4), (1, 4), (6, 0), (7, 1), (9, 2), (10, 255), (16, 0)] { + let mut bad = literal.to_vec(); + bad[position] = value; + assert!(decode(bad.into()).is_err()); + } + let mut bad = literal.to_vec(); + bad.push(0); + assert!(decode(bad.into()).is_err()); + for host in ["", "bad\0name"] { + assert!( + connect(&Destination::Domain { + host: host.into(), + port: 80 + }) + .is_err() + ); + } + } + + #[tokio::test] + async fn uni_parser_rejects_unknown_owner_before_reading_body_and_requires_fin() { + let (client, mut peer) = tokio::io::duplex(64); + peer.write_all(b"\x05\x02\xff\xff\x00\x00\x01\x00\xff\xff") + .await + .unwrap(); + assert!( + tokio::time::timeout( + std::time::Duration::from_millis(20), + read_packet(client, |_| None) + ) + .await + .unwrap() + .is_err() + ); + let literal = &b"\x05\x02\x00\x01\x00\x00\x01\x00\x00\x01\x00\x01x\x00\x35a"[..]; + for suffix in [&b""[..], &b"x"[..]] { + let (client, mut peer) = tokio::io::duplex(1); + let suffix = suffix.to_vec(); + let invalid = !suffix.is_empty(); + let sent = tokio::spawn(async move { + for byte in literal { + peer.write_all(&[*byte]).await.unwrap(); + } + let _ = peer.write_all(&suffix).await; + }); + let result = read_packet(client, |id| if id == 1 { Some(1) } else { None }).await; + assert_eq!(result.is_err(), invalid); + sent.await.unwrap(); + } + assert!(read_packet(literal, |_| Some(0)).await.is_err()); + } +} diff --git a/src/outbound/anytls/uot.rs b/src/outbound/uot.rs similarity index 83% rename from src/outbound/anytls/uot.rs rename to src/outbound/uot.rs index 518965d..6014b03 100644 --- a/src/outbound/anytls/uot.rs +++ b/src/outbound/uot.rs @@ -3,7 +3,7 @@ use std::{io, net::SocketAddr, sync::Arc}; use async_trait::async_trait; use bytes::{BufMut as _, Bytes, BytesMut}; use tokio::{ - io::{AsyncRead, AsyncReadExt as _, AsyncWriteExt as _}, + io::{AsyncRead, AsyncReadExt as _, AsyncWrite, AsyncWriteExt as _}, sync::mpsc, task::JoinHandle, }; @@ -15,8 +15,6 @@ use crate::{ socks5::encode_address, }; -use super::stream::AnyTlsStream; - pub(crate) const MAGIC_DESTINATION: &str = "sp.v2.udp-over-tcp.arpa"; const UOT_ADDRESS_IPV4: u8 = 0x00; const UOT_ADDRESS_IPV6: u8 = 0x01; @@ -75,7 +73,7 @@ impl Drop for SendGuard { } pub(crate) struct UotTransport { - writer: tokio::io::WriteHalf, + writer: Box, responses: mpsc::Receiver, cancellation: CancellationToken, reader_task: Option>, @@ -94,13 +92,17 @@ impl std::fmt::Debug for UotTransport { } impl UotTransport { - pub(crate) fn new( - stream: AnyTlsStream, + pub(crate) fn new( + reader: R, + writer: W, max_response_payload_size: u16, parent_cancellation: CancellationToken, tracker: &TaskTracker, - ) -> Self { - let (reader, writer) = tokio::io::split(stream); + ) -> Self + where + R: AsyncRead + Unpin + Send + 'static, + W: AsyncWrite + Unpin + Send + 'static, + { let cancellation = parent_cancellation.child_token(); let (responses, receiver) = mpsc::channel(RESPONSE_QUEUE_CAPACITY); let reader_cancellation = cancellation.clone(); @@ -111,7 +113,7 @@ impl UotTransport { reader_cancellation, ))); Self { - writer, + writer: Box::new(writer), responses: receiver, cancellation, reader_task: Some(reader_task), @@ -125,9 +127,7 @@ impl UotTransport { impl DatagramTransport for UotTransport { async fn send(&mut self, datagram: Datagram) -> Result<(), DispatchError> { if self.closed || self.cancellation.is_cancelled() { - return Err(DispatchError::Other( - "AnyTLS UoT association is closed".to_owned(), - )); + return Err(DispatchError::Other("UoT association is closed".to_owned())); } let packet = if self.first_write { encode_first_packet(&datagram).map_err(DispatchError::from)? @@ -135,11 +135,14 @@ impl DatagramTransport for UotTransport { encode_datagram(&datagram).map_err(DispatchError::from)? }; let mut send_guard = SendGuard::new(self.cancellation.clone()); - self.writer - .write_all(&packet) - .await - .map_err(DispatchError::from)?; - self.writer.flush().await.map_err(DispatchError::from)?; + tokio::select! { + biased; + () = self.cancellation.cancelled() => return Err(DispatchError::NotAllowed), + result = async { + self.writer.write_all(&packet).await?; + self.writer.flush().await + } => result.map_err(DispatchError::from)?, + } self.first_write = false; send_guard.commit(); Ok(()) @@ -147,9 +150,7 @@ impl DatagramTransport for UotTransport { async fn receive(&mut self) -> Result { if self.closed || self.cancellation.is_cancelled() { - return Err(DispatchError::Other( - "AnyTLS UoT association is closed".to_owned(), - )); + return Err(DispatchError::Other("UoT association is closed".to_owned())); } match self.responses.recv().await { Some(ReceiveEvent::Datagram(datagram)) => Ok(datagram), @@ -161,7 +162,7 @@ impl DatagramTransport for UotTransport { self.closed = true; Err(DispatchError::from(io::Error::new( io::ErrorKind::UnexpectedEof, - "AnyTLS UoT response stream ended", + "UoT response stream ended", ))) } } @@ -256,7 +257,7 @@ fn encode_datagram(datagram: &Datagram) -> io::Result { let payload_length = u16::try_from(datagram.payload.len()).map_err(|_| { io::Error::new( io::ErrorKind::InvalidInput, - "AnyTLS UoT datagram exceeds 65535 bytes", + "UoT datagram exceeds 65535 bytes", ) })?; let mut output = BytesMut::with_capacity(259 + 2 + datagram.payload.len()); @@ -282,7 +283,7 @@ fn encode_uot_address(destination: &Destination, output: &mut BytesMut) -> io::R let length = u8::try_from(host.len()).map_err(|_| { io::Error::new(io::ErrorKind::InvalidInput, "UoT domain is too long") })?; - if length == 0 || *port == 0 { + if length == 0 || *port == 0 || host.bytes().any(|byte| byte.is_ascii_control()) { return Err(io::Error::new( io::ErrorKind::InvalidInput, "UoT destination is invalid", @@ -361,7 +362,7 @@ where if length == 0 { return Err(io::Error::new( io::ErrorKind::InvalidData, - "AnyTLS UoT response has an empty domain", + "UoT response has an empty domain", )); } let mut host = vec![0_u8; length]; @@ -369,7 +370,7 @@ where let host = String::from_utf8(host).map_err(|_| { io::Error::new( io::ErrorKind::InvalidData, - "AnyTLS UoT response domain is not UTF-8", + "UoT response domain is not UTF-8", ) })?; let port = reader.read_u16().await?; @@ -378,14 +379,14 @@ where _ => { return Err(io::Error::new( io::ErrorKind::InvalidData, - "AnyTLS UoT response has an unknown address type", + "UoT response has an unknown address type", )); } }; if destination.port() == 0 { return Err(io::Error::new( io::ErrorKind::InvalidData, - "AnyTLS UoT response port is zero", + "UoT response port is zero", )); } Ok(destination) @@ -450,6 +451,58 @@ mod tests { assert_eq!(packet[datagram_offset], UOT_ADDRESS_DOMAIN); } + #[test] + fn rejects_invalid_destinations_and_enforces_the_u16_payload_limit() { + for remote in [ + Destination::Ip("127.0.0.1:0".parse().unwrap()), + Destination::Ip("[::1]:0".parse().unwrap()), + Destination::Domain { + host: String::new(), + port: 53, + }, + Destination::Domain { + host: "a".repeat(256), + port: 53, + }, + Destination::Domain { + host: "bad\nname.test".into(), + port: 53, + }, + Destination::Domain { + host: "dns.test".into(), + port: 0, + }, + ] { + assert!(encode_first_packet(&datagram(remote, b"x")).is_err()); + } + let mut packet = datagram(Destination::domain("a".repeat(255), 53).unwrap(), b""); + packet.payload = Bytes::from(vec![7; 65_535]); + assert!(encode_first_packet(&packet).is_ok()); + packet.payload = Bytes::from(vec![7; 65_536]); + assert!(encode_first_packet(&packet).is_err()); + } + + #[tokio::test] + async fn malformed_and_truncated_responses_are_rejected_without_a_datagram() { + // Independent wire vectors, including a length-prefixed invalid UTF-8 + // name and incomplete payload. No production encoder creates input. + for frame in [ + vec![3], + vec![2, 0], + vec![2, 1, 255, 0, 53, 0, 0], + vec![2, 1, b'\n', 0, 53, 0, 0], + vec![0, 127, 0, 0, 1, 0, 0, 0, 0], + vec![1, 0], + vec![0, 127, 0, 0, 1, 0, 53, 0, 2, 7], + ] { + assert!( + read_datagram(&mut frame.as_slice(), u16::MAX) + .await + .is_err() + ); + } + } + #[tokio::test] async fn reads_fragmented_datagram() { let encoded = encode_datagram(&datagram( diff --git a/src/resources/observation.rs b/src/resources/observation.rs index f3138c0..19bdde5 100644 --- a/src/resources/observation.rs +++ b/src/resources/observation.rs @@ -41,13 +41,15 @@ pub enum QueueKind { Hysteria2Udp, QuicIncoming, QuicOutgoing, + TuicUdp, } impl QueueKind { - pub const ALL: [Self; 4] = [ + pub const ALL: [Self; 5] = [ Self::SocksUdp, Self::Hysteria2Udp, Self::QuicIncoming, Self::QuicOutgoing, + Self::TuicUdp, ]; } @@ -82,7 +84,7 @@ mod enabled { #[derive(Debug, Clone)] pub struct ResourceProbe { counters: Arc<[ActivityStats; 8]>, - queues: Arc<[ActivityStats; 4]>, + queues: Arc<[ActivityStats; QueueKind::ALL.len()]>, } impl Default for ResourceProbe { fn default() -> Self { @@ -150,7 +152,7 @@ mod enabled { } /// Maximum occupancy of an individual queue in each category, not the /// sum across queues. Reserved send permits count as occupied slots. - pub fn queues(&self) -> [QueueCount; 4] { + pub fn queues(&self) -> [QueueCount; QueueKind::ALL.len()] { std::array::from_fn(|i| QueueCount { kind: QueueKind::ALL[i], capacity: self.queues[i].current.load(Ordering::Relaxed), diff --git a/src/runtime.rs b/src/runtime.rs index c158bbd..da1f53b 100644 --- a/src/runtime.rs +++ b/src/runtime.rs @@ -72,7 +72,9 @@ use crate::security::StandardTlsClient; feature = "outbound-vless", feature = "outbound-trojan", feature = "outbound-vmess", - feature = "outbound-hysteria2" + feature = "outbound-hysteria2", + feature = "outbound-tuic", + feature = "shadow-tls-v3" ))] use crate::security::{SecurityContext, TLS_RESUMPTION_SESSION_BUDGET}; @@ -600,7 +602,9 @@ fn build_proxy_graph( feature = "outbound-vless", feature = "outbound-trojan", feature = "outbound-vmess", - feature = "outbound-hysteria2" + feature = "outbound-hysteria2", + feature = "outbound-tuic", + feature = "shadow-tls-v3" ))] let (security_client_count, standard_tls_count) = security_counts(proxies); #[cfg(any( @@ -608,7 +612,9 @@ fn build_proxy_graph( feature = "outbound-vless", feature = "outbound-trojan", feature = "outbound-vmess", - feature = "outbound-hysteria2" + feature = "outbound-hysteria2", + feature = "outbound-tuic", + feature = "shadow-tls-v3" ))] let security_context = (security_client_count != 0).then(SecurityContext::new); #[cfg(any( @@ -616,7 +622,9 @@ fn build_proxy_graph( feature = "outbound-vless", feature = "outbound-trojan", feature = "outbound-vmess", - feature = "outbound-hysteria2" + feature = "outbound-hysteria2", + feature = "outbound-tuic", + feature = "shadow-tls-v3" ))] let resumption_sessions = standard_tls_resumption_sessions(standard_tls_count); @@ -681,6 +689,25 @@ fn build_proxy_graph( &dialer, )?; let connector: Arc = match &proxy.protocol { + ProxyProtocol::Tuic(config) => { + #[cfg(feature = "outbound-tuic")] + { + Arc::new(crate::outbound::tuic::TuicOutbound::with_shared_security( + config, + upstream, + security_context.as_ref().expect("TLS context"), + limits.tls_buffer_limit, + )?) + } + #[cfg(not(feature = "outbound-tuic"))] + { + let _ = config; + return Err(io::Error::new( + io::ErrorKind::Unsupported, + "TUIC support is disabled in this build", + )); + } + } ProxyProtocol::Hysteria2(config) => { #[cfg(feature = "outbound-hysteria2")] { @@ -748,7 +775,14 @@ fn build_proxy_graph( ProxyProtocol::Shadowsocks(config) => { #[cfg(feature = "outbound-shadowsocks")] { - Arc::new(ShadowsocksOutbound::new_with_path(config, upstream)?) + #[cfg(feature = "shadow-tls-v3")] + let security = security_context.as_ref(); + Arc::new(ShadowsocksOutbound::with_security( + config, + upstream, + #[cfg(feature = "shadow-tls-v3")] + security, + )?) } #[cfg(not(feature = "outbound-shadowsocks"))] { @@ -930,6 +964,7 @@ async fn prepare_proxy_endpoints( | ProxyProtocol::Vmess(_) | ProxyProtocol::AnyTls(_) | ProxyProtocol::Shadowsocks(_) + | ProxyProtocol::Tuic(_) | ProxyProtocol::Hysteria2(_) => None, }; @@ -994,7 +1029,9 @@ fn restrict_endpoint_addresses( feature = "outbound-vless", feature = "outbound-trojan", feature = "outbound-vmess", - feature = "outbound-hysteria2" + feature = "outbound-hysteria2", + feature = "outbound-tuic", + feature = "shadow-tls-v3" ))] fn security_counts(proxies: &[ProxyConfig]) -> (usize, usize) { proxies.iter().fold( @@ -1024,9 +1061,12 @@ fn security_counts(proxies: &[ProxyConfig]) -> (usize, usize) { client_count + 1, standard_count + usize::from(config.tls.is_some()), ), - ProxyProtocol::Socks5(_) | ProxyProtocol::Shadowsocks(_) => { - (client_count, standard_count) - } + ProxyProtocol::Shadowsocks(config) => ( + client_count + usize::from(config.shadow_tls.is_some()), + standard_count, + ), + ProxyProtocol::Socks5(_) => (client_count, standard_count), + ProxyProtocol::Tuic(_) => (client_count + 1, standard_count), }, ) } @@ -1036,7 +1076,9 @@ fn security_counts(proxies: &[ProxyConfig]) -> (usize, usize) { feature = "outbound-vless", feature = "outbound-trojan", feature = "outbound-vmess", - feature = "outbound-hysteria2" + feature = "outbound-hysteria2", + feature = "outbound-tuic", + feature = "shadow-tls-v3" ))] fn standard_tls_resumption_sessions(standard_tls_count: usize) -> usize { if standard_tls_count == 0 || standard_tls_count > TLS_RESUMPTION_SESSION_BUDGET { @@ -1356,6 +1398,11 @@ mod tests { ", password: fixture", cfg!(feature = "outbound-hysteria2"), ), + ( + "tuic", + ", uuid: 08080808-0808-0808-0808-080808080808, password: fixture", + cfg!(feature = "outbound-tuic"), + ), ]; for (protocol, fields, enabled) in variants { let _case = crate::resources::case_events::Case::new("INTEGRATION-FEATURE", protocol); diff --git a/src/security/boring.rs b/src/security/boring.rs index 9f768ed..7af3028 100644 --- a/src/security/boring.rs +++ b/src/security/boring.rs @@ -40,14 +40,12 @@ struct JlsCredentials { #[derive(Clone)] enum Connector { - #[cfg(feature = "outbound-vless")] Default(SslConnector), Named(FingerprintConnector), } impl Connector { fn configure(&self, alpn: &[u8]) -> Result { match self { - #[cfg(feature = "outbound-vless")] Self::Default(connector) => { let mut config = connector.configure()?; config.set_alpn_protos(alpn)?; @@ -145,11 +143,15 @@ impl BoringTlsClient { builder.set_private_key(&key).map_err(|_| invalid())?; builder.check_private_key().map_err(|_| invalid())?; } - let profile = profile(options.client_fingerprint.ok_or_else(invalid)?); - let connector = FingerprintConnector::new(builder, profile).map_err(|_| invalid())?; + let connector = match options.client_fingerprint { + Some(value) => Connector::Named( + FingerprintConnector::new(builder, profile(value)).map_err(|_| invalid())?, + ), + None => Connector::Default(builder.build()), + }; let alpn = wire_alpn(&options.alpn)?; Ok(Self { - connector: Connector::Named(connector), + connector, server_name: server_name.to_owned(), alpn, required_alpn: options.required_alpn.clone(), @@ -279,6 +281,14 @@ impl BoringTlsClient { async fn handshake( &self, stream: S, + ) -> io::Result>> { + self.handshake_configured(stream, |_| Ok(())).await + } + + pub(super) async fn handshake_configured( + &self, + stream: S, + configure: impl FnOnce(&mut ConnectConfiguration) -> io::Result<()>, ) -> io::Result>> { let mut config = self .connector @@ -303,6 +313,7 @@ impl BoringTlsClient { .set_jls_client(&jls.username, &jls.password) .map_err(|_| invalid())?; } + configure(&mut config)?; let tls = tokio_boring::connect(config, &self.server_name, KeepOpen(stream)) .await .map_err(|_| io::Error::other("TLS handshake failed"))?; diff --git a/src/security/mod.rs b/src/security/mod.rs index 47abdaa..42f206a 100644 --- a/src/security/mod.rs +++ b/src/security/mod.rs @@ -12,9 +12,15 @@ mod context; #[cfg(feature = "outbound-vless")] mod ech; mod resumption; +#[cfg(feature = "shadow-tls-v3")] +mod shadow_tls; +#[cfg(all(test, feature = "shadow-tls-v3"))] +mod shadow_tls_tests; mod stream; mod tls; mod verifier; +#[cfg(feature = "shadow-tls-v3")] +pub use shadow_tls::ShadowTlsClient; #[cfg(feature = "outbound-vless")] pub(crate) mod vision; diff --git a/src/security/shadow_tls.rs b/src/security/shadow_tls.rs new file mode 100644 index 0000000..7e7eebe --- /dev/null +++ b/src/security/shadow_tls.rs @@ -0,0 +1,454 @@ +//! Strict ShadowTLS v3 over caller-owned IO. Native TLS verifies the complete +//! cover handshake; only then may authenticated relay records carry SS bytes. +//! Wire reference: https://github.com/ihciah/shadow-tls/blob/master/docs/protocol-v3-en.md +use std::{ + future::Future, + io, + pin::Pin, + sync::Arc, + task::{Context, Poll, ready}, +}; + +use ring::hmac; +use sha2::{Digest, Sha256}; +use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt, ReadBuf}; +use zeroize::Zeroizing; + +use super::{SecurityContext, TlsClientOptions, TlsVersions, boring::BoringTlsClient}; +use crate::{config::ShadowTlsConfig, dispatch::BoxStream}; + +const MAX_RECORD: usize = 18_436; +const MAX_PAYLOAD: usize = 16_384; +const RECORD_HEADER: usize = 5; +const AUTH_HEADER: usize = 9; + +/// An immutable cover policy. This client has no resolver, socket factory, +/// session cache or background task; cancellation drops all handshake state. +#[derive(Clone)] +pub struct ShadowTlsClient { + tls: BoringTlsClient, + password: Arc>>, +} + +impl std::fmt::Debug for ShadowTlsClient { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ShadowTlsClient").finish_non_exhaustive() + } +} + +impl ShadowTlsClient { + pub fn new(context: &SecurityContext, config: &ShadowTlsConfig) -> io::Result { + config.validate().map_err(|_| invalid())?; + Ok(Self { + tls: BoringTlsClient::standard( + context, + &config.server_name, + &TlsClientOptions { + versions: TlsVersions::Tls13, + alpn: config.alpn.clone(), + certificate: config.certificate.clone(), + client_fingerprint: config.client_fingerprint, + ..Default::default() + }, + 0, + )?, + password: Arc::new(Zeroizing::new(config.password.as_bytes().to_vec())), + }) + } + + /// The caller retains its original establishment deadline and cancellation. + /// No business bytes are written before TLS and relay authentication succeed. + pub async fn connect(&self, raw: BoxStream) -> io::Result { + let mut relay = Relay::new(raw, self.password.clone()); + let mut tls = self + .tls + .handshake_configured(&mut relay, |config| { + config + .set_shadow_tls_v3_client(&self.password) + .map_err(|_| invalid()) + }) + .await?; + if tls.ssl().version2() != Some(boring::ssl::SslVersion::TLS1_3) || tls.ssl().pending() != 0 + { + return Err(invalid()); + } + tls.flush().await?; + // Borrowing the relay lets us drop SSL without a new fork extraction API. + // Record reads never over-read into the next record at this transition. + drop(tls); + Ok(Box::new(relay.verified()?)) + } +} + +fn invalid() -> io::Error { + io::Error::new( + io::ErrorKind::InvalidData, + "ShadowTLS authentication or record failed", + ) +} + +struct Mac(hmac::Context); +impl Mac { + fn new(password: &[u8], seed: &[u8], direction: &[u8]) -> Self { + let key = hmac::Key::new(hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY, password); + let mut value = hmac::Context::with_key(&key); + value.update(seed); + value.update(direction); + Self(value) + } + fn tag(&mut self, bytes: &[u8], chained: bool) -> [u8; 4] { + self.0.update(bytes); + let tag: [u8; 4] = self.0.clone().sign().as_ref()[..4].try_into().unwrap(); + if chained { + self.0.update(&tag); + } + tag + } + fn verifies(&mut self, record: &[u8], chained: bool) -> bool { + record.len() >= AUTH_HEADER + && boring::memcmp::eq(&self.tag(&record[AUTH_HEADER..], chained), &record[5..9]) + } +} + +/// One bounded record, retaining partial input across Pending/read cancellation. +struct Record { + bytes: Vec, + filled: usize, + size: usize, +} +impl Record { + fn new() -> Self { + Self { + bytes: vec![0; RECORD_HEADER], + filled: 0, + size: RECORD_HEADER, + } + } + fn clear(&mut self) { + self.bytes.clear(); + self.bytes.resize(RECORD_HEADER, 0); + self.filled = 0; + self.size = RECORD_HEADER; + } + fn poll(&mut self, raw: &mut BoxStream, cx: &mut Context<'_>) -> Poll> { + loop { + if self.filled < self.size { + let mut read = ReadBuf::new(&mut self.bytes[self.filled..self.size]); + ready!(Pin::new(&mut **raw).poll_read(cx, &mut read))?; + let count = read.filled().len(); + if count == 0 { + return if self.filled == 0 { + Poll::Ready(Ok(false)) + } else { + Poll::Ready(Err(io::ErrorKind::UnexpectedEof.into())) + }; + } + self.filled += count; + if self.filled < self.size { + continue; + } + } + if self.size != RECORD_HEADER { + return Poll::Ready(Ok(true)); + } + let size = usize::from(u16::from_be_bytes([self.bytes[3], self.bytes[4]])); + if self.bytes[1] != 3 + || !(1..=3).contains(&self.bytes[2]) + || !(1..=MAX_RECORD).contains(&size) + { + return Poll::Ready(Err(invalid())); + } + self.size = RECORD_HEADER + size; + self.bytes.resize(self.size, 0); + } + } +} + +struct Relay { + raw: BoxStream, + password: Arc>>, + record: Record, + pending: Option, + hello_prefix: Vec, + seed: Option<[u8; 32]>, + mask: Zeroizing<[u8; 32]>, + ignore: Option, + authorized: bool, +} +impl Relay { + fn new(raw: BoxStream, password: Arc>>) -> Self { + Self { + raw, + password, + record: Record::new(), + pending: None, + hello_prefix: Vec::new(), + seed: None, + mask: Zeroizing::new([0; 32]), + ignore: None, + authorized: false, + } + } + fn decode(&mut self) -> io::Result<()> { + let record = &mut self.record.bytes; + match record[0] { + 22 if self.seed.is_none() => { + let count = (38 - self.hello_prefix.len()).min(record.len() - RECORD_HEADER); + self.hello_prefix.extend_from_slice(&record[5..5 + count]); + if self.hello_prefix[0] != 2 { + return Err(invalid()); + } + if self.hello_prefix.len() == 38 { + let seed: [u8; 32] = self.hello_prefix[6..38].try_into().unwrap(); + self.ignore = Some(Mac::new(&self.password, &seed, &[])); + let mut digest = Sha256::new(); + digest.update(&**self.password); + digest.update(seed); + *self.mask = digest.finalize().into(); + // HRR and the final ServerHello share the first relay seed. + self.seed = Some(seed); + } + } + 23 => { + self.authorized = false; + if record.len() <= AUTH_HEADER + || record[1..3] != [3, 3] + || !self + .ignore + .as_mut() + .ok_or_else(invalid)? + .verifies(record, false) + { + return Err(invalid()); + } + for (index, byte) in record[AUTH_HEADER..].iter_mut().enumerate() { + *byte ^= self.mask[index % 32]; + } + record.drain(5..9); + let size = (record.len() - RECORD_HEADER) as u16; + record[3..5].copy_from_slice(&size.to_be_bytes()); + self.authorized = true; + } + _ => {} + } + Ok(()) + } + fn verified(self) -> io::Result { + if !self.authorized || self.pending.is_some() || self.record.filled != 0 { + return Err(invalid()); + } + let seed = self.seed.ok_or_else(invalid)?; + Ok(Verified { + raw: self.raw, + record: self.record, + pending: None, + tx: Mac::new(&self.password, &seed, b"C"), + rx: Mac::new(&self.password, &seed, b"S"), + ignore: self.ignore, + write: Vec::new(), + written: 0, + failed: false, + closing: None, + closed: false, + }) + } +} +impl AsyncRead for Relay { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + out: &mut ReadBuf<'_>, + ) -> Poll> { + let this = self.get_mut(); + if out.remaining() == 0 { + return Poll::Ready(Ok(())); + } + if this.pending.is_none() { + if !ready!(this.record.poll(&mut this.raw, cx))? { + return Poll::Ready(Ok(())); + } + this.decode()?; + this.pending = Some(0); + } + copy_pending(&mut this.record, &mut this.pending, out); + Poll::Ready(Ok(())) + } +} +impl AsyncWrite for Relay { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + bytes: &[u8], + ) -> Poll> { + Pin::new(&mut *self.raw).poll_write(cx, bytes) + } + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut *self.raw).poll_flush(cx) + } + fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { + Poll::Ready(Err(io::ErrorKind::NotConnected.into())) + } +} + +fn copy_pending(record: &mut Record, pending: &mut Option, out: &mut ReadBuf<'_>) { + let at = pending.unwrap(); + let count = out.remaining().min(record.bytes.len() - at); + out.put_slice(&record.bytes[at..at + count]); + if at + count == record.bytes.len() { + record.clear(); + *pending = None; + } else { + *pending = Some(at + count); + } +} + +struct Verified { + raw: BoxStream, + record: Record, + pending: Option, + tx: Mac, + rx: Mac, + ignore: Option, + write: Vec, + written: usize, + failed: bool, + closing: Option>>, + closed: bool, +} +impl Verified { + fn drain(&mut self, cx: &mut Context<'_>) -> Poll> { + while self.written < self.write.len() { + let count = + ready!(Pin::new(&mut *self.raw).poll_write(cx, &self.write[self.written..]))?; + if count == 0 { + return Poll::Ready(Err(io::ErrorKind::WriteZero.into())); + } + self.written += count; + } + self.write.clear(); + self.written = 0; + Poll::Ready(Ok(())) + } + fn read(&mut self, cx: &mut Context<'_>, out: &mut ReadBuf<'_>) -> Poll> { + if self.failed { + return Poll::Ready(Err(invalid())); + } + if out.remaining() == 0 { + return Poll::Ready(Ok(())); + } + // Advance accepted writes, but don't let write backpressure block reads. + if let Poll::Ready(result) = self.drain(cx) { + result?; + } + for _ in 0..32 { + if self.pending.is_some() { + copy_pending(&mut self.record, &mut self.pending, out); + return Poll::Ready(Ok(())); + } + if !ready!(self.record.poll(&mut self.raw, cx))? { + return Poll::Ready(Ok(())); + } + let record = &self.record.bytes; + if record[0..3] != [23, 3, 3] || record.len() < AUTH_HEADER { + return Poll::Ready(Err(invalid())); + } + if let Some(ignore) = &mut self.ignore { + if ignore.verifies(record, false) { + self.record.clear(); + continue; + } + self.ignore = None; + } + if !self.rx.verifies(record, true) { + return Poll::Ready(Err(invalid())); + } + if record.len() == AUTH_HEADER { + self.record.clear(); + continue; + } + self.pending = Some(AUTH_HEADER); + } + // Bound work per poll without imposing a lifetime business-record quota. + cx.waker().wake_by_ref(); + Poll::Pending + } +} +impl AsyncRead for Verified { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + out: &mut ReadBuf<'_>, + ) -> Poll> { + let this = self.get_mut(); + let result = this.read(cx, out); + if matches!(result, Poll::Ready(Err(_))) { + this.failed = true; + } + result + } +} +impl AsyncWrite for Verified { + fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bytes: &[u8], + ) -> Poll> { + let this = self.get_mut(); + if this.failed || this.closing.is_some() { + return Poll::Ready(Err(io::ErrorKind::BrokenPipe.into())); + } + if let Err(error) = ready!(this.drain(cx)) { + this.failed = true; + return Poll::Ready(Err(error)); + } + if bytes.is_empty() { + return Poll::Ready(Ok(0)); + } + let size = bytes.len().min(MAX_PAYLOAD); + let tag = this.tx.tag(&bytes[..size], true); + this.write.extend_from_slice(&[23, 3, 3]); + this.write + .extend_from_slice(&((size + 4) as u16).to_be_bytes()); + this.write.extend_from_slice(&tag); + this.write.extend_from_slice(&bytes[..size]); + Poll::Ready(Ok(size)) + } + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + if this.failed { + return Poll::Ready(Err(invalid())); + } + if let Err(error) = ready!(this.drain(cx)) { + this.failed = true; + return Poll::Ready(Err(error)); + } + let result = Pin::new(&mut *this.raw).poll_flush(cx); + if matches!(result, Poll::Ready(Err(_))) { + this.failed = true; + } + result + } + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + if self.closed { + return Poll::Ready(Ok(())); + } + if self.closing.is_none() { + self.closing = Some(Box::pin(tokio::time::sleep(super::CLOSE_NOTIFY_TIMEOUT))); + } + if self.closing.as_mut().unwrap().as_mut().poll(cx).is_ready() { + self.failed = true; + return Poll::Ready(Err(io::ErrorKind::TimedOut.into())); + } + ready!(self.as_mut().poll_flush(cx))?; + // This is now a relay stream, not a TLS application channel. Never send + // a TLS close_notify into the SS payload or release unread relay bytes. + let result = Pin::new(&mut *self.raw).poll_shutdown(cx); + if matches!(result, Poll::Ready(Ok(()))) { + self.closed = true; + } + if matches!(result, Poll::Ready(Err(_))) { + self.failed = true; + } + result + } +} diff --git a/src/security/shadow_tls_tests.rs b/src/security/shadow_tls_tests.rs new file mode 100644 index 0000000..703a1ba --- /dev/null +++ b/src/security/shadow_tls_tests.rs @@ -0,0 +1,570 @@ +//! Public wrapper behavior with native TLS over bounded memory IO. The scripted +//! relay is only a fault fixture; official server interoperability is separate. +use super::{SecurityContext, ShadowTlsClient}; +use crate::config::ShadowTlsConfig; +use rustls::{RootCertStore, ServerConfig, ServerConnection, pki_types::PrivateKeyDer}; +use sha2::{Digest, Sha256}; +use std::{ + io, + sync::{ + Arc, Mutex, + atomic::{AtomicBool, Ordering}, + }, + time::Duration, +}; +use tokio::io::{AsyncReadExt, AsyncWriteExt, DuplexStream}; + +const PASSWORD: &[u8] = b"synthetic-memory-relay"; + +struct Material { + server: Arc, + context: SecurityContext, + options: ShadowTlsConfig, + pin: [u8; 32], +} + +fn material() -> Material { + let rcgen::CertifiedKey { cert, signing_key } = + rcgen::generate_simple_self_signed(vec!["cover.invalid".into()]).unwrap(); + let mut provider = rustls::crypto::ring::default_provider(); + provider.cipher_suites = vec![rustls::crypto::ring::cipher_suite::TLS13_AES_128_GCM_SHA256]; + let provider = Arc::new(provider); + let mut roots = RootCertStore::empty(); + roots.add(cert.der().clone()).unwrap(); + let mut server = ServerConfig::builder_with_provider(provider.clone()) + .with_protocol_versions(&[&rustls::version::TLS13]) + .unwrap() + .with_no_client_auth() + .with_single_cert( + vec![cert.der().clone()], + PrivateKeyDer::Pkcs8(signing_key.serialize_der().into()), + ) + .unwrap(); + server.send_tls13_tickets = 0; + Material { + pin: Sha256::digest(cert.der()).into(), + server: Arc::new(server), + context: SecurityContext { + provider, + tls_roots: Arc::new(roots), + }, + options: ShadowTlsConfig { + server_name: "cover.invalid".into(), + password: String::from_utf8(PASSWORD.to_vec()).unwrap(), + alpn: vec![], + certificate: Default::default(), + client_fingerprint: None, + }, + } +} + +#[derive(Debug)] +struct ForgedResolver(Arc); +impl rustls::server::ResolvesServerCert for ForgedResolver { + fn resolve( + &self, + hello: rustls::server::ClientHello<'_>, + ) -> Option> { + let genuine = self.0.resolve(hello)?; + Some(Arc::new(rustls::sign::CertifiedKey::new( + genuine.cert.clone(), + Arc::new(ForgedKey), + ))) + } +} +#[derive(Debug)] +struct ForgedKey; +impl rustls::sign::SigningKey for ForgedKey { + fn choose_scheme( + &self, + schemes: &[rustls::SignatureScheme], + ) -> Option> { + schemes + .contains(&rustls::SignatureScheme::ECDSA_NISTP256_SHA256) + .then(|| Box::new(Self) as Box) + } + fn algorithm(&self) -> rustls::SignatureAlgorithm { + rustls::SignatureAlgorithm::ECDSA + } +} +impl rustls::sign::Signer for ForgedKey { + fn sign(&self, _: &[u8]) -> Result, rustls::Error> { + Ok(vec![0; 64]) + } + fn scheme(&self) -> rustls::SignatureScheme { + rustls::SignatureScheme::ECDSA_NISTP256_SHA256 + } +} + +#[tokio::test] +async fn certificate_policy_and_native_signature_must_succeed_before_a_shadowtls_stream_exists() { + let _case = crate::resources::case_events::Case::new("SHADOWTLS-UNIT", "native_signature"); + for profile in super::test_profiles() { + for failure in [ + "name", + "untrusted", + "pin", + "signature", + "signature-skip", + "signature-pin", + ] { + let mut material = material(); + material.options.client_fingerprint = *profile; + match failure { + "name" => { + material.options.certificate.verification_name = Some("wrong.invalid".into()) + } + "untrusted" => material.context = SecurityContext::new(), + "pin" => material.options.certificate.fingerprint = Some([0; 32]), + "signature-skip" => material.options.certificate.skip_cert_verify = true, + "signature-pin" => material.options.certificate.fingerprint = Some(material.pin), + _ => {} + } + if failure.starts_with("signature") { + let server = Arc::make_mut(&mut material.server); + server.cert_resolver = Arc::new(ForgedResolver(server.cert_resolver.clone())); + } + let client = ShadowTlsClient::new(&material.context, &material.options).unwrap(); + let (raw, mut peer) = tokio::io::duplex(73); + tokio::time::timeout(Duration::from_secs(3), async { + let (consumer, native) = tokio::join!( + client.connect(Box::new(raw)), + handshake(&mut peer, material.server) + ); + assert!(consumer.is_err(), "{failure} / {profile:?}"); + assert!( + native.is_err(), + "native TLS did not authenticate the client Finished" + ); + }) + .await + .unwrap(); + } + } +} + +// Test oracle deliberately uses boring's one-shot HMAC and a bounded transcript, +// not the production ring context or record implementation. +struct Transcript(Vec); +impl Transcript { + fn new(seed: &[u8], direction: &[u8]) -> Self { + Self([seed, direction].concat()) + } + fn tag(&mut self, payload: &[u8], chain: bool) -> [u8; 4] { + self.0.extend_from_slice(payload); + assert!(self.0.len() <= 1024 * 1024, "memory oracle bound"); + let tag: [u8; 4] = boring::hash::hmac_sha1(PASSWORD, &self.0).unwrap()[..4] + .try_into() + .unwrap(); + if chain { + self.0.extend_from_slice(&tag); + } + tag + } + fn seal(&mut self, payload: &[u8], chain: bool) -> Vec { + let mut output = vec![23, 3, 3]; + output.extend_from_slice(&u16::try_from(payload.len() + 4).unwrap().to_be_bytes()); + output.extend_from_slice(&self.tag(payload, chain)); + output.extend_from_slice(payload); + output + } +} + +async fn record(raw: &mut DuplexStream) -> io::Result> { + let mut header = [0; 5]; + raw.read_exact(&mut header).await?; + let size = usize::from(u16::from_be_bytes([header[3], header[4]])); + assert!((1..=18436).contains(&size)); + let mut bytes = header.to_vec(); + bytes.resize(5 + size, 0); + raw.read_exact(&mut bytes[5..]).await?; + Ok(bytes) +} + +struct Flight { + seed: Option<[u8; 32]>, + cover: Option, + mask: [u8; 32], + finished_fault: Option, +} +impl Flight { + fn new() -> Self { + Self { + seed: None, + cover: None, + mask: [0; 32], + finished_fault: None, + } + } + fn transform(&mut self, records: &[u8]) -> Vec { + let mut output = Vec::new(); + let mut at = 0; + while at < records.len() { + let size = usize::from(u16::from_be_bytes([records[at + 3], records[at + 4]])); + let mut wire = records[at..at + 5 + size].to_vec(); + if wire[0] == 23 + && let Some(fault) = &mut self.finished_fault + { + fault.mutate(&mut wire); + } + let record = wire.as_slice(); + if record[0] == 22 && self.seed.is_none() { + assert_eq!(record[5], 2); + let seed: [u8; 32] = record[11..43].try_into().unwrap(); + self.cover = Some(Transcript::new(&seed, b"")); + self.mask = Sha256::digest([PASSWORD, &seed].concat()).into(); + self.seed = Some(seed); + } + if record[0] == 23 { + let payload: Vec<_> = record[5..] + .iter() + .enumerate() + .map(|(i, b)| b ^ self.mask[i % 32]) + .collect(); + output.extend(self.cover.as_mut().unwrap().seal(&payload, false)); + } else { + output.extend_from_slice(record); + } + at += 5 + size; + } + output + } + async fn flush( + &mut self, + tls: &mut ServerConnection, + raw: &mut DuplexStream, + ) -> io::Result<()> { + let mut records = Vec::new(); + while tls.wants_write() { + tls.write_tls(&mut records)?; + } + let transformed = self.transform(&records); + for chunk in transformed.chunks(7) { + raw.write_all(chunk).await?; + } + raw.flush().await + } +} + +async fn handshake( + raw: &mut DuplexStream, + config: Arc, +) -> io::Result<(ServerConnection, Flight)> { + handshake_with_flight(raw, config, Flight::new()).await +} + +async fn handshake_with_flight( + raw: &mut DuplexStream, + config: Arc, + mut flight: Flight, +) -> io::Result<(ServerConnection, Flight)> { + let mut tls = ServerConnection::new(config).unwrap(); + while tls.is_handshaking() { + let wire = record(raw).await?; + tls.read_tls(&mut io::Cursor::new(wire))?; + tls.process_new_packets().map_err(io::Error::other)?; + flight.flush(&mut tls, raw).await?; + } + Ok((tls, flight)) +} + +// Fault injection uses only the public native TLS key-log seam, retained in +// memory for this synthetic connection. Native rustls creates the entire TLS +// flight. We alter Finished verify_data and reseal that one record with ring, +// so its AEAD and outer ShadowTLS MAC remain valid. No test TLS engine, key log +// file, production hook or copied third-party implementation is involved. +#[derive(Default)] +struct Secret(Mutex>>); +impl std::fmt::Debug for Secret { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("SyntheticHandshakeSecret") + .finish_non_exhaustive() + } +} +impl rustls::KeyLog for Secret { + fn log(&self, label: &str, _: &[u8], secret: &[u8]) { + if label == "SERVER_HANDSHAKE_TRAFFIC_SECRET" { + self.0.lock().unwrap().extend_from_slice(secret); + } + } +} +struct FinishedFault { + secret: Arc, + sequence: u64, + applied: Arc, +} +impl FinishedFault { + fn mutate(&mut self, record: &mut [u8]) { + use ring::{aead, hkdf}; + struct Size(usize); + impl hkdf::KeyType for Size { + fn len(&self) -> usize { + self.0 + } + } + let derive = |label: &[u8], size: usize| { + let secret = self.secret.0.lock().unwrap(); + assert_eq!(secret.len(), 32); + let prk = hkdf::Prk::new_less_safe(hkdf::HKDF_SHA256, &secret); + let label = [b"tls13 ", label].concat(); + let mut info = (size as u16).to_be_bytes().to_vec(); + info.push(label.len() as u8); + info.extend_from_slice(&label); + info.push(0); + let mut output = zeroize::Zeroizing::new(vec![0; size]); + prk.expand(&[&info], Size(size)) + .unwrap() + .fill(&mut output) + .unwrap(); + output + }; + let key = aead::LessSafeKey::new( + aead::UnboundKey::new(&aead::AES_128_GCM, &derive(b"key", 16)).unwrap(), + ); + let mut nonce: [u8; 12] = derive(b"iv", 12).as_slice().try_into().unwrap(); + for (index, byte) in self.sequence.to_be_bytes().iter().enumerate() { + nonce[index + 4] ^= byte; + } + self.sequence += 1; + let header: [u8; 5] = record[..5].try_into().unwrap(); + let mut plain = record[5..].to_vec(); + let len = key + .open_in_place( + aead::Nonce::assume_unique_for_key(nonce), + aead::Aad::from(header), + &mut plain, + ) + .unwrap() + .len(); + plain.truncate(len); + assert_eq!(plain.last(), Some(&22)); + let mut at = 0; + while at + 1 < plain.len() { + let len = u32::from_be_bytes([0, plain[at + 1], plain[at + 2], plain[at + 3]]) as usize; + assert!(at + 4 + len < plain.len()); + if plain[at] == 20 { + assert_eq!(len, 32); + assert!(!self.applied.swap(true, Ordering::SeqCst)); + plain[at + 4] ^= 1; + } + at += 4 + len; + } + key.seal_in_place_append_tag( + aead::Nonce::assume_unique_for_key(nonce), + aead::Aad::from(header), + &mut plain, + ) + .unwrap(); + record[5..].copy_from_slice(&plain); + } +} + +#[tokio::test] +async fn a_forged_finished_is_rejected_even_when_record_aead_relay_mac_and_pin_are_valid() { + let _case = crate::resources::case_events::Case::new("SHADOWTLS-UNIT", "native_finished"); + for profile in super::test_profiles() { + for policy in ["webpki", "skip", "pin"] { + let mut material = material(); + material.options.client_fingerprint = *profile; + if policy == "skip" { + material.options.certificate.skip_cert_verify = true; + } + if policy == "pin" { + material.options.certificate.fingerprint = Some(material.pin); + } + let secret = Arc::new(Secret::default()); + Arc::make_mut(&mut material.server).key_log = secret.clone(); + let applied = Arc::new(AtomicBool::new(false)); + let mut flight = Flight::new(); + flight.finished_fault = Some(FinishedFault { + secret, + sequence: 0, + applied: applied.clone(), + }); + let client = ShadowTlsClient::new(&material.context, &material.options).unwrap(); + let (raw, mut peer) = tokio::io::duplex(73); + tokio::time::timeout(Duration::from_secs(3), async { + let (consumer, native) = tokio::join!( + client.connect(Box::new(raw)), + handshake_with_flight(&mut peer, material.server, flight) + ); + assert!(applied.load(Ordering::SeqCst)); + assert!(consumer.is_err(), "{profile:?} / {policy}"); + assert!(native.is_err()); + }) + .await + .unwrap(); + } + } +} + +#[tokio::test] +async fn authenticated_stream_ignores_residual_cover_and_preserves_partial_io_flush_and_eof() { + let _case = crate::resources::case_events::Case::new("SHADOWTLS-UNIT", "stream_io"); + for profile in super::test_profiles() { + let mut material = material(); + material.options.client_fingerprint = *profile; + let client = ShadowTlsClient::new(&material.context, &material.options).unwrap(); + let (raw, mut peer) = tokio::io::duplex(73); + tokio::time::timeout(Duration::from_secs(10), async { + let server = async { + let (mut tls, mut flight) = handshake(&mut peer, material.server).await.unwrap(); + // More than one poll's record quota, from real native TLS. + for _ in 0..40 { + io::Write::write_all(&mut tls.writer(), b"residual-cover").unwrap(); + flight.flush(&mut tls, &mut peer).await.unwrap(); + } + let seed = flight.seed.unwrap(); + let mut transmit = Transcript::new(&seed, b"S"); + peer.write_all(&transmit.seal(b"server-first", true)) + .await + .unwrap(); + let mut receive = Transcript::new(&seed, b"C"); + let mut input = Vec::new(); + while input.len() < 131_072 { + let bytes = record(&mut peer).await.unwrap(); + assert_eq!(&bytes[..3], &[23, 3, 3]); + assert_eq!(receive.tag(&bytes[9..], true), bytes[5..9]); + input.extend_from_slice(&bytes[9..]); + } + assert_eq!(input, vec![0x5a; 131_072]); + assert_eq!( + peer.read(&mut [0; 1]).await.unwrap(), + 0, + "only raw FIN after flush; no TLS close_notify as SS bytes" + ); + peer.write_all(&transmit.seal(b"tail", true)).await.unwrap(); + peer.shutdown().await.unwrap(); + }; + let consumer = async { + let mut stream = client.connect(Box::new(raw)).await.unwrap(); + let mut hello = [0; 12]; + for byte in &mut hello { + stream.read_exact(std::slice::from_mut(byte)).await.unwrap(); + } + assert_eq!(&hello, b"server-first"); + stream.write_all(&vec![0x5a; 131_072]).await.unwrap(); + stream.flush().await.unwrap(); + stream.shutdown().await.unwrap(); + let mut tail = Vec::new(); + stream.read_to_end(&mut tail).await.unwrap(); + assert_eq!(tail, b"tail"); + }; + tokio::join!(server, consumer); + }) + .await + .unwrap(); + } +} + +#[tokio::test] +async fn cancelling_a_partial_authenticated_record_read_preserves_it_for_the_next_reader() { + let _case = crate::resources::case_events::Case::new("SHADOWTLS-UNIT", "read_cancel"); + let material = material(); + let client = ShadowTlsClient::new(&material.context, &material.options).unwrap(); + let (raw, mut peer) = tokio::io::duplex(73); + let (sent, seen) = tokio::sync::oneshot::channel(); + let (resume, ready) = tokio::sync::oneshot::channel(); + tokio::time::timeout(Duration::from_secs(3), async { + let server = async { + let (_, flight) = handshake(&mut peer, material.server).await.unwrap(); + let mut transmit = Transcript::new(&flight.seed.unwrap(), b"S"); + let wire = transmit.seal(b"one-intact-response", true); + peer.write_all(&wire[..8]).await.unwrap(); + sent.send(()).unwrap(); + ready.await.unwrap(); + peer.write_all(&wire[8..]).await.unwrap(); + peer.shutdown().await.unwrap(); + }; + let consumer = async { + let mut stream = client.connect(Box::new(raw)).await.unwrap(); + seen.await.unwrap(); + assert!( + tokio::time::timeout(Duration::from_millis(10), stream.read(&mut [0; 1])) + .await + .is_err() + ); + resume.send(()).unwrap(); + let mut data = Vec::new(); + stream.read_to_end(&mut data).await.unwrap(); + assert_eq!(data, b"one-intact-response"); + }; + tokio::join!(server, consumer); + }) + .await + .unwrap(); +} + +struct WriteGate { + io: DuplexStream, + blocked: Arc, +} +impl tokio::io::AsyncRead for WriteGate { + fn poll_read( + mut self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + out: &mut tokio::io::ReadBuf<'_>, + ) -> std::task::Poll> { + std::pin::Pin::new(&mut self.io).poll_read(cx, out) + } +} +impl tokio::io::AsyncWrite for WriteGate { + fn poll_write( + mut self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + bytes: &[u8], + ) -> std::task::Poll> { + if self.blocked.load(Ordering::SeqCst) { + return std::task::Poll::Pending; + } + std::pin::Pin::new(&mut self.io).poll_write(cx, bytes) + } + fn poll_flush( + mut self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::pin::Pin::new(&mut self.io).poll_flush(cx) + } + fn poll_shutdown( + mut self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::pin::Pin::new(&mut self.io).poll_shutdown(cx) + } +} + +#[tokio::test(start_paused = true)] +async fn shutdown_has_a_five_second_bound_even_when_the_caller_transport_never_becomes_writable() { + let _case = crate::resources::case_events::Case::new("SHADOWTLS-UNIT", "close_deadline"); + let material = material(); + let client = ShadowTlsClient::new(&material.context, &material.options).unwrap(); + let (raw, mut peer) = tokio::io::duplex(73); + let blocked = Arc::new(AtomicBool::new(false)); + let io = WriteGate { + io: raw, + blocked: blocked.clone(), + }; + let server = async { + handshake(&mut peer, material.server).await.unwrap(); + assert_eq!(peer.read(&mut [0; 1]).await.unwrap(), 0); + }; + let consumer = async { + let mut stream = client.connect(Box::new(io)).await.unwrap(); + blocked.store(true, Ordering::SeqCst); + stream + .write_all(b"accepted-but-backpressured") + .await + .unwrap(); + let started = tokio::time::Instant::now(); + let error = stream.shutdown().await.unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::TimedOut); + assert_eq!(started.elapsed(), Duration::from_secs(5)); + assert!(stream.write_all(b"must-not-retry").await.is_err()); + drop(stream); + }; + tokio::time::timeout(Duration::from_secs(6), async { + tokio::join!(server, consumer); + }) + .await + .unwrap(); +} diff --git a/src/security/tls.rs b/src/security/tls.rs index 7b49b1c..8bad1c8 100644 --- a/src/security/tls.rs +++ b/src/security/tls.rs @@ -139,7 +139,11 @@ impl std::fmt::Debug for StandardTlsClient { } impl StandardTlsClient { - #[cfg(any(feature = "outbound-vless", feature = "outbound-hysteria2"))] + #[cfg(any( + feature = "outbound-vless", + feature = "outbound-hysteria2", + feature = "outbound-tuic" + ))] pub(crate) fn quic_config(&self) -> io::Result<(Arc, String)> { match &self.connector { StandardConnector::Rustls(connector) => { diff --git a/src/transport/ws.rs b/src/transport/ws.rs index cf9bc3a..e5ad623 100644 --- a/src/transport/ws.rs +++ b/src/transport/ws.rs @@ -1,4 +1,5 @@ use std::{ + future::{Future, poll_fn}, io, pin::Pin, sync::{ @@ -46,6 +47,7 @@ pub struct WebSocketOptions { uri: http::Uri, headers: http::HeaderMap, early_data: Option, + http_upgrade: Option, } impl std::fmt::Debug for WebSocketOptions { @@ -120,8 +122,21 @@ impl WebSocketOptions { uri, headers, early_data, + http_upgrade: None, }) } + + /// Select raw HTTPUpgrade on the same supplied IO and initial-data seam. + /// Unlike framed WS, only the standard early-data header is meaningful. + pub fn with_http_upgrade(mut self, fast_open: bool) -> io::Result { + if self.early_data.as_ref().is_some_and(|early| { + !matches!(early, WebSocketEarlyData::Header { name, .. } if name == "sec-websocket-protocol") + }) { + return Err(invalid_options()); + } + self.http_upgrade = Some(fast_open); + Ok(self) + } } fn reserved(name: &http::HeaderName) -> bool { @@ -151,6 +166,9 @@ pub async fn connect_websocket( initial_data: &[u8], deadline: Instant, ) -> io::Result { + if let Some(fast_open) = options.http_upgrade { + return http_upgrade(stream, options, initial_data, fast_open, deadline).await; + } timeout_at(deadline, connect_inner(stream, options, initial_data)) .await .map_err(|_| io::Error::from(io::ErrorKind::TimedOut))? @@ -176,7 +194,7 @@ pub async fn http_upgrade( fast_open: bool, deadline: Instant, ) -> io::Result { - timeout_at(deadline, async move { + let handshake = async move { let mut headers = options.headers.clone(); let mut early = 0; if let Some(ed) = &options.early_data { @@ -260,7 +278,24 @@ pub async fn http_upgrade( stream, tail: tail.into(), }) as BoxStream) - }) + }; + tokio::pin!(handshake); + // timeout_at polls ready IO before its timer. Check every handshake poll, + // including resumes after Pending, before any further read/write or success. + // The returned stream has no setup timer, so established IO stays unrestricted. + timeout_at( + deadline, + poll_fn(|cx| { + if Instant::now() >= deadline { + return Poll::Ready(Err(io::ErrorKind::TimedOut.into())); + } + let result = ready!(handshake.as_mut().poll(cx)); + if Instant::now() >= deadline { + return Poll::Ready(Err(io::ErrorKind::TimedOut.into())); + } + Poll::Ready(result) + }), + ) .await .map_err(|_| io::Error::from(io::ErrorKind::TimedOut))? } diff --git a/tests/README.md b/tests/README.md index e1d0e18..3a11993 100644 --- a/tests/README.md +++ b/tests/README.md @@ -10,6 +10,7 @@ protocol_security、protocol_integration;事件标签与报告采用同一套 | 日常 | 严格配置、feature、协议/TLS 内存 IO、局部上限、取消、FFI 边界和确定性回归 | check core --profile debug/release | | 构建 | 精简 feature、生产 feature、全目标编译 | check core --profile features | | 工具 | 子进程/容器清理、下载、原始证据完整性、平台产物 | scripts/tests | +| 对端设施 | 官方客户端到官方服务端的真实 TCP/UDP 能力,不计 VCore 支持 | check protocol-peers | | 网络 | 公开消费者、真实原生认证/传输/UDP/上游和资源 | protocol-interop --suite … | | 发布候选 | 有序两跳、故障/重建/长测、平台产物/ABI | integration suite 与平台构建 | @@ -29,9 +30,26 @@ protocol_security、protocol_integration;事件标签与报告采用同一套 当作客户端关闭期限。上传完整性、一秒关闭上限和 Stop 验证保持独立。 - shadowsocks_backpressure:三算法 Pending 重试长度、读先于写时的 codec 刷新,以及 官方服务端对空首包零 padding 的确定性拒绝;不修改官方库,不把 codec 夹具当作互通。 + SS/SS v3/EIH TCP 容器数据验收使用非空首段的 client-first,保留完整数据量; + server-first/空首包为已知限制,其他协议仍验证服务器先发。 - hysteria2_packet_ids:完成后重用 16 位分片 ID,不误丢后续业务包。 +- shadowtls_config/stream 与 security::shadow_tls_tests:严格 v3、原生签名/Finished、 + 残留 cover、背压/flush、读取取消和关闭期限;shadowtls suite 另验官方容器对端。 +- uot_config、shadowsocks_uot 与共享 outbound::uot:仅 v2、SS 首包/读取门控、 + 三算法 u16 边界、收发预算、受控 DNS、取消/Stop;uot suite 验 TCP-only 官方 + Mihomo 六组合、上游/切组及无原生 UDP 回退,不把 ssserver 作为 UoT 正向服务端。 - security_capabilities:公开配置经真实 SecurityClient 在主/下载腿产生实际混合 share; 不再重复测试 fork 的纯 API 准入。 +- tuic_config/tuic_memory 与 outbound::tuic:严格 v5、当前 TLS exporter、无 ACK、 + 双 UDP wire、分片/重组、关联 ID 退役、窗口/credit、Heartbeat 和 Stop;tuic suite + 验官方 Mihomo 数据与身份负例、独立上游容器、嵌套组/重建/测速,并回归 HY2/H3。 +- httpupgrade_config/httpupgrade_memory:类型化普通/fast-open、ED 边界、严格 101、 + 部分写、首包恰好一次和原期限;等待后的就绪响应/写入不能越过期限,已建连接不受限。 + httpupgrade suite 另验 VMess/Trojan 真实消费者、 + UDP、Mihomo 关闭对照、命名 TLS 模板及既有 Upgrade/WS/其他传输。 +- vless_public::integration:64 个基础有序两跳与 SS v3/UoT/TUIC 强耦合链、公开入站/ + 合成 TUN、DNS/测速和旧连接组快照;100 次生命周期、100 轮混合重建、1800 秒长测。 + 新组合不替代七协议回归;资源归零、五秒静默、堆/队列与实际轮换配置独立复核。 - fingerprints/mihomo-selected-v1.json:官方独立 ClientHello golden,不从待测实现重新生成期望; [指纹验证](fingerprints/README.md)分别维护独立基线、内存报文与容器互通。 - protocols/encryption-crypto.json 及 Go 生成器:独立密码向量;许可证和来源必须保留。 diff --git a/tests/datagram_foundations.rs b/tests/datagram_foundations.rs index d956792..74144d1 100644 --- a/tests/datagram_foundations.rs +++ b/tests/datagram_foundations.rs @@ -36,6 +36,8 @@ async fn shadowsocks_budget_accounts_for_cipher_headers_and_identity_chain() { port: address.port(), cipher, password, + shadow_tls: None, + udp_over_tcp: false, }, UpstreamPath::direct( ResolvedEndpoint { diff --git a/tests/feature_foundations.rs b/tests/feature_foundations.rs index 98f2a53..be83f0b 100644 --- a/tests/feature_foundations.rs +++ b/tests/feature_foundations.rs @@ -11,8 +11,8 @@ fn feature_skeletons_do_not_open_unimplemented_yaml_or_measurement_protocols() { let yaml = "proxies:\n - name: node\n type: wireguard\n server: example.com\n port: 443\nrules:\n - MATCH,node\n"; assert!(Config::parse_yaml(yaml.as_bytes()).is_err()); assert_eq!(vcore::INVOKE_API_VERSION, 5); - assert_eq!(vcore::CONFIG_VERSION, 27); - assert!(vcore::BUILD_IDENTITY.ends_with("invokeApiVersion=5;configVersion=27")); + assert_eq!(vcore::CONFIG_VERSION, 31); + assert!(vcore::BUILD_IDENTITY.ends_with("invokeApiVersion=5;configVersion=31")); } #[test] diff --git a/tests/httpupgrade_config.rs b/tests/httpupgrade_config.rs new file mode 100644 index 0000000..43faa80 --- /dev/null +++ b/tests/httpupgrade_config.rs @@ -0,0 +1,149 @@ +#![cfg(any(feature = "outbound-vmess", feature = "outbound-trojan"))] + +use serde_json::{Value, json}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use vcore::{ + config::{Config, ProxyProtocol}, + transport::{WebSocketOptions, connect_websocket}, +}; + +const PROTOCOLS: &[&str] = &[ + #[cfg(feature = "outbound-vmess")] + "vmess", + #[cfg(feature = "outbound-trojan")] + "trojan", +]; + +fn document(protocol: &str, options: Value) -> Vec { + let mut node = json!({"name":"edge","type":protocol,"server":"example.com","port":443,"network":"ws","ws-opts":options}); + if protocol == "trojan" { + node["password"] = json!("synthetic-upgrade"); + } else { + node["uuid"] = json!("07070707-0707-0707-0707-070707070707"); + } + serde_json::to_vec(&json!({"socks-port":1080,"proxies":[node],"rules":["MATCH,edge"]})).unwrap() +} + +fn options(protocol: &str, value: Value) -> WebSocketOptions { + let config = Config::parse_yaml(&document(protocol, value)).unwrap(); + match &config.proxies[0].protocol { + ProxyProtocol::Trojan(node) => node.transport.websocket_options().unwrap().unwrap(), + ProxyProtocol::Vmess(node) => node.transport.websocket_options().unwrap().unwrap(), + _ => unreachable!(), + } +} + +#[test] +fn httpupgrade_rejects_ambiguous_modes_and_early_data_before_io() { + #[cfg(feature = "interop-test")] + let _case = vcore::resources::case_events::Case::new("HTTPUPGRADE-UNIT", "config_bounds"); + for &protocol in PROTOCOLS { + for fast in [false, true] { + for early in [0, 1, 2048] { + let opts = json!({"v2ray-http-upgrade":true,"v2ray-http-upgrade-fast-open":fast,"max-early-data":early}); + assert!(Config::parse_yaml(&document(protocol, opts.clone())).is_ok()); + if early > 0 { + let mut explicit = opts; + explicit["early-data-header-name"] = json!("sEc-WeBsOcKeT-pRoToCoL"); + assert!(Config::parse_yaml(&document(protocol, explicit)).is_ok()); + } + } + } + for extra in [ + json!({"v2ray-http-upgrade":false,"v2ray-http-upgrade-fast-open":true}), + json!({"v2ray-http-upgrade":null}), + json!({"v2ray-http-upgrade":"true"}), + json!({"v2ray-http-upgrade-fast-open":null}), + json!({"v2ray-http-upgrade-fast-open":1}), + json!({"max-early-data":2049}), + json!({"max-early-data":-1}), + json!({"max-early-data":null}), + json!({"max-early-data":1,"early-data-header-name":""}), + json!({"max-early-data":1,"early-data-header-name":"X-ED"}), + json!({"max-early-data":0,"early-data-header-name":"Sec-WebSocket-Protocol"}), + json!({"max-early-data":1,"early-data-header-name":null}), + json!({"headers":{"Sec-WebSocket-Protocol":"override"}}), + json!({"headers":{"Upgrade":"override"}}), + json!({"headers":{"Host":"one.invalid","host":"two.invalid"}}), + json!({"path":"/bad#fragment"}), + json!({"unexpected":true}), + ] { + let mut opts = json!({"v2ray-http-upgrade":true}); + opts.as_object_mut() + .unwrap() + .extend(extra.as_object().unwrap().clone()); + assert!( + Config::parse_yaml(&document(protocol, opts.clone())).is_err(), + "accepted {protocol} {opts}" + ); + } + let mut config: Value = + serde_json::from_slice(&document(protocol, json!({"v2ray-http-upgrade":true}))) + .unwrap(); + for network in ["tcp", "grpc", "httpupgrade"] { + config["proxies"][0]["network"] = json!(network); + assert!(Config::parse_yaml(config.to_string().as_bytes()).is_err()); + } + } +} + +#[tokio::test] +async fn httpupgrade_configuration_selects_raw_upgrade_and_commits_prefix_once() { + #[cfg(feature = "interop-test")] + let _case = vcore::resources::case_events::Case::new("HTTPUPGRADE-UNIT", "config_dispatch"); + for &protocol in PROTOCOLS { + for fast in [false, true] { + let options = options( + protocol, + json!({ + "path":"/upgrade?q=1","headers":{"Host":"cover.invalid:443"}, + "v2ray-http-upgrade":true,"v2ray-http-upgrade-fast-open":fast + }), + ); + let (io, mut peer) = tokio::io::duplex(4096); + let remote = tokio::spawn(async move { + let mut head = Vec::new(); + while !head.ends_with(b"\r\n\r\n") { + head.push(peer.read_u8().await.unwrap()); + } + let text = String::from_utf8(head).unwrap().to_ascii_lowercase(); + assert!(text.starts_with("get /upgrade?q=1 http/1.1\r\n")); + assert!(text.contains("host: cover.invalid:443\r\n")); + assert!(!text.contains("sec-websocket-key")); + let mut prefix = [0; 14]; + if fast { + peer.read_exact(&mut prefix).await.unwrap(); + } else { + assert!( + tokio::time::timeout(std::time::Duration::from_millis(10), peer.read_u8()) + .await + .is_err() + ); + } + peer.write_all(b"HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\nserver-first").await.unwrap(); + if !fast { + peer.read_exact(&mut prefix).await.unwrap(); + } + assert_eq!(&prefix, b"protocol-first"); + let mut business = [0; 11]; + peer.read_exact(&mut business).await.unwrap(); + assert_eq!(&business, b"application"); + assert_eq!(peer.read(&mut [0; 1]).await.unwrap(), 0); + }); + let mut stream = connect_websocket( + Box::new(io), + &options, + b"protocol-first", + tokio::time::Instant::now() + std::time::Duration::from_secs(2), + ) + .await + .unwrap(); + let mut first = [0; 12]; + stream.read_exact(&mut first).await.unwrap(); + assert_eq!(&first, b"server-first"); + stream.write_all(b"application").await.unwrap(); + stream.shutdown().await.unwrap(); + remote.await.unwrap(); + } + } +} diff --git a/tests/httpupgrade_memory.rs b/tests/httpupgrade_memory.rs new file mode 100644 index 0000000..436d0d5 --- /dev/null +++ b/tests/httpupgrade_memory.rs @@ -0,0 +1,311 @@ +#![cfg(feature = "stream-transport")] + +use std::{io, time::Duration}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + time::Instant, +}; +use vcore::transport::{WebSocketEarlyData, WebSocketOptions, connect_websocket}; + +fn options(fast: bool) -> WebSocketOptions { + WebSocketOptions::new("ws://cover.invalid/upgrade?q=1", Default::default(), None) + .unwrap() + .with_http_upgrade(fast) + .unwrap() +} + +async fn head(peer: &mut tokio::io::DuplexStream) -> Vec { + let mut head = Vec::new(); + while !head.ends_with(b"\r\n\r\n") { + head.push(peer.read_u8().await.unwrap()); + assert!(head.len() <= 16384); + } + head +} + +#[tokio::test] +async fn httpupgrade_early_data_partial_writes_and_response_tail_keep_byte_order() { + #[cfg(feature = "interop-test")] + let _case = vcore::resources::case_events::Case::new("HTTPUPGRADE-UNIT", "early_data"); + use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; + tokio::time::timeout(Duration::from_secs(5), async { + for fast in [false, true] { + for early in [0, 1, 2048] { + let options = WebSocketOptions::new("ws://cover.invalid/edge?q=1", Default::default(), (early > 0).then(|| WebSocketEarlyData::Header {name:"Sec-WebSocket-Protocol".parse().unwrap(),max_bytes:early})).unwrap().with_http_upgrade(fast).unwrap(); + let prefix: Vec = (0..4096).map(|i| (i % 251) as u8).collect(); + let expected = prefix.clone(); + let (io, mut peer) = tokio::io::duplex(17); + let remote = tokio::spawn(async move { + let request = String::from_utf8(head(&mut peer).await).unwrap(); + let ed = request.lines().find_map(|l| l.strip_prefix("sec-websocket-protocol: ")); + let mut received = ed.map(|s| URL_SAFE_NO_PAD.decode(s).unwrap()).unwrap_or_default(); + assert_eq!(received.len(), early); + assert_eq!(&received, &expected[..early]); + let mut remainder = vec![0; expected.len() - early]; + if fast { peer.read_exact(&mut remainder).await.unwrap(); } + peer.write_all(b"HTTP/1.1 101 Switching Protocols\r\nConnection: keep-alive, Upgrade\r\nUpgrade: WebSocket\r\n\r\ntail").await.unwrap(); + if !fast { peer.read_exact(&mut remainder).await.unwrap(); } + received.extend(remainder); + assert_eq!(received, expected); + let mut business = Vec::new(); + peer.read_to_end(&mut business).await.unwrap(); + assert_eq!(business, b"business"); + }); + let mut io = connect_websocket(Box::new(io), &options, &prefix, Instant::now()+Duration::from_secs(2)).await.unwrap(); + let mut tail = [0;4]; + io.read_exact(&mut tail).await.unwrap(); + assert_eq!(&tail,b"tail"); + io.write_all(b"business").await.unwrap(); + io.shutdown().await.unwrap(); + remote.await.unwrap(); + } + } + }).await.unwrap(); + for early in [ + WebSocketEarlyData::Path { max_bytes: 1 }, + WebSocketEarlyData::Header { + name: "x-ed".parse().unwrap(), + max_bytes: 1, + }, + ] { + assert!( + WebSocketOptions::new("ws://cover.invalid/", Default::default(), Some(early)) + .unwrap() + .with_http_upgrade(false) + .is_err() + ); + } +} + +#[tokio::test] +async fn httpupgrade_rejects_invalid_oversized_and_truncated_responses_without_replay() { + #[cfg(feature = "interop-test")] + let _case = vcore::resources::case_events::Case::new("HTTPUPGRADE-UNIT", "invalid_response"); + let responses = [ + "HTTP/1.1 200 OK\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n".to_owned(), + "HTTP/1.0 101 OK\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n".to_owned(), + "HTTP/1.1 101 OK\r\nConnection: Upgrade\r\nUpgrade: other\r\n\r\n".to_owned(), + "HTTP/1.1 101 OK\r\nConnection: close\r\nUpgrade: websocket\r\n\r\n".to_owned(), + "HTTP/1.1 101 OK\r\nConnection: Upgrade\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n".to_owned(), + "HTTP/1.1 101 OK\r\nConnection: Upgrade\r\nUpgrade: websocket\r\nUpgrade: websocket\r\n\r\n".to_owned(), + "HTTP/1.1 101 OK\r\nConnection: Upgrade\r\nUpgrade: websocket\r\nContent-Length: 0\r\n\r\n".to_owned(), + "HTTP/1.1 101 OK\r\nConnection: Upgrade\r\nUpgrade: websocket\r\nTransfer-Encoding: chunked\r\n\r\n".to_owned(), + "HTTP/1.1 101 OK\r\n".to_owned()+&"X-A: a\r\n".repeat(65)+"\r\n", + "HTTP/1.1 101 OK\r\nX-A: ".to_owned()+&"a".repeat(16384)+"\r\n\r\n", + "HTTP/1.1 101 Switching Protocols\r\nConnection: Upgr".to_owned(), + ]; + for fast in [false, true] { + for response in &responses { + let response = response.clone(); + let (io, mut peer) = tokio::io::duplex(65536); + let remote = tokio::spawn(async move { + head(&mut peer).await; + if fast { + let mut prefix = [0; 6]; + peer.read_exact(&mut prefix).await.unwrap(); + assert_eq!(&prefix, b"prefix"); + } + let _ = peer.write_all(response.as_bytes()).await; + let _ = peer.shutdown().await; + let mut rest = Vec::new(); + peer.read_to_end(&mut rest).await.unwrap(); + assert!( + rest.is_empty(), + "prefix was duplicated or sent after invalid response" + ); + }); + let result = connect_websocket( + Box::new(io), + &options(fast), + b"prefix", + Instant::now() + Duration::from_secs(1), + ) + .await; + assert!( + matches!(result, Err(e) if matches!(e.kind(),io::ErrorKind::InvalidData|io::ErrorKind::UnexpectedEof)), + "invalid response accepted or timed out" + ); + remote.await.unwrap(); + } + } +} + +#[tokio::test(start_paused = true)] +async fn httpupgrade_waits_for_101_under_the_original_deadline_and_drops_cancelled_io() { + #[cfg(feature = "interop-test")] + let _case = vcore::resources::case_events::Case::new("HTTPUPGRADE-UNIT", "deadline_cancel"); + for fast in [false, true] { + let start = Instant::now(); + let deadline = start + Duration::from_millis(100); + tokio::time::advance(Duration::from_millis(60)).await; + let (io, mut peer) = tokio::io::duplex(4096); + let result = connect_websocket(Box::new(io), &options(fast), b"prefix", deadline).await; + assert!(matches!(result, Err(e) if e.kind()==io::ErrorKind::TimedOut)); + assert_eq!(Instant::now(), deadline); + let mut received = Vec::new(); + peer.read_to_end(&mut received).await.unwrap(); + assert!(received.ends_with(if fast { b"prefix" } else { b"\r\n\r\n" })); + let (io, mut peer) = tokio::io::duplex(4096); + let task = tokio::spawn(async move { + connect_websocket( + Box::new(io), + &options(fast), + b"prefix", + Instant::now() + Duration::from_secs(10), + ) + .await + }); + head(&mut peer).await; + task.abort(); + assert!(task.await.is_err_and(|e| e.is_cancelled())); + let mut rest = Vec::new(); + peer.read_to_end(&mut rest).await.unwrap(); + assert_eq!(rest, if fast { b"prefix".to_vec() } else { vec![] }); + } +} + +#[tokio::test] +async fn expired_httpupgrade_deadline_writes_no_prefix_or_head() { + #[cfg(feature = "interop-test")] + let _case = vcore::resources::case_events::Case::new("HTTPUPGRADE-UNIT", "expired_deadline"); + for fast in [false, true] { + let (io, mut peer) = tokio::io::duplex(4096); + let result = connect_websocket( + Box::new(io), + &options(fast), + b"prefix", + Instant::now() - Duration::from_secs(1), + ) + .await; + assert!(matches!(result, Err(e) if e.kind() == io::ErrorKind::TimedOut)); + let mut received = Vec::new(); + peer.read_to_end(&mut received).await.unwrap(); + assert!(received.is_empty(), "expired setup transmitted a prefix"); + } +} + +#[tokio::test(start_paused = true)] +async fn httpupgrade_rejects_ready_101_after_waiting_past_setup_deadline() { + #[cfg(feature = "interop-test")] + let _case = vcore::resources::case_events::Case::new("HTTPUPGRADE-UNIT", "late_response"); + for fast in [false, true] { + let options = options(fast); + let (io, mut peer) = tokio::io::duplex(4096); + let deadline = Instant::now() + Duration::from_millis(100); + let mut handshake = Box::pin(connect_websocket( + Box::new(io), + &options, + b"prefix", + deadline, + )); + assert!(futures_util::poll!(handshake.as_mut()).is_pending()); + head(&mut peer).await; + if fast { + let mut prefix = [0; 6]; + peer.read_exact(&mut prefix).await.unwrap(); + assert_eq!(&prefix, b"prefix"); + } + + // Resume only after both the timeout and the response are ready. + tokio::time::advance(Duration::from_millis(101)).await; + peer.write_all(b"HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n") + .await + .unwrap(); + let result = handshake.await; + assert!(matches!(result, Err(error) if error.kind() == io::ErrorKind::TimedOut)); + let mut late_bytes = Vec::new(); + peer.read_to_end(&mut late_bytes).await.unwrap(); + assert!(late_bytes.is_empty(), "expired setup transmitted a prefix"); + } +} + +#[tokio::test(start_paused = true)] +async fn httpupgrade_does_not_resume_a_blocked_prefix_after_setup_deadline() { + #[cfg(feature = "interop-test")] + let _case = vcore::resources::case_events::Case::new("HTTPUPGRADE-UNIT", "late_write"); + const RESPONSE: &[u8] = + b"HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n"; + tokio::time::timeout(Duration::from_secs(5), async { + for fast in [false, true] { + let options = options(fast); + let (io, mut peer) = tokio::io::duplex(1); + let deadline = Instant::now() + Duration::from_millis(100); + let mut handshake = Box::pin(connect_websocket( + Box::new(io), + &options, + b"prefix", + deadline, + )); + let mut request = Vec::new(); + while !request.ends_with(b"\r\n\r\n") { + // Each manual handshake poll needs a fresh cooperative IO budget. + tokio::task::yield_now().await; + assert!(futures_util::poll!(handshake.as_mut()).is_pending()); + request.push(peer.read_u8().await.unwrap()); + } + if !fast { + for byte in RESPONSE { + tokio::task::yield_now().await; + peer.write_all(&[*byte]).await.unwrap(); + assert!(futures_util::poll!(handshake.as_mut()).is_pending()); + } + } else { + assert!(futures_util::poll!(handshake.as_mut()).is_pending()); + } + // The prefix has only partially reached the supplied IO. Make the + // writer ready again, but do not poll setup until its deadline expires. + assert_eq!(peer.read_u8().await.unwrap(), b'p'); + tokio::time::advance(Duration::from_millis(100)).await; + let result = handshake.await; + assert!(matches!(result, Err(error) if error.kind() == io::ErrorKind::TimedOut)); + let mut late_bytes = Vec::new(); + peer.read_to_end(&mut late_bytes).await.unwrap(); + assert!( + late_bytes.is_empty(), + "expired setup resumed a partial write" + ); + } + }) + .await + .unwrap(); +} + +#[tokio::test(start_paused = true)] +async fn established_httpupgrade_io_outlives_its_setup_deadline() { + #[cfg(feature = "interop-test")] + let _case = vcore::resources::case_events::Case::new("HTTPUPGRADE-UNIT", "established_io"); + for fast in [false, true] { + let (io, mut peer) = tokio::io::duplex(4096); + peer.write_all(b"HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\ntail") + .await + .unwrap(); + let mut stream = connect_websocket( + Box::new(io), + &options(fast), + b"prefix", + Instant::now() + Duration::from_millis(100), + ) + .await + .unwrap(); + head(&mut peer).await; + let mut prefix = [0; 6]; + peer.read_exact(&mut prefix).await.unwrap(); + assert_eq!(&prefix, b"prefix"); + + tokio::time::advance(Duration::from_secs(1)).await; + let mut tail = [0; 4]; + stream.read_exact(&mut tail).await.unwrap(); + assert_eq!(&tail, b"tail"); + stream.write_all(b"upload").await.unwrap(); + stream.flush().await.unwrap(); + stream.shutdown().await.unwrap(); + let mut uploaded = Vec::new(); + peer.read_to_end(&mut uploaded).await.unwrap(); + assert_eq!(uploaded, b"upload"); + peer.write_all(b"download").await.unwrap(); + peer.shutdown().await.unwrap(); + let mut downloaded = Vec::new(); + stream.read_to_end(&mut downloaded).await.unwrap(); + assert_eq!(downloaded, b"download"); + } +} diff --git a/tests/limit_foundations.rs b/tests/limit_foundations.rs index 33ce104..f50cdc1 100644 --- a/tests/limit_foundations.rs +++ b/tests/limit_foundations.rs @@ -17,6 +17,22 @@ fn registry_matches_live_production_constants_and_has_owned_boundary_cases() { use vcore::{ResourceLimits, dispatch, transport}; let defaults = ResourceLimits::default(); let expected = BTreeMap::from([ + ("tuic-quic-payload", vcore::limits::TUIC_QUIC_PAYLOAD), + ("tuic-uni-streams", vcore::limits::TUIC_UNI_STREAMS), + ("tuic-stream-window", vcore::limits::TUIC_STREAM_WINDOW), + ( + "tuic-connection-window", + vcore::limits::TUIC_CONNECTION_WINDOW, + ), + ("tuic-datagram-buffer", vcore::limits::TUIC_DATAGRAM_BUFFER), + ("tuic-udp-queue", vcore::limits::TUIC_UDP_QUEUE), + ("tuic-pending-packets", vcore::limits::TUIC_PENDING_PACKETS), + ("tuic-pending-bytes", vcore::limits::TUIC_PENDING_BYTES), + ("tuic-fin-grace", vcore::limits::TUIC_FIN_GRACE_SECONDS), + ( + "tuic-fragment-ttl", + vcore::limits::TUIC_FRAGMENT_TTL_SECONDS, + ), ( "shadowsocks-write-chunk", vcore::limits::SHADOWSOCKS_WRITE_CHUNK, diff --git a/tests/protocols/limits.json b/tests/protocols/limits.json index ce61d9d..8941dc3 100644 --- a/tests/protocols/limits.json +++ b/tests/protocols/limits.json @@ -3,6 +3,114 @@ "kind": "runtime-limit-registry", "scope": "FOUNDATIONS shared foundations through INTEGRATION integration; per-object bounds, not global admission caps", "limits": [ + { + "id": "tuic-fin-grace", + "value": 5, + "unit": "seconds", + "owner": "limits::TUIC_FIN_GRACE_SECONDS", + "saturation": "retain TCP send ownership until FIN acknowledgement or bounded grace before retiring the physical connection", + "cancellation": "node Stop cancels and joins the owned FIN waiter without waiting out the grace", + "boundary_cases": ["TUIC-MEMORY"] + }, + { + "id": "tuic-quic-payload", + "value": 1400, + "unit": "bytes", + "owner": "limits::TUIC_QUIC_PAYLOAD", + "saturation": "cap endpoint payload at path budget; reject either direction below 1200", + "cancellation": "node Stop cancels and joins all owned QUIC, parser, heartbeat and upstream tasks", + "boundary_cases": [ + "TUIC-MEMORY" + ] + }, + { + "id": "tuic-uni-streams", + "value": 32, + "unit": "streams", + "owner": "limits::TUIC_UNI_STREAMS", + "saturation": "withhold incoming credit and expire partial parsers after five seconds", + "cancellation": "node Stop cancels and joins all owned QUIC, parser, heartbeat and upstream tasks", + "boundary_cases": [ + "TUIC-MEMORY" + ] + }, + { + "id": "tuic-stream-window", + "value": 262144, + "unit": "bytes", + "owner": "limits::TUIC_STREAM_WINDOW", + "saturation": "QUIC receive flow control applies backpressure to unread logical streams", + "cancellation": "node Stop cancels and joins all owned QUIC, parser, heartbeat and upstream tasks", + "boundary_cases": [ + "TUIC-MEMORY" + ] + }, + { + "id": "tuic-connection-window", + "value": 1048576, + "unit": "bytes-per-direction", + "owner": "limits::TUIC_CONNECTION_WINDOW", + "saturation": "bound QUIC receive credit and unacknowledged send buffering per connection", + "cancellation": "node Stop cancels and joins all owned QUIC, parser, heartbeat and upstream tasks", + "boundary_cases": [ + "TUIC-MEMORY" + ] + }, + { + "id": "tuic-datagram-buffer", + "value": 262144, + "unit": "bytes-per-direction", + "owner": "limits::TUIC_DATAGRAM_BUFFER", + "saturation": "bounded Quinn DATAGRAM receive queue; send_datagram_wait applies backpressure", + "cancellation": "node Stop cancels and joins all owned QUIC, parser, heartbeat and upstream tasks", + "boundary_cases": [ + "TUIC-MEMORY" + ] + }, + { + "id": "tuic-udp-queue", + "value": 32, + "unit": "packets", + "owner": "limits::TUIC_UDP_QUEUE", + "saturation": "drop complete overflow packets without blocking sibling traffic", + "cancellation": "node Stop cancels and joins all owned QUIC, parser, heartbeat and upstream tasks", + "boundary_cases": [ + "TUIC-MEMORY" + ] + }, + { + "id": "tuic-pending-packets", + "value": 64, + "unit": "packets-per-association", + "owner": "limits::TUIC_PENDING_PACKETS", + "saturation": "drop new partial packets when all pending slots are occupied", + "cancellation": "node Stop cancels and joins all owned QUIC, parser, heartbeat and upstream tasks", + "boundary_cases": [ + "TUIC-MEMORY" + ] + }, + { + "id": "tuic-pending-bytes", + "value": 262144, + "unit": "payload-bytes-per-association", + "owner": "limits::TUIC_PENDING_BYTES", + "saturation": "drop partial packet whose fragments exceed owner or caller budget", + "cancellation": "node Stop cancels and joins all owned QUIC, parser, heartbeat and upstream tasks", + "boundary_cases": [ + "TUIC-MEMORY" + ] + }, + { + "id": "tuic-fragment-ttl", + "value": 5, + "unit": "seconds", + "owner": "limits::TUIC_FRAGMENT_TTL_SECONDS", + "saturation": "discard expired incomplete packets without retaining completed packet IDs", + "cancellation": "node Stop cancels and joins all owned QUIC, parser, heartbeat and upstream tasks", + "boundary_cases": [ + "TUIC-MEMORY" + ] + }, { "id": "shadowsocks-write-chunk", "value": 16384, diff --git a/tests/shadowsocks_backpressure.rs b/tests/shadowsocks_backpressure.rs index 476074a..1cdb500 100644 --- a/tests/shadowsocks_backpressure.rs +++ b/tests/shadowsocks_backpressure.rs @@ -69,6 +69,8 @@ async fn growing_caller_buffer_after_backpressure_never_loses_plaintext() { port: 443, cipher, password: STANDARD.encode(&key), + shadow_tls: None, + udp_over_tcp: false, }; let (client, peer) = tokio::io::duplex(4096); let outbound = ShadowsocksOutbound::new_with_path( @@ -153,6 +155,8 @@ async fn read_first_flushes_the_official_header_over_a_buffered_upstream() { port: 443, cipher, password: STANDARD.encode(&key), + shadow_tls: None, + udp_over_tcp: false, }; let (client, peer) = tokio::io::duplex(4096); // Buffered carriers may acknowledge the complete SS header before diff --git a/tests/shadowsocks_uot.rs b/tests/shadowsocks_uot.rs new file mode 100644 index 0000000..2588a75 --- /dev/null +++ b/tests/shadowsocks_uot.rs @@ -0,0 +1,505 @@ +#![cfg(feature = "outbound-shadowsocks")] +//! Public connector behavior over bounded memory IO; no host protocol server. +use std::{ + sync::{Arc, Mutex}, + time::Duration, +}; + +use async_trait::async_trait; +use base64::{Engine as _, engine::general_purpose::STANDARD}; +use bytes::Bytes; +use shadowsocks::{ + config::ServerType, context::Context, relay::tcprelay::proxy_stream::ProxyServerStream, +}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use vcore::{ + config::{Config, ProxyProtocol}, + dispatch::{BoxStream, DatagramBudget, DatagramTransport, DispatchError}, + outbound::{ + ConnectedStream, DatagramRequest, EstablishContext, OutboundConnector, ShadowsocksOutbound, + UpstreamPath, + }, + session::{Datagram, DatagramSession, Destination, InboundKind, StreamSession}, +}; + +struct MemoryUpstream(Mutex>); +#[async_trait] +impl OutboundConnector for MemoryUpstream { + async fn connect_stream( + &self, + session: StreamSession, + _: &EstablishContext, + ) -> Result { + Ok(ConnectedStream { + io: self.0.lock().unwrap().take().unwrap(), + effective_peer: session.destination, + }) + } + async fn open_datagram( + &self, + _: DatagramRequest, + _: &EstablishContext, + ) -> Result, DispatchError> { + panic!("UoT must not request native UDP from its upstream") + } +} + +fn request() -> DatagramRequest { + DatagramRequest::new(DatagramSession::new( + InboundKind::Socks5, + "127.0.0.1:1234".parse().unwrap(), + )) +} + +fn packet(size: usize) -> Datagram { + Datagram { + remote: Destination::Ip("127.0.0.1:53".parse().unwrap()), + payload: Bytes::from(vec![7; size]), + sniffed_domain: None, + } +} + +fn fixture(cipher: &str, capacity: usize) -> (ShadowsocksOutbound, tokio::io::DuplexStream) { + let key = vec![7; if cipher.contains("aes-128") { 16 } else { 32 }]; + let yaml = serde_json::json!({ + "port":1080,"proxies":[{"name":"ss","type":"ss","server":"fixture.invalid", + "port":443,"cipher":cipher,"password":STANDARD.encode(key),"udp":true, + "udp-over-tcp":true,"udp-over-tcp-version":2}],"rules":["MATCH,ss"] + }); + let config = Config::parse_yaml(&serde_json::to_vec(&yaml).unwrap()).unwrap(); + let ProxyProtocol::Shadowsocks(config) = &config.proxies[0].protocol else { + unreachable!() + }; + let (raw, peer) = tokio::io::duplex(capacity); + let outbound = ShadowsocksOutbound::new_with_path( + config, + UpstreamPath::proxy(Arc::new(MemoryUpstream(Mutex::new(Some(Box::new(raw)))))), + ) + .unwrap(); + (outbound, peer) +} + +fn decoder( + peer: tokio::io::DuplexStream, + cipher: &str, +) -> ProxyServerStream { + ProxyServerStream::from_stream( + Context::new_shared(ServerType::Server), + peer, + cipher.parse().unwrap(), + &vec![7; if cipher.contains("aes-128") { 16 } else { 32 }], + ) +} + +const CIPHERS: [&str; 3] = [ + "2022-blake3-aes-128-gcm", + "2022-blake3-aes-256-gcm", + "2022-blake3-chacha20-poly1305", +]; + +#[tokio::test] +async fn never_sent_close_drop_and_stop_release_io_without_an_empty_ss_write() { + #[cfg(feature = "interop-test")] + let _case = vcore::resources::case_events::Case::new("UOT-SS", "never_sent"); + for cipher in CIPHERS { + for ending in ["close", "drop", "stop"] { + let (outbound, mut peer) = fixture(cipher, 64); + let mut association = Some( + outbound + .open_datagram(request(), &EstablishContext::default()) + .await + .unwrap(), + ); + match ending { + "close" => association.as_mut().unwrap().close().await.unwrap(), + "drop" => drop(association.take()), + _ => outbound.shutdown().await, + } + let mut wire = Vec::new(); + tokio::time::timeout(Duration::from_secs(1), peer.read_to_end(&mut wire)) + .await + .unwrap() + .unwrap(); + assert!( + wire.is_empty(), + "{cipher} {ending} emitted SS initialization" + ); + outbound.shutdown().await; + assert!( + outbound + .open_datagram(request(), &EstablishContext::default()) + .await + .is_err() + ); + } + } +} + +#[tokio::test(start_paused = true)] +async fn late_first_packet_uses_original_deadline_but_established_io_does_not() { + #[cfg(feature = "interop-test")] + let _case = vcore::resources::case_events::Case::new("UOT-SS", "deadline"); + let (outbound, mut peer) = fixture(CIPHERS[0], 4096); + let context = EstablishContext::with_timeout(Duration::from_secs(2)); + let mut association = outbound.open_datagram(request(), &context).await.unwrap(); + tokio::time::advance(Duration::from_secs(3)).await; + assert!(association.send(packet(0)).await.is_err()); + outbound.shutdown().await; + assert_eq!(peer.read(&mut [0; 1]).await.unwrap(), 0); + + let (outbound, peer) = fixture(CIPHERS[0], 4096); + let mut association = outbound + .open_datagram( + request(), + &EstablishContext::with_timeout(Duration::from_secs(2)), + ) + .await + .unwrap(); + association.send(packet(0)).await.unwrap(); + let mut decoded = decoder(peer, CIPHERS[0]); + assert_eq!( + decoded.handshake().await.unwrap(), + ("sp.v2.udp-over-tcp.arpa".to_owned(), 0).into() + ); + let mut first = [0; 17]; + decoded.read_exact(&mut first).await.unwrap(); + tokio::time::advance(Duration::from_secs(3)).await; + association.send(packet(0)).await.unwrap(); + let mut next = [0; 9]; + decoded.read_exact(&mut next).await.unwrap(); + assert_eq!(&first[8..], &next); + outbound.shutdown().await; + assert_eq!(decoded.read(&mut [0; 1]).await.unwrap(), 0); +} + +#[tokio::test] +async fn cancelled_partial_send_poisoning_and_stop_release_a_blocked_writer() { + #[cfg(feature = "interop-test")] + let _case = vcore::resources::case_events::Case::new("UOT-SS", "cancel_write"); + for stop in [false, true] { + let (outbound, mut peer) = fixture(CIPHERS[0], 64); + let mut association = outbound + .open_datagram(request(), &EstablishContext::default()) + .await + .unwrap(); + if stop { + let (sent, ()) = tokio::join!(association.send(packet(65_535)), async { + tokio::task::yield_now().await; + outbound.shutdown().await; + }); + assert!(sent.is_err()); + } else { + assert!( + tokio::time::timeout(Duration::from_millis(10), association.send(packet(65_535))) + .await + .is_err() + ); + assert!(association.send(packet(0)).await.is_err()); + outbound.shutdown().await; + } + let mut bytes = Vec::new(); + tokio::time::timeout(Duration::from_secs(1), peer.read_to_end(&mut bytes)) + .await + .unwrap() + .unwrap(); + assert!(bytes.len() <= 64); + } +} + +#[tokio::test] +async fn all_ciphers_preserve_budget_edges_and_fragmented_receive_cancellation() { + #[cfg(feature = "interop-test")] + let _case = vcore::resources::case_events::Case::new("UOT-SS", "budget_read_cancel"); + for cipher in CIPHERS { + let (outbound, peer) = fixture(cipher, 4096); + let mut association = outbound + .open_datagram( + request().with_budget(DatagramBudget::new(65_535, 8)), + &EstablishContext::default(), + ) + .await + .unwrap(); + assert!(association.send(packet(65_536)).await.is_err()); + let (ready, arrived) = tokio::sync::oneshot::channel(); + let (resume, proceed) = tokio::sync::oneshot::channel(); + let decoding = tokio::spawn(async move { + let mut decoded = decoder(peer, cipher); + assert_eq!( + decoded.handshake().await.unwrap(), + ("sp.v2.udp-over-tcp.arpa".to_owned(), 0).into() + ); + let mut request = [0; 17]; + for byte in &mut request { + *byte = decoded.read_u8().await.unwrap(); + } + assert_eq!( + request, + [0, 1, 127, 0, 0, 1, 0, 53, 0, 127, 0, 0, 1, 0, 53, 255, 255] + ); + let mut payload = vec![0; 65_535]; + decoded.read_exact(&mut payload).await.unwrap(); + assert!(payload.iter().all(|b| *b == 7)); + // Coalesced oversize response then a partial valid response. The + // caller's cancelled receive must not lose either parser position. + decoded + .write_all(b"\x00\x7f\x00\x00\x01\x00\x35\x00\x09oversized\x00\x7f") + .await + .unwrap(); + decoded.flush().await.unwrap(); + ready.send(()).unwrap(); + proceed.await.unwrap(); + for b in b"\x00\x00\x02\x00\x36\x00\x02ok" { + decoded.write_all(&[*b]).await.unwrap(); + decoded.flush().await.unwrap(); + } + assert_eq!(decoded.read(&mut [0; 1]).await.unwrap(), 0); + }); + tokio::time::timeout(Duration::from_secs(2), async { + association.send(packet(65_535)).await.unwrap(); + arrived.await.unwrap(); + assert!( + tokio::time::timeout(Duration::from_millis(10), association.receive()) + .await + .is_err() + ); + resume.send(()).unwrap(); + let response = association.receive().await.unwrap(); + assert_eq!( + response.remote, + Destination::Ip("127.0.0.2:54".parse().unwrap()) + ); + assert_eq!(response.payload.as_ref(), b"ok"); + outbound.shutdown().await; + decoding.await.unwrap(); + }) + .await + .unwrap(); + } +} + +struct ControlledResolver { + calls: std::sync::atomic::AtomicUsize, + pending: bool, +} + +#[async_trait] +impl vcore::dialer::Resolver for ControlledResolver { + async fn resolve( + &self, + host: &str, + port: u16, + ) -> std::io::Result { + assert_eq!(host, "dns.test", "only the business name may be resolved"); + assert_eq!(port, 53); + self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + if self.pending { + std::future::pending::<()>().await; + } + Ok(vcore::dialer::ResolvedEndpoint { + logical_host: host.into(), + port, + addresses: vec!["127.0.0.1:53".parse().unwrap()], + }) + } +} + +#[tokio::test] +async fn domains_use_only_the_supplied_resolver_and_stop_cancels_pending_dns() { + #[cfg(feature = "interop-test")] + let _case = vcore::resources::case_events::Case::new("UOT-SS", "dns"); + use std::sync::atomic::{AtomicUsize, Ordering}; + use vcore::dns::resolution::ResolutionContext; + let mut datagram = packet(0); + datagram.remote = Destination::domain("dns.test", 53).unwrap(); + let (outbound, mut peer) = fixture(CIPHERS[0], 4096); + let mut association = outbound + .open_datagram(request(), &EstablishContext::default()) + .await + .unwrap(); + assert!(association.send(datagram.clone()).await.is_err()); + assert!( + tokio::time::timeout(Duration::from_millis(10), peer.read_u8()) + .await + .is_err() + ); + outbound.shutdown().await; + for pending in [false, true] { + let resolver = Arc::new(ControlledResolver { + calls: AtomicUsize::new(0), + pending, + }); + let context = EstablishContext::with_resolution( + Duration::from_secs(2), + ResolutionContext::measurement(resolver.clone(), true), + ); + let (outbound, peer) = fixture(CIPHERS[0], 4096); + let mut association = outbound.open_datagram(request(), &context).await.unwrap(); + assert_eq!(resolver.calls.load(Ordering::SeqCst), 0); + if pending { + let (sent, ()) = tokio::join!(association.send(datagram.clone()), async { + while resolver.calls.load(Ordering::SeqCst) == 0 { + tokio::task::yield_now().await; + } + outbound.shutdown().await; + }); + assert!(sent.is_err()); + } else { + association.send(datagram.clone()).await.unwrap(); + let mut decoded = decoder(peer, CIPHERS[0]); + assert_eq!( + decoded.handshake().await.unwrap(), + ("sp.v2.udp-over-tcp.arpa".to_owned(), 0).into() + ); + let mut wire = [0; 17]; + decoded.read_exact(&mut wire).await.unwrap(); + assert_eq!( + wire, + [0, 1, 127, 0, 0, 1, 0, 53, 0, 127, 0, 0, 1, 0, 53, 0, 0] + ); + outbound.shutdown().await; + } + assert_eq!(resolver.calls.load(Ordering::SeqCst), 1); + } +} + +#[cfg(feature = "interop-test")] +#[tokio::test] +async fn stop_joins_a_full_receiver_and_releases_io_with_the_association_retained() { + let _case = vcore::resources::case_events::Case::new("UOT-SS", "stop_full_queue"); + let probe = vcore::resources::observation::ResourceProbe::default(); + let (outbound, peer) = fixture(CIPHERS[0], 4096); + let mut association = probe + .scope(outbound.open_datagram(request(), &EstablishContext::default())) + .await + .unwrap(); + let (ready, arrived) = tokio::sync::oneshot::channel(); + let producer = tokio::spawn(async move { + let mut decoded = decoder(peer, CIPHERS[0]); + decoded.handshake().await.unwrap(); + let mut first = [0; 17]; + decoded.read_exact(&mut first).await.unwrap(); + let frame = [ + b"\x00\x7f\x00\x00\x01\x00\x35\x01\x00".as_slice(), + &[7; 256], + ] + .concat(); + for _ in 0..4 { + decoded.write_all(&frame).await.unwrap(); + decoded.flush().await.unwrap(); + } + ready.send(()).unwrap(); + for _ in 0..64 { + if decoded.write_all(&frame).await.is_err() || decoded.flush().await.is_err() { + return; + } + } + panic!("unconsumed replies exceeded the bounded reader and memory IO"); + }); + tokio::time::timeout(Duration::from_secs(2), async { + association.send(packet(0)).await.unwrap(); + arrived.await.unwrap(); + for _ in 0..4 { + tokio::task::yield_now().await; + } + assert!(!probe.snapshot().is_idle()); + outbound.shutdown().await; + // This caller intentionally retains the closed logical handle. Its + // object guard is not a live read task or an owned physical stream. + use vcore::resources::observation::ResourceKind; + assert_eq!(probe.snapshot().current(ResourceKind::Task), 0); + assert_eq!(probe.snapshot().current(ResourceKind::Association), 1); + assert!(association.receive().await.is_err()); + assert!(association.send(packet(0)).await.is_err()); + producer.await.unwrap(); + drop(association); + assert!(probe.snapshot().is_idle(), "{:?}", probe.snapshot()); + }) + .await + .unwrap(); +} + +#[tokio::test] +async fn zero_length_first_datagram_initializes_ss_once_without_an_empty_write() { + #[cfg(feature = "interop-test")] + let _case = vcore::resources::case_events::Case::new("UOT-SS", "first_packet"); + let config = Config::parse_yaml(br#" +port: 1080 +proxies: + - {name: ss, type: ss, server: fixture.invalid, port: 443, cipher: 2022-blake3-aes-128-gcm, password: BwcHBwcHBwcHBwcHBwcHBw==, udp: true, udp-over-tcp: true} +rules: ['MATCH,ss'] +"#).expect("SS UoT v2 configuration"); + let ProxyProtocol::Shadowsocks(config) = &config.proxies[0].protocol else { + panic!("wrong protocol") + }; + let (raw, mut peer) = tokio::io::duplex(4096); + let outbound = ShadowsocksOutbound::new_with_path( + config, + UpstreamPath::proxy(Arc::new(MemoryUpstream(Mutex::new(Some(Box::new(raw)))))), + ) + .unwrap(); + let mut association = outbound + .open_datagram( + DatagramRequest::new(DatagramSession::new( + InboundKind::Socks5, + "127.0.0.1:1234".parse().unwrap(), + )), + &EstablishContext::default(), + ) + .await + .unwrap(); + assert!( + tokio::time::timeout(Duration::from_millis(10), association.receive()) + .await + .is_err() + ); + assert!( + tokio::time::timeout(Duration::from_millis(10), peer.read_u8()) + .await + .is_err(), + "background reading emitted an empty SS handshake" + ); + let decoder = tokio::spawn(async move { + let mut decoded = ProxyServerStream::from_stream( + Context::new_shared(ServerType::Server), + peer, + "2022-blake3-aes-128-gcm".parse().unwrap(), + &[7; 16], + ); + let target = decoded.handshake().await.unwrap(); + assert_eq!(target, ("sp.v2.udp-over-tcp.arpa".to_owned(), 0).into()); + let mut first = [0; 17]; + decoded.read_exact(&mut first).await.unwrap(); + // Request uses SOCKS ATYP=1; datagram uses UoT ATYP=0. Empty UDP is + // still a nonempty encrypted first write accepted by the strict codec. + assert_eq!( + first, + [0, 1, 127, 0, 0, 1, 0, 53, 0, 127, 0, 0, 1, 0, 53, 0, 0] + ); + decoded.write_all(&first[8..]).await.unwrap(); + decoded.flush().await.unwrap(); + let mut next = [0; 13]; + decoded.read_exact(&mut next).await.unwrap(); + assert_eq!(&next, b"\x00\x7f\x00\x00\x01\x00\x35\x00\x04next"); + decoded.write_all(&next).await.unwrap(); + decoded.flush().await.unwrap(); + assert_eq!(decoded.read(&mut [0; 1]).await.unwrap(), 0); + }); + tokio::time::timeout(Duration::from_secs(2), async { + for payload in [b"".as_slice(), b"next"] { + let datagram = Datagram { + remote: Destination::Ip("127.0.0.1:53".parse().unwrap()), + payload: Bytes::copy_from_slice(payload), + sniffed_domain: None, + }; + association.send(datagram.clone()).await.unwrap(); + let response = association.receive().await.unwrap(); + assert_eq!(response.remote, datagram.remote); + assert_eq!(response.payload, datagram.payload); + } + association.close().await.unwrap(); + outbound.shutdown().await; + decoder.await.unwrap(); + }) + .await + .unwrap(); +} diff --git a/tests/shadowtls_config.rs b/tests/shadowtls_config.rs new file mode 100644 index 0000000..de63295 --- /dev/null +++ b/tests/shadowtls_config.rs @@ -0,0 +1,227 @@ +//! Public YAML admission for the SS2022 ShadowTLS v3 wrapper; no network IO. +use vcore::config::Config; +#[cfg(feature = "shadow-tls-v3")] +use { + serde_json::{Value, json}, + vcore::config::{ClientFingerprint, ProxyProtocol, ShadowTlsConfig}, +}; + +fn yaml(extra: &str) -> String { + format!( + "port: 1080\nproxies:\n - name: ss\n type: ss\n server: fixture.invalid\n port: 443\n cipher: 2022-blake3-aes-128-gcm\n password: BwcHBwcHBwcHBwcHBwcHBw==\n udp: true\n{extra}\nrules: ['MATCH,ss']\n" + ) +} + +#[cfg(feature = "shadow-tls-v3")] +fn node() -> Value { + json!({"name":"ss", "type":"ss", "server":"fixture.invalid", "port":443, + "cipher":"2022-blake3-aes-128-gcm", "password":"BwcHBwcHBwcHBwcHBwcHBw==", + "udp":true, "plugin":"shadow-tls", "plugin-opts":{ + "version":3, "host":"cover.invalid", "password":" synthetic-private-marker "}}) +} + +#[cfg(feature = "shadow-tls-v3")] +fn parse(node: Value) -> vcore::Result { + Config::parse_yaml( + &serde_json::to_vec(&json!({"socks-port":1080, + "proxies":[node], "rules":["MATCH,ss"]})) + .unwrap(), + ) +} + +#[cfg(feature = "shadow-tls-v3")] +fn policy(node: Value) -> ShadowTlsConfig { + let config = parse(node).unwrap(); + let ProxyProtocol::Shadowsocks(ss) = &config.proxies[0].protocol else { + panic!() + }; + ss.shadow_tls.clone().unwrap() +} + +#[cfg(feature = "shadow-tls-v3")] +#[test] +fn shadowtls_preserves_policy_values_and_shared_profile_aliases() { + #[cfg(feature = "interop-test")] + let _case = vcore::resources::case_events::Case::new("SHADOWTLS-CFG", "policy"); + let config = policy(node()); + assert_eq!(config.password, " synthetic-private-marker "); + assert_eq!(config.alpn, [b"h2".to_vec(), b"http/1.1".to_vec()]); + assert!(!config.certificate.skip_cert_verify); + assert!(config.certificate.fingerprint.is_none()); + assert!(config.certificate.verification_name.is_none()); + assert_eq!(config.client_fingerprint, None); + for (name, expected) in [ + ("", None), + ("none", None), + ("chrome", Some(ClientFingerprint::Chrome133)), + ("chrome120", Some(ClientFingerprint::Chrome120)), + ("firefox", Some(ClientFingerprint::Firefox120)), + ("firefox120", Some(ClientFingerprint::Firefox120)), + ("safari", Some(ClientFingerprint::Safari16)), + ("safari16", Some(ClientFingerprint::Safari16)), + ] { + let mut n = node(); + n["client-fingerprint"] = json!(name); + assert_eq!(policy(n).client_fingerprint, expected); + } + for alpn in [ + vec![], + vec!["custom".to_owned(), "h2".to_owned()], + vec!["x".repeat(255)], + ] { + let mut n = node(); + n["plugin-opts"]["alpn"] = json!(alpn); + assert_eq!( + policy(n).alpn, + alpn.into_iter().map(String::into_bytes).collect::>() + ); + } + for host in ["cover.invalid", "192.0.2.7", "2001:db8::7"] { + let mut n = node(); + let o = &mut n["plugin-opts"]; + o["host"] = json!(host); + o["skip-cert-verify"] = json!(true); + o["fingerprint"] = json!((0..32).map(|_| "ab").collect::>().join(":")); + o["name-cert-verify"] = json!("verified.invalid"); + let policy = policy(n); + assert_eq!(policy.server_name, host); + assert!(policy.certificate.skip_cert_verify); + assert_eq!(policy.certificate.fingerprint, Some([0xab; 32])); + assert_eq!( + policy.certificate.verification_name.as_deref(), + Some("verified.invalid") + ); + let debug = format!("{policy:?}"); + for secret in ["synthetic-private-marker", "verified.invalid", host] { + assert!(!debug.contains(secret)); + } + } + let mut maximum = node(); + maximum["plugin-opts"]["password"] = json!("x".repeat(65_535)); + assert_eq!(policy(maximum).password.len(), 65_535); +} + +#[cfg(feature = "shadow-tls-v3")] +#[test] +fn shadowtls_rejects_invalid_types_bounds_unknown_fields_and_nulls_without_secrets() { + #[cfg(feature = "interop-test")] + let _case = vcore::resources::case_events::Case::new("SHADOWTLS-CFG", "reject"); + let assert_rejected = |n| { + let error = parse(n).expect_err("must reject before IO").to_string(); + assert!(!error.contains("synthetic-private-marker"), "{error}"); + }; + for key in ["plugin", "plugin-opts", "client-fingerprint"] { + let mut n = node(); + n[key] = Value::Null; + assert_rejected(n); + } + for key in [ + "version", + "host", + "password", + "alpn", + "skip-cert-verify", + "fingerprint", + "name-cert-verify", + ] { + let mut n = node(); + n["plugin-opts"][key] = Value::Null; + assert_rejected(n); + } + for (key, values) in [ + ( + "version", + vec![ + json!(1), + json!(2), + json!(4), + json!(3.0), + json!("3"), + json!(true), + ], + ), + ( + "host", + vec![ + json!(""), + json!("bad name"), + json!("cover.invalid:443"), + json!(7), + ], + ), + ( + "password", + vec![json!(""), json!("x".repeat(65_536)), json!(true), json!(7)], + ), + ( + "alpn", + vec![ + json!("h2"), + json!([""]), + json!(["x".repeat(256)]), + json!([7]), + json!(vec!["x".repeat(255); 256]), + ], + ), + ("skip-cert-verify", vec![json!(1), json!("true")]), + ( + "fingerprint", + vec![json!(""), json!("ff"), json!("z".repeat(64)), json!(true)], + ), + ( + "name-cert-verify", + vec![json!(""), json!("bad name"), json!(false)], + ), + ("strict-mode", vec![json!(true), json!(false)]), + ("unknown", vec![json!("synthetic-private-marker")]), + ] { + for value in values { + let mut n = node(); + n["plugin-opts"][key] = value; + assert_rejected(n); + } + } + for value in [json!("chrome133"), json!("random"), json!(true), json!([])] { + let mut n = node(); + n["client-fingerprint"] = value; + assert_rejected(n); + } + for key in ["plugin", "plugin-opts"] { + let mut n = node(); + n.as_object_mut().unwrap().remove(key); + assert_rejected(n); + } +} + +#[test] +fn shadowtls_requires_explicit_v3_and_a_complete_plugin_policy() { + #[cfg(feature = "interop-test")] + let _case = vcore::resources::case_events::Case::new("SHADOWTLS-CFG", "feature"); + let fields = " plugin: shadow-tls\n plugin-opts: {version: 3, host: cover.invalid, password: ' secret '}"; + let result = Config::parse_yaml(yaml(fields).as_bytes()); + // This protocol is independently removable even when boring is present. + if !cfg!(feature = "shadow-tls-v3") { + assert!(result.is_err()); + return; + } + assert!(result.is_ok(), "{result:?}"); + for fields in [ + " plugin: shadow-tls", + " plugin-opts: {version: 3, host: cover.invalid, password: secret}", + " plugin: obfs\n plugin-opts: {version: 3, host: cover.invalid, password: secret}", + " client-fingerprint: none", + ] { + assert!(Config::parse_yaml(yaml(fields).as_bytes()).is_err()); + } + for replacement in [ + "version: 1", + "version: 2", + "version: 4", + "version: null", + "version: '3'", + "unused: 3", + ] { + let invalid = fields.replace("version: 3", replacement); + assert!(Config::parse_yaml(yaml(&invalid).as_bytes()).is_err()); + } +} diff --git a/tests/shadowtls_stream.rs b/tests/shadowtls_stream.rs new file mode 100644 index 0000000..e94d87b --- /dev/null +++ b/tests/shadowtls_stream.rs @@ -0,0 +1,103 @@ +//! Public ShadowTLS stream and cancellation behavior over bounded memory IO. +//! These are local fault/IO checks, not replacements for official container peers. +#![cfg(feature = "shadow-tls-v3")] + +use std::{collections::HashSet, time::Duration}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use vcore::{ + config::{ClientFingerprint, ShadowTlsConfig}, + security::{SecurityContext, ShadowTlsClient}, +}; + +const PASSWORD: &str = " synthetic-memory-shadow-password "; + +fn options(profile: Option) -> ShadowTlsConfig { + ShadowTlsConfig { + server_name: "cover.invalid".into(), + password: PASSWORD.into(), + alpn: vec![b"h2".to_vec(), b"http/1.1".to_vec()], + certificate: Default::default(), + client_fingerprint: profile, + } +} + +#[tokio::test] +async fn cancelled_shadowtls_handshakes_release_io_and_never_reuse_authenticated_hellos() { + #[cfg(feature = "interop-test")] + let _case = vcore::resources::case_events::Case::new("SHADOWTLS-STREAM", "cancelled_hello"); + use ClientFingerprint::*; + tokio::time::timeout(Duration::from_secs(10), async { + let mut seen = HashSet::new(); + for profile in [ + None, + Some(Chrome120), + Some(Chrome133), + Some(Firefox120), + Some(Safari16), + ] { + let client = ShadowTlsClient::new(&SecurityContext::new(), &options(profile)).unwrap(); + for _ in 0..4 { + let (io, mut peer) = tokio::io::duplex(73); + let client = client.clone(); + let task = tokio::spawn(async move { client.connect(Box::new(io)).await }); + let mut header = [0; 5]; + peer.read_exact(&mut header).await.unwrap(); + assert_eq!(header[0], 22); + let size = usize::from(u16::from_be_bytes([header[3], header[4]])); + assert!(size <= 16_384); + let mut hello = vec![0; size]; + peer.read_exact(&mut hello).await.unwrap(); + assert_eq!(hello[0], 1); + assert_eq!(hello[38], 32); + let session_id: [u8; 32] = hello[39..71].try_into().unwrap(); + hello[67..71].fill(0); + assert_eq!( + &session_id[28..], + &boring::hash::hmac_sha1(PASSWORD.as_bytes(), &hello).unwrap()[..4] + ); + assert!(seen.insert(session_id)); + task.abort(); + assert!(task.await.is_err_and(|error| error.is_cancelled())); + assert_eq!(peer.read(&mut header).await.unwrap(), 0); + } + } + }) + .await + .unwrap(); +} + +#[tokio::test] +async fn truncated_or_oversized_shadowtls_handshake_records_never_create_a_business_stream() { + #[cfg(feature = "interop-test")] + let _case = vcore::resources::case_events::Case::new("SHADOWTLS-STREAM", "invalid_record"); + tokio::time::timeout(Duration::from_secs(10), async { + for record in [ + vec![], + vec![22], + vec![22, 3, 3, 0], + vec![22, 3, 3, 0, 7, 2, 0], + vec![22, 3, 3, 0, 0], + vec![22, 3, 3, 0xff, 0xff], + vec![22, 2, 0, 0, 1, 0], + vec![23, 3, 3, 0, 4, 0, 0, 0, 0], + ] { + let client = ShadowTlsClient::new(&SecurityContext::new(), &options(None)).unwrap(); + let (io, mut peer) = tokio::io::duplex(65_536); + let task = tokio::spawn(async move { client.connect(Box::new(io)).await }); + let mut header = [0; 5]; + peer.read_exact(&mut header).await.unwrap(); + let mut hello = vec![0; usize::from(u16::from_be_bytes([header[3], header[4]]))]; + peer.read_exact(&mut hello).await.unwrap(); + for byte in record { + if peer.write_all(&[byte]).await.is_err() { + break; + } + tokio::task::yield_now().await; + } + let _ = peer.shutdown().await; + assert!(task.await.unwrap().is_err()); + } + }) + .await + .unwrap(); +} diff --git a/tests/trojan_config.rs b/tests/trojan_config.rs index 8620b57..1f36dcd 100644 --- a/tests/trojan_config.rs +++ b/tests/trojan_config.rs @@ -217,7 +217,7 @@ fn trojan_transport_boundaries_fail_before_runtime_io() { json!({"max-early-data":1,"early-data-header-name":null}), json!({"max-early-data":1,"early-data-header-name":"x-ed","headers":{"X-ED":"duplicate"}}), json!({"max-early-data":1,"early-data-header-name":"","path":"/edge?q=1"}), - json!({"v2ray-http-upgrade":true}), + json!({"v2ray-http-upgrade":null}), ] { assert!( Config::parse_yaml(&document(json!({"network":"ws","ws-opts":opts.clone()}))).is_err(), diff --git a/tests/tuic_config.rs b/tests/tuic_config.rs new file mode 100644 index 0000000..6e676e1 --- /dev/null +++ b/tests/tuic_config.rs @@ -0,0 +1,168 @@ +use serde_json::{Value, json}; +use vcore::config::Config; + +fn node() -> Value { + json!({"name":"tuic","type":"tuic","server":"peer.invalid","port":443, + "uuid":"01234567-89ab-cdef-0123-456789abcdef","password":""}) +} + +fn parse(node: Value) -> vcore::Result { + Config::parse_yaml( + json!({"port":1080,"proxies":[node],"rules":["MATCH,tuic"]}) + .to_string() + .as_bytes(), + ) +} + +#[test] +fn explicit_v5_identity_accepts_empty_password_without_enabling_business_udp() { + #[cfg(feature = "interop-test")] + let _case = vcore::resources::case_events::Case::new("TUIC-CFG", "identity"); + if !cfg!(feature = "outbound-tuic") { + assert!(parse(node()).is_err()); + return; + } + let c = parse(node()).unwrap(); + assert!(!c.proxies[0].udp); + assert_eq!(c.proxies[0].address(), "peer.invalid"); + for field in ["uuid", "password"] { + let mut n = node(); + n.as_object_mut().unwrap().remove(field); + assert!(parse(n).is_err()); + } +} + +#[test] +fn malformed_tuic_values_do_not_leak_input_in_errors() { + #[cfg(feature = "interop-test")] + let _case = vcore::resources::case_events::Case::new("TUIC-CFG", "redaction"); + for field in ["uuid", "port", "alpn", "congestion-controller"] { + let mut n = node(); + n[field] = json!("synthetic-private-marker"); + let error = parse(n).unwrap_err().to_string(); + assert!(!error.contains("synthetic-private-marker"), "{error}"); + } +} + +#[cfg(feature = "outbound-tuic")] +#[test] +fn v5_business_udp_accepts_exactly_native_or_quic() { + #[cfg(feature = "interop-test")] + let _case = vcore::resources::case_events::Case::new("TUIC-CFG", "udp"); + let mut n = node(); + n["udp"] = json!(true); + assert!(parse(n.clone()).is_ok()); + for mode in ["native", "quic"] { + n["udp-relay-mode"] = json!(mode); + assert!(parse(n.clone()).is_ok()); + } + for bad in [ + Value::Null, + json!("tcp"), + json!("uot"), + json!(1), + json!(true), + json!(""), + ] { + n["udp-relay-mode"] = bad; + assert!(parse(n.clone()).is_err()); + } +} + +#[cfg(feature = "outbound-tuic")] +#[test] +fn strict_v5_tls_and_identity_bounds_preserve_values() { + use vcore::config::{ProxyProtocol, TuicCongestion}; + #[cfg(feature = "interop-test")] + let _case = vcore::resources::case_events::Case::new("TUIC-CFG", "bounds"); + let extract = |n| { + let c = parse(n).unwrap(); + let ProxyProtocol::Tuic(t) = c.proxies.into_iter().next().unwrap().protocol else { + panic!("protocol"); + }; + t + }; + let t = extract(node()); + assert_eq!(t.tls.server_name, "peer.invalid"); + assert_eq!(t.tls.alpn, [b"h3".to_vec()]); + assert!(t.tls.tls13_only); + assert_eq!(t.congestion, TuicCongestion::Cubic); + for password in [String::new(), " 原样\t\0 ".to_string(), "x".repeat(65535)] { + let mut n = node(); + n["password"] = json!(password); + assert_eq!(extract(n).password, password); + } + for (value, expected) in [ + ("new_reno", TuicCongestion::NewReno), + ("bbr", TuicCongestion::Bbr), + ("cubic", TuicCongestion::Cubic), + ] { + let mut n = node(); + n["congestion-controller"] = json!(value); + assert_eq!(extract(n).congestion, expected); + } + let mut n = node(); + n["sni"] = json!("sni.invalid"); + n["name-cert-verify"] = json!("verified.invalid"); + n["alpn"] = json!(["custom", "h3"]); + n["skip-cert-verify"] = json!(true); + n["fingerprint"] = json!("12".repeat(32)); + let t = extract(n); + assert_eq!(t.tls.alpn, [b"custom".to_vec(), b"h3".to_vec()]); + assert_eq!(t.tls.certificate.fingerprint, Some([0x12; 32])); + assert_eq!( + t.tls.certificate.verification_name.as_deref(), + Some("verified.invalid") + ); + assert!(t.tls.certificate.skip_cert_verify); + for value in [ + "peer.invalid", + "sni.invalid", + "verified.invalid", + "01234567-89ab-cdef-0123-456789abcdef", + ] { + assert!(!format!("{t:?}").contains(value)); + } + for (field, bad) in [ + ("password", json!("x".repeat(65536))), + ("uuid", json!("0123456789abcdef0123456789abcdef")), + ("port", json!(0)), + ("port", json!(65536)), + ("server", json!("")), + ("sni", json!("")), + ("name-cert-verify", json!("bad\nname")), + ("alpn", json!([])), + ("alpn", json!([""])), + ("alpn", json!(["x".repeat(256)])), + ("alpn", json!(vec!["x".repeat(255); 256])), + ("congestion-controller", json!("reno")), + ("fingerprint", json!("bad-pin")), + ("client-fingerprint", json!("none")), + ("reduce-rtt", json!(true)), + ("version", json!(4)), + ("certificate", json!("unsupported")), + ("private-key", json!("unsupported")), + ] { + let mut n = node(); + n[field] = bad; + assert!(parse(n).is_err(), "{field}"); + } + for field in [ + "server", + "port", + "uuid", + "password", + "sni", + "alpn", + "skip-cert-verify", + "fingerprint", + "name-cert-verify", + "congestion-controller", + "dialer-proxy", + "udp", + ] { + let mut n = node(); + n[field] = Value::Null; + assert!(parse(n).is_err(), "{field}"); + } +} diff --git a/tests/tuic_memory.rs b/tests/tuic_memory.rs new file mode 100644 index 0000000..b470de8 --- /dev/null +++ b/tests/tuic_memory.rs @@ -0,0 +1,1119 @@ +#![cfg(all(feature = "outbound-tuic", feature = "interop-test"))] +//! Real Quinn over bounded memory packets, never a host network server. +use std::{ + collections::VecDeque, + sync::{Arc, Mutex}, + time::Duration, +}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + sync::mpsc, +}; +use vcore::{ + config::{Config, ProxyProtocol, TuicCongestion, TuicOutboundConfig}, + dispatch::{DatagramBudget, DatagramTransport, DispatchError}, + outbound::{ + ConnectedStream, DatagramRequest, EstablishContext, OutboundConnector, UpstreamPath, + tuic::TuicOutbound, + }, + resources::{ + case_events::Case, + observation::{ResourceKind, ResourceProbe}, + }, + session::{Datagram, DatagramSession, Destination, InboundKind, StreamSession}, +}; +#[path = "support/memory_quic.rs"] +mod memory_quic; +use memory_quic::{MemoryPackets, MemoryUpstream, PeerSocket}; + +struct BudgetPackets(MemoryPackets, u16); +#[async_trait::async_trait] +impl DatagramTransport for BudgetPackets { + fn payload_budget(&self, _: &Destination) -> DatagramBudget { + DatagramBudget::new(self.1, self.1) + } + async fn send(&mut self, packet: Datagram) -> Result<(), DispatchError> { + assert!(packet.payload.len() <= self.1 as usize); + self.0.send(packet).await + } + async fn receive(&mut self) -> Result { + self.0.receive().await + } + async fn close(&mut self) -> Result<(), DispatchError> { + self.0.close().await + } +} + +fn fixture( + budget: u16, + datagrams: bool, + credit: u32, + congestion: &str, +) -> (Arc, quinn::Endpoint) { + fixture_mode(budget, datagrams, credit, congestion, "native") +} + +fn fixture_mode( + budget: u16, + datagrams: bool, + credit: u32, + congestion: &str, + mode: &str, +) -> (Arc, quinn::Endpoint) { + let (config, packets, endpoint) = fixture_parts(budget, datagrams, credit, congestion, mode); + let outbound = TuicOutbound::new_with_path( + &config, + UpstreamPath::proxy(Arc::new(MemoryUpstream(Mutex::new(Some(packets))))), + ) + .unwrap(); + (Arc::new(outbound), endpoint) +} + +fn fixture_parts( + budget: u16, + datagrams: bool, + credit: u32, + congestion: &str, + mode: &str, +) -> (TuicOutboundConfig, BudgetPackets, quinn::Endpoint) { + let server_address = "192.0.2.1:443".parse().unwrap(); + let client_address = "192.0.2.2:1234".parse().unwrap(); + let (to_server, from_client) = mpsc::channel(32); + let (to_client, from_server) = mpsc::channel(32); + let packets = BudgetPackets( + MemoryPackets { + send: to_server, + receive: from_server, + remote: server_address, + }, + budget, + ); + let socket = Arc::new(PeerSocket { + send: to_client, + receive: Mutex::new(from_client), + local: server_address, + remote: client_address, + }); + let cert = rcgen::generate_simple_self_signed(vec!["fixture.invalid".into()]).unwrap(); + let key = rustls::pki_types::PrivatePkcs8KeyDer::from(cert.signing_key.serialize_der()); + let mut tls = rustls::ServerConfig::builder_with_provider(Arc::new( + rustls::crypto::ring::default_provider(), + )) + .with_protocol_versions(&[&rustls::version::TLS13]) + .unwrap() + .with_no_client_auth() + .with_single_cert(vec![cert.cert.der().clone()], key.into()) + .unwrap(); + tls.alpn_protocols = vec![b"h3".to_vec()]; + let crypto = quinn::crypto::rustls::QuicServerConfig::try_from(tls).unwrap(); + let mut config = quinn::ServerConfig::with_crypto(Arc::new(crypto)); + Arc::get_mut(&mut config.transport) + .unwrap() + .datagram_receive_buffer_size(datagrams.then_some(256 * 1024)) + .send_window(64 * 1024) + .initial_mtu(budget.max(1200)) + .min_mtu(budget.max(1200)) + .max_concurrent_bidi_streams(credit.into()) + .max_concurrent_uni_streams(2_u32.into()) + .mtu_discovery_config(None); + let endpoint = quinn::Endpoint::new_with_abstract_socket( + quinn::EndpointConfig::default(), + Some(config), + socket, + Arc::new(quinn::TokioRuntime), + ) + .unwrap(); + let yaml = serde_json::json!({"socks-port":1080,"proxies":[{"name":"peer","type":"tuic","server":"192.0.2.1","port":443,"uuid":"07070707-0707-0707-0707-070707070707","password":" raw\u{0000}context ","sni":"fixture.invalid","skip-cert-verify":true,"congestion-controller":congestion,"udp":true,"udp-relay-mode":mode}],"rules":["MATCH,peer"]}); + let parsed = Config::parse_yaml(yaml.to_string().as_bytes()).unwrap(); + let ProxyProtocol::Tuic(config) = &parsed.proxies[0].protocol else { + panic!("TUIC"); + }; + (config.clone(), packets, endpoint) +} + +fn request() -> StreamSession { + StreamSession { + inbound: InboundKind::Socks5, + source: "127.0.0.1:1".parse().unwrap(), + destination: Destination::domain("x", 80).unwrap(), + sniffed_domain: None, + } +} + +async fn authenticated(endpoint: &quinn::Endpoint) -> quinn::Connection { + let connection = endpoint.accept().await.unwrap().await.unwrap(); + let auth = connection + .accept_uni() + .await + .unwrap() + .read_to_end(50) + .await + .unwrap(); + assert_eq!(auth.len(), 50); + assert_eq!( + &auth[..18], + &[5, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7] + ); + let mut expected = [0; 32]; + connection + .export_keying_material(&mut expected, &[7; 16], b" raw\0context ") + .unwrap(); + assert_eq!(&auth[18..], &expected); + connection +} + +async fn finish(endpoint: quinn::Endpoint, peer: tokio::task::JoinHandle<()>) { + endpoint.close(0_u8.into(), b""); + tokio::time::timeout(Duration::from_secs(2), peer) + .await + .unwrap() + .unwrap(); + tokio::time::timeout(Duration::from_secs(2), endpoint.wait_idle()) + .await + .unwrap(); +} + +#[tokio::test] +async fn authenticates_current_session_without_ack_and_preserves_stream_isolation() { + let _case = Case::new("TUIC-UNIT", "tcp_owner"); + for (algorithm, expected) in [ + ("cubic", TuicCongestion::Cubic), + ("new_reno", TuicCongestion::NewReno), + ("bbr", TuicCongestion::Bbr), + ] { + let probe = ResourceProbe::default(); + let (outbound, endpoint) = fixture(1200, true, 8, algorithm); + let ep = endpoint.clone(); + let peer = tokio::spawn(async move { + let connection = authenticated(&ep).await; + let mut streams = Vec::new(); + for _ in 0..2 { + let (mut send, mut recv) = connection.accept_bi().await.unwrap(); + let mut connect = [0; 7]; + recv.read_exact(&mut connect).await.unwrap(); + assert_eq!(&connect, b"\x05\x01\x00\x01x\x00\x50"); + send.write_all(b"hello").await.unwrap(); + streams.push((send, recv)); + } + let (mut send, mut recv) = streams.pop().unwrap(); + let mut payload = [0; 7]; + recv.read_exact(&mut payload).await.unwrap(); + assert_eq!(&payload, b"sibling"); + send.write_all(&payload).await.unwrap(); + connection.closed().await; + }); + probe + .scope(async { + let mut a = outbound + .connect_stream(request(), &EstablishContext::default()) + .await + .unwrap() + .io; + let mut b = outbound + .connect_stream(request(), &EstablishContext::default()) + .await + .unwrap() + .io; + assert_eq!(outbound.congestion_observation().await, Some(expected)); + for stream in [&mut a, &mut b] { + let mut hello = [0; 5]; + stream.read_exact(&mut hello).await.unwrap(); + assert_eq!(&hello, b"hello"); + } + a.shutdown().await.unwrap(); + drop(a); + b.write_all(b"sibling").await.unwrap(); + let mut response = [0; 7]; + b.read_exact(&mut response).await.unwrap(); + assert_eq!(&response, b"sibling"); + let now = tokio::time::Instant::now(); + outbound.shutdown().await; + assert!(now.elapsed() < Duration::from_secs(3)); + assert!(b.read_u8().await.is_err()); + drop(b); + assert!( + outbound + .connect_stream(request(), &EstablishContext::default()) + .await + .is_err() + ); + }) + .await; + assert!(probe.snapshot().is_idle(), "{:?}", probe.snapshot()); + finish(endpoint, peer).await; + } +} + +#[tokio::test] +async fn stream_credit_wait_keeps_original_deadline_and_leaves_sibling_alive() { + let _case = Case::new("TUIC-UNIT", "credit_deadline"); + let (outbound, endpoint) = fixture(1400, true, 1, "cubic"); + let ep = endpoint.clone(); + let peer = tokio::spawn(async move { + let connection = authenticated(&ep).await; + let (mut send, mut recv) = connection.accept_bi().await.unwrap(); + let mut header = [0; 7]; + recv.read_exact(&mut header).await.unwrap(); + let mut payload = [0; 1]; + recv.read_exact(&mut payload).await.unwrap(); + send.write_all(&payload).await.unwrap(); + connection.closed().await; + }); + let mut first = outbound + .connect_stream(request(), &EstablishContext::default()) + .await + .unwrap() + .io; + let context = EstablishContext::with_timeout(Duration::from_millis(60)); + tokio::time::sleep(Duration::from_millis(40)).await; + let before = tokio::time::Instant::now(); + assert!(matches!( + outbound.connect_stream(request(), &context).await, + Err(DispatchError::TimedOut) + )); + assert!(before.elapsed() < Duration::from_millis(55)); + first.write_all(b"a").await.unwrap(); + assert_eq!(first.read_u8().await.unwrap(), b'a'); + drop(first); + outbound.shutdown().await; + finish(endpoint, peer).await; +} + +#[tokio::test] +async fn insufficient_path_budget_and_missing_datagrams_never_fall_back() { + let _case = Case::new("TUIC-UNIT", "path_requirements"); + for (budget, datagrams) in [(1199, true), (1400, false)] { + let (outbound, endpoint) = fixture(budget, datagrams, 8, "cubic"); + let ep = endpoint.clone(); + let peer = tokio::spawn(async move { + if let Some(incoming) = ep.accept().await + && let Ok(connection) = incoming.await + { + connection.closed().await; + } + }); + let probe = ResourceProbe::default(); + probe + .scope(async { + assert!( + outbound + .connect_stream( + request(), + &EstablishContext::with_timeout(Duration::from_secs(1)) + ) + .await + .is_err() + ); + outbound.shutdown().await; + }) + .await; + assert!(probe.snapshot().is_idle(), "{:?}", probe.snapshot()); + finish(endpoint, peer).await; + } +} + +#[tokio::test] +async fn stalled_quic_handshake_obeys_setup_deadline_and_stop_barrier() { + let _case = Case::new("TUIC-UNIT", "handshake_stop"); + for stop in [false, true] { + // Do not accept the QUIC handshake. It can never reach TUIC auth. + let (outbound, endpoint) = fixture(1400, true, 8, "cubic"); + let probe = ResourceProbe::default(); + probe.scope(async { + let context = EstablishContext::with_timeout(Duration::from_millis(if stop {1000} else {40})); + let connect = outbound.connect_stream(request(), &context); + tokio::pin!(connect); + if stop { + tokio::select! { _ = &mut connect => panic!("unexpected handshake"), _ = tokio::time::sleep(Duration::from_millis(20)) => {} } + outbound.begin_shutdown(); + } + let result = connect.await; + assert!(matches!(result,Err(DispatchError::NotAllowed | DispatchError::TimedOut))); + outbound.shutdown().await; + }).await; + assert!(probe.snapshot().is_idle(), "{:?}", probe.snapshot()); + endpoint.close(0_u8.into(), b""); + tokio::time::timeout(Duration::from_secs(2), endpoint.wait_idle()) + .await + .unwrap(); + } +} + +#[tokio::test] +async fn both_udp_modes_preserve_empty_and_u16_packets_and_dissociate() { + let _case = Case::new("TUIC-UNIT", "udp_wire"); + const SIZES: &[usize] = &[0, 1, 1400, 4096, 65535]; + for mode in ["native", "quic"] { + let (outbound, endpoint) = fixture_mode(1400, true, 8, "cubic", mode); + let ep = endpoint.clone(); + let peer = tokio::spawn(async move { + let connection = authenticated(&ep).await; + for (packet, size) in SIZES.iter().copied().enumerate() { + let mut received = Vec::new(); + let mut payload = Vec::new(); + loop { + let raw = if mode == "native" { + connection.read_datagram().await.unwrap() + } else { + connection + .accept_uni() + .await + .unwrap() + .read_to_end(66000) + .await + .unwrap() + .into() + }; + assert_eq!(&raw[..4], &[5, 2, 0, 0]); + assert_eq!(u16::from_be_bytes([raw[4], raw[5]]), packet as u16); + let start = if raw[7] == 0 { + assert_eq!(&raw[10..14], b"\0\x01x\0"); + assert_eq!(raw[14], 80); + 15 + } else { + assert_eq!(raw[10], 255); + 11 + }; + assert_eq!( + u16::from_be_bytes([raw[8], raw[9]]) as usize, + raw.len() - start + ); + payload.extend_from_slice(&raw[start..]); + let total = raw[6]; + received.push(raw); + if received.len() == total as usize { + break; + } + } + assert_eq!(payload, vec![packet as u8; size]); + // Unknown local association must never allocate delivery/reassembly state. + let mut unknown = received[0].to_vec(); + unknown[2..4].copy_from_slice(&65535_u16.to_be_bytes()); + if mode == "native" { + connection.send_datagram_wait(unknown.into()).await.unwrap(); + } + for raw in received.iter().rev() { + if mode == "native" { + connection.send_datagram_wait(raw.clone()).await.unwrap(); + if raw[7] == 1 { + connection.send_datagram_wait(raw.clone()).await.unwrap(); + } + } else { + let mut send = connection.open_uni().await.unwrap(); + send.write_all(raw).await.unwrap(); + send.finish().unwrap(); + } + } + } + let dissociate = connection + .accept_uni() + .await + .unwrap() + .read_to_end(4) + .await + .unwrap(); + assert_eq!(&dissociate, &[5, 3, 0, 0]); + connection.closed().await; + }); + let probe = ResourceProbe::default(); + let outcome = probe + .scope(async { + let mut udp = outbound + .open_datagram( + vcore::outbound::DatagramRequest::new(DatagramSession::new( + InboundKind::Socks5, + "127.0.0.1:1".parse().unwrap(), + )) + .with_budget(DatagramBudget::new(u16::MAX, u16::MAX)), + &EstablishContext::default(), + ) + .await?; + assert!( + udp.send(Datagram { + remote: Destination::domain("x", 80).unwrap(), + payload: vec![9; 65536].into(), + sniffed_domain: None + }) + .await + .is_err() + ); + assert!( + tokio::time::timeout(Duration::from_millis(1), udp.receive()) + .await + .is_err() + ); + let result = tokio::time::timeout(Duration::from_secs(5), async { + for (packet, size) in SIZES.iter().copied().enumerate() { + let request = Datagram { + remote: Destination::domain("x", 80).unwrap(), + payload: vec![packet as u8; size].into(), + sniffed_domain: None, + }; + udp.send(request.clone()).await.unwrap(); + let response = udp.receive().await.unwrap(); + assert_eq!(response.remote, request.remote); + assert_eq!(response.payload, request.payload); + } + udp.close().await.unwrap(); + }) + .await; + drop(udp); + Ok::<_, DispatchError>(result) + }) + .await; + outbound.shutdown().await; + assert!(probe.snapshot().is_idle(), "{:?}", probe.snapshot()); + assert!( + matches!(outcome, Ok(Ok(()))), + "{mode} u16 datagram outcome: {outcome:?}" + ); + finish(endpoint, peer).await; + outcome.unwrap().unwrap(); + } +} + +#[tokio::test] +async fn unused_association_close_does_not_create_peer_state_or_control_tasks() { + let _case = Case::new("TUIC-UNIT", "unused_association"); + let (outbound, endpoint) = fixture(1400, true, 8, "cubic"); + let ep = endpoint.clone(); + let peer = tokio::spawn(async move { + let connection = authenticated(&ep).await; + assert!( + tokio::time::timeout(Duration::from_millis(100), connection.accept_uni()) + .await + .is_err() + ); + connection.closed().await; + }); + let mut unused = outbound + .open_datagram( + vcore::outbound::DatagramRequest::new(DatagramSession::new( + InboundKind::Socks5, + "127.0.0.1:1".parse().unwrap(), + )), + &EstablishContext::default(), + ) + .await + .unwrap(); + unused.close().await.unwrap(); + drop(unused); + tokio::time::sleep(Duration::from_millis(120)).await; + outbound.shutdown().await; + finish(endpoint, peer).await; +} + +struct Paths(Mutex>); +#[async_trait::async_trait] +impl OutboundConnector for Paths { + async fn connect_stream( + &self, + _: StreamSession, + _: &EstablishContext, + ) -> Result { + panic!("TUIC must not fall back to TCP"); + } + async fn open_datagram( + &self, + _: DatagramRequest, + _: &EstablishContext, + ) -> Result, DispatchError> { + Ok(Box::new( + self.0 + .lock() + .unwrap() + .pop_front() + .expect("one upstream per physical session"), + )) + } +} +fn udp_request() -> DatagramRequest { + DatagramRequest::new(DatagramSession::new( + InboundKind::Socks5, + "127.0.0.1:1".parse().unwrap(), + )) +} + +#[tokio::test] +async fn association_id_exhaustion_retires_without_reuse_or_migrating_old_streams() { + let _case = Case::new("TUIC-UNIT", "session_retirement"); + let (config, first_path, first_ep) = fixture_parts(1400, true, 8, "cubic", "native"); + let (_, next_path, next_ep) = fixture_parts(1400, true, 8, "cubic", "native"); + let paths = Arc::new(Paths(Mutex::new(VecDeque::from([first_path, next_path])))); + let outbound = + TuicOutbound::new_with_path(&config, UpstreamPath::proxy(paths.clone())).unwrap(); + let ep = first_ep.clone(); + let first_peer = tokio::spawn(async move { + let connection = authenticated(&ep).await; + let (mut send, mut recv) = connection.accept_bi().await.unwrap(); + let mut header = [0; 7]; + recv.read_exact(&mut header).await.unwrap(); + assert_eq!(&header, b"\x05\x01\x00\x01x\x00\x50"); + assert_eq!(recv.read_u8().await.unwrap(), b'a'); + send.write_all(b"a").await.unwrap(); + assert_eq!(recv.read_u8().await.unwrap(), b'b'); + // Late association 0 on the retired physical session cannot enter new + // association 0 on the replacement connection. + connection + .send_datagram_wait(bytes::Bytes::from_static( + b"\x05\x02\x00\x00\x00\x00\x01\x00\x00\x05\x00\x01x\x00\x50stale", + )) + .await + .unwrap(); + send.write_all(b"b").await.unwrap(); + // Retirement must not close the physical connection before a final + // accepted upload and FIN have arrived on its last logical stream. + let trailer = recv.read_to_end(1024 * 1024).await.unwrap(); + assert_eq!(trailer, vec![23; 1024 * 1024]); + connection.closed().await; + }); + let ep = next_ep.clone(); + let next_peer = tokio::spawn(async move { + let connection = authenticated(&ep).await; + let raw = connection.read_datagram().await.unwrap(); + assert_eq!(&raw[..4], &[5, 2, 0, 0]); + assert_eq!(&raw[15..], b"fresh"); + connection.send_datagram_wait(raw).await.unwrap(); + connection.closed().await; + }); + let probe = ResourceProbe::default(); + probe + .scope(async { + let mut old = outbound + .connect_stream(request(), &EstablishContext::default()) + .await + .unwrap() + .io; + old.write_all(b"a").await.unwrap(); + assert_eq!(old.read_u8().await.unwrap(), b'a'); + for id in 0..=u16::MAX { + drop( + outbound + .open_datagram(udp_request(), &EstablishContext::default()) + .await + .unwrap(), + ); + if id % 256 == 0 { + tokio::task::yield_now().await; + } + } + let mut fresh = outbound + .open_datagram(udp_request(), &EstablishContext::default()) + .await + .unwrap(); + assert!(paths.0.lock().unwrap().is_empty()); + old.write_all(b"b").await.unwrap(); + assert_eq!(old.read_u8().await.unwrap(), b'b'); + fresh + .send(Datagram { + remote: request().destination, + payload: bytes::Bytes::from_static(b"fresh"), + sniffed_domain: None, + }) + .await + .unwrap(); + assert_eq!( + tokio::time::timeout(Duration::from_secs(1), fresh.receive()) + .await + .unwrap() + .unwrap() + .payload, + b"fresh"[..] + ); + assert_eq!(probe.snapshot().current(ResourceKind::Pool), 2); + old.write_all(&vec![23; 1024 * 1024]).await.unwrap(); + old.shutdown().await.unwrap(); + drop(old); + tokio::time::timeout(Duration::from_secs(2), async { + while probe.snapshot().current(ResourceKind::Pool) != 1 { + tokio::time::sleep(Duration::from_millis(5)).await; + } + }) + .await + .unwrap(); + outbound.shutdown().await; + assert!(fresh.receive().await.is_err()); + drop(fresh); + assert!(probe.snapshot().is_idle(), "{:?}", probe.snapshot()); + }) + .await; + finish(first_ep, first_peer).await; + finish(next_ep, next_peer).await; +} + +#[tokio::test] +async fn quic_partial_control_streams_have_a_credit_bound_and_expire_without_blocking_tcp() { + let _case = Case::new("TUIC-UNIT", "partial_control_expiry"); + let (outbound, endpoint) = fixture_mode(1400, true, 8, "cubic", "quic"); + let ep = endpoint.clone(); + let (ready, wait) = tokio::sync::oneshot::channel(); + let peer = tokio::spawn(async move { + let connection = authenticated(&ep).await; + connection + .accept_uni() + .await + .unwrap() + .read_to_end(64) + .await + .unwrap(); + let mut partial = Vec::new(); + for _ in 0..32 { + let mut stream = connection.open_uni().await.unwrap(); + stream + .write_all(&[5, 2, 0, 0, 0, 0, 1, 0, 0, 1]) + .await + .unwrap(); + partial.push(stream); + } + assert!( + tokio::time::timeout(Duration::from_millis(50), connection.open_uni()) + .await + .is_err() + ); + ready.send(()).unwrap(); + let (mut send, mut recv) = connection.accept_bi().await.unwrap(); + let mut request = [0; 8]; + recv.read_exact(&mut request).await.unwrap(); + assert_eq!(request[7], b'a'); + send.write_all(b"a").await.unwrap(); + for stream in &partial { + assert_eq!( + tokio::time::timeout(Duration::from_secs(6), stream.stopped()) + .await + .unwrap() + .unwrap(), + Some(0_u8.into()) + ); + } + // STOP_SENDING requests cancellation. Quinn correctly retains the + // receive credit until this peer supplies FIN/RESET_STREAM; respond to + // the request instead of treating local timeout as peer acknowledgement. + drop(partial); + let mut available = tokio::time::timeout(Duration::from_secs(6), connection.open_uni()) + .await + .unwrap() + .unwrap(); + available + .write_all(b"\x05\x02\x00\x00\x00\x00\x01\x00\x00\x01\x00\x01x\x00\x50z") + .await + .unwrap(); + available.finish().unwrap(); + connection.closed().await; + }); + let probe = ResourceProbe::default(); + probe + .scope(async { + let mut udp = outbound + .open_datagram(udp_request(), &EstablishContext::default()) + .await + .unwrap(); + udp.send(Datagram { + remote: request().destination, + payload: bytes::Bytes::from_static(b"start"), + sniffed_domain: None, + }) + .await + .unwrap(); + wait.await.unwrap(); + let mut tcp = outbound + .connect_stream( + request(), + &EstablishContext::with_timeout(Duration::from_secs(1)), + ) + .await + .unwrap() + .io; + tcp.write_all(b"a").await.unwrap(); + assert_eq!( + tokio::time::timeout(Duration::from_secs(1), tcp.read_u8()) + .await + .unwrap() + .unwrap(), + b'a' + ); + assert_eq!( + tokio::time::timeout(Duration::from_secs(6), udp.receive()) + .await + .unwrap() + .unwrap() + .payload, + b"z"[..] + ); + outbound.shutdown().await; + drop(udp); + drop(tcp); + assert!(probe.snapshot().is_idle(), "{:?}", probe.snapshot()); + }) + .await; + finish(endpoint, peer).await; +} + +#[tokio::test] +async fn cancelled_uni_credit_wait_does_not_replay_or_close_sibling_tcp() { + let _case = Case::new("TUIC-UNIT", "udp_credit_cancel"); + let (outbound, endpoint) = fixture_mode(1400, true, 8, "cubic", "quic"); + let ep = endpoint.clone(); + let (ready, wait) = tokio::sync::oneshot::channel(); + let peer = tokio::spawn(async move { + let connection = authenticated(&ep).await; + let mut unread = Vec::new(); + // Explicit fixture credit is two; leave both bodies unread. + for _ in 0..2 { + unread.push(connection.accept_uni().await.unwrap()); + } + ready.send(()).unwrap(); + let (mut send, mut recv) = connection.accept_bi().await.unwrap(); + let mut request = [0; 8]; + recv.read_exact(&mut request).await.unwrap(); + assert_eq!(request[7], b'a'); + send.write_all(b"a").await.unwrap(); + connection.closed().await; + drop(unread); + }); + let probe = ResourceProbe::default(); + probe + .scope(async { + let mut udp = outbound + .open_datagram(udp_request(), &EstablishContext::default()) + .await + .unwrap(); + let packet = Datagram { + remote: request().destination, + payload: bytes::Bytes::from_static(b"x"), + sniffed_domain: None, + }; + for _ in 0..2 { + tokio::time::timeout(Duration::from_secs(1), udp.send(packet.clone())) + .await + .unwrap() + .unwrap(); + } + tokio::time::timeout(Duration::from_secs(1), wait) + .await + .unwrap() + .unwrap(); + assert!( + tokio::time::timeout(Duration::from_millis(40), udp.send(packet)) + .await + .is_err() + ); + let mut tcp = outbound + .connect_stream(request(), &EstablishContext::default()) + .await + .unwrap() + .io; + tcp.write_all(b"a").await.unwrap(); + assert_eq!( + tokio::time::timeout(Duration::from_secs(1), tcp.read_u8()) + .await + .unwrap() + .unwrap(), + b'a' + ); + let before = tokio::time::Instant::now(); + outbound.shutdown().await; + assert!(before.elapsed() < Duration::from_secs(2)); + drop(tcp); + drop(udp); + assert!(probe.snapshot().is_idle(), "{:?}", probe.snapshot()); + }) + .await; + finish(endpoint, peer).await; +} + +#[cfg(unix)] +#[tokio::test] +async fn physical_protection_failure_stops_before_udp_or_tcp_fallback() { + use std::sync::atomic::{AtomicUsize, Ordering}; + use vcore::dialer::{Dialer, ResolvedEndpoint, SocketProtector}; + struct Reject(AtomicUsize); + impl SocketProtector for Reject { + fn protect(&self, _: i32) -> std::io::Result<()> { + self.0.fetch_add(1, Ordering::Relaxed); + Err(std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "denied", + )) + } + } + let _case = Case::new("TUIC-UNIT", "protect_fail_closed"); + let (config, _, endpoint) = fixture_parts(1400, true, 8, "cubic", "native"); + let reject = Arc::new(Reject(AtomicUsize::new(0))); + let path = UpstreamPath::direct( + ResolvedEndpoint { + logical_host: "192.0.2.1".into(), + port: 443, + addresses: vec!["192.0.2.1:443".parse().unwrap()], + }, + Dialer::default().with_protector(reject.clone()), + ); + let outbound = TuicOutbound::new_with_path(&config, path).unwrap(); + let probe = ResourceProbe::default(); + probe + .scope(async { + assert!( + outbound + .connect_stream(request(), &EstablishContext::default()) + .await + .is_err() + ); + assert_eq!(reject.0.load(Ordering::Relaxed), 1); + outbound.shutdown().await; + }) + .await; + assert!(probe.snapshot().is_idle(), "{:?}", probe.snapshot()); + endpoint.close(0_u8.into(), b""); + endpoint.wait_idle().await; +} + +#[tokio::test] +async fn heartbeat_and_full_delivery_queue_remain_owned_until_synchronous_stop() { + let _case = Case::new("TUIC-UNIT", "heartbeat_full_queue_stop"); + for mode in ["native", "quic"] { + let (outbound, endpoint) = fixture_mode(1400, true, 8, "cubic", mode); + let ep = endpoint.clone(); + let (ready, wait) = tokio::sync::oneshot::channel(); + let peer = tokio::spawn(async move { + let connection = authenticated(&ep).await; + let first = if mode == "native" { + connection.read_datagram().await.unwrap() + } else { + connection + .accept_uni() + .await + .unwrap() + .read_to_end(64) + .await + .unwrap() + .into() + }; + assert_eq!(&first[..4], &[5, 2, 0, 0]); + for id in 0..33_u16 { + let mut packet = + b"\x05\x02\x00\x00\x00\x00\x01\x00\x00\x01\x00\x01x\x00\x50z".to_vec(); + packet[4..6].copy_from_slice(&id.to_be_bytes()); + if mode == "native" { + connection.send_datagram_wait(packet.into()).await.unwrap(); + } else { + let mut stream = connection.open_uni().await.unwrap(); + stream.write_all(&packet).await.unwrap(); + stream.finish().unwrap(); + } + } + // TUIC heartbeat uses a DATAGRAM even in quic UDP relay mode. + let heartbeat = + tokio::time::timeout(Duration::from_secs(12), connection.read_datagram()) + .await + .unwrap() + .unwrap(); + assert_eq!(heartbeat, b"\x05\x04"[..]); + ready.send(()).unwrap(); + connection.closed().await; + }); + let probe = ResourceProbe::default(); + probe + .scope(async { + let mut udp = outbound + .open_datagram(udp_request(), &EstablishContext::default()) + .await + .unwrap(); + udp.send(Datagram { + remote: request().destination, + payload: bytes::Bytes::from_static(b"start"), + sniffed_domain: None, + }) + .await + .unwrap(); + tokio::time::timeout(Duration::from_secs(13), wait) + .await + .unwrap() + .unwrap(); + let queue = probe + .queues() + .into_iter() + .find(|q| q.kind == vcore::resources::observation::QueueKind::TuicUdp) + .unwrap(); + assert_eq!((queue.peak, queue.capacity), (32, 32)); + let before = tokio::time::Instant::now(); + outbound.shutdown().await; + assert!(before.elapsed() < Duration::from_secs(2)); + drop(udp); + assert!(probe.snapshot().is_idle(), "{:?}", probe.snapshot()); + }) + .await; + finish(endpoint, peer).await; + } +} + +#[tokio::test] +async fn receive_flow_control_bounds_unread_streams_and_connection_then_stop_releases_them() { + let _case = Case::new("TUIC-UNIT", "receive_windows"); + for streams in [1, 8] { + let (outbound, endpoint) = fixture(1400, true, 8, "cubic"); + let ep = endpoint.clone(); + let (ready, wait) = tokio::sync::oneshot::channel(); + let peer = tokio::spawn(async move { + let connection = authenticated(&ep).await; + let mut writes = tokio::task::JoinSet::new(); + for _ in 0..streams { + let (mut send, mut recv) = connection.accept_bi().await.unwrap(); + let mut header = [0; 7]; + recv.read_exact(&mut header).await.unwrap(); + writes.spawn(async move { + let mut accepted = 0; + let data = [0; 4096]; + while let Ok(n) = + tokio::time::timeout(Duration::from_millis(500), send.write(&data)).await + { + accepted += n.unwrap(); + assert!(accepted <= 2 * 1024 * 1024, "unbounded unread stream"); + } + (accepted, send, recv) + }); + } + let mut stalled = Vec::new(); + while let Some(result) = writes.join_next().await { + stalled.push(result.unwrap()); + } + let accepted: usize = stalled.iter().map(|s| s.0).sum(); + let window = if streams == 1 { + 256 * 1024 + } else { + 1024 * 1024 + }; + // Successful peer writes include its bounded 64 KiB send buffer, + // not just acknowledged bytes retained in the VCore receive window. + assert!( + accepted >= window && accepted <= window + 64 * 1024, + "{streams} streams accepted {accepted}" + ); + assert!(stalled.iter().all(|s| s.0 <= 256 * 1024 + 64 * 1024)); + ready.send(()).unwrap(); + connection.closed().await; + }); + let probe = ResourceProbe::default(); + probe + .scope(async { + let mut unread = Vec::new(); + for _ in 0..streams { + unread.push( + outbound + .connect_stream(request(), &EstablishContext::default()) + .await + .unwrap() + .io, + ); + } + tokio::time::timeout(Duration::from_secs(5), wait) + .await + .unwrap() + .unwrap(); + let before = tokio::time::Instant::now(); + outbound.shutdown().await; + assert!(before.elapsed() < Duration::from_secs(2)); + drop(unread); + assert!(probe.snapshot().is_idle(), "{:?}", probe.snapshot()); + }) + .await; + finish(endpoint, peer).await; + } +} + +#[tokio::test] +async fn blocked_outer_path_bounds_stream_and_datagram_send_buffers_and_stop() { + use std::sync::atomic::{AtomicBool, Ordering}; + struct Blockable(BudgetPackets, Arc); + #[async_trait::async_trait] + impl DatagramTransport for Blockable { + fn payload_budget(&self, peer: &Destination) -> DatagramBudget { + self.0.payload_budget(peer) + } + async fn send(&mut self, packet: Datagram) -> Result<(), DispatchError> { + if self.1.load(Ordering::Acquire) { + std::future::pending::<()>().await; + } + self.0.send(packet).await + } + async fn receive(&mut self) -> Result { + self.0.receive().await + } + async fn close(&mut self) -> Result<(), DispatchError> { + self.0.close().await + } + } + let _case = Case::new("TUIC-UNIT", "send_buffers"); + let (config, packets, endpoint) = fixture_parts(1400, true, 8, "cubic", "native"); + let blocked = Arc::new(AtomicBool::new(false)); + let outbound = TuicOutbound::new_with_path( + &config, + UpstreamPath::proxy(Arc::new(MemoryUpstream(Mutex::new(Some(Blockable( + packets, + blocked.clone(), + )))))), + ) + .unwrap(); + let ep = endpoint.clone(); + let peer = tokio::spawn(async move { + let connection = authenticated(&ep).await; + let (mut send, mut recv) = connection.accept_bi().await.unwrap(); + let mut header = [0; 7]; + recv.read_exact(&mut header).await.unwrap(); + send.write_all(b"ready").await.unwrap(); + connection.closed().await; + }); + let probe = ResourceProbe::default(); + probe + .scope(async { + let mut tcp = outbound + .connect_stream(request(), &EstablishContext::default()) + .await + .unwrap() + .io; + let mut ready = [0; 5]; + tcp.read_exact(&mut ready).await.unwrap(); + tokio::time::sleep(Duration::from_millis(100)).await; + let mut udp = outbound + .open_datagram(udp_request(), &EstablishContext::default()) + .await + .unwrap(); + // Quinn includes each queued Datagram's Bytes metadata in this + // buffer and reserves one metadata slot in its space query. + assert_eq!( + outbound.datagram_buffer_space().await, + Some(256 * 1024 - size_of::()) + ); + blocked.store(true, Ordering::Release); + let mut accepted = 0; + while let Ok(n) = + tokio::time::timeout(Duration::from_millis(50), tcp.write(&[0; 4096])).await + { + accepted += n.unwrap(); + assert!(accepted <= 1024 * 1024); + } + assert_eq!(accepted, 1024 * 1024); + let packet = Datagram { + remote: request().destination, + payload: vec![0; 1000].into(), + sniffed_domain: None, + }; + let mut sent = 0; + while let Ok(result) = + tokio::time::timeout(Duration::from_millis(50), udp.send(packet.clone())).await + { + result.unwrap(); + sent += 1; + assert!(sent < 400, "unbounded datagram buffering"); + } + assert!(sent >= 250); + assert!(outbound.datagram_buffer_space().await.unwrap() < 1015); + // Pending graceful FIN ownership must not delay the node Stop. + tcp.shutdown().await.unwrap(); + let before = tokio::time::Instant::now(); + outbound.shutdown().await; + assert!(before.elapsed() < Duration::from_secs(2)); + drop((tcp, udp)); + assert!(probe.snapshot().is_idle(), "{:?}", probe.snapshot()); + }) + .await; + finish(endpoint, peer).await; +} diff --git a/tests/uot_config.rs b/tests/uot_config.rs new file mode 100644 index 0000000..abcd3cb --- /dev/null +++ b/tests/uot_config.rs @@ -0,0 +1,86 @@ +use serde_json::{Value, json}; +use vcore::config::{Config, ProxyProtocol}; + +fn node() -> Value { + json!({"name":"ss","type":"ss","server":"fixture.invalid","port":443, + "cipher":"2022-blake3-aes-128-gcm","password":"BwcHBwcHBwcHBwcHBwcHBw==","udp":true}) +} + +fn parse(node: Value) -> vcore::Result { + Config::parse_yaml( + json!({"port":1080,"proxies":[node],"rules":["MATCH,ss"]}) + .to_string() + .as_bytes(), + ) +} + +#[test] +fn ss_uot_is_opt_in_and_accepts_only_explicit_or_default_v2() { + #[cfg(feature = "interop-test")] + let _case = vcore::resources::case_events::Case::new("UOT-CFG", "strict_v2"); + if !cfg!(feature = "outbound-shadowsocks") { + let mut n = node(); + n["udp-over-tcp"] = json!(true); + assert!(parse(n).is_err()); + return; + } + for enabled in [false, true] { + let mut n = node(); + n["udp-over-tcp"] = json!(enabled); + let c = parse(n.clone()).unwrap(); + let ProxyProtocol::Shadowsocks(ss) = &c.proxies[0].protocol else { + panic!("protocol") + }; + assert_eq!(ss.udp_over_tcp, enabled); + n["udp-over-tcp-version"] = json!(2); + assert_eq!( + parse(n.clone()).is_ok(), + enabled, + "only enabled v2 accepts a version" + ); + for bad in [ + json!(0), + json!(1), + json!(3), + json!(256), + json!(-1), + json!(2.0), + json!("2"), + json!(null), + json!(true), + json!({}), + ] { + n["udp-over-tcp-version"] = bad; + assert!(parse(n.clone()).is_err()); + } + } + let c = parse(node()).unwrap(); + let ProxyProtocol::Shadowsocks(ss) = &c.proxies[0].protocol else { + panic!("protocol") + }; + assert!(!ss.udp_over_tcp); + for udp in [Some(json!(false)), None] { + let mut n = node(); + if let Some(udp) = udp { + n["udp"] = udp; + } else { + n.as_object_mut().unwrap().remove("udp"); + } + n["udp-over-tcp"] = json!(true); + assert!(parse(n).is_err()); + } + for bad in [json!(null), json!("true"), json!(1), json!([])] { + let mut n = node(); + n["udp-over-tcp"] = bad; + assert!(parse(n).is_err()); + } + let mut n = node(); + n["udp-over-tcp-version"] = json!(2); + assert!(parse(n).is_err()); + let mut n = node(); + n["udp-over-tcp"] = json!(true); + n["plugin"] = json!("shadow-tls"); + n["plugin-opts"] = json!({"host":"cover.invalid","version":3,"password":"synthetic-secret"}); + assert_eq!(parse(n).is_ok(), cfg!(feature = "shadow-tls-v3")); + assert!(parse(json!({"name":"ss","type":"anytls","server":"fixture.invalid","port":443,"password":"synthetic-secret","udp":true,"udp-over-tcp":true})).is_err()); +} diff --git a/tests/vless_public.rs b/tests/vless_public.rs index 282730c..a673f87 100644 --- a/tests/vless_public.rs +++ b/tests/vless_public.rs @@ -47,6 +47,14 @@ impl Case { "VLESS-OWNED" => "INTEGRATION-OWNED", _ => panic!("unknown public consumer suite"), } + } else if std::env::var("VCORE_PROTOCOL_STAGE").as_deref() == Ok("HTTPUPGRADE") { + match suite { + "VLESS-PUBLIC" => "HTTPUPGRADE-PUBLIC", + "VLESS-BASE" => "HTTPUPGRADE-BASE", + "VLESS-LIFE" => "HTTPUPGRADE-LIFE", + "VLESS-OWNED" => "HTTPUPGRADE-OWNED", + _ => panic!("unknown public consumer suite"), + } } else { suite }; @@ -56,6 +64,10 @@ impl Case { const TIMEOUT: Duration = Duration::from_secs(10); const DOMAIN: &str = "vcore-fixture.test"; +#[cfg(all(feature = "outbound-vmess", feature = "outbound-trojan"))] +#[path = "vless_public/httpupgrade.rs"] +mod httpupgrade; + #[cfg(feature = "outbound-hysteria2")] #[path = "vless_public/hysteria2.rs"] mod hysteria2; @@ -63,9 +75,18 @@ mod hysteria2; mod integration; #[path = "vless_public/runtime.rs"] mod runtime; +#[cfg(feature = "shadow-tls-v3")] +#[path = "vless_public/shadowtls.rs"] +mod shadowtls; +#[cfg(feature = "outbound-tuic")] +#[path = "vless_public/tuic.rs"] +mod tuic; #[cfg(target_os = "macos")] #[path = "vmess_public/tun.rs"] mod tun; +#[cfg(feature = "outbound-shadowsocks")] +#[path = "vless_public/uot.rs"] +mod uot; fn fixture() -> Value { let value: Value = serde_json::from_slice( @@ -294,9 +315,16 @@ fn reply(client: &mut TcpStream) -> SocketAddr { SocketAddr::new(ip, u16::from_be_bytes(port)) } fn connect(port: u16, target: SocketAddr, domain: bool) -> TcpStream { + connect_with_initial(port, target, domain, &[]) +} +fn connect_with_initial(port: u16, target: SocketAddr, domain: bool, initial: &[u8]) -> TcpStream { let mut client = login(port); let mut request = vec![5, 1, 0]; request.extend(address(target, domain)); + // Queue actual application bytes with CONNECT before the relay can poll + // its read side. Waiting for the SOCKS reply first is not a guaranteed + // nonempty first write at the SS adapter, even for a client-first origin. + request.extend(initial); client.write_all(&request).unwrap(); reply(&mut client); client @@ -413,8 +441,7 @@ impl Association { } fn echo(port: u16, f: &Value) { let mut origin = Origin::new(f, 13, false); - let mut client = connect(port, origin.target, false); - client.write_all(b"client-first").unwrap(); + let mut client = connect_with_initial(port, origin.target, false, b"client-first"); let mut bytes = [0; 12]; client.read_exact(&mut bytes).unwrap(); assert_eq!(&bytes, b"client-first"); @@ -423,15 +450,24 @@ fn echo(port: u16, f: &Value) { origin.marker(b'D'); } fn bulk(port: u16, f: &Value, ipv6: bool, domain: bool) { + bulk_start(port, f, ipv6, domain, true); +} +fn bulk_client_first(port: u16, f: &Value, ipv6: bool, domain: bool) { + bulk_start(port, f, ipv6, domain, false); +} +fn bulk_start(port: u16, f: &Value, ipv6: bool, domain: bool, server_first: bool) { let _case = Case::start("VLESS-BASE", "tcp_10mib_both_directions"); - let mut origin = Origin::new(f, 10, ipv6); - let mut client = connect(port, origin.target, domain); - let mut hello = [0; 5]; - client.read_exact(&mut hello).unwrap(); - assert_eq!(&hello, b"hello"); - origin.marker(b'A'); + let mut origin = Origin::new(f, if server_first { 10 } else { 22 }, ipv6); let data = vec![0x5a; 10 * 1024 * 1024]; - for fragment in data.chunks(4093) { + let initial_length = if server_first { 0 } else { 4093 }; + let mut client = connect_with_initial(port, origin.target, domain, &data[..initial_length]); + if server_first { + let mut hello = [0; 5]; + client.read_exact(&mut hello).unwrap(); + assert_eq!(&hello, b"hello"); + } + origin.marker(b'A'); + for fragment in data[initial_length..].chunks(4093) { client.write_all(fragment).unwrap(); } let mut hash = Sha256::new(); diff --git a/tests/vless_public/httpupgrade.rs b/tests/vless_public/httpupgrade.rs new file mode 100644 index 0000000..64faa6f --- /dev/null +++ b/tests/vless_public/httpupgrade.rs @@ -0,0 +1,247 @@ +//! Shared public consumers; every protocol peer and origin is container-owned. +use super::*; +use vcore::resources::observation::ResourceProbe; + +fn save(value: Value) { + std::fs::write( + std::env::var("VCORE_HTTPUPGRADE_OBSERVATIONS").unwrap(), + value.to_string(), + ) + .unwrap(); +} + +#[test] +#[ignore = "isolated HTTPUpgrade peer and origin required"] +fn tcp() { + let f = fixture(); + initialize(&f); + let _case = RecordedCase::new("HTTPUPGRADE-PUBLIC", "tcp"); + let probe = ResourceProbe::default(); + let port = free_port(); + let core = probe.scope_sync(|| Core::start(&config(f["node"].clone(), port))); + for (ipv6, domain) in [(false, false), (true, false), (false, true)] { + bulk(port, &f, ipv6, domain); + } + echo(port, &f); + let before = Instant::now(); + core.stop(); + assert!(before.elapsed() < Duration::from_secs(5)); + assert!(probe.snapshot().is_idle(), "{:?}", probe.snapshot()); + save( + json!({"families":["ipv4","ipv6","domain"],"tcp_bytes_each_family_each_direction":10*1024*1024,"server_first":true,"client_first":true,"stop_idle":true}), + ); +} + +fn no_udp(association: &mut Association, payload: &[u8]) { + association + .client + .send_to(&association.packet(payload), association.relay) + .unwrap(); + association + .client + .set_read_timeout(Some(Duration::from_millis(150))) + .unwrap(); + assert!( + matches!(association.client.recv_from(&mut [0;64]), Err(e) if matches!(e.kind(),io::ErrorKind::WouldBlock|io::ErrorKind::TimedOut)) + ); + association.origin.quiet(); + association.client.set_read_timeout(Some(TIMEOUT)).unwrap(); +} + +#[test] +#[ignore = "isolated HTTPUpgrade UDP peer and origin required"] +fn udp() { + let f = fixture(); + initialize(&f); + let _case = RecordedCase::new("HTTPUPGRADE-PUBLIC", "udp"); + let vmess = f["node"]["type"] == "vmess"; + let native = f["peer_kind"] == "XR"; + let codec = if vmess { + f["node"]["packet-encoding"].as_str().unwrap() + } else { + "trojan" + }; + let probe = ResourceProbe::default(); + let port = free_port(); + let mut dns_origin = Origin::new(&f, 17, false); + let mut yaml = config(f["node"].clone(), port); + dns(&mut yaml, &dns_origin, "DIRECT"); + let core = probe.scope_sync(|| Core::start(&yaml)); + let mut live = Vec::new(); + let mut rows = Vec::new(); + for (family, ipv6, domain) in [ + ("ipv4", false, false), + ("ipv6", true, false), + ("domain", false, true), + ] { + if !f["families"] + .as_array() + .unwrap() + .iter() + .any(|v| v == family) + { + continue; + } + if vmess || native { + let mut empty = Association::new(&f, port, ipv6, domain); + no_udp(&mut empty, b""); + live.push(empty); + } + let mut association = Association::new(&f, port, ipv6, domain); + let cap = if vmess { + 15000 + - if codec == "packetaddr" { + if ipv6 || domain { 19 } else { 7 } + } else { + 0 + } + } else if native { + 8166 // Native reply's 8192 total-frame budget minus this domain header. + } else { + 8192 + }; + let mut sizes = vec![1, 64, 512, 1200, cap]; + if !vmess && !native { + sizes.insert(0, 0); + } + for &size in &sizes { + for sequence in 0..100_u8 { + association.exchange(&vec![sequence; size]); + } + } + if native { + // Upload fits VCore, but exceeds the native reply frame. The + // incomplete reply must not become a successful shortened UDP. + let mut overflow = Association::new(&f, port, ipv6, domain); + let payload = vec![7; cap + 1]; + overflow + .client + .send_to(&overflow.packet(&payload), overflow.relay) + .unwrap(); + overflow.origin.udp(&payload); + overflow + .client + .set_read_timeout(Some(Duration::from_millis(150))) + .unwrap(); + assert!( + matches!(overflow.client.recv_from(&mut [0;20000]),Err(e) if matches!(e.kind(),io::ErrorKind::WouldBlock|io::ErrorKind::TimedOut)) + ); + no_udp(&mut association, &vec![7; 8193]); + live.push(overflow); + } else { + no_udp(&mut association, &vec![7; cap + 1]); + } + rows.push(json!({"family":family,"sizes":sizes,"packets":sizes.len()*100})); + live.push(association); + } + if codec == "packetaddr" { + let mut header = [0; 4]; + dns_origin.observer.read_exact(&mut header).unwrap(); + let mut question = vec![0; u16::from_be_bytes([header[0], header[1]]) as usize]; + dns_origin.observer.read_exact(&mut question).unwrap(); + assert_eq!(&question[12..], b"\x0dvcore-fixture\x04test\0\0\x01\0\x01"); + } + echo(port, &f); + let before = Instant::now(); + core.stop(); + assert!(before.elapsed() < Duration::from_secs(5)); + assert!(probe.snapshot().is_idle(), "{:?}", probe.snapshot()); + for association in &mut live { + association.origin.quiet(); + } + save( + json!({"udp":rows,"zero_no_delivery":vmess || native,"oversize_rejected":true,"tcp_sibling":true,"stop_idle":true}), + ); +} + +#[test] +#[ignore = "isolated HTTPUpgrade peer and origin required"] +fn echo_and_stop() { + let f = fixture(); + initialize(&f); + let _case = RecordedCase::new("HTTPUPGRADE-PUBLIC", "echo_and_stop"); + let probe = ResourceProbe::default(); + let port = free_port(); + let core = probe.scope_sync(|| Core::start(&config(f["node"].clone(), port))); + echo(port, &f); + let (mut client, mut origin) = runtime::live(port, &f); + runtime::exchange(&mut client, b"before-stop"); + let start = Instant::now(); + core.stop(); + assert!(start.elapsed() < Duration::from_secs(5)); + assert!(probe.snapshot().is_idle(), "{:?}", probe.snapshot()); + runtime::assert_closed(&mut client); + origin.marker(b'D'); + origin.quiet(); + save(json!({"authenticated_echo":true,"live_stream_cancelled":true,"stop_idle":true})); +} + +#[test] +#[ignore = "isolated HTTPUpgrade negative fixture required"] +fn rejected() { + let f = fixture(); + initialize(&f); + let _case = RecordedCase::new("HTTPUPGRADE-PUBLIC", "rejected"); + let probe = ResourceProbe::default(); + probe.scope_sync(|| denied(f["node"].clone(), &f)); + assert!(probe.snapshot().is_idle(), "{:?}", probe.snapshot()); + save(json!({"origin_connected":false,"received_business_bytes":0,"stop_idle":true})); +} + +#[tokio::test] +#[ignore = "isolated HTTPUpgrade peer and official close reference required"] +async fn close() { + use std::sync::Arc; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + use vcore::{ + config::{Config, ProxyProtocol}, + dialer::{Dialer, ResolvedEndpoint}, + outbound::{ + EstablishContext, OutboundConnector, UpstreamPath, trojan::TrojanOutbound, + vmess::VmessOutbound, + }, + session::{InboundKind, StreamSession}, + }; + let f = fixture(); + let _case = RecordedCase::new("HTTPUPGRADE-PUBLIC", "close"); + let parsed = + Config::parse_yaml(config(f["node"].clone(), 1080).to_string().as_bytes()).unwrap(); + let proxy = &parsed.proxies[0]; + let probe = ResourceProbe::default(); + let mut origin = Origin::new(&f, 11, false); + let tail = probe.scope(async { + let path = UpstreamPath::direct(ResolvedEndpoint { + logical_host: proxy.address().into(), port: proxy.port(), + addresses: vec![SocketAddr::new(proxy.address().parse().unwrap(), proxy.port())], + }, Dialer::default()); + let outbound: Arc = match &proxy.protocol { + ProxyProtocol::Vmess(c) => Arc::new(VmessOutbound::new_with_path(c,path).unwrap()), + ProxyProtocol::Trojan(c) => Arc::new(TrojanOutbound::new_with_path(c,path).unwrap()), + _ => unreachable!(), + }; + let mut io = outbound.connect_stream(StreamSession { + inbound: InboundKind::InternalMeasure, source:"127.0.0.1:1".parse().unwrap(), + destination: origin.target.into(), sniffed_domain:None, + }, &EstablishContext::default()).await.unwrap().io; + let tail = tokio::time::timeout(TIMEOUT, async { + let mut hello=[0;5]; io.read_exact(&mut hello).await.unwrap(); assert_eq!(&hello,b"hello"); + io.write_all(b"ping").await.unwrap(); io.flush().await.unwrap(); + let mut echo=[0;4]; io.read_exact(&mut echo).await.unwrap(); assert_eq!(&echo,b"ping"); + io.shutdown().await.unwrap(); + let mut tail=Vec::new(); + let terminal=io.read_to_end(&mut tail).await; + assert!(terminal.is_ok() || matches!(terminal,Err(ref e) if matches!(e.kind(),io::ErrorKind::ConnectionReset|io::ErrorKind::UnexpectedEof|io::ErrorKind::BrokenPipe))); + tail + }).await.expect("close did not terminate"); + drop(io); + tokio::time::timeout(Duration::from_secs(5),outbound.shutdown()).await.unwrap(); + tail + }).await; + assert!(probe.snapshot().is_idle(), "{:?}", probe.snapshot()); + origin.marker(b'A'); + origin.marker(b'D'); + let hex: String = tail.iter().map(|b| format!("{b:02x}")).collect(); + assert_eq!(f["close_reference"]["terminated"], true); + assert_eq!(hex, f["close_reference"]["tail_hex"].as_str().unwrap()); + save(json!({"tail_hex":hex,"terminated":true,"stop_idle":true})); +} diff --git a/tests/vless_public/integration/connector.rs b/tests/vless_public/integration/connector.rs index 3b3d330..66a4752 100644 --- a/tests/vless_public/integration/connector.rs +++ b/tests/vless_public/integration/connector.rs @@ -48,6 +48,17 @@ pub(super) fn node( ProxyProtocol::Vmess(c) => Arc::new(VmessOutbound::new_with_path(c, path).unwrap()), ProxyProtocol::Vless(c) => Arc::new(VlessOutbound::new_with_path(c, path).unwrap()), ProxyProtocol::Hysteria2(c) => Arc::new(Hysteria2Outbound::new_with_path(c, path).unwrap()), + ProxyProtocol::Tuic(c) => { + #[cfg(feature = "outbound-tuic")] + { + Arc::new(vcore::outbound::tuic::TuicOutbound::new_with_path(c, path).unwrap()) + } + #[cfg(not(feature = "outbound-tuic"))] + { + let _ = c; + panic!("TUIC is not compiled"); + } + } ProxyProtocol::AnyTls(c) => { let tls = StandardTlsClient::with_options( &SecurityContext::new(), @@ -170,8 +181,8 @@ pub(super) fn carrier_pair(f: &Value) -> Value { .build() .unwrap(); let kind = f["last"]["type"].as_str().unwrap(); - let tcp_allowed = kind != "hysteria2"; - let udp_allowed = !matches!(kind, "socks5" | "ss" | "hysteria2"); + let tcp_allowed = !matches!(kind, "hysteria2" | "tuic"); + let udp_allowed = !matches!(kind, "socks5" | "ss" | "hysteria2" | "tuic"); runtime.block_on(probe.scope(async { let first = node(&f["first"], None, Dialer::default()); let controlled = Arc::new(NoDatagrams { @@ -300,6 +311,10 @@ fn protect_failure() { let mut case = RecordedCase::new("INTEGRATION-FAILURES-SOURCE", protocol); let port = free_port(); let probe = ResourceProbe::default(); + if protocol == "tuic" { + runtime.block_on(probe.scope(transmit_budget(&f["nodes"][protocol], &f))); + assert!(probe.snapshot().is_idle()); + } let core = probe.scope_sync(|| Core::start(&config(f["nodes"][protocol].clone(), port))); let mut first = Association::new(&f, port, false, false); @@ -311,11 +326,16 @@ fn protect_failure() { .send_to(&first.packet(b"unauthorized-source"), first.relay) .unwrap(); first.origin.quiet(); - first - .client - .send_to(&first.packet(&vec![0; 65246]), first.relay) - .unwrap(); - first.origin.quiet(); + // Retain the older codecs' wire-limit negative. TUIC fragments + // this otherwise valid payload: 65245 is the SOCKS reply limit, + // not a universal transmit cap. Its explicit budget is tested above. + if protocol != "tuic" { + first + .client + .send_to(&first.packet(&vec![0; 65246]), first.relay) + .unwrap(); + first.origin.quiet(); + } second.exchange(b"survives-foreign-and-oversize"); drop(first); second.exchange(b"survives-single-association-cancel"); @@ -326,6 +346,42 @@ fn protect_failure() { } } observe( - json!({"protect_rejected":PROTOCOLS,"auth_rejected":PROTOCOLS,"certificate_pin_rejected":["anytls","trojan","vmess","vless","hysteria2"],"source_and_oversize_isolated":PROTOCOLS,"cancel_preserves_sibling":PROTOCOLS,"no_origin_bytes":true,"stop_idle":true}), + json!({"protect_rejected":PROTOCOLS,"auth_rejected":PROTOCOLS,"certificate_pin_rejected":["anytls","trojan","vmess","vless","hysteria2","tuic"],"source_and_oversize_isolated":PROTOCOLS,"tuic_transmit_budget":{"limit":128,"rejected":129,"following_roundtrip":128},"cancel_preserves_sibling":PROTOCOLS,"no_origin_bytes":true,"stop_idle":true}), ); } + +async fn transmit_budget(raw: &Value, f: &Value) { + let outbound = node(raw, None, Dialer::default()); + let mut udp = outbound + .open_datagram( + request().with_budget(DatagramBudget::new(128, 128)), + &EstablishContext::default(), + ) + .await + .unwrap(); + let mut origin = Origin::new(f, 4, false); + let target = origin.target; + let packet = |size| Datagram { + remote: target.into(), + payload: vec![7; size].into(), + sniffed_domain: None, + }; + assert_eq!( + udp.payload_budget(&origin.target.into()), + DatagramBudget::new(128, 128) + ); + assert!(udp.send(packet(129)).await.is_err()); + origin.quiet(); + udp.send(packet(128)).await.unwrap(); + let response = tokio::time::timeout(TIMEOUT, udp.receive()) + .await + .unwrap() + .unwrap(); + assert_eq!(response.remote, origin.target.into()); + assert_eq!(&response.payload[..], &[7; 128]); + origin.udp(&[7; 128]); + udp.close().await.unwrap(); + drop(udp); + outbound.begin_shutdown(); + outbound.shutdown().await; +} diff --git a/tests/vless_public/integration/lifecycle.rs b/tests/vless_public/integration/lifecycle.rs index d5aee9a..086d547 100644 --- a/tests/vless_public/integration/lifecycle.rs +++ b/tests/vless_public/integration/lifecycle.rs @@ -1,6 +1,19 @@ use super::*; -const NEW_PROTOCOLS: [&str; 4] = ["trojan", "vmess", "vless", "hysteria2"]; +const GROUPS: [&str; 12] = [ + "socks5", + "anytls", + "ss", + "trojan", + "vmess", + "vless", + "hysteria2", + "tuic", + "ss-v3", + "ss-uot", + "ss-uot-v3", + "httpupgrade", +]; pub(super) fn fd_count() -> usize { std::fs::read_dir("/dev/fd").unwrap().count() @@ -30,7 +43,8 @@ fn lifecycle_tracer() { fn lifetimes(count: usize) { let f = fixture(); initialize(&f); - for protocol in NEW_PROTOCOLS { + for group in GROUPS { + let protocol = f["profile_groups"][group][0].as_str().unwrap(); let port = free_port(); let core = Core::start(&config(f["nodes"][protocol].clone(), port)); echo(port, &f); @@ -38,7 +52,11 @@ fn lifetimes(count: usize) { } let mut observations = Vec::new(); for cycle in 0..count { - let protocol = NEW_PROTOCOLS[(cycle / 5) % NEW_PROTOCOLS.len()]; + let group = GROUPS[(cycle / 5) % GROUPS.len()]; + let options = f["profile_groups"][group].as_array().unwrap(); + let protocol = options[(cycle / (5 * GROUPS.len())) % options.len()] + .as_str() + .unwrap(); let mode = cycle % 5; let mut case = RecordedCase::new("INTEGRATION-LIFECYCLE", "stop_and_remain_quiet"); let probe = ResourceProbe::default(); @@ -52,7 +70,15 @@ fn lifetimes(count: usize) { let mut occupied = None; let mut node = f["nodes"][protocol].clone(); if mode == 2 { - let origin = Origin::new(&f, if protocol == "hysteria2" { 20 } else { 15 }, false); + let origin = Origin::new( + &f, + if matches!(group, "hysteria2" | "tuic") { + 20 + } else { + 15 + }, + false, + ); node["server"] = json!(origin.target.ip().to_string()); node["port"] = json!(origin.target.port()); blackhole = Some(origin); @@ -123,7 +149,7 @@ fn lifetimes(count: usize) { association.client.set_nonblocking(true).unwrap(); } if let Some(origin) = &mut blackhole - && protocol != "hysteria2" + && !matches!(group, "hysteria2" | "tuic") { origin.marker(b'D'); } @@ -161,7 +187,7 @@ fn lifetimes(count: usize) { drop((tcp, udp, blackhole, rebound_tcp, rebound_udp)); let end = fd_count(); assert!(end <= baseline); - observations.push(json!({"cycle":cycle,"protocol":protocol,"mode":mode,"baseline_fd":baseline,"retained_fixture_fd":retained,"after_stop_fd":after_stop,"final_fd":end,"stop_ms":stop_ms,"quiet_seconds":quiet_seconds,"active":active,"after_stop":stopped,"quiet":probe.snapshot(),"ports_rebound":true})); + observations.push(json!({"cycle":cycle,"group":group,"profile":protocol,"mode":mode,"baseline_fd":baseline,"retained_fixture_fd":retained,"after_stop_fd":after_stop,"final_fd":end,"stop_ms":stop_ms,"quiet_seconds":quiet_seconds,"active":active,"after_stop":stopped,"quiet":probe.snapshot(),"ports_rebound":true})); println!("INTEGRATION lifecycle: {}/{count}", cycle + 1); } observe(json!({"count":count,"cycles":observations})); diff --git a/tests/vless_public/integration/mod.rs b/tests/vless_public/integration/mod.rs index bc18dc7..95c6059 100644 --- a/tests/vless_public/integration/mod.rs +++ b/tests/vless_public/integration/mod.rs @@ -35,8 +35,19 @@ fn resource_tracer() { let udp_queue = &queues[QueueKind::SocksUdp as usize]; assert_eq!(udp_queue.capacity, 16); assert!((1..=16).contains(&udp_queue.peak)); - if protocol == "hysteria2" { - assert!(queues.iter().all(|q| q.peak > 0 && q.peak <= q.capacity)); + if matches!(protocol, "hysteria2" | "tuic") { + let inactive = if protocol == "tuic" { + QueueKind::Hysteria2Udp + } else { + QueueKind::TuicUdp + }; + for (index, queue) in queues.iter().enumerate() { + if index == inactive as usize { + assert_eq!((queue.capacity, queue.peak), (0, 0)); + } else { + assert!(queue.peak > 0 && queue.peak <= queue.capacity); + } + } } case.checkpoint("active", active); core.stop(); @@ -54,7 +65,7 @@ fn resource_tracer() { observe(json!({"protocols":PROTOCOLS,"active_observed":true,"stop_idle":true})); } -const PROTOCOLS: [&str; 7] = [ +const PROTOCOLS: [&str; 8] = [ "socks5", "anytls", "ss", @@ -62,6 +73,7 @@ const PROTOCOLS: [&str; 7] = [ "vmess", "vless", "hysteria2", + "tuic", ]; fn observe(value: Value) { @@ -103,7 +115,7 @@ fn graph() { runtime::select(controller, "REJECT"); runtime::exchange(&mut old, b"old-transport-snapshot"); udp.exchange(b"old-udp-snapshot"); - if protocol == "hysteria2" { + if matches!(protocol, "hysteria2" | "tuic") { echo(port, &f); // Reuse is allowed only on the old physical session. } else { // AnyTLS reuses idle sessions, not a session with an active stream; @@ -161,8 +173,11 @@ fn dns_measure() { ]); let core = Core::start(&yaml); let mut origin = Origin::new(&f, 13, false); - let mut client = connect(port, origin.target, true); - runtime::exchange(&mut client, b"controlled-dns-route"); + let payload = b"controlled-dns-route"; + let mut client = connect_with_initial(port, origin.target, true, payload); + let mut response = vec![0; payload.len()]; + client.read_exact(&mut response).unwrap(); + assert_eq!(&response, payload); origin.marker(b'A'); let mut header = [0; 4]; dns_origin.observer.read_exact(&mut header).unwrap(); @@ -231,7 +246,7 @@ fn ss_bulk_stress() { let core = Core::start(&json!({"socks-port":port,"proxies":[last,first],"rules":["MATCH,peer"]})); for _ in 0..50 { - bulk(port, &f, false, false); + bulk_client_first(port, &f, false, false); } core.stop(); } @@ -250,6 +265,13 @@ fn ordered_pair() { let _case = RecordedCase::new("INTEGRATION-PAIR", "ordered_pair"); let f = fixture(); initialize(&f); + if let Some(variant) = f.get("variant") { + assert_eq!(f["first"]["udp-relay-mode"], variant["udp_mode"]); + assert_eq!(f["last"]["cipher"], variant["cipher"]); + assert_eq!(f["last"]["plugin"], "shadow-tls"); + assert_eq!(f["last"]["plugin-opts"]["version"], 3); + assert!(f["last"].get("udp-over-tcp").is_none()); + } let mut observations = Vec::new(); for outer_ipv6 in [false, true] { for grouped in [false, true] { @@ -271,8 +293,9 @@ fn ordered_pair() { ]); } let core = Core::start(&yaml); + let server_first = f["last"]["type"] != "ss"; for (ipv6, domain) in [(false, false), (true, false), (false, true)] { - bulk(port, &f, ipv6, domain); + bulk_start(port, &f, ipv6, domain, server_first); } echo(port, &f); // Keep source tuples alive until Stop. Trojan's documented Mihomo @@ -298,20 +321,23 @@ fn ordered_pair() { drop(associations); let _tcp = TcpListener::bind((Ipv4Addr::LOCALHOST, port)).unwrap(); let _udp = UdpSocket::bind((Ipv4Addr::LOCALHOST, port)).unwrap(); - observations.push(json!({ + let mut path = json!({ "outer_ipv6":outer_ipv6,"nested_select":grouped, "tcp_target_kinds":3,"tcp_bytes_each_direction":3*10*1024*1024, "udp_target_kinds":target_count,"udp_packets":target_count*400,"udp_sizes":[1,64,512,1200], - "server_first":true,"client_first":true,"ports_rebound":true - })); + "server_first":server_first,"client_first":true,"ports_rebound":true + }); + if !server_first { + path["server_first_limitation"] = json!("official-ss2022-empty-first-write"); + } + observations.push(path); } } - std::fs::write( - std::env::var("VCORE_INTEGRATION_OBSERVATIONS").unwrap(), - json!({"first":f["first"]["type"],"last":f["last"]["type"],"paths":observations,"domain_native":domain_terminal(&f),"budgets":connector::budget_pair(&f),"routed_udp":routed_udp_pair(&f),"carrier_capability":connector::carrier_pair(&f)}) - .to_string(), - ) - .unwrap(); + let mut value = json!({"first":f["first"]["type"],"last":f["last"]["type"],"paths":observations,"domain_native":domain_terminal(&f),"budgets":connector::budget_pair(&f),"routed_udp":routed_udp_pair(&f),"carrier_capability":connector::carrier_pair(&f)}); + if let Some(variant) = f.get("variant") { + value["variant"] = variant.clone(); + } + observe(value); } fn routed_udp_pair(f: &Value) -> Value { diff --git a/tests/vless_public/integration/pressure.rs b/tests/vless_public/integration/pressure.rs index 92b58f0..c4a0529 100644 --- a/tests/vless_public/integration/pressure.rs +++ b/tests/vless_public/integration/pressure.rs @@ -1,11 +1,13 @@ use super::*; -const NEW_PROTOCOLS: [&str; 4] = ["trojan", "vmess", "vless", "hysteria2"]; +const TCP_GROUPS: [&str; 4] = ["socks5", "ss-v3", "tuic", "httpupgrade"]; +const UDP_GROUPS: [&str; 4] = ["ss-uot", "ss-uot-v3", "tuic", "httpupgrade"]; struct Flows { tcp: Vec<(TcpStream, Origin)>, udp: Vec, setup_us: Vec, + profiles: Value, } impl Flows { @@ -14,18 +16,36 @@ impl Flows { tcp: Vec::with_capacity(20), udp: Vec::with_capacity(20), setup_us: Vec::with_capacity(40), + profiles: json!({"tcp":[],"udp":[]}), }; - for protocol in NEW_PROTOCOLS { - runtime::select(controller, protocol); - for _ in 0..5 { + for (tcp_group, udp_group) in TCP_GROUPS.into_iter().zip(UDP_GROUPS) { + for index in 0..5 { + let profile = |group| { + let options = f["profile_groups"][group].as_array().unwrap(); + options[(generation + index) % options.len()] + .as_str() + .unwrap() + }; + let tcp_profile = profile(tcp_group); + runtime::select(controller, tcp_profile); let start = Instant::now(); flows.tcp.push(runtime::live(port, f)); flows.setup_us.push(start.elapsed().as_micros() as u64); + flows.profiles["tcp"] + .as_array_mut() + .unwrap() + .push(json!(tcp_profile)); + let udp_profile = profile(udp_group); + runtime::select(controller, udp_profile); let start = Instant::now(); let mut udp = Association::new(f, port, false, false); udp.exchange(&payload(generation, flows.udp.len(), 0, true)); flows.udp.push(udp); flows.setup_us.push(start.elapsed().as_micros() as u64); + flows.profiles["udp"] + .as_array_mut() + .unwrap() + .push(json!(udp_profile)); } } assert_eq!((flows.tcp.len(), flows.udp.len()), (20, 20)); @@ -70,7 +90,16 @@ fn close_peer(f: &Value) { fn start(f: &Value, probe: &ResourceProbe) -> (Core, u16, u16) { let port = free_port(); let controller = free_port(); - let nodes: Vec<_> = NEW_PROTOCOLS + let mut members = Vec::new(); + for group in TCP_GROUPS.into_iter().chain(UDP_GROUPS) { + for profile in f["profile_groups"][group].as_array().unwrap() { + let name = profile.as_str().unwrap(); + if !members.contains(&name) { + members.push(name); + } + } + } + let nodes: Vec<_> = members .iter() .map(|protocol| { let mut node = f["nodes"][protocol].clone(); @@ -78,7 +107,7 @@ fn start(f: &Value, probe: &ResourceProbe) -> (Core, u16, u16) { node }) .collect(); - let yaml = json!({"socks-port":port,"external-controller":format!("127.0.0.1:{controller}"),"secret":"fixture-only","proxies":nodes,"proxy-groups":[{"name":"inner","type":"select","proxies":NEW_PROTOCOLS}],"rules":["MATCH,inner"]}); + let yaml = json!({"socks-port":port,"external-controller":format!("127.0.0.1:{controller}"),"secret":"fixture-only","proxies":nodes,"proxy-groups":[{"name":"inner","type":"select","proxies":members}],"rules":["MATCH,inner"]}); (probe.scope_sync(|| Core::start(&yaml)), port, controller) } @@ -195,14 +224,15 @@ fn run_rebuild(count: usize) { close_peer(&f); flows.assert_tcp_closed(); let setup = flows.setup_us.clone(); + let profiles = flows.profiles.clone(); drop(flows); - cycles.push(json!({"generation":generation,"tcp":20,"udp":20,"per_protocol_tcp":5,"per_protocol_udp":5,"active":active,"setup_us":setup,"fault":"owned-peer-connections-closed","new_clients":true,"after_clients":sample(&probe)})); + cycles.push(json!({"generation":generation,"tcp":20,"udp":20,"per_group_tcp":5,"per_group_udp":5,"flow_profiles":profiles,"active":active,"setup_us":setup,"fault":"owned-peer-connections-closed","new_clients":true,"after_clients":sample(&probe)})); println!("INTEGRATION rebuild: {}/{count}", generation + 1); } let stopped = stop_quiet(core, &probe, port, controller, baseline); case.resources(probe.snapshot()); observe( - json!({"count":count,"same_running_session":true,"protocols":NEW_PROTOCOLS,"cold_fd":cold_fd,"baseline_fd":baseline,"cycles":cycles,"stopped":stopped}), + json!({"count":count,"same_running_session":true,"tcp_groups":TCP_GROUPS,"udp_groups":UDP_GROUPS,"cold_fd":cold_fd,"baseline_fd":baseline,"cycles":cycles,"stopped":stopped}), ); } @@ -245,6 +275,7 @@ fn run_soak(seconds: u64) { let (core, port, controller) = start(&f, &probe); let mut flows = Flows::open(&f, port, controller, 0); let first_setup = flows.setup_us.clone(); + let first_profiles = flows.profiles.clone(); let first_median = median(first_setup.iter().copied()); let start = Instant::now(); let mut waves = 0; @@ -258,7 +289,15 @@ fn run_soak(seconds: u64) { flows.exchange(faults.len(), waves); waves += 1; while start.elapsed().as_secs() >= next_switch { - runtime::select(controller, NEW_PROTOCOLS[switches.len() % 4]); + let options = f["profile_groups"][TCP_GROUPS[switches.len() % 4]] + .as_array() + .unwrap(); + runtime::select( + controller, + options[(switches.len() / 4) % options.len()] + .as_str() + .unwrap(), + ); switches.push(start.elapsed().as_secs_f64()); next_switch += 1; } @@ -289,13 +328,14 @@ fn run_soak(seconds: u64) { } let elapsed = start.elapsed().as_secs_f64(); let last_setup = flows.setup_us.clone(); + let last_profiles = flows.profiles.clone(); let last_median = median(last_setup.iter().copied()); assert!(last_median <= first_median * 2); let active_end = sample(&probe); drop(flows); let stopped = stop_quiet(core, &probe, port, controller, baseline); case.resources(probe.snapshot()); - let mut report = json!({"seconds":elapsed,"requested_seconds":seconds,"protocols":NEW_PROTOCOLS,"tcp":20,"udp":20,"per_protocol_tcp":5,"per_protocol_udp":5,"waves":waves,"normal_verified_bytes":waves*20*2*2*257,"normal_corruption":0,"normal_misdirection":0,"normal_unexpected_loss":0,"switches":switches,"faults":faults,"cold_fd":cold_fd,"baseline_fd":baseline,"samples":samples,"first_setup_us":first_setup,"last_setup_us":last_setup,"first_setup_median_us":first_median,"last_setup_median_us":last_median,"active_end":active_end,"stopped":stopped}); + let mut report = json!({"seconds":elapsed,"requested_seconds":seconds,"tcp_groups":TCP_GROUPS,"udp_groups":UDP_GROUPS,"tcp":20,"udp":20,"per_group_tcp":5,"per_group_udp":5,"first_profiles":first_profiles,"last_profiles":last_profiles,"waves":waves,"normal_verified_bytes":waves*20*2*2*257,"normal_corruption":0,"normal_misdirection":0,"normal_unexpected_loss":0,"switches":switches,"faults":faults,"cold_fd":cold_fd,"baseline_fd":baseline,"samples":samples,"first_setup_us":first_setup,"last_setup_us":last_setup,"first_setup_median_us":first_median,"last_setup_median_us":last_median,"active_end":active_end,"stopped":stopped}); if seconds >= 1800 { assert!(samples.len() >= 25 && faults.len() >= 29 && switches.len() >= 1799); let early = &samples[..10]; @@ -331,11 +371,14 @@ fn run_soak(seconds: u64) { assert!( samples .iter() - .all(|p| p["queues"].as_array().unwrap().iter().all(|q| q["peak"] - .as_u64() - .unwrap() - > 0 - && q["peak"].as_u64() <= q["capacity"].as_u64())) + .all(|p| p["queues"].as_array().unwrap().iter().all(|q| { + if q["kind"] == "hysteria2_udp" { + q["peak"] == 0 && q["capacity"] == 0 + } else { + q["peak"].as_u64().unwrap() > 0 + && q["peak"].as_u64() <= q["capacity"].as_u64() + } + })) ); } observe(report); diff --git a/tests/vless_public/integration/shadowsocks.rs b/tests/vless_public/integration/shadowsocks.rs index 7774077..c675812 100644 --- a/tests/vless_public/integration/shadowsocks.rs +++ b/tests/vless_public/integration/shadowsocks.rs @@ -44,7 +44,7 @@ fn algorithms() { let port = free_port(); let core = Core::start(&config(node.clone(), port)); for (ipv6, domain) in [(false, false), (true, false), (false, true)] { - bulk(port, &f, ipv6, domain); + bulk_client_first(port, &f, ipv6, domain); let mut udp = Association::new(&f, port, ipv6, domain); for size in [1, 64, 512, 1200, 4096] { for sequence in 0..100_u8 { @@ -84,7 +84,7 @@ fn eih() { } let core = Core::start(&config(node, port)); for ipv6 in [false, true] { - bulk(port, &f, ipv6, false); + bulk_client_first(port, &f, ipv6, false); let mut udp = Association::new(&f, port, ipv6, false); for size in [1, 64, 512, 1200, 4096] { println!("EIH UDP: outer_ipv6={outer_ipv6}, inner_ipv6={ipv6}, size={size}"); diff --git a/tests/vless_public/runtime.rs b/tests/vless_public/runtime.rs index 95dd57c..2755cac 100644 --- a/tests/vless_public/runtime.rs +++ b/tests/vless_public/runtime.rs @@ -90,7 +90,7 @@ pub(super) fn entrypoints(f: &Value) { let mut client = socket((Ipv4Addr::LOCALHOST, port).into()); write!( client, - "CONNECT {} HTTP/1.1\r\nHost: {}\r\n\r\n", + "CONNECT {} HTTP/1.1\r\nHost: {}\r\n\r\nhttp-connect", origin.target, origin.target ) .unwrap(); @@ -102,7 +102,9 @@ pub(super) fn entrypoints(f: &Value) { assert!(header.len() < 4096); } assert!(header.starts_with(b"HTTP/1.1 200")); - exchange(&mut client, b"http-connect"); + let mut response = [0; 12]; + client.read_exact(&mut response).unwrap(); + assert_eq!(&response, b"http-connect"); origin.marker(b'A'); core.stop(); assert_closed(&mut client); @@ -182,8 +184,10 @@ pub(super) fn assert_closed(client: &mut TcpStream) { } pub(super) fn live(port: u16, f: &Value) -> (TcpStream, Origin) { let mut origin = Origin::new(f, 13, false); - let mut client = connect(port, origin.target, false); - exchange(&mut client, b"live"); + let mut client = connect_with_initial(port, origin.target, false, b"live"); + let mut response = [0; 4]; + client.read_exact(&mut response).unwrap(); + assert_eq!(&response, b"live"); origin.marker(b'A'); (client, origin) } diff --git a/tests/vless_public/shadowtls.rs b/tests/vless_public/shadowtls.rs new file mode 100644 index 0000000..c0ec074 --- /dev/null +++ b/tests/vless_public/shadowtls.rs @@ -0,0 +1,257 @@ +//! Public SS + ShadowTLS consumers; peers and origins belong to the container lab. +use super::*; +use vcore::resources::observation::ResourceProbe; + +fn fault_counts(f: &Value) -> Value { + let mut io = socket(f["fault_control"].as_str().unwrap().parse().unwrap()); + io.write_all(b"?").unwrap(); + serde_json::from_reader(io.take(1024)).unwrap() +} + +fn await_count(f: &Value, field: &str, expected: u64) { + let until = Instant::now() + Duration::from_secs(3); + loop { + let count = fault_counts(f)[field].as_u64().unwrap(); + if count == expected { + return; + } + assert!( + count < expected && Instant::now() < until, + "{field}: {count}" + ); + thread::sleep(Duration::from_millis(10)); + } +} + +#[test] +#[ignore = "owned ShadowTLS stalled handshake container fixture required"] +fn stall() { + let f = fixture(); + initialize(&f); + let probe = ResourceProbe::default(); + let _case = RecordedCase::new("SHADOWTLS", "stall"); + let baseline = fault_counts(&f); + let seen = baseline["hello_seen"].as_u64().unwrap(); + let closed = baseline["client_closed"].as_u64().unwrap(); + assert_eq!(seen, closed); + let port = free_port(); + let core = probe.scope_sync(|| Core::start(&config(f["node"].clone(), port))); + let mut origin = Origin::new(&f, 13, false); + let mut client = login(port); + let mut request = vec![5, 1, 0]; + request.extend(address(origin.target, false)); + request.extend_from_slice(b"must-not-reach-origin"); + client.write_all(&request).unwrap(); + await_count(&f, "hello_seen", seen + 1); + let before = Instant::now(); + core.stop(); + assert!(before.elapsed() < Duration::from_secs(5)); + assert!(probe.snapshot().is_idle(), "{:?}", probe.snapshot()); + await_count(&f, "client_closed", closed + 1); + // A SOCKS failure response may precede EOF. It must never be a success. + let mut tail = Vec::new(); + match client.take(64).read_to_end(&mut tail) { + Ok(_) => {} + Err(error) => assert_eq!(error.kind(), io::ErrorKind::ConnectionReset), + } + assert!(tail.is_empty() || tail.len() >= 2 && tail[0] == 5 && tail[1] != 0); + origin.quiet(); + + let before = Instant::now(); + let response = probe.scope_sync(|| { + invoke( + "measureDelay", + None, + json!({"configYamls":[json!({"proxies":[f["node"]]}).to_string()], + "timeout":1,"url":format!("http://{}/",origin.target)}), + ) + }); + assert_eq!(response["results"][0]["success"], false); + assert!((Duration::from_millis(800)..Duration::from_secs(3)).contains(&before.elapsed())); + assert!(probe.snapshot().is_idle(), "{:?}", probe.snapshot()); + await_count(&f, "hello_seen", seen + 2); + await_count(&f, "client_closed", closed + 2); + origin.quiet(); + std::fs::write( + std::env::var("VCORE_SHADOWTLS_OBSERVATIONS").unwrap(), + json!({"stop_idle":true,"stop_handshake_cancelled":true, + "measure_deadline":true,"origin_connected":false,"closed_handshakes":2}) + .to_string(), + ) + .unwrap(); +} + +#[test] +#[ignore = "owned TCP-only ShadowTLS container fixture required"] +fn native_udp_disabled() { + let f = fixture(); + initialize(&f); + let probe = ResourceProbe::default(); + let _case = RecordedCase::new("SHADOWTLS", "native_udp_disabled"); + let port = free_port(); + let core = probe.scope_sync(|| Core::start(&config(f["node"].clone(), port))); + echo(port, &f); + let mut udp = Association::new(&f, port, false, false); + let packet = udp.packet(b"no-implicit-uot"); + udp.client.send_to(&packet, udp.relay).unwrap(); + udp.client + .set_read_timeout(Some(Duration::from_millis(500))) + .unwrap(); + let error = udp.client.recv_from(&mut [0; 128]).unwrap_err(); + assert!(matches!( + error.kind(), + io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut + )); + udp.origin.quiet(); + core.stop(); + assert!(probe.snapshot().is_idle(), "{:?}", probe.snapshot()); + udp.origin.quiet(); + std::fs::write( + std::env::var("VCORE_SHADOWTLS_OBSERVATIONS").unwrap(), + json!({"tcp_accepted":true,"udp_delivered":false,"stop_idle":true}).to_string(), + ) + .unwrap(); +} + +#[test] +#[ignore = "owned ShadowTLS fault container fixture required"] +fn corrupt() { + let f = fixture(); + initialize(&f); + let probe = ResourceProbe::default(); + let _case = RecordedCase::new("SHADOWTLS", "corrupt"); + let port = free_port(); + let core = probe.scope_sync(|| Core::start(&config(f["node"].clone(), port))); + let mut origin = Origin::new(&f, 13, false); + let mut client = connect(port, origin.target, false); + client.write_all(b"must-not-be-delivered-back").unwrap(); + origin.marker(b'A'); + match client.read(&mut [0; 1]) { + Ok(0) => {} + Err(error) => assert!(matches!( + error.kind(), + io::ErrorKind::ConnectionReset + | io::ErrorKind::UnexpectedEof + | io::ErrorKind::BrokenPipe + )), + other => panic!("corrupted authenticated response was delivered: {other:?}"), + } + core.stop(); + assert!(probe.snapshot().is_idle()); + origin.marker(b'D'); + origin.quiet(); + std::fs::write( + std::env::var("VCORE_SHADOWTLS_OBSERVATIONS").unwrap(), + json!({"origin_connected":true, "delivered_bytes":0, "stop_idle":true}).to_string(), + ) + .unwrap(); +} + +#[test] +#[ignore = "owned ShadowTLS container fixture required"] +fn policy() { + let f = fixture(); + initialize(&f); + let probe = ResourceProbe::default(); + let _case = RecordedCase::new("SHADOWTLS", "policy"); + let port = free_port(); + let core = probe.scope_sync(|| Core::start(&config(f["node"].clone(), port))); + let mut origin = Origin::new(&f, 13, false); + let success = f["expected_success"].as_bool().unwrap(); + let mut client = login(port); + let mut request = vec![5, 1, 0]; + request.extend(address(origin.target, false)); + // Pipeline business bytes to prove that failed identity cannot reach the + // business origin. A transport timeout is never an authentication success. + request.extend_from_slice(b"authenticated-business"); + client.write_all(&request).unwrap(); + if success { + reply(&mut client); + let mut bytes = [0; 22]; + client.read_exact(&mut bytes).unwrap(); + assert_eq!(&bytes, b"authenticated-business"); + origin.marker(b'A'); + } else { + let mut header = [0; 3]; + client.read_exact(&mut header).unwrap(); + assert_eq!(header[0], 5); + assert_ne!( + header[1], 0, + "authentication must fail before SOCKS success" + ); + assert_eq!(header[2], 0); + origin.quiet(); + } + core.stop(); + assert!(probe.snapshot().is_idle()); + if success { + origin.marker(b'D'); + } + origin.quiet(); + std::fs::write( + std::env::var("VCORE_SHADOWTLS_OBSERVATIONS").unwrap(), + json!({"accepted":success,"origin_connected":success,"stop_idle":true}).to_string(), + ) + .unwrap(); +} + +#[test] +#[ignore = "owned ShadowTLS container fixture required"] +fn data() { + data_gate(true); +} + +#[test] +#[ignore = "owned native ShadowTLS and SS container fixture required"] +fn native_tcp() { + data_gate(false); +} + +fn data_gate(native_udp: bool) { + let f = fixture(); + initialize(&f); + let probe = ResourceProbe::default(); + let _case = RecordedCase::new("SHADOWTLS", if native_udp { "data" } else { "native_tcp" }); + let port = free_port(); + let core = probe.scope_sync(|| Core::start(&config(f["node"].clone(), port))); + // Client-first avoids the documented official SS empty-first-write padding + // limitation. This is not used as evidence of server-first support. + let mut origin = Origin::new(&f, 13, false); + let mut client = connect(port, origin.target, false); + let mut upload = Sha256::new(); + let mut download = Sha256::new(); + for sequence in 0..2560_u32 { + let bytes: Vec = (0..4096).map(|n| ((n + sequence) % 251) as u8).collect(); + client.write_all(&bytes).unwrap(); + if sequence == 0 { + origin.marker(b'A'); + } + let mut reply = vec![0; bytes.len()]; + client.read_exact(&mut reply).unwrap(); + assert_eq!(reply, bytes); + upload.update(&bytes); + download.update(&reply); + } + assert_eq!(upload.finalize(), download.finalize()); + let mut udp = native_udp.then(|| Association::new(&f, port, false, false)); + if let Some(udp) = udp.as_mut() { + for size in [1, 64, 512, 1200, 4096] { + for sequence in 0..100_u8 { + udp.exchange(&vec![sequence; size]); + } + } + } + let before = Instant::now(); + core.stop(); + assert!(before.elapsed() < Duration::from_secs(5)); + assert!(probe.snapshot().is_idle(), "{:?}", probe.snapshot()); + runtime::assert_closed(&mut client); + origin.marker(b'D'); + origin.quiet(); + let observation = json!({"tcp_bytes_each_direction":10*1024*1024,"udp_packets":if native_udp {500} else {0},"udp_sizes":if native_udp {vec![1,64,512,1200,4096]} else {vec![]},"stop_idle":true}); + std::fs::write( + std::env::var("VCORE_SHADOWTLS_OBSERVATIONS").unwrap(), + observation.to_string(), + ) + .unwrap(); +} diff --git a/tests/vless_public/tuic.rs b/tests/vless_public/tuic.rs new file mode 100644 index 0000000..392a5f7 --- /dev/null +++ b/tests/vless_public/tuic.rs @@ -0,0 +1,292 @@ +//! TUIC public consumers. No protocol server is started on the host. +use super::*; +use vcore::resources::observation::ResourceProbe; + +fn save(value: Value) { + std::fs::write( + std::env::var("VCORE_TUIC_OBSERVATIONS").unwrap(), + value.to_string(), + ) + .unwrap(); +} + +#[test] +#[ignore = "owned TUIC UDP container fixture required"] +fn udp() { + let f = fixture(); + initialize(&f); + let _case = RecordedCase::new("TUIC-PUBLIC", "udp"); + let probe = ResourceProbe::default(); + let port = free_port(); + let core = probe.scope_sync(|| Core::start(&config(f["node"].clone(), port))); + let mut associations = Vec::new(); + let mut alternates = Vec::new(); + for (ipv6, domain) in [(false, false), (true, false), (false, true)] { + let mut udp = Association::new(&f, port, ipv6, domain); + let mut other = Origin::new(&f, if ipv6 { 6 } else { 4 }, ipv6); + for size in [0, 1, 64, 512, 1200, 4096, 16384] { + for sequence in 0..100_u8 { + std::mem::swap(&mut udp.origin, &mut other); + udp.exchange(&vec![sequence; size]); + } + } + associations.push(udp); + alternates.push(other); + } + echo(port, &f); + let before = Instant::now(); + core.stop(); + assert!(before.elapsed() < Duration::from_secs(5)); + assert!(probe.snapshot().is_idle(), "{:?}", probe.snapshot()); + for udp in &mut associations { + udp.origin.quiet(); + } + for origin in &mut alternates { + origin.quiet(); + } + save( + json!({"udp_packets":2100,"udp_sizes":[0,1,64,512,1200,4096,16384],"families":["ipv4","ipv6","domain"],"alternating_origins":true,"tcp_sibling":true,"stop_idle":true}), + ); +} + +#[test] +#[ignore = "owned TUIC container fixture required"] +fn tcp() { + let f = fixture(); + initialize(&f); + let _case = RecordedCase::new("TUIC-PUBLIC", "tcp"); + let probe = ResourceProbe::default(); + let port = free_port(); + let core = probe.scope_sync(|| Core::start(&config(f["node"].clone(), port))); + // Keep several logical streams live on one node, across address families. + let mut origins = Vec::new(); + let mut clients = Vec::new(); + for (ipv6, domain) in [(false, false), (true, false), (false, true)] { + let mut origin = Origin::new(&f, 13, ipv6); + let mut io = connect(port, origin.target, domain); + let mut upload = Sha256::new(); + let mut download = Sha256::new(); + for sequence in 0..2560_u32 { + let bytes: Vec = (0..4096).map(|i| ((i + sequence) % 251) as u8).collect(); + io.write_all(&bytes).unwrap(); + if sequence == 0 { + origin.marker(b'A'); + } + let mut reply = vec![0; bytes.len()]; + io.read_exact(&mut reply).unwrap(); + assert_eq!(reply, bytes); + upload.update(bytes); + download.update(reply); + } + assert_eq!(upload.finalize(), download.finalize()); + origins.push(origin); + clients.push(io); + } + // One client closes, its siblings remain functional on the same pool. + clients + .remove(0) + .shutdown(std::net::Shutdown::Both) + .unwrap(); + origins.remove(0).marker(b'D'); + for client in &mut clients { + client.write_all(b"sibling").unwrap(); + let mut bytes = [0; 7]; + client.read_exact(&mut bytes).unwrap(); + assert_eq!(&bytes, b"sibling"); + } + let before = Instant::now(); + core.stop(); + assert!(before.elapsed() < Duration::from_secs(5)); + assert!(probe.snapshot().is_idle(), "{:?}", probe.snapshot()); + for client in &mut clients { + runtime::assert_closed(client); + } + for origin in &mut origins { + origin.marker(b'D'); + origin.quiet(); + } + save( + json!({"families":["ipv4","ipv6","domain"],"tcp_bytes_each_family_each_direction":10*1024*1024,"sibling_survives":true,"stop_idle":true}), + ); +} + +#[test] +#[ignore = "owned TUIC rejection container fixture required"] +fn rejected() { + let f = fixture(); + initialize(&f); + let _case = RecordedCase::new("TUIC-PUBLIC", "rejected"); + let probe = ResourceProbe::default(); + let port = free_port(); + let mut yaml = config(f["node"].clone(), port); + if let Some(upstream) = f.get("upstream") { + yaml["proxies"] + .as_array_mut() + .unwrap() + .push(upstream.clone()); + yaml["proxies"][0]["dialer-proxy"] = json!("hop"); + } + let core = probe.scope_sync(|| Core::start(&yaml)); + let mut origin = Origin::new(&f, 13, false); + let mut client = login(port); + let mut request = vec![5, 1, 0]; + request.extend(address(origin.target, false)); + request.extend_from_slice(b"must-not-reach-origin"); + client.write_all(&request).unwrap(); + let mut header = [0; 3]; + match client.read_exact(&mut header) { + Ok(_) => { + assert_eq!(header[0], 5); + assert_eq!(header[2], 0); + if header[1] == 0 { + // TUIC has no auth ACK: local SOCKS success can precede rejection. + let mut atyp = [0]; + client.read_exact(&mut atyp).unwrap(); + let length = match atyp[0] { + 1 => 6, + 4 => 18, + _ => panic!("invalid SOCKS reply"), + }; + client.read_exact(&mut vec![0; length]).unwrap(); + runtime::assert_closed(&mut client); + } + } + Err(error) => assert!(matches!( + error.kind(), + io::ErrorKind::UnexpectedEof | io::ErrorKind::ConnectionReset + )), + } + origin.quiet(); + let before = Instant::now(); + core.stop(); + assert!(before.elapsed() < Duration::from_secs(5)); + assert!(probe.snapshot().is_idle(), "{:?}", probe.snapshot()); + origin.quiet(); + save(json!({"origin_connected":false,"received_business_bytes":0,"stop_idle":true})); +} + +#[test] +#[ignore = "owned TUIC business UDP policy fixture required"] +fn udp_disabled() { + let f = fixture(); + initialize(&f); + let _case = RecordedCase::new("TUIC-PUBLIC", "udp_disabled"); + assert_eq!(f["node"]["udp"], false); + let probe = ResourceProbe::default(); + let port = free_port(); + let core = probe.scope_sync(|| Core::start(&config(f["node"].clone(), port))); + echo(port, &f); + let mut udp = Association::new(&f, port, false, false); + udp.client + .send_to(&udp.packet(b"disabled"), udp.relay) + .unwrap(); + udp.client + .set_read_timeout(Some(Duration::from_millis(500))) + .unwrap(); + let error = udp.client.recv_from(&mut [0; 128]).unwrap_err(); + assert!(matches!( + error.kind(), + io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut + )); + udp.origin.quiet(); + core.stop(); + assert!(probe.snapshot().is_idle(), "{:?}", probe.snapshot()); + udp.origin.quiet(); + save(json!({"udp_packets":0,"tcp_works":true,"stop_idle":true})); +} + +#[test] +#[ignore = "owned TUIC upstream and restart fixture required"] +fn group() { + let f = fixture(); + initialize(&f); + let _case = RecordedCase::new("TUIC-PUBLIC", "group"); + let probe = ResourceProbe::default(); + let port = free_port(); + let controller = free_port(); + let mut yaml = config(f["node"].clone(), port); + yaml["proxies"] + .as_array_mut() + .unwrap() + .push(f["upstream"].clone()); + yaml["proxies"][0]["dialer-proxy"] = json!("outer"); + yaml["proxy-groups"] = json!([ + {"name":"outer","type":"select","proxies":["inner"]}, + {"name":"inner","type":"select","proxies":["hop","DIRECT","REJECT"]} + ]); + yaml["external-controller"] = json!(format!("127.0.0.1:{controller}")); + yaml["secret"] = json!("fixture-only"); + let core = probe.scope_sync(|| Core::start(&yaml)); + let (mut old, mut origin) = runtime::live(port, &f); + let mut udp = Association::new(&f, port, false, false); + udp.exchange(b"old-path"); + runtime::select(controller, "REJECT"); + runtime::exchange(&mut old, b"old-stream"); + // Logical flows on the already established QUIC pool retain its path. + echo(port, &f); + let mut pooled = Association::new(&f, port, false, false); + pooled.exchange(b"new-logical-existing-pool"); + let mut control = socket(f["restart_control"].as_str().unwrap().parse().unwrap()); + control.write_all(b"R").unwrap(); + let mut ack = [0]; + control.read_exact(&mut ack).unwrap(); + assert_eq!(ack, [b'R']); + old.set_read_timeout(Some(Duration::from_secs(35))).unwrap(); + runtime::assert_closed(&mut old); + origin.marker(b'D'); + let mut denied_origin = Origin::new(&f, 13, false); + let mut denied = login(port); + let mut connect = vec![5, 1, 0]; + connect.extend(address(denied_origin.target, false)); + connect.extend_from_slice(b"no-fallback"); + denied.write_all(&connect).unwrap(); + let mut reply = [0; 3]; + denied.read_exact(&mut reply).unwrap(); + assert_eq!(reply[0], 5); + assert_ne!(reply[1], 0); + denied_origin.quiet(); + runtime::select(controller, "DIRECT"); + echo(port, &f); + let mut fresh = Association::new(&f, port, false, false); + fresh.exchange(b"new-physical-direct"); + let start = Instant::now(); + core.stop(); + assert!(start.elapsed() < Duration::from_secs(5)); + assert!(probe.snapshot().is_idle(), "{:?}", probe.snapshot()); + udp.origin.quiet(); + pooled.origin.quiet(); + fresh.origin.quiet(); + denied_origin.quiet(); + drop((old, origin, udp, pooled, fresh, denied, denied_origin)); + + let mut measure_origin = Origin::new(&f, 14, false); + let result=probe.scope_sync(||invoke("measureDelay",None,json!({"configYamls":[json!({"proxies":[f["node"]]}).to_string()],"timeout":5,"url":format!("http://{}/",measure_origin.target)}))); + assert_eq!(result["results"][0]["success"], true); + measure_origin.marker(b'A'); + measure_origin.marker(b'D'); + let rejected = invoke( + "measureDelay", + None, + json!({"configYamls":[json!({"proxies":[f["node"]],"proxy-groups":[{"name":"group","type":"select","proxies":["peer"]}]}).to_string()],"timeout":5,"url":format!("http://{}/",measure_origin.target)}), + ); + assert_eq!(rejected["results"][0]["success"], false); + measure_origin.quiet(); + assert!(probe.snapshot().is_idle()); + drop(measure_origin); + let occupied = UdpSocket::bind((Ipv4Addr::LOCALHOST, port)).unwrap(); + let prepared = probe.scope_sync(|| Core::prepare(&yaml)); + assert_eq!( + probe.scope_sync(|| invoke_response("start", prepared.0.as_deref(), json!({})))["success"], + false + ); + prepared.stop(); + drop(occupied); + assert!(probe.snapshot().is_idle()); + let rebuilt = probe.scope_sync(|| Core::start(&yaml)); + echo(port, &f); + rebuilt.stop(); + assert!(probe.snapshot().is_idle()); + save( + json!({"nested_select":true,"pooled_path_retained":true,"explicit_rebuild":true,"reject_no_fallback":true,"new_direct":true,"node_measure":true,"group_measure_rejected":true,"rollback":true,"stop_idle":true}), + ); +} diff --git a/tests/vless_public/uot.rs b/tests/vless_public/uot.rs new file mode 100644 index 0000000..c7a52b4 --- /dev/null +++ b/tests/vless_public/uot.rs @@ -0,0 +1,186 @@ +//! Public UoT consumers. Every protocol peer, DNS and origin is container-owned. +use super::*; +use vcore::resources::observation::ResourceProbe; + +fn no_native_udp(f: &Value) { + let mut observer = socket(f["udp_observer"].as_str().unwrap().parse().unwrap()); + observer.write_all(b"?").unwrap(); + let counts: Value = serde_json::from_reader(observer.take(4096)).unwrap(); + assert_eq!(counts["native_udp_packets"], 0); + assert!( + counts["ports"] + .as_array() + .unwrap() + .contains(&f["node"]["port"]) + ); +} + +fn save(value: Value) { + std::fs::write( + std::env::var("VCORE_UOT_OBSERVATIONS").unwrap(), + value.to_string(), + ) + .unwrap(); +} + +#[test] +#[ignore = "owned UoT container fixture required"] +fn data() { + let f = fixture(); + initialize(&f); + let _case = RecordedCase::new("UOT-PUBLIC", "data"); + let probe = ResourceProbe::default(); + let port = free_port(); + let mut dns_origin = Origin::new(&f, 17, false); + let mut yaml = config(f["node"].clone(), port); + if let Some(upstream) = f.get("upstream") { + assert_eq!(upstream["udp"], false); + yaml["proxies"] + .as_array_mut() + .unwrap() + .push(upstream.clone()); + yaml["proxies"][0]["dialer-proxy"] = json!("hop"); + } + dns(&mut yaml, &dns_origin, "DIRECT"); + let core = probe.scope_sync(|| Core::start(&yaml)); + echo(port, &f); + let mut associations = Vec::new(); + let mut alternates = Vec::new(); + for (ipv6, domain) in [(false, false), (true, false), (false, true)] { + let mut association = Association::new(&f, port, ipv6, domain); + let mut alternate = Origin::new(&f, if ipv6 { 6 } else { 4 }, ipv6); + for size in [0, 1, 64, 512, 1200, 4096, 16_384] { + for sequence in 0..100_u8 { + std::mem::swap(&mut association.origin, &mut alternate); + association.exchange(&vec![sequence; size]); + } + } + // The official Mihomo UoT reader uses a 16 KiB packet buffer. One byte + // beyond it fails at that peer; this is not VCore's u16 codec ceiling. + let oversize = vec![7; 16_385]; + association + .client + .send_to(&association.packet(&oversize), association.relay) + .unwrap(); + association.origin.quiet(); + association + .client + .set_read_timeout(Some(Duration::from_millis(100))) + .unwrap(); + let error = association.client.recv_from(&mut [0; 32]).unwrap_err(); + assert!(matches!( + error.kind(), + io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut + )); + association.client.set_read_timeout(Some(TIMEOUT)).unwrap(); + associations.push(association); + alternates.push(alternate); + } + let before = Instant::now(); + core.stop(); + assert!(before.elapsed() < Duration::from_secs(5)); + assert!(probe.snapshot().is_idle(), "{:?}", probe.snapshot()); + // The controlled resolver accepts only this business name. Internal UoT + // magic reaching DNS would make the fixture reject the request. + let mut header = [0; 4]; + dns_origin.observer.read_exact(&mut header).unwrap(); + let mut question = vec![0; u16::from_be_bytes([header[0], header[1]]) as usize]; + dns_origin.observer.read_exact(&mut question).unwrap(); + assert_eq!(&question[12..], b"\x0dvcore-fixture\x04test\0\0\x01\0\x01"); + for association in &mut associations { + association.origin.quiet(); + } + for origin in &mut alternates { + origin.quiet(); + } + no_native_udp(&f); + save(json!({ + "udp_packets":2100,"udp_sizes":[0,1,64,512,1200,4096,16384], + "families":["ipv4","ipv6","domain"],"alternating_origins":true, + "controlled_dns":true,"tcp_regression":true,"stop_idle":true, + "tcp_only_upstream":f.get("upstream").is_some(), + "peer_oversize_rejected":true,"native_udp_packets":0 + })); +} + +#[test] +#[ignore = "owned UoT TCP-only upstream fixture required"] +fn group() { + let f = fixture(); + initialize(&f); + let _case = RecordedCase::new("UOT-PUBLIC", "group"); + let probe = ResourceProbe::default(); + let port = free_port(); + let controller = free_port(); + let mut yaml = config(f["node"].clone(), port); + yaml["proxies"] + .as_array_mut() + .unwrap() + .push(f["upstream"].clone()); + yaml["proxies"][0]["dialer-proxy"] = json!("outer"); + yaml["proxy-groups"] = json!([ + {"name":"outer","type":"select","proxies":["inner"]}, + {"name":"inner","type":"select","proxies":["hop","DIRECT","REJECT"]} + ]); + yaml["external-controller"] = json!(format!("127.0.0.1:{controller}")); + yaml["secret"] = json!("fixture-only"); + let core = probe.scope_sync(|| Core::start(&yaml)); + let mut existing = Association::new(&f, port, false, false); + existing.exchange(b"initial-hop"); + runtime::select(controller, "REJECT"); + existing.exchange(b"old-association-snapshot"); + let mut rejected = Association::new(&f, port, false, false); + rejected + .client + .send_to(&rejected.packet(b"must-not-fallback"), rejected.relay) + .unwrap(); + rejected.origin.quiet(); + runtime::select(controller, "DIRECT"); + let mut direct = Association::new(&f, port, false, false); + direct.exchange(b"new-direct-association"); + existing.exchange(b"still-original-hop"); + core.stop(); + assert!(probe.snapshot().is_idle(), "{:?}", probe.snapshot()); + existing.origin.quiet(); + direct.origin.quiet(); + rejected.origin.quiet(); + no_native_udp(&f); + save( + json!({"nested_select":true,"old_association_snapshot":true,"new_direct":true, + "reject_no_fallback":true,"native_udp_packets":0,"stop_idle":true}), + ); +} + +#[test] +#[ignore = "owned UoT negative peer fixture required"] +fn rejected() { + let f = fixture(); + initialize(&f); + let _case = RecordedCase::new("UOT-PUBLIC", "rejected"); + let probe = ResourceProbe::default(); + let port = free_port(); + let core = probe.scope_sync(|| Core::start(&config(f["node"].clone(), port))); + let mut association = Association::new(&f, port, false, false); + let bytes = association.packet(b"must-not-reach-origin"); + association + .client + .send_to(&bytes, association.relay) + .unwrap(); + association + .client + .set_read_timeout(Some(Duration::from_millis(500))) + .unwrap(); + let error = association.client.recv_from(&mut [0; 128]).unwrap_err(); + assert!(matches!( + error.kind(), + io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut + )); + association.origin.quiet(); + let before = Instant::now(); + core.stop(); + assert!(before.elapsed() < Duration::from_secs(5)); + assert!(probe.snapshot().is_idle(), "{:?}", probe.snapshot()); + association.origin.quiet(); + no_native_udp(&f); + save(json!({"origin_packets":0,"received_packets":0,"native_udp_packets":0,"stop_idle":true})); +} diff --git a/tests/vmess_lifecycle.rs b/tests/vmess_lifecycle.rs index 2379c32..151c893 100644 --- a/tests/vmess_lifecycle.rs +++ b/tests/vmess_lifecycle.rs @@ -47,14 +47,33 @@ async fn vmess_all_handshakes_keep_the_original_deadline_and_join_cancelled_io() "vmess_all_handshakes_keep_the_original_deadline_and_join_cancelled_io", ); use tokio::io::{AsyncReadExt, AsyncWriteExt}; - for mode in ["tcp", "tls", "ws", "grpc", "http", "h2"] { - let mut node = serde_json::json!({"name":"edge","type":"vmess","server":"fixture.invalid","port":443,"uuid":"07070707-0707-0707-0707-070707070707","network":if mode=="tls" {"tcp"}else{mode}}); + for mode in [ + "tcp", + "tls", + "ws", + "grpc", + "http", + "h2", + "upgrade", + "upgrade-fast", + ] { + let network = if mode == "tls" { + "tcp" + } else if mode.starts_with("upgrade") { + "ws" + } else { + mode + }; + let mut node = serde_json::json!({"name":"edge","type":"vmess","server":"fixture.invalid","port":443,"uuid":"07070707-0707-0707-0707-070707070707","network":network}); match mode { "tls" => { node["tls"] = serde_json::json!(true); } "grpc" => node["grpc-opts"] = serde_json::json!({"grpc-service-name":"edge"}), "h2" => node["h2-opts"] = serde_json::json!({"host":["fixture.invalid"]}), + "upgrade" | "upgrade-fast" => { + node["ws-opts"] = serde_json::json!({"v2ray-http-upgrade":true,"v2ray-http-upgrade-fast-open":mode=="upgrade-fast"}) + } _ => {} } let parsed = Config::parse_yaml( diff --git a/tests/xray_interop.rs b/tests/xray_interop.rs index 1d60fe0..65ce6bf 100644 --- a/tests/xray_interop.rs +++ b/tests/xray_interop.rs @@ -44,7 +44,7 @@ fn sole_vless(config: &Config) -> &VlessOutboundConfig { ProxyProtocol::AnyTls(_) => panic!("interop config must contain VLESS"), ProxyProtocol::Shadowsocks(_) => panic!("interop config must contain VLESS"), ProxyProtocol::Trojan(_) => panic!("interop config must contain VLESS"), - ProxyProtocol::Vmess(_) | ProxyProtocol::Hysteria2(_) => { + ProxyProtocol::Vmess(_) | ProxyProtocol::Hysteria2(_) | ProxyProtocol::Tuic(_) => { panic!("interop config must contain VLESS") } }