diff --git a/ios/.gitattributes b/ios/.gitattributes index 2de85a2..46f7310 100644 --- a/ios/.gitattributes +++ b/ios/.gitattributes @@ -1,10 +1,10 @@ -* text=auto -*.swift text eol=lf -*.sh text eol=lf -*.py text eol=lf -*.md text eol=lf -*.yml text eol=lf -*.plist text eol=lf -*.json text eol=lf -*.dat binary -*.png binary +* text=auto +*.swift text eol=lf +*.sh text eol=lf +*.py text eol=lf +*.md text eol=lf +*.yml text eol=lf +*.plist text eol=lf +*.json text eol=lf +*.dat binary +*.png binary diff --git a/ios/.gitignore b/ios/.gitignore index 11908b3..3289e78 100644 --- a/ios/.gitignore +++ b/ios/.gitignore @@ -1,15 +1,15 @@ -DerivedData/ -build/ -*.xcarchive -*.ipa -*.mobileprovision -*.p12 -*.cer -xcuserdata/ -.DS_Store -Vendor/libxray-apple-cgo-v26.7.28.zip -Vendor/libxray-apple-cgo-v26.7.28/ -Vendor/libXray-source-v26.7.28/ -Vendor/Xray-core-source/ -Vendor/LibXray.xcframework/ -BuildArtifacts/ +DerivedData/ +build/ +*.xcarchive +*.ipa +*.mobileprovision +*.p12 +*.cer +xcuserdata/ +.DS_Store +Vendor/libxray-apple-cgo-v26.7.28.zip +Vendor/libxray-apple-cgo-v26.7.28/ +Vendor/libXray-source-v26.7.28/ +Vendor/Xray-core-source/ +Vendor/LibXray.xcframework/ +BuildArtifacts/ diff --git a/ios/App/AppState.swift b/ios/App/AppState.swift index 7d5f8e1..bc58bb9 100644 --- a/ios/App/AppState.swift +++ b/ios/App/AppState.swift @@ -143,7 +143,7 @@ final class AppState: ObservableObject { let configJSON = try response.configJSONString() if !transport.domainOnly, let endpoint = ProxyTransportPolicy.authorizedInternalEndpoint(response: response) { - let reachable = await InternalIPProbe.isReachable(endpoint.address) + let reachable = await InternalIPProbe.isReachable(endpoint.address, port: endpoint.port) try Task.checkCancellation() if reachable { message = "正在通过内部 IP 连接 \(response.node.displayName)…" diff --git a/ios/App/ContentView.swift b/ios/App/ContentView.swift index 30dd634..785a59a 100644 --- a/ios/App/ContentView.swift +++ b/ios/App/ContentView.swift @@ -179,7 +179,7 @@ private struct RegistrationPrompt: View { var prompt = AttributedString("还没有账号?") prompt.foregroundColor = UCVLColors.muted var link = AttributedString("注册新用户") - link.link = URL(string: "https://vpn.example.invalid/register/") + link.link = URL(string: "https://vpn.ucvl.cn/register/") link.foregroundColor = UCVLColors.royal link.font = .footnote.weight(.semibold) prompt.append(link) diff --git a/ios/App/InternalIPProbe.swift b/ios/App/InternalIPProbe.swift index 840368a..ea09df8 100644 --- a/ios/App/InternalIPProbe.swift +++ b/ios/App/InternalIPProbe.swift @@ -2,20 +2,20 @@ import Darwin import Foundation enum InternalIPProbe { - static func isReachable(_ address: String) async -> Bool { - guard NetworkAddress.isAuthorizedInternalIPv4(address), !Task.isCancelled else { return false } - let attempt = PingAttempt() + static func isReachable(_ address: String, port: Int) async -> Bool { + guard NetworkAddress.isAuthorizedInternalIPv4(address), (1...65535).contains(port), !Task.isCancelled else { return false } + let attempt = EndpointAttempt() return await withTaskCancellationHandler(operation: { await withCheckedContinuation { continuation in DispatchQueue.global(qos: .utility).async { - continuation.resume(returning: attempt.run(address)) + continuation.resume(returning: attempt.run(address, port: UInt16(port))) } } }, onCancel: { attempt.cancel() }) } } -private final class PingAttempt: @unchecked Sendable { +private final class EndpointAttempt: @unchecked Sendable { private let lock = NSLock() private var cancelled = false @@ -31,12 +31,11 @@ private final class PingAttempt: @unchecked Sendable { return cancelled } - func run(_ address: String) -> Bool { - let deadline = DispatchTime.now().uptimeNanoseconds + 1_000_000_000 + func run(_ address: String, port: UInt16) -> Bool { + let deadline = DispatchTime.now().uptimeNanoseconds + 5_000_000_000 guard !isCancelled else { return false } - // Darwin datagram ICMP is unprivileged. Never run a shell, query a VPN - // service or replace ICMP with a TCP/HTTP test. - let descriptor = Darwin.socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP) + // Connect to the exact authorized endpoint using the system route. + let descriptor = Darwin.socket(AF_INET, SOCK_STREAM, IPPROTO_TCP) guard descriptor >= 0 else { return false } defer { Darwin.close(descriptor) } let flags = fcntl(descriptor, F_GETFL, 0) @@ -45,19 +44,16 @@ private final class PingAttempt: @unchecked Sendable { var destination = sockaddr_in() destination.sin_len = UInt8(MemoryLayout.size) destination.sin_family = sa_family_t(AF_INET) + destination.sin_port = port.bigEndian guard address.withCString({ inet_pton(AF_INET, $0, &destination.sin_addr) }) == 1 else { return false } let connected = withUnsafePointer(to: &destination) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { Darwin.connect(descriptor, $0, socklen_t(MemoryLayout.size)) } } - guard connected == 0, !isCancelled else { return false } - - let payload = Array(UUID().uuidString.utf8) - let packet = ICMPEchoPacket.request(identifier: UInt16.random(in: 1...UInt16.max), payload: payload) - let sent = packet.withUnsafeBytes { Darwin.write(descriptor, $0.baseAddress, $0.count) } - guard sent == packet.count else { return false } - var descriptorState = pollfd(fd: descriptor, events: Int16(POLLIN), revents: 0) + if connected == 0 { return !isCancelled } + guard errno == EINPROGRESS || errno == EINTR else { return false } + var descriptorState = pollfd(fd: descriptor, events: Int16(POLLOUT), revents: 0) while !isCancelled { let now = DispatchTime.now().uptimeNanoseconds guard now < deadline else { return false } @@ -68,26 +64,11 @@ private final class PingAttempt: @unchecked Sendable { return false } guard ready > 0 else { continue } - guard descriptorState.revents & Int16(POLLIN) != 0 else { return false } - var buffer = [UInt8](repeating: 0, count: 4096) - var sender = sockaddr_in() - var senderSize = socklen_t(MemoryLayout.size) - let received = withUnsafeMutablePointer(to: &sender) { senderPointer in - senderPointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { socketPointer in - buffer.withUnsafeMutableBytes { - Darwin.recvfrom(descriptor, $0.baseAddress, $0.count, 0, socketPointer, &senderSize) - } - } - } - guard received > 0 else { - if errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR { continue } - return false - } - if sender.sin_family == sa_family_t(AF_INET), - sender.sin_addr.s_addr == destination.sin_addr.s_addr, - ICMPEchoPacket.isReply(Array(buffer.prefix(received)), payload: payload) { - return !isCancelled && DispatchTime.now().uptimeNanoseconds < deadline - } + var socketError: Int32 = 0 + var size = socklen_t(MemoryLayout.size) + return descriptorState.revents & Int16(POLLOUT) != 0 + && getsockopt(descriptor, SOL_SOCKET, SO_ERROR, &socketError, &size) == 0 + && socketError == 0 && !isCancelled && DispatchTime.now().uptimeNanoseconds < deadline } return false } diff --git a/ios/App/PlatformAPI.swift b/ios/App/PlatformAPI.swift index 7a0c5d2..52ea8b4 100644 --- a/ios/App/PlatformAPI.swift +++ b/ios/App/PlatformAPI.swift @@ -4,7 +4,7 @@ import UIKit actor PlatformAPI { static let shared = PlatformAPI() - private let baseURL = URL(string: "https://vpn.example.invalid/")! + private let baseURL = URL(string: "https://vpn.ucvl.cn/")! private let session: URLSession private let decoder = JSONDecoder() private let encoder = JSONEncoder() @@ -16,7 +16,7 @@ actor PlatformAPI { configuration.waitsForConnectivity = true configuration.httpAdditionalHeaders = [ "Accept": "application/json", - "User-Agent": "UCVL-Zonghengjia/1.0.3 iOS", + "User-Agent": "UCVL-Zonghengjia/1.0.4 iOS", ] session = URLSession(configuration: configuration) } @@ -27,7 +27,7 @@ actor PlatformAPI { "password": password, "device_id": SecureStore.deviceID(), "device_name": await MainActor.run { UIDevice.current.name }, - "app_version": Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "1.0.3", + "app_version": Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "1.0.4", "platform": "ios", ] return try await send( @@ -66,10 +66,6 @@ actor PlatformAPI { } func verifyProxyEgress() async throws { - let endpoints = [ - URL(string: "https://api.openai.com/v1/models")!, - URL(string: "https://chatgpt.com/api/auth/session")!, - ] let configuration = URLSessionConfiguration.ephemeral configuration.timeoutIntervalForRequest = 12 configuration.timeoutIntervalForResource = 15 @@ -78,27 +74,38 @@ actor PlatformAPI { let verifier = URLSession(configuration: configuration) defer { verifier.invalidateAndCancel() } - for endpoint in endpoints { - var request = URLRequest(url: endpoint) - request.httpMethod = "GET" - request.setValue("no-cache", forHTTPHeaderField: "Cache-Control") - do { - let (_, response) = try await verifier.data(for: request) - if let http = response as? HTTPURLResponse, (200..<500).contains(http.statusCode) { - return + let reachable = await withTaskGroup(of: Bool.self) { probes in + for endpoint in TunnelConfigurationBuilder.egressProbeURLs { + probes.addTask { + var request = URLRequest(url: endpoint) + request.setValue("no-cache", forHTTPHeaderField: "Cache-Control") + do { + let (_, response) = try await verifier.data(for: request) + guard let response = response as? HTTPURLResponse else { return false } + return response.url?.scheme == "https" && response.url?.host == endpoint.host + && (100...599).contains(response.statusCode) + } catch { + return false + } } - } catch { - continue } + for await success in probes where success { + probes.cancelAll() + return true + } + return false + } + try Task.checkCancellation() + guard reachable else { + throw UCVLError.connection("当前入口未通过代理 HTTPS 出口验证。") } - throw UCVLError.connection("当前节点未通过 OpenAI/ChatGPT 出口验证,正在切换其它节点。") } func resolvePublicIPv4(host: String) async throws -> String { if NetworkAddress.isPublicIPv4(host) { return host } // 001/002 是后台节点名称。NPM TCP Stream 依靠 11081/11082 等端口 // 分流,不要求每个节点子域名都单独发布 A 记录;解析不到时使用统一入口。 - let candidateHosts = host == "vpn.example.invalid" ? [host] : [host, "vpn.example.invalid"] + let candidateHosts = host == "vpn.ucvl.cn" ? [host] : [host, "vpn.ucvl.cn"] let resolvers = [ "https://dns.alidns.com/resolve", "https://doh.pub/resolve", @@ -131,7 +138,7 @@ actor PlatformAPI { } } } - throw UCVLError.connection("无法取得 NPM 入口 vpn.example.invalid 的真实公网 IPv4;已拒绝 Fake-IP/内网地址。") + throw UCVLError.connection("无法取得 NPM 入口 vpn.ucvl.cn 的真实公网 IPv4;已拒绝 Fake-IP/内网地址。") } func logout(token: String) async { diff --git a/ios/App/UCVLZonghengjia.entitlements b/ios/App/UCVLZonghengjia.entitlements index c3f437e..a357b39 100644 --- a/ios/App/UCVLZonghengjia.entitlements +++ b/ios/App/UCVLZonghengjia.entitlements @@ -1,10 +1,10 @@ - - - - - com.apple.developer.networking.networkextension - - packet-tunnel-provider - - - + + + + + com.apple.developer.networking.networkextension + + packet-tunnel-provider + + + diff --git a/ios/App/VPNController.swift b/ios/App/VPNController.swift index 6170eb4..e08e08b 100644 --- a/ios/App/VPNController.swift +++ b/ios/App/VPNController.swift @@ -1,3 +1,4 @@ +import Combine import Foundation import NetworkExtension diff --git a/ios/PacketTunnel/PacketTunnel.entitlements b/ios/PacketTunnel/PacketTunnel.entitlements index c3f437e..a357b39 100644 --- a/ios/PacketTunnel/PacketTunnel.entitlements +++ b/ios/PacketTunnel/PacketTunnel.entitlements @@ -1,10 +1,10 @@ - - - - - com.apple.developer.networking.networkextension - - packet-tunnel-provider - - - + + + + + com.apple.developer.networking.networkextension + + packet-tunnel-provider + + + diff --git a/ios/PacketTunnel/PacketTunnelProvider.swift b/ios/PacketTunnel/PacketTunnelProvider.swift index e553730..8dd7234 100644 --- a/ios/PacketTunnel/PacketTunnelProvider.swift +++ b/ios/PacketTunnel/PacketTunnelProvider.swift @@ -113,8 +113,8 @@ final class PacketTunnelProvider: NEPacketTunnelProvider { let settings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: remoteAddress) let ipv4 = NEIPv4Settings(addresses: ["198.18.0.1"], subnetMasks: ["255.255.0.0"]) ipv4.includedRoutes = [NEIPv4Route.default()] - if Self.isIPv4Address(remoteAddress) { - ipv4.excludedRoutes = [NEIPv4Route(destinationAddress: remoteAddress, subnetMask: "255.255.255.255")] + ipv4.excludedRoutes = NetworkAddress.tunnelUnderlayIPv4(remoteAddress).map { + NEIPv4Route(destinationAddress: $0, subnetMask: "255.255.255.255") } settings.ipv4Settings = ipv4 @@ -149,11 +149,6 @@ final class PacketTunnelProvider: NEPacketTunnelProvider { return nil } - private static func isIPv4Address(_ value: String) -> Bool { - var address = in_addr() - return value.withCString { inet_pton(AF_INET, $0, &address) } == 1 - } - private static func resolveIPv4Address(_ host: String) throws -> String { if NetworkAddress.isPublicIPv4(host) { return host } diff --git a/ios/README.md b/ios/README.md index 8300369..f060e8d 100644 --- a/ios/README.md +++ b/ios/README.md @@ -1,29 +1,29 @@ -# 纵横家 iPhone / iPad 1.0.3 源码候选版 +# 纵横家 iPhone / iPad 1.0.4 源码候选版 -公司内部 Apple 系统 VPN 客户端源码,版本 `1.0.3`,构建号 `10003`,主应用 Bundle ID 为 `cn.toplc.zonghengjia`,Packet Tunnel 扩展 Bundle ID 为 `cn.toplc.zonghengjia.PacketTunnel`。 +公司内部 Apple 系统 VPN 客户端源码,版本 `1.0.4`,构建号 `10004`,主应用 Bundle ID 为 `cn.toplc.zonghengjia`,Packet Tunnel 扩展 Bundle ID 为 `cn.toplc.zonghengjia.PacketTunnel`。 -当前没有可安装的 IPA;以下功能指已编写的实现,不代表通过 Xcode 编译或 iPhone 真机验收。1.0.3 增加后台授权内部 IP 的 ICMP Ping 探测、同节点公网回退和本次连接的公网路径保持。平台/本机错误继续停止尝试,401/403 清理失效登录状态。对应 XCTest 已编写,但本机构建环境不能执行。 +1.0.4 源码更新了公司平台域名、已授权代理端口检测、HTTPS 出口验证和 Tailscale 底层路由。当前验证范围为源码静态审计。Xcode 编译、签名、IPA 导出与 iPhone 真机验证待完成。 登录与主页统一“纵横家”品牌,使用与 Windows 相同的原创山水背景及50%白色卡片;注册提示与链接保持同行自然换行,适配手机键盘和大字体。后台配置节点未提供 `status` 时按“未知”解析,避免有效配置在连接前解码失败;不把未知状态冒充在线。Xcode 的 Swift 语言模式为 `5.0`,它与编译器版本号不同。 ## 源码功能 -- 使用 `vpn.example.invalid` 平台账号登录与设备授权。 +- 使用 `vpn.ucvl.cn` 平台账号登录与设备授权。 - 展示套餐、流量、当前实际工作节点和代理模式;不向用户提供节点选择。 - 支持 AI 智能代理、全局代理与本地直连。 - 请求后台 `vpn-ai` 自动分配节点;连接失败时排除故障节点并重新分配,最多尝试三次。 -- Apple 系统 VPN 建立后使用 OpenAI / ChatGPT HTTPS 入口验证实际出口,未通过就自动恢复本地网络并切换节点。 +- Apple 系统 VPN 建立后,通过授权代理并行验证 Cloudflare、OpenAI 和 ChatGPT HTTPS 响应。内网出口验证失败时优先尝试同节点公网入口。 - 使用 Apple `NEPacketTunnelProvider` 实现 iPhone/iPad 整机代理。 - 断开时由 iOS 自动撤销虚拟路由并恢复原网络。 - 登录令牌通过 iOS Keychain 保存。 - 内嵌官方 libXray `v26.7.28` Apple XCFramework,支持 VLESS Reality。 -- 仅当后台 `config_contract=2` 为当前同一节点下发有效的 `tailscale_endpoint`、公开连接范围及兼容 VLESS Reality 配置时,先对授权内部 IP 做限时 ICMP Ping;收到匹配回复后才尝试该内部入口。任意私网地址、其它节点入口或用户自行输入的地址不会因此获得授权。 -- 内部 Ping 不通或内部传输失败时,先使用同一节点的原公网配置;一旦选用公网,本次用户发起的连接及其节点重试都保持公网路径,不自动切回内部入口。公网节点连接失败后才继续原有节点切换策略。 -- 内部 IP 路径使用系统现有的可达路由;客户端不登录、启动、停止或管理 Tailscale。没有承诺 iOS 上两个 Packet Tunnel 能同时运行,Ping 成功也不代表启动本应用 VPN 后仍然可达;后者仍须完成代理出口验证,失败则按上述规则回退。 -- 001/002 等节点的公网配置通过同一 NPM TCP Stream 入口、由端口分流,不要求各节点子域名单独发布 A 记录。需要公网路径时先解析节点域名,解析不到就通过阿里/腾讯 DoH 解析统一入口 `vpn.example.invalid` 的真实公网 IPv4;公网路径仍拒绝 Clash Fake-IP (`198.18.0.0/15`)、私网及 Tailscale 地址。 +- 仅当后台 `config_contract=2` 为当前节点下发有效的 `tailscale_endpoint`、公开连接范围及兼容 VLESS Reality 配置时,使用系统当前路由对已授权的 IP 和代理端口做最长 5 秒的 TCP 验证。 +- 端口或代理出口验证失败时,先尝试同一节点的公网入口。选用公网后,本次连接及其节点重试继续使用公网路径。 +- 使用内网入口时,隧道排除管理地址、已授权内网地址及三个公司 DERP 中继的 IPv4 主机路由,Xray 对 Tailscale 控制和中继域名优先直连。Tailscale 与 iOS 系统 VPN 同时运行的实际效果待真机验证。 +- 各节点的公网配置通过青岛 NPM TCP Stream 按端口转发。后台未下发统一网关时,先解析节点域名,再通过阿里或腾讯 DoH 解析 `vpn.ucvl.cn`。公网路径拒绝 Fake-IP、私网及 Tailscale 地址。 - 在接管默认路由前把 NPM 入口公网 IP 排除出隧道,并把运行时 VLESS 地址固定为同一 IP;节点端口及 Reality `serverName` 保持不变,避免节点连接被送回 TUN 形成回环。 - 兼容后台 `config_contract=2`:优先使用后台下发的统一 NPM 网关,旧后台未返回该字段时仍按原有域名解析流程连接。 -- OpenAI/ChatGPT 出口探测完成后再次核对系统 VPN 状态,避免把“探测成功但隧道已退出”误报为已连接。 +- HTTPS 出口探测完成后再次核对系统 VPN 状态。 ## 在 Mac 上生成工程 @@ -33,7 +33,7 @@ 4. 为两个 App ID 启用 Network Extensions / Packet Tunnel Provider 权限。 5. 使用真机运行;iOS 模拟器不能完整验证 Packet Tunnel 数据通路。 -具备上述条件后,可用 `DEVELOPMENT_TEAM=你的TeamID ./Scripts/verify-and-archive.sh` 执行测试并归档。脚本从 `project.yml` 的唯一数字三段 `MARKETING_VERSION` 生成归档路径;当前为 `build/UCVL-Zonghengjia-1.0.3.xcarchive`。默认模拟器为 `platform=iOS Simulator,name=iPhone 16 Pro`;可通过 `SIMULATOR_DESTINATION='platform=iOS Simulator,id=已安装模拟器的UDID'` 显式指定本机可用设备。 +具备上述条件后,可用 `DEVELOPMENT_TEAM=你的TeamID ./Scripts/verify-and-archive.sh` 执行测试并归档。本版归档路径为 `build/UCVL-Zonghengjia-1.0.4.xcarchive`。默认模拟器为 `platform=iOS Simulator,name=iPhone 16 Pro`。可通过 `SIMULATOR_DESTINATION='platform=iOS Simulator,id=已安装模拟器的UDID'` 指定本机可用设备。 如需同时导出 IPA,再传入 Xcode 生成且适用于所选分发方式的发布选项文件:`EXPORT_OPTIONS_PLIST=/path/ExportOptions.plist DEVELOPMENT_TEAM=你的TeamID ./Scripts/verify-and-archive.sh`。脚本在下载或构建前检查 Team 非空、版本唯一有效、导出文件可读及 `plutil -lint` 通过;任何依赖、测试、归档或导出失败都会停止后续步骤。plist 格式检查不代表签名配置和发布选项已被 Xcode 接受。 diff --git a/ios/Resources/Geo/README.md b/ios/Resources/Geo/README.md index 8c396a2..fb33fe0 100644 --- a/ios/Resources/Geo/README.md +++ b/ios/Resources/Geo/README.md @@ -1 +1 @@ -Public source export omits Resources/Geo/geoip.dat and Resources/Geo/geosite.dat because their redistribution license was not established. Before building, obtain legally licensed compatible data, verify its origin/license and SHA256, and restore those exact paths. Vendor/LibXray.xcframework must be restored using Scripts/fetch-libxray.sh and its pinned hash; ThirdParty/ contains the retained license texts. Logo/trademark rights are not granted by MIT. Source-audit evidence covers the private complete frozen snapshot only. This export has not been compiled with Xcode, run through XCTest, signed, exported as IPA, or accepted on an Apple device. +The public source candidate omits the original Geo databases. Obtain compatible GeoIP and GeoSite data with a redistribution license, verify their source and SHA-256, and place them at Resources/Geo/geoip.dat and Resources/Geo/geosite.dat before building. Scripts/fetch-libxray.sh pins the required libXray archive digest. ThirdParty/ contains the licenses. Static source validation was performed on the complete candidate. Xcode, XCTest, Apple signing, IPA export, TestFlight, and device validation remain pending. diff --git a/ios/Scripts/source-audit.py b/ios/Scripts/source-audit.py index a9c3455..1610ea0 100644 --- a/ios/Scripts/source-audit.py +++ b/ios/Scripts/source-audit.py @@ -27,10 +27,8 @@ EXPECTED = [ "Shared/ConnectionAttemptPolicy.swift", "Tests/ConnectionAttemptPolicyTests.swift", "Shared/ProxyTransportPolicy.swift", - "Shared/ICMPEchoPacket.swift", "App/InternalIPProbe.swift", "Tests/ProxyTransportPolicyTests.swift", - "Tests/ICMPEchoPacketTests.swift", "Resources/Assets.xcassets/MountainLandscape.imageset/Contents.json", "Resources/Assets.xcassets/MountainLandscape.imageset/landscape-header-v1.png", ] @@ -79,6 +77,15 @@ def main() -> int: require("selectedNodeID" not in app_state, "客户端仍暴露节点选择") require('URLQueryItem(name: "node", value: "auto")' in api, "未启用后台自动选节点") require("verifyProxyEgress" in api and "verifyProxyEgress" in app_state, "缺少出口验证") + require('https://vpn.ucvl.cn/' in api and "InternalIPProbe.isReachable(endpoint.address, port: endpoint.port)" in app_state, + "平台入口或已授权代理端口不匹配") + probe = (ROOT / "App/InternalIPProbe.swift").read_text(encoding="utf-8") + require("SOCK_STREAM" in probe and "IPPROTO_TCP" in probe and "SO_ERROR" in probe and "IPPROTO_ICMP" not in probe, + "已授权端口未使用 TCP 握手验证") + builder = (ROOT / "Shared/TunnelConfigurationBuilder.swift").read_text(encoding="utf-8") + require("https://cp.cloudflare.com/generate_204" in builder and '"outboundTag": "proxy"' in builder, + "独立 HTTPS 目标缺少强制代理路径") + require("NetworkAddress.tunnelUnderlayIPv4(remoteAddress)" in tunnel, "隧道缺少底层路由排除") require("resolveIPv4Address" in tunnel and "excludedRoutes" in tunnel, "缺少节点域名防回环处理") require("dns.alidns.com/resolve" in api and "doh.pub/resolve" in api, "缺少国内 DoH 真实地址解析") require("NetworkAddress.isPublicIPv4" in api and "NetworkAddress.isPublicIPv4" in tunnel, "未拒绝 Fake-IP/内网地址") @@ -114,7 +121,7 @@ def main() -> int: "documentation_version_matches": True, "scope": "Source audit only; no Xcode compile, signing, IPA export, or iPhone tunnel acceptance", "automatic_node_selection": True, - "egress_verification": ["api.openai.com", "chatgpt.com"], + "egress_verification": ["cp.cloudflare.com", "api.openai.com", "chatgpt.com"], "domain_loop_prevention": True, "gateway_contract": 2, "legacy_backend_compatible": True, diff --git a/ios/Scripts/tests/test_source_audit.py b/ios/Scripts/tests/test_source_audit.py index ca2a823..dd560ed 100644 --- a/ios/Scripts/tests/test_source_audit.py +++ b/ios/Scripts/tests/test_source_audit.py @@ -36,7 +36,7 @@ class SourceAuditTests(unittest.TestCase): def test_valid_source_reports_only_source_acceptance(self): report = self.run_audit() - self.assertEqual(report["source_version"], "1.0.3") + self.assertEqual(report["source_version"], "1.0.4") self.assertFalse(report["swift_compilation_executed"]) self.assertFalse(report["xctest_executed"]) self.assertFalse(report["ipa_generated"]) @@ -67,7 +67,7 @@ class SourceAuditTests(unittest.TestCase): def test_version_mismatch_stops_audit(self): path = self.root / "README.md" - path.write_text(path.read_text(encoding="utf-8").replace("1.0.3", "1.0.2"), encoding="utf-8") + path.write_text(path.read_text(encoding="utf-8").replace("1.0.4", "1.0.3"), encoding="utf-8") with self.assertRaisesRegex(RuntimeError, "版本不一致"): self.run_audit() diff --git a/ios/Shared/ICMPEchoPacket.swift b/ios/Shared/ICMPEchoPacket.swift deleted file mode 100644 index d21848b..0000000 --- a/ios/Shared/ICMPEchoPacket.swift +++ /dev/null @@ -1,38 +0,0 @@ -import Foundation - -// A nonce in the payload binds a reply to this request. The kernel may rewrite -// the identifier on an unprivileged datagram ICMP socket. -enum ICMPEchoPacket { - static func checksum(_ bytes: [UInt8]) -> UInt16 { - var sum: UInt32 = 0 - var index = 0 - while index + 1 < bytes.count { - sum += (UInt32(bytes[index]) << 8) | UInt32(bytes[index + 1]) - index += 2 - } - if index < bytes.count { sum += UInt32(bytes[index]) << 8 } - while sum >> 16 != 0 { sum = (sum & 0xffff) + (sum >> 16) } - return ~UInt16(sum) - } - - static func request(identifier: UInt16, payload: [UInt8]) -> [UInt8] { - var bytes: [UInt8] = [8, 0, 0, 0, UInt8(identifier >> 8), UInt8(identifier & 0xff), 0, 1] - bytes += payload - let value = checksum(bytes) - bytes[2] = UInt8(value >> 8) - bytes[3] = UInt8(value & 0xff) - return bytes - } - - static func isReply(_ received: [UInt8], payload: [UInt8]) -> Bool { - var offset = 0 - if let first = received.first, first >> 4 == 4 { - offset = Int(first & 0x0f) * 4 - guard offset >= 20 else { return false } - } - guard received.count == offset + 8 + payload.count else { return false } - let reply = Array(received.dropFirst(offset)) - return reply[0] == 0 && reply[1] == 0 && reply[6] == 0 && reply[7] == 1 - && Array(reply.dropFirst(8)) == payload && checksum(reply) == 0 - } -} diff --git a/ios/Shared/NetworkAddress.swift b/ios/Shared/NetworkAddress.swift index 7871bca..b7a7c57 100644 --- a/ios/Shared/NetworkAddress.swift +++ b/ios/Shared/NetworkAddress.swift @@ -1,6 +1,16 @@ import Foundation enum NetworkAddress { + static func tunnelUnderlayIPv4(_ remoteAddress: String) -> [String] { + let managementAddress = "47.104.134.190" + if isAuthorizedInternalIPv4(remoteAddress) { + // Preserve the management gateway and the three company relays. + return [remoteAddress, managementAddress, "8.216.53.107", "47.254.94.29", "192.236.188.22"] + } + guard isPublicIPv4(remoteAddress), remoteAddress != managementAddress else { return [managementAddress] } + return [remoteAddress, managementAddress] + } + static func isAuthorizedInternalIPv4(_ value: String) -> Bool { let parts = value.split(separator: ".", omittingEmptySubsequences: false) guard parts.count == 4 else { return false } diff --git a/ios/Shared/TunnelConfigurationBuilder.swift b/ios/Shared/TunnelConfigurationBuilder.swift index 877d968..15a8b47 100644 --- a/ios/Shared/TunnelConfigurationBuilder.swift +++ b/ios/Shared/TunnelConfigurationBuilder.swift @@ -1,6 +1,12 @@ import Foundation enum TunnelConfigurationBuilder { + static let egressProbeURLs = [ + URL(string: "https://cp.cloudflare.com/generate_204")!, + URL(string: "https://api.openai.com/v1/models")!, + URL(string: "https://chatgpt.com/api/auth/session")!, + ] + static func makeConfiguration( rawJSON: String, tunnelFileDescriptor: Int32, @@ -21,6 +27,7 @@ enum TunnelConfigurationBuilder { if let resolvedRemoteAddress { try replaceProxyRemoteAddress(in: &root, with: resolvedRemoteAddress) } + try addTransportRules(to: &root) root["inbounds"] = [[ "tag": "tun-in", "port": 0, @@ -44,6 +51,33 @@ enum TunnelConfigurationBuilder { return String(decoding: output, as: UTF8.self) } + private static func addTransportRules(to root: inout [String: Any]) throws { + guard let outbounds = root["outbounds"] as? [[String: Any]], + outbounds.contains(where: { $0["tag"] as? String == "proxy" }), + var routing = root["routing"] as? [String: Any], + var rules = routing["rules"] as? [[String: Any]] + else { + throw UCVLError.invalidConfiguration("线路配置缺少用于代理出口验证的路由。") + } + // A request to any probe host must use the authorized outbound even + // when the platform's smart routing rules would otherwise send it direct. + rules.insert([ + "type": "field", + "domain": egressProbeURLs.compactMap { $0.host }.map { "full:" + $0 }, + "port": "443", + "outboundTag": "proxy", + ], at: 0) + if outbounds.contains(where: { $0["tag"] as? String == "direct" }) { + rules.insert([ + "type": "field", + "domain": [#"regexp:(?i)(^|\.)(tailscale\.com|ts\.net)\.?$"#], + "outboundTag": "direct", + ], at: 0) + } + routing["rules"] = rules + root["routing"] = routing + } + static func remoteAddress(from rawJSON: String) -> String? { guard let data = rawJSON.data(using: .utf8), let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any], diff --git a/ios/Tests/ICMPEchoPacketTests.swift b/ios/Tests/ICMPEchoPacketTests.swift deleted file mode 100644 index 130bc8c..0000000 --- a/ios/Tests/ICMPEchoPacketTests.swift +++ /dev/null @@ -1,39 +0,0 @@ -import XCTest -@testable import UCVLZonghengjia - -final class ICMPEchoPacketTests: XCTestCase { - func testEchoRequestHasValidChecksumAndPayload() { - let payload: [UInt8] = [1, 2, 3, 4, 5] - let request = ICMPEchoPacket.request(identifier: 0x1234, payload: payload) - XCTAssertEqual(Array(request.prefix(2)), [8, 0]) - XCTAssertEqual(Array(request[4..<8]), [0x12, 0x34, 0, 1]) - XCTAssertEqual(Array(request.dropFirst(8)), payload) - XCTAssertEqual(ICMPEchoPacket.checksum(request), 0) - } - - func testAcceptsOnlyMatchingEchoReply() { - let payload: [UInt8] = [11, 12, 13] - var reply = ICMPEchoPacket.request(identifier: 7, payload: payload) - reply[0] = 0 - reply[2] = 0 - reply[3] = 0 - let checksum = ICMPEchoPacket.checksum(reply) - reply[2] = UInt8(checksum >> 8) - reply[3] = UInt8(checksum & 0xff) - XCTAssertTrue(ICMPEchoPacket.isReply(reply, payload: payload)) - XCTAssertFalse(ICMPEchoPacket.isReply(reply, payload: [99])) - XCTAssertFalse(ICMPEchoPacket.isReply(Array(reply.dropLast()), payload: payload)) - reply[1] = 1 - XCTAssertFalse(ICMPEchoPacket.isReply(reply, payload: payload)) - } - - func testRejectsRequestAndCorruptReply() { - let payload: [UInt8] = [11, 12] - let request = ICMPEchoPacket.request(identifier: 7, payload: payload) - XCTAssertFalse(ICMPEchoPacket.isReply(request, payload: payload)) - var corrupt = request - corrupt[0] = 0 - XCTAssertFalse(ICMPEchoPacket.isReply(corrupt, payload: payload)) - XCTAssertFalse(ICMPEchoPacket.isReply([], payload: [])) - } -} diff --git a/ios/Tests/TunnelConfigurationBuilderTests.swift b/ios/Tests/TunnelConfigurationBuilderTests.swift index 2eec894..f8626d0 100644 --- a/ios/Tests/TunnelConfigurationBuilderTests.swift +++ b/ios/Tests/TunnelConfigurationBuilderTests.swift @@ -40,5 +40,22 @@ final class TunnelConfigurationBuilderTests: XCTestCase { let reality = try XCTUnwrap(stream["realitySettings"] as? [String: Any]) XCTAssertEqual(reality["serverName"] as? String, "www.microsoft.com") XCTAssertEqual(TunnelConfigurationBuilder.remoteAddress(from: raw), "001.vpn.example.invalid") + let routing = try XCTUnwrap(root["routing"] as? [String: Any]) + let rules = try XCTUnwrap(routing["rules"] as? [[String: Any]]) + XCTAssertEqual(rules.count, 2) + XCTAssertEqual(rules[0]["outboundTag"] as? String, "direct") + XCTAssertEqual(rules[1]["outboundTag"] as? String, "proxy") + XCTAssertEqual(rules[1]["port"] as? String, "443") + XCTAssertEqual(rules[1]["domain"] as? [String], [ + "full:cp.cloudflare.com", "full:api.openai.com", "full:chatgpt.com", + ]) + } + + func testTailnetExcludesCompanyRelayRoutesOnlyForAuthorizedInternalAddress() { + XCTAssertEqual(NetworkAddress.tunnelUnderlayIPv4("100.99.142.38"), [ + "100.99.142.38", "47.104.134.190", "8.216.53.107", "47.254.94.29", "192.236.188.22", + ]) + XCTAssertEqual(NetworkAddress.tunnelUnderlayIPv4("47.104.134.190"), ["47.104.134.190"]) + XCTAssertEqual(NetworkAddress.tunnelUnderlayIPv4("8.8.8.8"), ["8.8.8.8", "47.104.134.190"]) } } diff --git a/ios/project.yml b/ios/project.yml index b1575d9..d19471f 100644 --- a/ios/project.yml +++ b/ios/project.yml @@ -8,8 +8,8 @@ options: settings: base: SWIFT_VERSION: "5.0" - MARKETING_VERSION: "1.0.3" - CURRENT_PROJECT_VERSION: "10003" + MARKETING_VERSION: "1.0.4" + CURRENT_PROJECT_VERSION: "10004" CODE_SIGN_STYLE: Automatic DEVELOPMENT_TEAM: "" CLANG_ENABLE_MODULES: YES @@ -24,8 +24,8 @@ targets: sources: - path: App - path: Shared - resources: - path: Resources/Assets.xcassets + buildPhase: resources entitlements: path: App/UCVLZonghengjia.entitlements info: @@ -67,8 +67,8 @@ targets: - path: Shared/Models.swift - path: Shared/NetworkAddress.swift - path: Shared/ProxyTransportPolicy.swift - resources: - path: Resources/Geo + buildPhase: resources entitlements: path: PacketTunnel/PacketTunnel.entitlements info: