diff --git a/.github/workflows/ci-linux.yml b/.github/workflows/ci-linux.yml index 0c3790ec..baa77df5 100644 --- a/.github/workflows/ci-linux.yml +++ b/.github/workflows/ci-linux.yml @@ -14,6 +14,7 @@ on: - "update.sh" - "uninstall.sh" - "validation/**" + - "libexec/**" - ".github/workflows/ci-linux.yml" workflow_dispatch: @@ -55,4 +56,34 @@ jobs: echo "::error::$fails validation test(s) failed" exit 1 fi - echo "All validation tests passed" \ No newline at end of file + echo "All validation tests passed" + + udp-runtime: + runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + include: + - version: "26.6.27" + sha256: "b3e5902d06d6282fe53cfa2fc426058b9aeaa429b2c812e20887cd47f26d08bf" + - version: "26.10.31" + sha256: "e4bd9119f50ae7c41658b1abd0679ae06f98bd864a2907ff33f2f2cf7081b214" + steps: + - uses: actions/checkout@v4 + - name: Install runtime fixture dependencies + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends jq uuid-runtime curl unzip python3 + - name: Verify official Xray release + env: + CORE_VERSION: ${{ matrix.version }} + CORE_SHA256: ${{ matrix.sha256 }} + run: | + mkdir -p "$RUNNER_TEMP/xray" + curl -fsSL "https://github.com/XTLS/Xray-core/releases/download/v${CORE_VERSION}/Xray-linux-64.zip" -o "$RUNNER_TEMP/xray.zip" + printf '%s %s\n' "$CORE_SHA256" "$RUNNER_TEMP/xray.zip" | sha256sum -c - + unzip -q "$RUNNER_TEMP/xray.zip" -d "$RUNNER_TEMP/xray" + - name: Verify UDP destination changes and failure isolation + timeout-minutes: 3 + run: | + python3 validation/test-private-cascade-udp-runtime.py --repo "$GITHUB_WORKSPACE" --xray "$RUNNER_TEMP/xray/xray" --local-ip 127.0.0.2 diff --git a/.gitignore b/.gitignore index aad44ef2..80394004 100644 --- a/.gitignore +++ b/.gitignore @@ -19,3 +19,6 @@ DESIGN-REVIEW-*.md # OS .DS_Store Thumbs.db + +# Python UDP helper validation +__pycache__/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 46cf9d16..b0e91afc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ User-facing Xrayebator changes. The server manager and Electron application are published from the canonical `howdeploy/Xrayebator` repository. +## [Unreleased] + +### Added + +- Opt-in private cascade configuration generation for a Russian ingress and foreign exit, with ordered TCP/UDP routing, a Python 3 UDP destination helper, fail-closed foreign routes, and deployment, update and removal guides. +- `profile-create --transport xhttp --without-pq` creates a legacy XHTTP profile with `encryption=none`. XHTTP profile creation uses PQ by default. + ## [0.7.3] - 2026-11-07 Secrets no longer travel in process arguments. `/proc//cmdline` is readable by every local @@ -856,4 +863,4 @@ The first combined release of the updated server manager and **Xrayebator Deskto - Hardening tasks found in a later audit around `safe_jq_write`, lifecycle rollback, JSON escaping, and existing-inbound validation are not included in this release. Detailed English release notes: [docs/releases/v0.5.0.en.md](docs/releases/v0.5.0.en.md). -Russian release notes: [docs/releases/v0.5.0.md](docs/releases/v0.5.0.md). \ No newline at end of file +Russian release notes: [docs/releases/v0.5.0.md](docs/releases/v0.5.0.md). diff --git a/CLAUDE.md b/CLAUDE.md index ac8b4d7c..e7e829bd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -9,7 +9,7 @@ Xrayebator — automated Xray Reality VPN manager for bypassing DPI censorship i ## Validation There IS automated test coverage (despite what older notes said): -- **`validation/`** — 49 Bash test scripts, including `test-main-readiness-regressions.sh`, covering migrations, VLESS URL generation, subscription formats (Clash/mihomo YAML + sing-box JSON), DNS-01 certificate wiring, transaction safety, dedup, firewall, menu numbering, the backend registry, the Hysteria 2 backend renderers/lifecycle, the AmneziaWG backend junk/renderers, per-profile traffic accounting and limits, Telegram alerts/monitoring, the bypass/sni-change/port-change/profile-revoke/profile-expire CLIs, the HAPP client-routing generator, update branch pinning, quickstart, email/inspect regressions, apt-lock race regressions, the quickstart http_tls fallback and audit regressions. They run on the host (`bash validation/test-*.sh`); CI installs `jq`, `uuidgen` and `ripgrep` on Ubuntu. A bare Windows Git Bash checkout is not equivalent to the Linux environment. +- **`validation/`** — 51 Bash test scripts, including `test-main-readiness-regressions.sh` and the Python-backed `test-private-cascade-udp.sh`, covering migrations, VLESS URL generation, subscription formats (Clash/mihomo YAML + sing-box JSON), DNS-01 certificate wiring, transaction safety, dedup, firewall, menu numbering, the backend registry, the Hysteria 2 backend renderers/lifecycle, the AmneziaWG backend junk/renderers, per-profile traffic accounting and limits, Telegram alerts/monitoring, the bypass/sni-change/port-change/profile-revoke/profile-expire CLIs, the HAPP client-routing generator, update branch pinning, quickstart, email/inspect regressions, apt-lock race regressions, the quickstart http_tls fallback and audit regressions. They run on the host (`bash validation/test-*.sh`); CI uses Python 3 and installs `jq`, `uuidgen` and `ripgrep` on Ubuntu. A bare Windows Git Bash checkout is not equivalent to the Linux environment. - **`gui-legacy/tests/`** — 16 pytest modules covering SSH, deploy, connection, subscription and TUN runtime (legacy PySide6 GUI). Run with the GUI venv: `gui-legacy/.venv/Scripts/python -m pytest gui-legacy/tests`. - **GUI (Electron)** — Vitest unit tests in `tests/`: `npm test`, plus `npm run typecheck`. - **CI** — `.github/workflows/ci-linux.yml` runs the full `validation/` suite; `.github/workflows/gui-release.yml` runs `ruff` + `pytest gui-legacy/tests` and builds Windows/macOS bundles; `.github/workflows/release.yml` ships the Electron app. @@ -26,7 +26,9 @@ bash -n uninstall.sh ### Single-file application -All logic lives in `xrayebator`. Supporting scripts (`install.sh`, `update.sh`, `uninstall.sh`) handle lifecycle but are not part of the runtime. The repository is a single runtime source file, but a deployed VPS is not literally one file: `xrayebator` generates additional root-owned runtime artifacts from heredocs — `/usr/local/bin/subhttp.sh` (the subscription/geo HTTP handler, which sources `xrayebator` in source-mode), systemd units (`xrayebator-sub.service`, `xrayebator-expire.service/.timer`, `xrayebator-traffic.service/.timer`, `xrayebator-monitor.service/.timer`, backend units) and nginx vhosts. Never edit those on the server — change `xrayebator` and regenerate. +The Bash manager lives in `xrayebator`. Supporting scripts (`install.sh`, `update.sh`, `uninstall.sh`) handle lifecycle. The optional private cascade also uses the maintained `libexec/private_cascade_udp.py` runtime helper, which requires Python 3 and its standard library. Its unit tests and real-core fixture also require `python3`. The cascade guide installs the helper as `/usr/local/libexec/xrayebator-private-udp.py` with two separate systemd units and documents their manual update and removal. + +`xrayebator` generates additional root-owned runtime artifacts from heredocs, including `/usr/local/bin/subhttp.sh` (the subscription/geo HTTP handler, which sources `xrayebator` in source-mode), systemd units (`xrayebator-sub.service`, `xrayebator-expire.service/.timer`, `xrayebator-traffic.service/.timer`, `xrayebator-monitor.service/.timer`, backend units) and nginx vhosts. Change their sources in `xrayebator` and regenerate them. ### Production paths @@ -131,6 +133,8 @@ Do NOT use raw `jq ... > temp && mv temp file` — always go through `safe_jq_wr ## CLI commands +- `xrayebator private-cascade render --policy-file F --upstream-file U --output O.json` — write a separate, protected ingress configuration and validate it with the installed Xray core. The live configuration is preserved. Deployment uses the Python 3 helper from `libexec/` and the dedicated units described in [Private cascade](docs/private-cascade.md). + Apart from the interactive menu (`sudo xrayebator`), the script exposes subcommands used by the GUI and by automation. They are dispatched at the very bottom of `xrayebator` (the `case "${1:-}" in ... esac` block guarded by `XRAYEBATOR_SOURCED`): - `xrayebator update` — update only the Xray-core binary; `xrayebator update ` self-updates the manager from the canonical raw branch, pins that branch in `/usr/local/etc/xray/.current_branch` (the GUI updater reads this file), then updates Xray-core. @@ -172,4 +176,4 @@ CLI JSON hygiene: `profile-create`/`profile-delete` **must** print only JSON on ## Language -Bash/server-facing strings, comments, and commit messages are in **Russian**. The active Electron renderer is intentionally multilingual (`ru`, `en`, `zh`); code identifiers and function names are in English. \ No newline at end of file +Bash/server-facing strings, comments, and commit messages are in **Russian**. The active Electron renderer is intentionally multilingual (`ru`, `en`, `zh`); code identifiers and function names are in English. diff --git a/docs/configuration.md b/docs/configuration.md index 2328d6da..7bb2d63c 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -124,7 +124,7 @@ is a client-side profile/route setting; changing it does not restart Xray or alt | `sudo xrayebator kernel-guard [--status\|--enable\|--disable] [--quiet]` | Hardening against CVE-2026-98432 (a use-after-free in IPv4 option processing, CVSS 9.8, affecting every IPv4 TCP listener). `--enable` disables MPTCP in the kernel (`net.mptcp.enabled = 0` in `/etc/sysctl.d/99-xrayebator-netguard.conf`) and drops inbound IPv4 TCP packets that carry IP options using Ubuntu Security Team's rule in a dedicated nftables table plus its own boot unit — deliberately not `nftables.service`, whose default `flush ruleset` would wipe the UFW ruleset at boot. MPTCP is also disabled automatically by migration `netguard_mptcp_2026`; the nft drop stays opt-in because it changes which packets the server accepts. `--status` reports the running kernel, `newer_kernel_installed`, `reboot_required`, `mptcp_enabled`, `ipv4_options_drop`, the Xray-core version and whether it is at or above `26.10.31` (`xray_mptcp_safe`). It is a mitigation, not a kernel update. Also available as menu item 16 | | `sudo xrayebator ssh-protect [--status\|--enable\|--disable] [--unban IP\|--prune-ignore] [--quiet]` | SSH brute-force protection: installs `fail2ban` with a journald-backed `sshd` jail (4 failures in 10 minutes → 30-minute ban, repeat offenders escalate up to a day) plus a `sshd_config.d` drop-in with `MaxAuthTries 3` / `LoginGraceTime 30`. **Password login stays enabled** — the desktop GUI manages the server with it, and key-only access remains a separate operator decision. Idempotent: the drop-in is validated with `sshd -t` before `ssh` is reloaded (not restarted), so open GUI sessions survive. Enabled automatically by `install.sh` and `quickstart` (the deploy JSON reports `ssh_protect`); `--quiet` suppresses the JSON for scripts. Also available as menu item 15 and as the **Security and TLS** tab in the GUI. Live measurement on a public VPS: 9 953 failed logins in 24 h from 115 addresses before, ≈72/h after. The address the command was run from is exempted from bans for 24 hours (`ignoreip` plus an epoch stamp; `--prune-ignore`, driven by `xrayebator-ssh-ignoreip.timer`, removes it on expiry) | | `sudo xrayebator profiles` | Print all server profiles as a JSON array for the desktop GUI Server Settings page; expiry includes both epoch seconds (`expire`) for enforcement and the server-local calendar date (`expire_date`) for display, so clients in another timezone still see the selected date | -| `sudo xrayebator profile-create --name NAME [--transport tcp\|tcp-utls\|tcp-xudp\|tcp-mux\|grpc\|xhttp] [--port P] [--count N] [--expire DATE]` | Create one or more profiles non-interactively; `--expire` accepts `YYYY-MM-DD[ HH:MM]`, epoch seconds or 13-digit milliseconds. A date without time is inclusive through `23:59:59` in the server's local timezone; an explicit time uses that server-local time. Past expiries are rejected; existing names are never overwritten — they are reported in `errors` (the GUI also pre-checks a name collision before creating, since deletion is per-profile and unique names keep it precise); prints `{"ok":true,"names":[...],"errors":[...]}` | +| `sudo xrayebator profile-create --name NAME [--transport tcp\|tcp-utls\|tcp-xudp\|tcp-mux\|grpc\|xhttp] [--port P] [--count N] [--expire DATE] [--without-pq]` | Create one or more profiles non-interactively; XHTTP uses PQ by default. `--without-pq` is valid only for XHTTP and creates a legacy `encryption=none` profile on a free port or a compatible existing inbound. `--expire` accepts `YYYY-MM-DD[ HH:MM]`, epoch seconds or 13-digit milliseconds. A date without time is inclusive through `23:59:59` in the server's local timezone; an explicit time uses that server-local time. Past expiries are rejected; existing names are never overwritten — they are reported in `errors` (the GUI also pre-checks a name collision before creating, since deletion is per-profile and unique names keep it precise); prints `{"ok":true,"names":[...],"errors":[...]}` | | `sudo xrayebator profile-delete --name NAME` | Delete a profile non-interactively; the deleted profile's backend grants are revoked immediately (the AWG peer is dropped from `awg0.conf`, the Hysteria password from `server.yaml` — no orphaned credentials) and the name is free for reuse; prints `{"ok":true,"name":"..."}` | | `sudo xrayebator profile-revoke --name NAME [--full]` | Reissue the subscription link: new `sub_token`; with `--full` also a new uuid in every inbound of the profile (already-downloaded configs are cut off); prints JSON | | `sudo xrayebator profile-expire --name NAME --expire DATE\|epoch\|none` | Set, extend or remove a profile expiry; a date without time is inclusive through `23:59:59` in the server's local timezone, while an explicit time is used as given in that timezone; applied immediately (a passed expiry removes the client, an extension restores it); prints JSON | @@ -676,6 +676,8 @@ button in Server settings. ## Cascade and upstream nodes +The scope of `--without-pq` depends on the command. `quickstart --without-pq` skips the additional PQ route in the managed multi-route profile. `profile-create --transport xhttp --without-pq` creates the base XHTTP profile with `encryption=none` instead of PQ. + The cascade is a server-side outbound and routing mode, not a new client profile. The client keeps connecting to the current VPS: @@ -696,6 +698,9 @@ Disabling the cascade removes the `cascade-upstream` outbound and returns the ca Item `10` configures the other side: it turns the current VPS into the foreign node that a cascade from another server connects to. +For a separate Russian ingress that routes selected destinations locally and sends other traffic +through a restricted foreign node, see [Private cascade deployment](private-cascade.md). + ## Custom domain and self-steal stub Self-steal puts nginx with a valid certificate on `127.0.0.1:9444`, and Reality inbounds receive diff --git a/docs/private-cascade.md b/docs/private-cascade.md new file mode 100644 index 00000000..eca9b9c5 --- /dev/null +++ b/docs/private-cascade.md @@ -0,0 +1,233 @@ +# Private cascade through a Russian VPS + +[← Back to README](../README.md) · [Русский](ru/private-cascade.md) · [简体中文](zh-CN/private-cascade.md) + +## Topology + +Use two VPSs. A private client connects to the Russian ingress. The ingress applies the same ordered policy to TCP and supported application UDP: selected Russian destinations exit in Russia; blocked and unmatched destinations go over VLESS REALITY to the foreign egress. + +| VPS | Role | Address required | +|---|---|---| +| Russian ingress, for example in Moscow | Receives client connections and sends explicitly selected traffic out in Russia | A public address reachable by the clients and a stable, known source address for the connection to the foreign VPS | +| Foreign egress | Accepts the cascade connection from the Russian VPS and sends forwarded traffic to the internet | A public listener address reachable from the Russian VPS and working outbound connectivity for the destinations clients need | + +One public IPv4 per VPS can cover these roles. The foreign listener and its public internet egress can share an address. The article's full design separates the foreign listener and final exit using another address, a gateway, or WARP. It makes an explicit exception for Russian destinations, which see the ingress public IP when routed direct. The article's explanation of how addresses are discovered and blocked is the author's hypothesis. [Habr article, section 4](https://habr.com/ru/articles/1103460/) + +## Before changing either VPS + +1. Check both providers' terms for the intended proxy use. Record the actual public addresses, the source address the egress will see after any provider NAT, the ports, and the path for emergency console access. Check SSH host keys independently. Use the supported OS matrix in [VPS recommendations](recommendations.md#choosing-a-vps). +2. Confirm the client network can reach the Russian listener over IPv4. For the hop between servers, use IPv4 with a source-scoped firewall or IPv6 if the route, listener, and firewall work end to end. Also check that the foreign VPS can reach IPv4 destinations if clients need them, regardless of the family used for the hop. +3. Record the current Xray routes and profiles, backends, listeners, provider firewall and host firewall. Take protected backups or snapshots and keep a separate administrative session. Use a maintenance window if preparing either node requires restarting an existing service or changing an active listener. +4. Reserve a dedicated TCP listener on the foreign VPS. At the provider firewall, allow its port only from the Russian VPS's observed source IP (`/32` for IPv4 or `/128` for IPv6). Apply equivalent restrictions on the host and check for broader allows, including those added by Xrayebator. Preserve existing SSH, subscription, and client listener rules. Set the provider restriction before creating the foreign inbound because the manager can open the listener port in UFW. +5. Keep SSH access, REALITY key pairs, and certificate keys separate per host. Issue a dedicated VLESS credential for the ingress-to-egress hop. Give clients only their ingress profile and keep the upstream link or UUID on the two hosts that need it. Store DNS credentials with root-only access and use the narrowest permissions available. Redact links and tokens from logs or handoffs. + +On fresh VPSs, install Xrayebator on both hosts. This example uses Xray and a Python 3 standard-library UDP helper on the ingress; it needs no optional VPN backend. If either host already runs optional backends, check their profile grants after creating a profile because Xrayebator applies profile lifecycle events to installed backends. [Installation](../README.md#installation) + +Both nodes require Xray-core 26.6.27 or newer for the destination restrictions below. Obtain the same reviewed Xrayebator checkout on each host; it must include `profile-create --without-pq`, `private-cascade` and `libexec/private_cascade_udp.py`. The installed manager alone does not install this standalone helper or its units. Run the commands below from that checkout, replacing `sudo xrayebator` with `sudo bash ./xrayebator` if the installed manager is older. Keep the helper and generated config on matching reviewed versions when updating. + +In an unused directory on each host, fetch the reviewed tag or commit, not a moving `latest` file. Replace the reference value before running: + +```bash +CASCADE_REVIEWED_REF='replace-with-reviewed-tag-or-commit' +git clone --no-checkout https://github.com/howdeploy/Xrayebator.git xrayebator-cascade-src +cd xrayebator-cascade-src +git fetch --depth 1 origin "$CASCADE_REVIEWED_REF" +git checkout --detach FETCH_HEAD +``` + +## Hostnames, certificates, and REALITY + +- Prefer a domain you already control. Use separate names such as `ingress.example.com` and `egress.example.com`. Point each `A` record to the corresponding public IPv4 and publish `AAAA` only after verifying IPv6 reachability and firewall scope. Use DNS-only records where a provider offers proxying. A VPS provider's default hostname works for this purpose only if you can verify the necessary DNS control and obtain a matching certificate with working renewal. +- With the standard REALITY decoy, keep the working target and SNI already configured by Xrayebator and dial each VPS by IP. This setup needs no new DNS account or certificate for the tunnel. +- The cascade dial address can be a reachable IP or a hostname. An IP certificate can serve the subscription HTTPS endpoint. For self-steal, set REALITY SNI to the hostname covered by the certificate on the loopback TLS target, and match the XHTTP `host` to it when using XHTTP. [Domain and DNS](configuration.md#domain-and-dns) · [Self-steal](configuration.md#custom-domain-and-self-steal-stub) +- For closed-port self-steal, use your DNS provider's ACME plugin in certificate-only mode, configure the loopback TLS site and add a deploy hook that reloads its TLS service after renewal. Verify the matching certificate on the loopback listener. The built-in `dns01-setup` configures a subscription listener for Cloudflare or Route 53. Use it only if you also intend to publish that subscription, and pass its secret through a file or stdin. [DNS-01](configuration.md#dns-01-certificate-and-subscription-domain-without-port-80) + +## Prepare the foreign egress + +On the foreign VPS, create the dedicated legacy XHTTP profile with `sudo xrayebator profile-create --name private-cascade-egress --transport xhttp --without-pq --port 25443`. Check that `names` includes the new profile and `errors` is empty. Export its XHTTP URI privately from the profile menu. Preserve the actual `path`, `host` and `mode` values. Put an IPv6 dial address in square brackets. + +```text +vless://@:?encryption=none&security=reality&type=xhttp&sni=&fp=&pbk=&sid=&host=&path=&mode= +``` + +TCP Vision is also supported. Use `--transport tcp` without `--without-pq` on a free non-443 port and keep `flow=xtls-rprx-vision` in the exported URI. With this flow Xray rejects UDP sessions opened to port 443 on the foreign route. Browsers can retry HTTPS over TCP when HTTP/3 is unavailable. The XHTTP example supports application UDP/443. + +Verify the restricted listener from both the ingress and a source outside its allowlist. Confirm the foreign node has a working internet egress. [Standard cascade](configuration.md#cascade-and-upstream-nodes) + +The foreign VPS resolves forwarded names independently. Enforce the public IPv4 policy at its exit, including for each UDP packet. Save a protected backup of its config, then append this dedicated outbound to `outbounds`. Both IPv4 strategy fields keep the configuration compatible with the supported core versions. Add any provider metadata addresses outside the private set to the block list. + +```json +{ + "tag": "private-cascade-exit", + "protocol": "freedom", + "settings": { + "domainStrategy": "ForceIPv4", + "finalRules": [{"action": "block", "ip": ["geoip:private", "::/0"]}] + }, + "streamSettings": {"sockopt": {"domainStrategy": "ForceIPv4"}} +} +``` + +These restrictions apply to client destinations. The connection between VPSs can still use IPv6. + +In the foreign node's `routing.rules`, insert this rule after the existing block rules and before the first general forwarding rule that matches the cascade inbound, including the TCP/UDP catch-all. Replace `inbound-25443` with the actual inbound tag if you used a different port or profile. + +```json +{ + "type": "field", + "inboundTag": ["inbound-25443"], + "outboundTag": "private-cascade-exit" +} +``` + +Validate the edited foreign config with `sudo /usr/local/bin/xray run -test -config /usr/local/etc/xray/config.json`. After a successful check, restart its Xray service in the maintenance window and confirm this inbound selects `private-cascade-exit`. On validation or restart failure, restore and validate the backup before restoring service. In a single XUDP association, send a datagram to a controlled, permitted IPv4 endpoint, then a datagram to a controlled, prohibited endpoint. Confirm that the first arrives and the second does not. Verify the restrictions for both literal addresses and names that resolve to them. + + +## Prepare the routing lists + +The example below uses the installed `geosite.dat` for Russian categories and the compact Re-filter domain and IP lists for blocked destinations. Before updating existing list files, save their hashes and protected backups. Download both assets from one release and verify GitHub's published SHA-256 digests before installing them. [Re-filter sources](https://github.com/1andrevich/Re-filter-lists) + +```bash +( + set -eu + stage=$(mktemp -d) + trap 'rm -rf -- "$stage"' EXIT + curl -fsSL https://api.github.com/repos/1andrevich/Re-filter-lists/releases/latest \ + -o "$stage/release.json" + for kind in geoip geosite; do + name="$kind.dat" + url=$(jq -er --arg name "$name" '.assets[] | select(.name == $name) | .browser_download_url' "$stage/release.json") + hash=$(jq -er --arg name "$name" '.assets[] | select(.name == $name) | .digest | select(test("^sha256:[a-f0-9]{64}$")) | ltrimstr("sha256:")' "$stage/release.json") + curl -fsSL "$url" -o "$stage/$name" + printf '%s %s\n' "$hash" "$stage/$name" | sha256sum -c - + done + sudo install -o root -g xray -m 0644 "$stage/geoip.dat" /usr/local/share/xray/refilter-geoip.dat + sudo install -o root -g xray -m 0644 "$stage/geosite.dat" /usr/local/share/xray/refilter-geosite.dat +) +``` + +Keep the installed country data and its `geoip:private` and `geoip:ru` categories. The policy uses `geosite:available-only-in-ru` and `geosite:category-ru` from the installed domain data. If these categories are absent, update or select reviewed data before rendering. Revalidate a new candidate whenever lists change. If a list update fails, restore its previous files before restarting a running cascade. + +## Render and start the ingress + +On the Russian VPS, choose a working VLESS REALITY TCP or legacy XHTTP inbound with `decryption=none` and an empty VLESS `fallbacks` list. On a fresh installation, reserve a free template port and keep it closed at the provider firewall. Run `sudo xrayebator profile-create --name private-cascade-template --transport xhttp --without-pq --port 15442` and check that `names` includes the template and `errors` is empty. This creates `inbound-15442` in the main Xray configuration. The standalone service will listen on its own port, `15443` in this example. + +Generate a fresh UUID with `uuidgen` for the standalone ingress. Create two root-owned `0600` files inside a root-only directory such as `/root/xrayebator-private-cascade/`. Write the single upstream URI to `upstream.txt`, and fill `policy.json` using this example. Replace the inbound tag, UUID and example destinations with your own values. + +```json +{ + "inbound_tag": "inbound-15442", + "client_id": "", + "listen": "0.0.0.0", + "port": 15443, + "udp_relay_port": 15444, + "udp_dispatch_port": 15445, + "russia_only_domains": ["geosite:available-only-in-ru"], + "blocked_domains": ["ext:refilter-geosite.dat:refilter"], + "blocked_ips": ["ext:refilter-geoip.dat:refilter"], + "russian_domains": ["domain:ru", "domain:su", "domain:xn--p1ai", "geosite:category-ru"], + "russian_ips": ["geoip:ru"] +} +``` + +Choose a free TCP port and open it at both ingress firewalls for the intended client sources. Both `blocked_domains` and `blocked_ips` are required arrays, with at least one entry between them. Optional arrays `russia_only_domains`, `russian_domains`, and `russian_ips` define direct routes. The defaults for the latter two are `.ru`/`.рф` and `geoip:ru`. Use Xray selectors matching your deployed assets. `ext:` rules require their corresponding local data files. The renderer reads those assets from the host and performs no downloads. + +Use an empty array to disable an optional route list. Omitting an optional field uses its default. + +`udp_relay_port` and `udp_dispatch_port` default to `15444` and `15445`. Reserve two free unprivileged TCP ports for them on the Russian VPS. All three ports must differ. The local ports bind only to `127.0.0.1`; do not open them in either firewall. The renderer generates a separate helper password and classifier UUID in the protected config. Do not export these internal credentials to clients. + +The ingress blocks private and IPv6 destinations matched by its IP rules. Sniffing preserves a client-supplied address in those denied sets. For other TCP connections, a sniffed name becomes the destination that Xray actually connects to. A recognized Russia-only name takes precedence over the blocked lists, whether the client originally sent that name or its public IP. The blocked lists take precedence over the general Russian rules. The direct outbounds resolve names using IPv4 only and recheck destination IPs at dial time. A route selected by `russian_ips` can only connect to those IPs. If a later DNS lookup conflicts with the selected direct route, the connection fails. + +For UDP, the public inbound first sends every datagram to the authenticated loopback helper, including virtual DNS and denied-address attempts. XUDP can change destinations within one association. The helper therefore opens a separate fixed-destination VLESS UDP stream for each destination in that association; Xray then applies DNS interception, destination blocks and the five ordered rules to that stream. The helper does not duplicate the domain/IP lists or connect directly to internet destinations. Its local Trojan framing does not change the client-facing VLESS REALITY transport or require another domain or certificate. + +Recognized Russian UDP can exit directly in Russia. Foreign-hop failure stops foreign TCP and UDP without a direct fallback; direct Russian TCP/UDP and ingress DNS remain available. Helper failure stops application UDP, including virtual UDP DNS, while TCP keeps its routes. The helper rejects payloads above 8190 bytes rather than splitting them; Xray's 8 KiB framing buffers can lower the usable size further depending on address/header overhead. Check applications that need large datagrams separately. Fixed connection, flow, queue and idle-time limits bound the helper's resource use; reaching them drops or closes the affected traffic instead of choosing another exit. + +The split key is the destination address and port within the original association. Sniffing runs at the start of that fixed-destination stream; different QUIC connections sharing the same endpoint are not separately reclassified by every SNI. This is destination routing, not inspection of every application message. + +The ingress uses service DoH with a local resolver fallback. Configure the client to send its DNS to `192.0.2.53:53` inside VLESS. The virtual address is reserved for DNS on port 53. Disable client-side fallback to direct or another profile. + +```bash +sudo xrayebator private-cascade render \ + --policy-file /root/xrayebator-private-cascade/policy.json \ + --upstream-file /root/xrayebator-private-cascade/upstream.txt \ + --output /root/xrayebator-private-cascade/ingress.json +``` + +To try a reviewed checkout whose renderer is newer than the installed manager, use `sudo bash ./xrayebator private-cascade render` with the same arguments from that checkout. + +The renderer creates a public client with the new UUID and takes its flow from the template inbound's first client. It also creates the internal loopback classifier and helper credentials. It preserves the public transport and REALITY settings, validates with `xray run -test` and writes a new root-owned `0600` file. This validates Xray's config, not the helper's service availability. Choose an unused service directory for first installation. + +```bash +sudo install -d -o root -g xray -m 0750 /etc/xray-private-cascade +sudo install -o root -g xray -m 0640 /root/xrayebator-private-cascade/ingress.json \ + /etc/xray-private-cascade/config.json +sudo install -d -o root -g root -m 0755 /usr/local/libexec +sudo install -o root -g root -m 0755 libexec/private_cascade_udp.py \ + /usr/local/libexec/xrayebator-private-udp.py +command -v python3 +``` + +The install command reads the helper from the reviewed checkout, not a separately downloaded latest file. Ensure Python 3 is installed at `/usr/bin/python3` before starting; on the supported Debian/Ubuntu hosts install the `python3` package if absent. Keep the config root-owned and group-readable only by `xray` (`0640`); both services need it. + +Create `/etc/systemd/system/xray-private-cascade-udp.service` as root: + +```ini +[Unit] +Description=Xray private cascade UDP destination splitter +PartOf=xray-private-cascade.service + +[Service] +User=xray +Group=xray +NoNewPrivileges=true +ExecStart=/usr/bin/python3 /usr/local/libexec/xrayebator-private-udp.py --config /etc/xray-private-cascade/config.json +Restart=on-failure +``` + +Create `/etc/systemd/system/xray-private-cascade.service` as root. `Wants` starts the helper but keeps existing TCP routes available if it fails. `PartOf` stops or restarts the helper with the ingress. The bind capability also supports a free privileged ingress port such as 443. Keep the two local helper ports above 1023. This example uses the standard Xrayebator binary and asset paths. + +```ini +[Unit] +Description=Xray private cascade ingress +Wants=network-online.target xray-private-cascade-udp.service +After=network-online.target xray-private-cascade-udp.service + +[Service] +User=xray +Group=xray +AmbientCapabilities=CAP_NET_BIND_SERVICE +CapabilityBoundingSet=CAP_NET_BIND_SERVICE +NoNewPrivileges=true +Environment=XRAY_LOCATION_ASSET=/usr/local/share/xray +ExecStart=/usr/local/bin/xray run -config /etc/xray-private-cascade/config.json +Restart=on-failure + +[Install] +WantedBy=multi-user.target +``` + +```bash +sudo systemctl daemon-reload +sudo systemctl start xray-private-cascade.service +sudo systemctl status --no-pager xray-private-cascade.service xray-private-cascade-udp.service +ss -ltn 'sport = :15443' +ss -ltn 'sport = :15444 or sport = :15445' +``` + +Confirm that both local listeners use `127.0.0.1`. A running Xray service alone does not prove UDP works. On an update, protect backups of the config, helper and both units; validate the candidate, then restart the ingress so its `PartOf` helper rereads the matching credentials. Restore those files together if validation or acceptance fails. + +Use the template inbound's first client URI as a private reference. Replace its UUID with the new ingress UUID and set the dial address and port to the standalone listener. Keep the REALITY fields, flow, fingerprint, and transport options, including the XHTTP host, path and mode if present. Import it as a separate test profile. Rotate its UUID in the standalone config and issue a new link when needed. + +## Update and uninstall + +The standalone cascade has a manual lifecycle. Before an update, save protected backups of its config, installed helper and both unit files. Check out the reviewed revision, render and validate a new candidate at a new output path, then install the matching config and copy `libexec/private_cascade_udp.py` to `/usr/local/libexec/xrayebator-private-udp.py` again. Compare both unit files with the guide and apply any changes. Run `sudo systemctl daemon-reload` after unit changes, then restart `xray-private-cascade.service` so its helper reloads the same credentials. Repeat acceptance and restore the saved files together if it fails. + +Before running the general `uninstall.sh`, follow the rollback below. Stop the ingress and helper before removing `/etc/systemd/system/xray-private-cascade.service`, `/etc/systemd/system/xray-private-cascade-udp.service`, `/etc/xray-private-cascade/` and the installed helper. Run `systemctl daemon-reload` after removal, close the cascade's public ports and remove its foreign profile and scoped route. Keep protected source inputs and backups until rollback is no longer needed. The operator manages these separate files and units when using the normal installer, updater or uninstaller. + +## Verify or roll back the cascade + +1. From a desktop or command-line client on the intended network, verify the REALITY connection and send a few small HTTPS and DNS requests. Use controlled endpoints or destination-side logs to confirm that an explicit Russian route sees the Russian source IP and an unmatched route sees the foreign source IP. Check a Russia-only name whose public IPv4 also matches `blocked_ips` both by name and by IP with the same SNI. Both should reach the actual Russia-only destination directly. A general Russian name resolving to a blocked IP must take the foreign path. +2. In one real XUDP association, send small UDP datagrams to controlled Russian, foreign and blocked destinations, then back to the Russian destination. Confirm each delivery's source address and replies; repeat in the reverse order and with a virtual DNS query first. A blocked destination must take the foreign path even if its address is Russian. Private and IPv6 targets must not receive packets. Independent single-destination tests do not verify this transition. +3. In a maintenance window, withdraw only the dedicated foreign hop and open fresh test connections. Direct Russian TCP/UDP and virtual DNS must still work; foreign TCP/UDP must fail without traffic from the Russian exit. Restore the hop and check recovery. Separately stop only `xray-private-cascade-udp.service`: application UDP and virtual UDP DNS must stop without bypass while TCP keeps its routes. Restart the helper and check recovery. +4. Compare the original Xray service, profiles and subscriptions, Hysteria 2 and AmneziaWG against the preflight baseline. The separate units leave their services and routing in place. After verification, enable only the ingress at boot with `sudo systemctl enable xray-private-cascade.service`; its `Wants` starts the helper. +5. To roll back, disconnect the cascade profile and run `sudo systemctl disable --now xray-private-cascade.service`, then `sudo systemctl stop xray-private-cascade-udp.service`. Verify that all three ingress-side listeners are gone. Remove the two dedicated units and installed config; remove the installed helper only if it belongs solely to this cascade. Run `sudo systemctl daemon-reload`. Close only the dedicated public ports in both firewalls; the loopback ports need no public rules. Delete `private-cascade-egress` on the foreign VPS with `sudo xrayebator profile-delete --name private-cascade-egress`, then remove its routing rule and `private-cascade-exit` outbound. If you created `private-cascade-template`, delete that profile by name on the Russian VPS. Recheck the baseline services. diff --git a/docs/ru/configuration.md b/docs/ru/configuration.md index d8a24871..0b8ecd35 100644 --- a/docs/ru/configuration.md +++ b/docs/ru/configuration.md @@ -127,7 +127,7 @@ legacy-файлы и блоки, ранее созданные Xrayebator, и с | `sudo xrayebator kernel-guard [--status\|--enable\|--disable] [--quiet]` | Защита от CVE-2026-98432 (use-after-free в разборе IPv4-опций, CVSS 9.8, уязвимы все IPv4 TCP-листенеры). `--enable` выключает MPTCP в ядре (`net.mptcp.enabled = 0` в `/etc/sysctl.d/99-xrayebator-netguard.conf`) и дропает входящие IPv4 TCP-пакеты с IP-опциями по правилу Ubuntu Security Team — в отдельной nft-таблице со своим юнитом автозагрузки, намеренно НЕ через `nftables.service`, чей дефолтный `flush ruleset` при загрузке снёс бы правила UFW. MPTCP дополнительно выключается миграцией `netguard_mptcp_2026`; дроп IPv4-опций остаётся осознанным решением, потому что меняет то, какие пакеты сервер принимает. `--status` отдаёт запущенное ядро, `newer_kernel_installed`, `reboot_required`, `mptcp_enabled`, `ipv4_options_drop`, версию Xray-core и признак того, что она не ниже `26.10.31` (`xray_mptcp_safe`). Это мера сокращения поверхности, а не обновление ядра. Доступно также пунктом меню 16 | | `sudo xrayebator ssh-protect [--status\|--enable\|--disable] [--unban IP\|--prune-ignore] [--quiet]` | Защита SSH от перебора: ставит `fail2ban` с джейлом `sshd` на journald (4 неудачи за 10 минут → бан на 30 минут, повторным — до суток) и drop-in в `sshd_config.d` с `MaxAuthTries 3` / `LoginGraceTime 30`. **Парольный вход остаётся включён** — по нему десктоп-GUI управляет сервером, а переход на ключи остаётся отдельным решением оператора. Идемпотентно: drop-in проверяется через `sshd -t`, `ssh` перечитывает конфиг (`reload`, не `restart`), поэтому открытые сессии GUI не рвутся. Включается автоматически в `install.sh` и в `quickstart` (в JSON деплоя есть `ssh_protect`); `--quiet` глушит JSON для скриптов. То же доступно пунктом меню 15 и вкладкой **Безопасность и TLS** в GUI. Замер на живом VPS: 9 953 неудачных входа за сутки со 115 адресов, после включения — ≈72/час. Адрес, с которого запускали команду, исключается из банов на 24 часа (`ignoreip` + метка срока; по истечении его снимает `--prune-ignore` по таймеру `xrayebator-ssh-ignoreip.timer`) | | `sudo xrayebator profiles` | Вывести все профили сервера JSON-массивом (для «Настроек сервера» GUI); срок содержит epoch-секунды (`expire`) для принуждения и календарную дату в зоне сервера (`expire_date`) для отображения, поэтому клиент с другой временной зоной видит выбранную дату | -| `sudo xrayebator profile-create --name ИМЯ [--transport tcp\|tcp-utls\|tcp-xudp\|tcp-mux\|grpc\|xhttp] [--port P] [--count N] [--expire ДАТА]` | Создать профили без интерактива; `--expire` принимает `ГГГГ-ММ-ДД[ ЧЧ:ММ]`, epoch-секунды или 13-значные миллисекунды. Дата без времени действует включительно до `23:59:59` по локальным часам сервера; указанное время трактуется в той же зоне. Уже прошедший срок отклоняется; существующие имена не перезаписываются — они попадают в `errors` (GUI дополнительно проверяет коллизию имени до создания, поскольку удаление идёт по профилю целиком и уникальность имён делает его прицельным); `{"ok":true,"names":[...],"errors":[...]}` | +| `sudo xrayebator profile-create --name ИМЯ [--transport tcp\|tcp-utls\|tcp-xudp\|tcp-mux\|grpc\|xhttp] [--port P] [--count N] [--expire ДАТА] [--without-pq]` | Создать профили без интерактива; XHTTP по умолчанию использует PQ. `--without-pq` допустим только для XHTTP и создаёт legacy-профиль с `encryption=none` на свободном порту или совместимом существующем inbound. `--expire` принимает `ГГГГ-ММ-ДД[ ЧЧ:ММ]`, epoch-секунды или 13-значные миллисекунды. Дата без времени действует включительно до `23:59:59` по локальным часам сервера; указанное время трактуется в той же зоне. Уже прошедший срок отклоняется; существующие имена не перезаписываются — они попадают в `errors` (GUI дополнительно проверяет коллизию имени до создания, поскольку удаление идёт по профилю целиком и уникальность имён делает его прицельным); `{"ok":true,"names":[...],"errors":[...]}` | | `sudo xrayebator profile-delete --name ИМЯ` | Удалить профиль без интерактива; бэкенд-гранты удалённого профиля отзываются сразу — peer снимается с `awg0.conf`, пароль уходит из `server.yaml` (осиротевших креденшелов нет), имя освобождается для повторного использования; `{"ok":true,"name":"..."}` | | `sudo xrayebator profile-revoke --name ИМЯ [--full]` | Перевыпустить ссылку подписки: новый `sub_token`; с `--full` — ещё и новый uuid во всех inbound'ах профиля (уже скачанные конфиги отваливаются); JSON | | `sudo xrayebator profile-expire --name ИМЯ --expire ДАТА\|epoch\|none` | Задать, продлить или снять срок действия профиля; дата без времени действует включительно до `23:59:59` по локальным часам сервера, указанное время используется как есть в той же зоне; применение немедленное (истёкший срок сразу снимает клиента, продление возвращает); JSON | @@ -665,6 +665,8 @@ IP-таймер shortlived-сертификатов ставится тольк ## Каскад и upstream-ноды +Действие `--without-pq` зависит от команды. `quickstart --without-pq` отключает добавление отдельного PQ-маршрута в управляемый многомаршрутный профиль. `profile-create --transport xhttp --without-pq` создает базовый XHTTP-профиль с `encryption=none` вместо PQ. + Каскад — серверный режим outbound и routing, а не новый профиль клиента. Клиент продолжает подключаться к текущему VPS: @@ -686,6 +688,9 @@ IP-таймер shortlived-сертификатов ставится тольк Пункт `10` настраивает обратную сторону: делает из текущего VPS зарубежную ноду, к которой подключается каскад с другого сервера. +Для отдельного российского входа с локальным выходом по выбранным правилам и закрытым зарубежным +узлом см. [Развертывание частного каскада](private-cascade.md). + ## Собственный домен и self-steal заглушка Self-steal ставит nginx с валидным сертификатом на `127.0.0.1:9444`, а Reality-инбаунды получают diff --git a/docs/ru/private-cascade.md b/docs/ru/private-cascade.md new file mode 100644 index 00000000..e93c289d --- /dev/null +++ b/docs/ru/private-cascade.md @@ -0,0 +1,233 @@ +# Приватный каскад через российский VPS + +[← Назад к README](../../README.ru.md) · [English](../private-cascade.md) · [简体中文](../zh-CN/private-cascade.md) + +## Схема + +Нужны два VPS. Клиент подключается к российскому узлу. Узел применяет одинаковую политику к TCP и поддерживаемому прикладному UDP: выбранные российские ресурсы выходят из России, заблокированные и не совпавшие с российскими правилами — через зарубежный VPS по VLESS REALITY. + +| VPS | Роль | Какой адрес нужен | +|---|---|---| +| Входной в России, например в Москве | Принимает клиентов и выпускает явно выбранный трафик из России | Публичный адрес, доступный клиентам, и известный стабильный исходящий адрес для связи с зарубежным VPS | +| Выходной за рубежом | Принимает соединение от российского VPS и выпускает переданный трафик в интернет | Публичный адрес подключения, доступный из России, и рабочий выход к ресурсам, которые нужны клиентам | + +Для этих ролей достаточно одного публичного IPv4 на каждый VPS. Зарубежный узел может принимать соединение и выпускать трафик с одного адреса. В полной схеме из статьи зарубежные адреса приёма и выхода дополнительно разделены через второй IP, шлюз или WARP. Для российских ресурсов автор делает явное исключение. При прямом маршруте такой ресурс видит публичный IP входного узла. Объяснение автора о том, как узнают и блокируют адреса, остаётся гипотезой. [Статья на Хабре, раздел 4](https://habr.com/ru/articles/1103460/) + +## Перед изменениями на VPS + +1. Проверьте условия обоих хостингов для предполагаемого использования прокси. Запишите фактические публичные адреса, исходящий IP, который зарубежный VPS увидит с учётом NAT провайдера, порты и способ входа через аварийную консоль. Сверьте ключи SSH-серверов по независимому источнику. Поддерживаемые ОС перечислены в [рекомендациях по VPS](recommendations.md#выбор-vps). +2. Убедитесь, что клиентская сеть достаёт до российского слушателя по IPv4. Между серверами используйте IPv4 с ограничением доступа по источнику или IPv6, если на всём пути работают маршрут, слушатель и правила firewall. Если клиентам нужны IPv4-ресурсы, отдельно проверьте, что зарубежный VPS до них достаёт. +3. Зафиксируйте текущие маршруты и профили Xray, бэкенды, слушатели и правила firewall на хостах и у провайдеров. Сделайте защищённые резервные копии или снимки и держите открытым отдельный сеанс администрирования. Если подготовка любого из узлов требует перезапуска действующей службы или изменения её порта, работайте в окно обслуживания. +4. Выделите отдельный TCP-порт на зарубежном VPS. В firewall провайдера разрешите подключения к этому порту только с фактического исходящего адреса российского VPS (`/32` для IPv4 или `/128` для IPv6). На самом хосте задайте такое же ограничение и проверьте отсутствие более широких разрешений, в том числе созданных Xrayebator. Сохраните правила для SSH, подписок и существующих клиентских портов. Ограничьте порт у провайдера до создания входящего подключения Xray, поскольку менеджер может открыть порт в UFW. +5. Используйте отдельные данные доступа по SSH, пары ключей REALITY и ключи сертификатов для каждого VPS. Создайте отдельный VLESS UUID для связи между узлами. Клиентам выдавайте только профиль российского входа. Ссылку или UUID зарубежного узла храните на двух VPS, которым они нужны. Дайте токенам DNS минимальные права и храните их в файлах, доступных только root. Убирайте ссылки и токены из журналов и отчётов. + +На чистых VPS установите Xrayebator на обоих узлах. Этот пример использует Xray и локальный UDP-обработчик на стандартной библиотеке Python 3 на входном узле; дополнительные VPN-бэкенды не нужны. Если на одном из узлов уже установлены дополнительные протоколы, после создания профиля проверьте выданный ему доступ. Xrayebator передаёт события создания и удаления профиля установленным бэкендам. [Установка](../../README.ru.md#установка) + +Для ограничений назначения ниже нужен Xray-core 26.6.27 или новее на обоих узлах. Получите на каждом VPS одну и ту же проверенную рабочую копию Xrayebator с командами `profile-create --without-pq`, `private-cascade` и файлом `libexec/private_cascade_udp.py`. Установленный менеджер сам по себе не устанавливает этот отдельный обработчик и его unit-файлы. Выполняйте команды ниже из рабочей копии; если установленный менеджер старее, замените `sudo xrayebator` на `sudo bash ./xrayebator`. При обновлении используйте согласованные проверенные версии обработчика и сгенерированного конфига. + +В свободном каталоге на каждом VPS получите проверенный тег или коммит, а не меняющийся latest-файл. До выполнения замените значение ссылки: + +```bash +CASCADE_REVIEWED_REF='replace-with-reviewed-tag-or-commit' +git clone --no-checkout https://github.com/howdeploy/Xrayebator.git xrayebator-cascade-src +cd xrayebator-cascade-src +git fetch --depth 1 origin "$CASCADE_REVIEWED_REF" +git checkout --detach FETCH_HEAD +``` + +## Имена, сертификаты и REALITY + +- Используйте уже имеющийся домен под вашим управлением. Выделите имена вроде `ingress.example.com` и `egress.example.com`. Направьте записи `A` на соответствующие публичные IPv4. Добавляйте `AAAA` после проверки доступности по IPv6 и ограничений firewall. Если DNS-провайдер предлагает проксирование, используйте режим DNS only. Служебное имя от хостинга подходит, если вы можете подтвердить необходимый контроль над DNS и выпускать и продлевать сертификат на это имя. +- Для стандартной маскировки REALITY оставьте рабочие SNI и TLS-цель, заданные в Xrayebator, и подключайтесь к VPS по IP. Для туннеля в этой схеме не требуется регистрировать домен или выпускать сертификат. +- Адрес для подключения каскада может быть доступным IP или именем. IP-сертификат подходит для HTTPS-подписки. Для self-steal задайте в SNI REALITY имя из сертификата TLS-сайта на loopback. Для XHTTP укажите это же имя в `host`. [Домен и DNS](configuration.md#домен-и-dns) · [Self-steal](configuration.md#собственный-домен-и-self-steal-заглушка) +- Для self-steal с закрытым портом 80 используйте ACME-плагин своего DNS-провайдера в режиме выпуска сертификата. Подключите сертификат к TLS-сайту на loopback, добавьте перечитывание конфигурации TLS-сервиса после продления и проверьте сертификат на loopback. Встроенная команда `dns01-setup` настраивает отдельный HTTPS-слушатель для подписки с Cloudflare или Route 53. Запускайте её, только если также хотите опубликовать подписку. Передавайте секрет через файл или stdin. [DNS-01](configuration.md#dns-01-сертификат-и-домен-подписки-без-порта-80) + +## Подготовьте зарубежный узел + +На зарубежном VPS создайте выделенный профиль legacy XHTTP командой `sudo xrayebator profile-create --name private-cascade-egress --transport xhttp --without-pq --port 25443`. Проверьте наличие имени в `names` и пустой список `errors`. Получите ссылку XHTTP в меню профилей и сохраните фактические значения `path`, `host` и `mode`. IPv6-адрес подключения возьмите в квадратные скобки. + +```text +vless://@:?encryption=none&security=reality&type=xhttp&sni=&fp=&pbk=&sid=&host=&path=&mode= +``` + +TCP Vision также поддерживается. Используйте `--transport tcp` без `--without-pq` на свободном порту, отличном от 443, и сохраните `flow=xtls-rprx-vision` в ссылке. При этом flow Xray отклоняет открытие UDP-сессий к порту 443 на зарубежном маршруте. Браузеры могут повторить HTTPS-запрос по TCP, если HTTP/3 недоступен. Пример с XHTTP поддерживает прикладной UDP/443. + +Проверьте доступность порта с российского VPS и отказ с адреса вне списка разрешённых. Убедитесь, что зарубежный VPS может выходить в интернет. [Обычный каскад](configuration.md#каскад-и-upstream-ноды) + +Зарубежный VPS самостоятельно разрешает имена назначения. Ограничьте его выход публичными IPv4-адресами, в том числе для каждого UDP-пакета. Сохраните защищённую копию конфига и добавьте следующий выход в `outbounds`. Два поля стратегии IPv4 обеспечивают совместимость с поддерживаемыми версиями ядра. Добавьте в список блокировки адреса метаданных хостинга, если их нет в наборе приватных адресов. + +```json +{ + "tag": "private-cascade-exit", + "protocol": "freedom", + "settings": { + "domainStrategy": "ForceIPv4", + "finalRules": [{"action": "block", "ip": ["geoip:private", "::/0"]}] + }, + "streamSettings": {"sockopt": {"domainStrategy": "ForceIPv4"}} +} +``` + +Эти ограничения относятся к назначениям клиентов. Межсерверное соединение может работать по IPv6. + +В `routing.rules` зарубежного узла добавьте это правило после существующих правил блокировки и перед первым общим правилом, которое может принять трафик каскада, включая маршрут TCP/UDP по умолчанию. Если использовали другой порт или профиль, подставьте фактический тег входа вместо `inbound-25443`. + +```json +{ + "type": "field", + "inboundTag": ["inbound-25443"], + "outboundTag": "private-cascade-exit" +} +``` + +Проверьте изменённый конфиг командой `sudo /usr/local/bin/xray run -test -config /usr/local/etc/xray/config.json`. После успешной проверки перезапустите Xray в окно обслуживания и подтвердите, что выделенный вход выбирает `private-cascade-exit`. При ошибке проверки или запуска восстановите и проверьте резервную копию перед возвратом службы. В одной XUDP-сессии отправьте первый пакет на контролируемый разрешённый IPv4-адрес, а второй — на контролируемый запрещённый адрес. Убедитесь, что первый дошёл, а второй был заблокирован. Проверьте ограничения и для IP, и для доменов, которые разрешаются в эти адреса. + + +## Подготовьте списки маршрутизации + +Пример ниже использует установленный `geosite.dat` для российских категорий и компактные списки Re-filter для заблокированных доменов и адресов. Перед обновлением существующих файлов сохраните их хеши и защищённые копии. Скачайте оба набора из одного релиза и проверьте SHA-256 из метаданных GitHub перед установкой. [Источники Re-filter](https://github.com/1andrevich/Re-filter-lists) + +```bash +( + set -eu + stage=$(mktemp -d) + trap 'rm -rf -- "$stage"' EXIT + curl -fsSL https://api.github.com/repos/1andrevich/Re-filter-lists/releases/latest \ + -o "$stage/release.json" + for kind in geoip geosite; do + name="$kind.dat" + url=$(jq -er --arg name "$name" '.assets[] | select(.name == $name) | .browser_download_url' "$stage/release.json") + hash=$(jq -er --arg name "$name" '.assets[] | select(.name == $name) | .digest | select(test("^sha256:[a-f0-9]{64}$")) | ltrimstr("sha256:")' "$stage/release.json") + curl -fsSL "$url" -o "$stage/$name" + printf '%s %s\n' "$hash" "$stage/$name" | sha256sum -c - + done + sudo install -o root -g xray -m 0644 "$stage/geoip.dat" /usr/local/share/xray/refilter-geoip.dat + sudo install -o root -g xray -m 0644 "$stage/geosite.dat" /usr/local/share/xray/refilter-geosite.dat +) +``` + +Сохраните установленную базу стран с категориями `geoip:private` и `geoip:ru`. Политика использует `geosite:available-only-in-ru` и `geosite:category-ru` из установленной базы доменов. Если этих категорий нет, обновите или выберите проверенные данные перед генерацией. После изменения списков проверяйте новый конфиг. При неудачном обновлении восстановите прежние файлы перед перезапуском действующего каскада. + +## Сгенерируйте конфигурацию и запустите входной узел + +На российском VPS выберите рабочий инбаунд VLESS REALITY TCP или legacy XHTTP с `decryption=none` и пустым списком VLESS `fallbacks`. На чистой установке выделите свободный порт для шаблона и оставьте его закрытым в firewall провайдера. Выполните `sudo xrayebator profile-create --name private-cascade-template --transport xhttp --without-pq --port 15442`. Проверьте наличие имени в `names` и пустой список `errors`. В основном конфиге появится `inbound-15442`. Отдельная служба будет слушать свой порт, в этом примере `15443`. + +Сгенерируйте новый UUID для выделенного входа командой `uuidgen`. В каталоге, доступном только root, например `/root/xrayebator-private-cascade/`, создайте два файла владельца root с правами `0600`. Запишите одну ссылку зарубежного узла в `upstream.txt`. Заполните `policy.json` по примеру, заменив тег инбаунда, UUID и демонстрационные адреса назначения своими значениями. + +```json +{ + "inbound_tag": "inbound-15442", + "client_id": "", + "listen": "0.0.0.0", + "port": 15443, + "udp_relay_port": 15444, + "udp_dispatch_port": 15445, + "russia_only_domains": ["geosite:available-only-in-ru"], + "blocked_domains": ["ext:refilter-geosite.dat:refilter"], + "blocked_ips": ["ext:refilter-geoip.dat:refilter"], + "russian_domains": ["domain:ru", "domain:su", "domain:xn--p1ai", "geosite:category-ru"], + "russian_ips": ["geoip:ru"] +} +``` + +Выберите свободный TCP-порт и откройте его для нужных клиентов в firewall хоста и провайдера. Массивы `blocked_domains` и `blocked_ips` обязательны. Хотя бы один из них должен содержать правило. Необязательные массивы `russia_only_domains`, `russian_domains` и `russian_ips` определяют прямые маршруты. Для двух последних значения по умолчанию покрывают `.ru`/`.рф` и `geoip:ru`. Указывайте селекторы Xray, доступные в установленных базах. Для `ext:` нужны соответствующие локальные файлы данных. Генератор использует базы на VPS без загрузки из сети. + +Чтобы отключить необязательный список, укажите пустой массив. Если поле пропущено, генератор использует значение по умолчанию. + +Значения `udp_relay_port` и `udp_dispatch_port` по умолчанию — `15444` и `15445`. Выделите для них два свободных непривилегированных TCP-порта на российском VPS. Все три порта должны различаться. Локальные порты слушают только `127.0.0.1`; не открывайте их в firewall хоста или провайдера. Генератор записывает отдельный пароль обработчика и UUID классификатора в защищённый конфиг. Не передавайте эти внутренние данные клиентам. + +Входной узел блокирует приватные и IPv6-адреса назначения, которые совпадают с его правилами по IP. Sniffing сохраняет переданный клиентом адрес из этих запрещённых наборов. Для остальных TCP-соединений распознанное имя становится фактическим назначением. Домен из `russia_only_domains` имеет приоритет перед списками блокировок и при передаче имени, и при передаче его публичного IP с тем же SNI. Списки блокировок имеют приоритет перед общими российскими правилами. Прямые выходы разрешают имена только в IPv4 и повторно проверяют адрес назначения при подключении. Маршрут по `russian_ips` разрешает соединения только с адресами из этого списка. Если результат повторного DNS-запроса противоречит выбранному прямому маршруту, соединение закрывается. + +Для UDP публичный инбаунд сначала передаёт каждый пакет локальному обработчику с аутентификацией, включая запросы к виртуальному DNS и запрещённым адресам. XUDP может менять назначение внутри одной сессии. Поэтому обработчик открывает отдельный VLESS UDP-поток с неизменным назначением для каждого адреса и порта этой сессии. Затем Xray применяет к нему перехват DNS, запреты адресов и пять правил в нужном порядке. Обработчик не дублирует доменные/IP-списки и сам не подключается к интернет-ресурсам. Его локальное обрамление Trojan не меняет клиентский VLESS REALITY и не требует нового домена или сертификата. + +Распознанный российский UDP может выходить напрямую из России. При отказе зарубежного узла зарубежные TCP и UDP останавливаются без прямого обхода; российские TCP/UDP и DNS входного узла продолжают работать. При отказе обработчика прикладной UDP, в том числе виртуальный UDP DNS, останавливается, а TCP сохраняет свои маршруты. Обработчик отклоняет полезную нагрузку больше 8190 байт, а не дробит её; буферы обрамления Xray размером 8 КиБ могут дополнительно уменьшать доступный размер в зависимости от адреса и заголовка. Приложения с крупными датаграммами проверяйте отдельно. Фиксированные ограничения числа соединений, потоков, очередей и времени бездействия ограничивают ресурсы обработчика; при их достижении соответствующий трафик отбрасывается или закрывается без выбора другого выхода. + +Ключ разделения — адрес назначения и порт внутри исходной ассоциации. Сниффинг выполняется в начале такого потока с фиксированной целью; разные QUIC-соединения к одному адресу и порту не классифицируются заново по каждому SNI. Это маршрутизация назначений, а не проверка каждого сообщения приложения. + +Входной узел использует служебный DoH с локальным резолвером в резерве. Настройте клиентский DNS на `192.0.2.53:53` внутри VLESS. Виртуальный адрес выделен для DNS на порту 53. Отключите на клиенте автоматическое переключение на прямое подключение или другой профиль. + +```bash +sudo xrayebator private-cascade render \ + --policy-file /root/xrayebator-private-cascade/policy.json \ + --upstream-file /root/xrayebator-private-cascade/upstream.txt \ + --output /root/xrayebator-private-cascade/ingress.json +``` + +Если установленный менеджер ещё не содержит генератор, запустите `sudo bash ./xrayebator private-cascade render` с теми же аргументами из проверенной рабочей копии проекта. + +Генератор добавляет публичного клиента с новым UUID и берёт его flow из первого клиента исходного инбаунда. Также он создаёт внутренний loopback-классификатор и данные доступа обработчика. Параметры публичного транспорта и REALITY сохраняются. Генератор проверяет конфигурацию через `xray run -test` и записывает новый файл владельца root с правами `0600`. Это проверка конфига Xray, а не доступности службы обработчика. Для первой установки выберите отдельный свободный каталог. + +```bash +sudo install -d -o root -g xray -m 0750 /etc/xray-private-cascade +sudo install -o root -g xray -m 0640 /root/xrayebator-private-cascade/ingress.json \ + /etc/xray-private-cascade/config.json +sudo install -d -o root -g root -m 0755 /usr/local/libexec +sudo install -o root -g root -m 0755 libexec/private_cascade_udp.py \ + /usr/local/libexec/xrayebator-private-udp.py +command -v python3 +``` + +Команда установки берёт обработчик из проверенной рабочей копии, а не отдельно загруженный latest-файл. До запуска убедитесь, что Python 3 установлен по пути `/usr/bin/python3`; на поддерживаемых Debian/Ubuntu при его отсутствии установите пакет `python3`. Конфиг должен принадлежать root и читаться только группой `xray` (`0640`): он нужен обеим службам. + +Создайте от root файл `/etc/systemd/system/xray-private-cascade-udp.service`: + +```ini +[Unit] +Description=Xray private cascade UDP destination splitter +PartOf=xray-private-cascade.service + +[Service] +User=xray +Group=xray +NoNewPrivileges=true +ExecStart=/usr/bin/python3 /usr/local/libexec/xrayebator-private-udp.py --config /etc/xray-private-cascade/config.json +Restart=on-failure +``` + +Создайте от root файл `/etc/systemd/system/xray-private-cascade.service`. `Wants` запускает обработчик и сохраняет TCP-маршруты при его отказе. `PartOf` останавливает или перезапускает обработчик вместе со входным узлом. Право привязки к низкому порту позволяет использовать свободный порт 443. Оба локальных порта обработчика оставьте выше 1023. Пример использует стандартные пути Xrayebator к бинарнику и базам. + +```ini +[Unit] +Description=Xray private cascade ingress +Wants=network-online.target xray-private-cascade-udp.service +After=network-online.target xray-private-cascade-udp.service + +[Service] +User=xray +Group=xray +AmbientCapabilities=CAP_NET_BIND_SERVICE +CapabilityBoundingSet=CAP_NET_BIND_SERVICE +NoNewPrivileges=true +Environment=XRAY_LOCATION_ASSET=/usr/local/share/xray +ExecStart=/usr/local/bin/xray run -config /etc/xray-private-cascade/config.json +Restart=on-failure + +[Install] +WantedBy=multi-user.target +``` + +```bash +sudo systemctl daemon-reload +sudo systemctl start xray-private-cascade.service +sudo systemctl status --no-pager xray-private-cascade.service xray-private-cascade-udp.service +ss -ltn 'sport = :15443' +ss -ltn 'sport = :15444 or sport = :15445' +``` + +Убедитесь, что оба локальных слушателя используют `127.0.0.1`. Работающая служба Xray сама по себе не подтверждает UDP. При обновлении сохраните защищённые копии конфига, обработчика и обоих unit-файлов. Проверьте кандидат и перезапустите входной узел, чтобы обработчик через `PartOf` перечитал согласованные данные доступа. При неудачной проверке или приёмке восстановите эти файлы вместе. + +Возьмите ссылку первого клиента из исходного инбаунда за образец в закрытом канале. Подставьте новый UUID, адрес и порт отдельной службы. Сохраните параметры REALITY, flow, fingerprint и настройки транспорта, в том числе `host`, `path` и `mode` для XHTTP. Импортируйте ссылку как отдельный тестовый профиль. При ротации обновите UUID в отдельном конфиге и выдайте новую ссылку. + +## Обновление и удаление + +Отдельный каскад обслуживается вручную. Перед обновлением сохраните защищенные копии конфига, установленного помощника и обоих unit-файлов. Переключите исходники на проверенную ревизию, сгенерируйте и проверьте новый конфиг с новым путем вывода, затем установите его и повторно скопируйте `libexec/private_cascade_udp.py` в `/usr/local/libexec/xrayebator-private-udp.py`. Сверьте оба unit-файла с инструкцией и внесите изменения. После изменения unit-файлов выполните `sudo systemctl daemon-reload`, затем перезапустите `xray-private-cascade.service`, чтобы помощник перечитал те же учетные данные. Повторите приемку и при ошибке восстановите сохраненные файлы вместе. + +Перед запуском общего `uninstall.sh` выполните откат ниже. Сначала остановите входной узел и помощник, затем удалите `/etc/systemd/system/xray-private-cascade.service`, `/etc/systemd/system/xray-private-cascade-udp.service`, `/etc/xray-private-cascade/` и установленного помощника. Выполните `systemctl daemon-reload`, закройте публичные порты каскада и удалите его зарубежный профиль и выделенное правило маршрутизации. Сохраняйте защищенные исходные файлы и резервные копии, пока они нужны для отката. При использовании обычных установщика, обновления и удаления оператор обслуживает эти отдельные файлы и службы вручную. + +## Проверьте каскад и подготовьте откат + +1. С компьютера или клиента командной строки в нужной сети проверьте подключение REALITY и выполните несколько небольших HTTPS- и DNS-запросов. По журналам на контролируемых ресурсах подтвердите, что явно выбранный российский маршрут выходит с российского адреса, а маршрут по умолчанию — с зарубежного. Проверьте домен из российского исключения, чей публичный IPv4 также входит в `blocked_ips`, по имени и по IP с тем же SNI. Оба запроса должны доходить до фактического российского исключения напрямую. Обычный российский домен с адресом из списка блокировки должен идти через зарубежный узел. +2. В одной настоящей XUDP-сессии отправьте небольшие UDP-пакеты на контролируемый российский, зарубежный и заблокированный адрес, затем снова на российский. Подтвердите исходящий адрес каждой доставки и ответы; повторите в обратном порядке и с запросом к виртуальному DNS в начале. Заблокированное назначение должно идти за рубеж, даже если его адрес российский. Приватные и IPv6-назначения не должны получать пакеты. Раздельные тесты с одним назначением такую смену не проверяют. +3. В окно обслуживания отключите только выделенный зарубежный канал и откройте новые тестовые соединения. Прямые российские TCP/UDP и виртуальный DNS должны работать, зарубежные TCP/UDP — остановиться без трафика с российского выхода. Восстановите канал и проверьте связь. Отдельно остановите только `xray-private-cascade-udp.service`: прикладной UDP и виртуальный UDP DNS должны остановиться без обхода, а TCP — сохранить маршруты. Запустите обработчик и проверьте восстановление. +4. Сверьте обычную службу Xray, профили, подписки, Hysteria 2 и AmneziaWG с исходным состоянием. Отдельные службы сохраняют их маршруты и настройки. После успешной проверки включите запуск при загрузке только входного узла командой `sudo systemctl enable xray-private-cascade.service`; его `Wants` запускает обработчик. +5. Для отката отключите профиль каскада на клиенте и выполните `sudo systemctl disable --now xray-private-cascade.service`, затем `sudo systemctl stop xray-private-cascade-udp.service`. Убедитесь, что все три слушателя на входном узле исчезли. Удалите два выделенных unit-файла и установленный конфиг; удаляйте установленный обработчик, только если его использует исключительно этот каскад. Выполните `sudo systemctl daemon-reload`. Закройте только выделенные публичные порты в обоих firewall: для loopback-портов публичные правила не нужны. Удалите профиль зарубежного узла командой `sudo xrayebator profile-delete --name private-cascade-egress`, затем его правило маршрутизации и выход `private-cascade-exit`. Если создавался профиль `private-cascade-template`, удалите его по имени на российском VPS. Повторно проверьте исходные службы. diff --git a/docs/ru/testing.md b/docs/ru/testing.md index 559e8857..67e18866 100644 --- a/docs/ru/testing.md +++ b/docs/ru/testing.md @@ -28,6 +28,8 @@ ShellCheck не является CI-гейтом в текущих workflow. Г полный набор validation на Ubuntu; локальные результаты ShellCheck не стоит описывать как отдельное требование CI. +Для тестов UDP-помощника и runtime-стенда с настоящим ядром нужен `python3`. Перед прямым запуском стенда проверьте `command -v python3`. Bash-обертка тестов помощника сообщает о пропуске, если интерпретатор отсутствует. + Bash-тесты используют linux-инструменты: `jq`, `uuidgen`, `rg`. Поэтому голый чекаут в Windows Git Bash может не суметь прогнать весь набор; для достоверных результатов используйте окружение Ubuntu CI или Linux-машину. Проверки lifecycle должны также убеждаться в состоянии Xray, DNS и endpoint/сервиса @@ -36,7 +38,7 @@ Linux-машину. Проверки lifecycle должны также убеж ## Что покрывают тесты -В `validation/` ровно 49 скриптов. Запускайте каждый `validation/test-*.sh`; текущий набор: +В `validation/` ровно 51 Bash-скрипт. Запускайте каждый `validation/test-*.sh`; текущий набор: | Тест | Что проверяет | |---|---| @@ -54,6 +56,8 @@ Linux-машину. Проверки lifecycle должны также убеж | `test-certbot-snap-ip.sh` | Certbot для IP-сертификатов: единственная реализация `_ensure_certbot_ip_tls` (в quickstart нет своего `snap install`), ожидание готовности snapd (`snap wait system seed.loaded`), повтор установки, проверка результата по фактическим флагам бинарника, вывод snap в лог вместо stdout; функционально — `_certbot_supports_ip_address` отличает certbot 5.4+ от apt-версии и от бинарника без `--preferred-profile` | | `test-profile-revoke-expire-cli.sh` | CLI `profile-revoke` (только токен / ротация uuid с сохранением чужих клиентов на общем порту) и сроки профилей (отключение, возврат из снимка, rebuild без снимка, идемпотентный `expire-check`) | | `test-cascade-routing.sh` | Cascade routing | +| `test-private-cascade-udp.sh` | Локальный UDP-обработчик: аутентификация, границы кадров, разделение назначений, ответы, освобождение ресурсов и лимиты на стенде стандартной библиотеки Python | +| `test-profile-create-without-pq.sh` | Создание и экспорт legacy XHTTP, обычный режим PQ, несовместимые порты и события бэкендов | | `test-cascade-upstream-import.sh` | Импорт upstream каскада из ссылки VLESS | | `test-dead-stealth-route-pruning.sh` | Отсечение мёртвых stealth-маршрутов | | `test-fingerprint-subscription-sync.sh` | Синхронность маршрутов и подписки при смене fingerprint | @@ -99,6 +103,8 @@ Linux-машину. Проверки lifecycle должны также убеж > без сертификата Let's Encrypt на подписку — при живом серте `_hysteria2_tls_mode_detect` честно > отвечает `le `, тогда как тест ожидает `selfsigned`. +Задания `udp-runtime` в CI дополнительно запускают `test-private-cascade-udp-runtime.py` с официальными Xray 26.6.27 и 26.10.31 после проверки SHA-256. Локальные приёмники и узкие тестовые исключения позволяют наблюдать реальные исходящие адреса UDP, смену назначений одной XUDP-сессии, ответы, замену цели по QUIC и поведение при отказе. В Linux запускайте `python3 validation/test-private-cascade-udp-runtime.py --repo "$PWD" --xray /путь/к/xray --local-ip 127.0.0.2`; рядом с бинарём нужны его geo-файлы. На другой системе укажите уже существующий локальный IPv4, отличный от `127.0.0.1`, и Bash 4+ через `--bash`, с GNU coreutils в PATH. Не добавляйте сетевой адрес только ради теста. Это не заменяет проверку firewall провайдера и живых клиентов. + ## Проверка lifecycle и HAPP-эндпоинта Для новой развёртки прогоните широкий путь `quickstart --email <адрес>` и убедитесь, что он поднимает @@ -218,7 +224,7 @@ npm run build - `.github/workflows/ci-linux.yml` — гейт Bash-ядра на `ubuntu-24.04`: ставит `jq`, `uuid-runtime` и `ripgrep`, прогоняет все четыре проверки синтаксиса Bash, затем запускает каждый - `validation/test-*.sh` (на момент написания — 49). + `validation/test-*.sh` (сейчас их 51). - `.github/workflows/release.yml` — активный путь релиза Electron для тегов `v*` и ручных запусков. Сначала job `preflight` проверяет, что файл релизных заметок `docs/releases/.en.md` существует и что секрет репозитория `AP3X0` (если задан) действительно может создавать релизы — проверка идёт diff --git a/docs/testing.md b/docs/testing.md index 9adcdd5f..fe42a20d 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -28,6 +28,8 @@ ShellCheck is not a CI gate in the current workflows. The Linux CI gate is the f plus the complete validation suite on Ubuntu; local ShellCheck results should not be described as a separate CI requirement. +The UDP helper tests and real-core runtime fixture require `python3`. Check `command -v python3` before invoking the runtime fixture directly. The Bash helper-test wrapper reports a skip when the interpreter is absent. + The Bash tests use Linux-flavoured tools such as `jq`, `uuidgen` and `rg`. A bare Windows Git Bash checkout may therefore be unable to run the complete suite; use the Ubuntu CI environment or a Linux machine for authoritative results. Lifecycle checks should also verify Xray, DNS and the subscription @@ -36,7 +38,7 @@ promise that installer and updater paths behave identically. ## Validation suite -`validation/` contains exactly 49 scripts. Run every `validation/test-*.sh`; the current set is: +`validation/` contains exactly 51 Bash scripts. Run every `validation/test-*.sh`; the current set is: | Script | What it checks | |---|---| @@ -54,6 +56,8 @@ promise that installer and updater paths behave identically. | `test-certbot-snap-ip.sh` | Certbot for IP certificates: a single `_ensure_certbot_ip_tls` implementation (quickstart keeps no `snap install` of its own), waiting for snapd readiness (`snap wait system seed.loaded`), a retried install, the result verified by the binary's actual flags, snap output going to a log instead of stdout; functionally, `_certbot_supports_ip_address` tells certbot 5.4+ apart from the apt build and from a binary without `--preferred-profile` | | `test-profile-revoke-expire-cli.sh` | Subscription revoke (token-only and uuid rotation, foreign clients on shared ports survive) and profile expiry (disable/enable, rebuild without a snapshot, idempotent `expire-check`) | | `test-cascade-routing.sh` | Cascade routing configuration | +| `test-private-cascade-udp.sh` | Local UDP helper: authenticated framing, destination isolation, replies, cleanup and resource limits using a Python standard-library fixture | +| `test-profile-create-without-pq.sh` | Legacy XHTTP creation and URI export, unchanged PQ default, incompatible ports and backend lifecycle events | | `test-cascade-upstream-import.sh` | Cascade upstream import from a VLESS link | | `test-dead-stealth-route-pruning.sh` | Pruning dead stealth routes | | `test-fingerprint-subscription-sync.sh` | Fingerprint changes and subscription synchronisation | @@ -100,6 +104,8 @@ disables `fail2ban` (re-enable it afterwards), and `test-hysteria2-lifecycle.sh` a subscription Let's Encrypt certificate — with a real one present `_hysteria2_tls_mode_detect` correctly answers `le ` while the test expects `selfsigned`. +The `udp-runtime` CI jobs additionally run `test-private-cascade-udp-runtime.py` against SHA-256-verified official Xray 26.6.27 and 26.10.31 binaries. Local sinks and narrowly scoped test-only destination exceptions expose actual UDP exit source addresses, mixed destinations in one XUDP association, replies, QUIC destination rewriting and failure behavior. On Linux run `python3 validation/test-private-cascade-udp-runtime.py --repo "$PWD" --xray /path/to/xray --local-ip 127.0.0.2`; the binary directory must contain its geo assets. On other hosts, use an existing local IPv4 distinct from `127.0.0.1` and provide Bash 4+ through `--bash` with GNU coreutils on PATH. Do not add a network address merely for this test. This does not replace provider-firewall or live-client acceptance. + ## Lifecycle and HAPP endpoint checks For a new deployment, exercise the broad `quickstart --email
` path and confirm that it @@ -218,7 +224,7 @@ The workflows have separate responsibilities: - `.github/workflows/ci-linux.yml` is the Bash core gate on `ubuntu-24.04`: it installs `jq`, `uuid-runtime` and `ripgrep`, runs all four Bash syntax checks, then runs every - `validation/test-*.sh` script (49 at the time of writing). + `validation/test-*.sh` script (currently 51). - `.github/workflows/release.yml` is the active Electron release path for `v*` tags or manual runs. A `preflight` job first checks that the release notes file `docs/releases/.en.md` exists and that the `AP3X0` repository secret (if set) can actually create releases — it probes with a draft diff --git a/docs/zh-CN/configuration.md b/docs/zh-CN/configuration.md index d7d7d01e..db912373 100644 --- a/docs/zh-CN/configuration.md +++ b/docs/zh-CN/configuration.md @@ -112,7 +112,7 @@ Xrayebator 不会更改主机的 TCP 拥塞控制算法,也不会写入或应 | `sudo xrayebator kernel-guard [--status\|--enable\|--disable] [--quiet]` | 针对 CVE-2026-98432 的加固(IPv4 选项处理中的 use-after-free,CVSS 9.8,影响所有 IPv4 TCP 监听器)。`--enable` 在内核中关闭 MPTCP(`/etc/sysctl.d/99-xrayebator-netguard.conf` 中的 `net.mptcp.enabled = 0`),并按 Ubuntu 安全团队的规则丢弃带 IP 选项的入站 IPv4 TCP 报文——使用独立的 nftables 表与自己的开机单元,刻意**不用** `nftables.service`,因为其默认的 `flush ruleset` 会在开机时清掉 UFW 规则集。MPTCP 还会由迁移 `netguard_mptcp_2026` 自动关闭;丢弃 IPv4 选项则保持显式开启,因为它改变服务器接受哪些报文。`--status` 报告运行中的内核、`newer_kernel_installed`、`reboot_required`、`mptcp_enabled`、`ipv4_options_drop`、Xray-core 版本以及是否不低于 `26.10.31`(`xray_mptcp_safe`)。它是缓解措施,不是内核更新。同样提供为菜单第 16 项 | | `sudo xrayebator ssh-protect [--status\|--enable\|--disable] [--unban IP\|--prune-ignore] [--quiet]` | SSH 防爆破保护:安装 `fail2ban`,启用基于 journald 的 `sshd` 规则(10 分钟内 4 次失败 → 封禁 30 分钟,屡犯最长一天),并在 `sshd_config.d` 写入 `MaxAuthTries 3` / `LoginGraceTime 30`。**密码登录保持启用** —— 桌面 GUI 通过它管理服务器,改用密钥属于运营者的独立决定。幂等:drop-in 先经 `sshd -t` 校验,`ssh` 只 `reload` 不 `restart`,已打开的 GUI 会话不会被断开。`install.sh` 与 `quickstart` 会自动启用(部署 JSON 中有 `ssh_protect`);`--quiet` 供脚本使用。菜单第 15 项与 GUI 的**安全与 TLS**选项卡提供同一功能。实测:公开 VPS 上 24 小时 9 953 次失败(115 个地址),启用后约 72 次/小时。执行命令的地址在 24 小时内免于封禁(`ignoreip` 加过期标记;到期后由 `--prune-ignore` 经 `xrayebator-ssh-ignoreip.timer` 移除) | | `sudo xrayebator profiles` | 以 JSON 数组输出服务器全部配置档(供桌面 GUI「服务器设置」页使用);有效期同时包含用于服务端执行的 epoch 秒(`expire`)和用于界面显示的服务器本地日历日期(`expire_date`),因此不同时区的客户端也会显示用户选择的日期 | -| `sudo xrayebator profile-create --name 名称 [--transport tcp\|tcp-utls\|tcp-xudp\|tcp-mux\|grpc\|xhttp] [--port P] [--count N] [--expire 日期]` | 非交互式创建单个或多个配置档;`--expire` 接受 `YYYY-MM-DD[ HH:MM]`、epoch 秒或 13 位毫秒。只选日期时,配置档在服务器本地时区的当天 `23:59:59` 之前(含该秒)有效;指定时间时按同一服务器时区执行。过去的有效期会被拒绝;已有名称不会被覆盖——它们会进入 `errors`(GUI 在创建前也会预检名称冲突,因为删除以配置档为单位,名称唯一才能保证删除精确),打印 `{"ok":true,"names":[...],"errors":[...]}` | +| `sudo xrayebator profile-create --name 名称 [--transport tcp\|tcp-utls\|tcp-xudp\|tcp-mux\|grpc\|xhttp] [--port P] [--count N] [--expire 日期] [--without-pq]` | 非交互式创建单个或多个配置档。XHTTP 默认使用 PQ。`--without-pq` 仅适用于 XHTTP,在空闲端口或兼容入站上创建 `encryption=none` 的旧式配置档。`--expire` 接受 `YYYY-MM-DD[ HH:MM]`、epoch 秒或 13 位毫秒。只选日期时,配置档在服务器本地时区的当天 `23:59:59` 之前(含该秒)有效;指定时间时按同一服务器时区执行。过去的有效期会被拒绝;已有名称不会被覆盖——它们会进入 `errors`(GUI 在创建前也会预检名称冲突,因为删除以配置档为单位,名称唯一才能保证删除精确),打印 `{"ok":true,"names":[...],"errors":[...]}` | | `sudo xrayebator profile-delete --name 名称` | 非交互式删除配置档;被删配置档的后端授权会立即吊销——AWG peer 从 `awg0.conf` 移除,Hysteria 密码从 `server.yaml` 移除(不会残留孤立凭据),名称可立即复用;打印 `{"ok":true,"name":"..."}` | | `sudo xrayebator profile-revoke --name 名称 [--full]` | 重新签发订阅链接:新的 `sub_token`;带 `--full` 时还会更换该配置档所有 inbound 中的 uuid(已下载的配置立即失效),打印 JSON | | `sudo xrayebator profile-expire --name 名称 --expire 日期\|epoch\|none` | 设置、延长或取消配置档有效期;只输入日期时,在服务器本地时区的当天 `23:59:59`(含)到期,显式输入的时间按同一时区原样使用;立即生效(已过期会移除客户端,延长则恢复),打印 JSON | @@ -594,6 +594,8 @@ nginx,也不会用 IP 覆盖订阅标记(否则 GUI 会拿到一个失效的 ## 级联与上游节点 +`--without-pq` 的范围取决于命令。`quickstart --without-pq` 表示不向受管理的多线路配置档添加额外 PQ 线路。`profile-create --transport xhttp --without-pq` 则以 `encryption=none` 创建基础 XHTTP 配置档。 + 级联是服务端的出站与路由模式,而不是新的客户端配置档。客户端仍然连接当前 VPS: ```text @@ -613,6 +615,8 @@ nginx,也不会用 IP 覆盖订阅标记(否则 GUI 会拿到一个失效的 第 `10` 项配置的是另一侧:把当前 VPS 变成境外节点,供另一台服务器的级联连入。 +通过俄罗斯入口对目的地进行分流并连接受限境外节点的部署方式,见[私有级联部署](private-cascade.md)。 + ## 自有域名与 self-steal 挡板 Self-steal 会在 `127.0.0.1:9444` 部署带有效证书的 nginx,Reality 入站则获得 diff --git a/docs/zh-CN/private-cascade.md b/docs/zh-CN/private-cascade.md new file mode 100644 index 00000000..4a21d0c7 --- /dev/null +++ b/docs/zh-CN/private-cascade.md @@ -0,0 +1,232 @@ +# 通过俄罗斯 VPS 部署私有级联 + +[← 返回 README](../../README.zh-CN.md) · [English](../private-cascade.md) · [Русский](../ru/private-cascade.md) + +## 拓扑 + +使用两台 VPS。私有客户端连接俄罗斯入口。入口对 TCP 和支持的应用 UDP 使用相同的有序策略。选定的俄罗斯目标从俄罗斯出站,被封锁及未匹配的目标通过 VLESS REALITY 转发到境外出口。 + +| VPS | 作用 | 地址要求 | +|---|---|---| +| 俄罗斯入口,例如位于莫斯科 | 接收客户端连接,并将明确选定的流量从俄罗斯发出 | 客户端可达的公网地址,以及连接境外 VPS 时稳定且已知的源地址 | +| 境外出口 | 接收俄罗斯 VPS 的级联连接,并将转发流量送往互联网 | 俄罗斯 VPS 可达的公网监听地址,以及访问客户端所需目标的出站能力 | + +每台 VPS 一个公网 IPv4 即可实现这些角色。境外监听和互联网出口可以共用地址。文章的完整方案通过另一个地址、网关或 WARP 分离境外监听和最终出口。文章对俄罗斯目标明确允许例外,直连时这些目标会看到入口的公网 IP。文章对地址发现和封锁机制的解释属于作者的假设。[Habr 文章第 4 节](https://habr.com/ru/articles/1103460/) + +## 修改 VPS 前 + +1. 确认两家服务商允许所需的代理用途。记录实际公网地址、出口在服务商 NAT 后看到的源地址、端口和应急控制台访问方式。独立核对 SSH 主机密钥。使用 [VPS 建议](recommendations.md) 中支持的操作系统。 +2. 确认客户端网络能通过 IPv4 连接俄罗斯监听。服务器间可使用限制源地址的 IPv4,或已验证路由、监听和防火墙的 IPv6。无论服务器间使用哪个地址族,都要确认境外 VPS 能访问客户端所需的 IPv4 目标。 +3. 记录现有 Xray 路由、配置档、后端、监听、服务商防火墙和主机防火墙。保存受保护的备份或快照,并保留独立管理会话。若准备过程需要重启已有服务或修改活动监听,请安排维护窗口。 +4. 为境外 VPS 预留独立 TCP 监听。在服务商防火墙上,仅允许俄罗斯 VPS 的实际出站源 IP 访问该端口,IPv4 使用 `/32`,IPv6 使用 `/128`。主机防火墙设置同等限制,并检查包括 Xrayebator 所建规则在内的更宽泛许可。保留 SSH、订阅和现有客户端监听规则。先设置服务商限制,再创建境外入站,因为管理器可能在 UFW 中开放监听端口。 +5. 每台主机分别保管 SSH、REALITY 密钥对和证书私钥。服务器间连接使用专用 VLESS 凭据。客户端仅获得入口配置档,上游链接或 UUID 只存于需要它的两台主机。DNS 凭据仅供 root 读取,权限按用途缩小。日志和交接材料中隐藏链接和令牌。 + +新 VPS 上先在两台主机安装 Xrayebator。此例在入口使用 Xray 和基于 Python 3 标准库的 UDP 辅助程序。若主机已有可选 VPN 后端,创建配置档后检查其授权,因为 Xrayebator 会向已安装后端传递配置档生命周期事件。[安装](../../README.zh-CN.md) + +以下目标限制要求两端使用 Xray-core 26.6.27 或更新版本。在两台主机取得相同的已审核源码版本,包含 `profile-create --without-pq`、`private-cascade` 和 `libexec/private_cascade_udp.py`。独立辅助程序和单元按下文手动安装。如果已安装管理器较旧,从此源码目录运行命令,并将 `sudo xrayebator` 替换为 `sudo bash ./xrayebator`。更新时使用相互匹配的辅助程序和生成配置。 + +在两台主机的空闲目录获取已审核的 tag 或提交。执行前替换引用值。 + +```bash +CASCADE_REVIEWED_REF='replace-with-reviewed-tag-or-commit' +git clone --no-checkout https://github.com/howdeploy/Xrayebator.git xrayebator-cascade-src +cd xrayebator-cascade-src +git fetch --depth 1 origin "$CASCADE_REVIEWED_REF" +git checkout --detach FETCH_HEAD +``` + +## 主机名、证书和 REALITY + +- 优先使用已受你控制的域名,分别设置 `ingress.example.com` 和 `egress.example.com` 等名称。`A` 记录指向各自公网 IPv4。验证 IPv6 可达性和防火墙范围后再发布 `AAAA`。DNS 提供商支持代理时使用 DNS-only。服务商默认主机名需要具备必要的 DNS 控制权,并能签发和续期匹配证书。 +- 使用标准 REALITY 伪装站点时,保留 Xrayebator 已配置且可用的目标与 SNI,通过 IP 连接 VPS。 +- 级联拨号地址可以是可达 IP 或主机名。IP 证书可用于订阅 HTTPS。使用 self-steal 时,REALITY SNI 应匹配回环 TLS 目标证书中的主机名,XHTTP 的 `host` 也使用该名称。[域名与 DNS](configuration.md#域名与-dns) · [Self-steal](configuration.md#自有域名与-self-steal-挡板) +- 关闭公网 80 端口的 self-steal 使用 DNS 提供商的 ACME 插件,仅签发证书。配置回环 TLS 站点并添加续期后重载 TLS 服务的 deploy hook,检查监听实际提供的匹配证书。内置 `dns01-setup` 为 Cloudflare 或 Route 53 配置订阅监听。如需发布该订阅再使用它,秘密通过文件或 stdin 传入。[DNS-01](configuration.md) + +## 准备境外出口 + +在境外 VPS 上运行 `sudo xrayebator profile-create --name private-cascade-egress --transport xhttp --without-pq --port 25443`,创建专用旧式 XHTTP 配置档。确认 `names` 包含该配置档且 `errors` 为空。私下从配置档菜单导出 XHTTP URI,保留实际 `path`、`host` 和 `mode`。IPv6 拨号地址用方括号包围。 + +```text +vless://@:?encryption=none&security=reality&type=xhttp&sni=&fp=&pbk=&sid=&host=&path=&mode= +``` + +也支持 TCP Vision。在空闲的非 443 端口上使用 `--transport tcp`,省略 `--without-pq`,并保留导出 URI 中的 `flow=xtls-rprx-vision`。此 flow 会拒绝向境外线路的 443 端口开启 UDP 会话。HTTP/3 不可用时,浏览器可以通过 TCP 重试 HTTPS。上述 XHTTP 示例支持应用 UDP/443。 + +从入口和允许列表外的地址分别验证监听许可与拒绝情况。确认境外节点可以出站到互联网。[标准级联](configuration.md#级联与上游节点) + +境外 VPS 独立解析转发的目标名称。出口限制为公网 IPv4,并对每个 UDP 数据报执行限制。先保存受保护的配置备份,再向 `outbounds` 末尾添加以下专用出站。两个 IPv4 策略字段兼容支持的内核版本。若服务商元数据地址不在私有地址集合中,也应加入禁止列表。 + +```json +{ + "tag": "private-cascade-exit", + "protocol": "freedom", + "settings": { + "domainStrategy": "ForceIPv4", + "finalRules": [{"action": "block", "ip": ["geoip:private", "::/0"]}] + }, + "streamSettings": {"sockopt": {"domainStrategy": "ForceIPv4"}} +} +``` + +这些限制适用于客户端目标。两台 VPS 之间仍可通过 IPv6 连接。 + +在境外节点的 `routing.rules` 中,将下列规则放在现有禁止规则之后、首个能匹配级联入站的普通转发规则之前,包括 TCP/UDP 兜底规则。若使用其他端口或配置档,以实际入站 tag 替换 `inbound-25443`。 + +```json +{ + "type": "field", + "inboundTag": ["inbound-25443"], + "outboundTag": "private-cascade-exit" +} +``` + +运行 `sudo /usr/local/bin/xray run -test -config /usr/local/etc/xray/config.json` 验证修改后的境外配置。成功后,在维护窗口重启其 Xray 服务,并确认该入站选择 `private-cascade-exit`。验证或重启失败时,恢复并验证备份,再恢复服务。在一个 XUDP 会话中,先向可控的允许 IPv4 目标发包,再向可控的禁止目标发包。确认第一包到达、第二包被丢弃。分别检查 IP 地址和解析为这些地址的域名。 + +## 准备路由列表 + +下例使用已安装的 `geosite.dat` 中的俄罗斯分类,以及 Re-filter 的紧凑域名和 IP 封锁列表。更新现有列表前,保存其哈希和受保护备份。从同一 release 下载两个文件,并校验 GitHub 发布的 SHA-256 后再安装。[Re-filter 来源](https://github.com/1andrevich/Re-filter-lists) + +```bash +( + set -eu + stage=$(mktemp -d) + trap 'rm -rf -- "$stage"' EXIT + curl -fsSL https://api.github.com/repos/1andrevich/Re-filter-lists/releases/latest \ + -o "$stage/release.json" + for kind in geoip geosite; do + name="$kind.dat" + url=$(jq -er --arg name "$name" '.assets[] | select(.name == $name) | .browser_download_url' "$stage/release.json") + hash=$(jq -er --arg name "$name" '.assets[] | select(.name == $name) | .digest | select(test("^sha256:[a-f0-9]{64}$")) | ltrimstr("sha256:")' "$stage/release.json") + curl -fsSL "$url" -o "$stage/$name" + printf '%s %s\n' "$hash" "$stage/$name" | sha256sum -c - + done + sudo install -o root -g xray -m 0644 "$stage/geoip.dat" /usr/local/share/xray/refilter-geoip.dat + sudo install -o root -g xray -m 0644 "$stage/geosite.dat" /usr/local/share/xray/refilter-geosite.dat +) +``` + +保留已安装的国家 IP 数据及 `geoip:private`、`geoip:ru` 分类。策略使用已安装域名数据的 `geosite:available-only-in-ru` 和 `geosite:category-ru`。若缺少分类,生成配置前更新或选择已审核数据。每次列表变化后验证新候选配置。列表更新失败时,先恢复原文件,再重启运行中的级联。 + +## 生成并启动入口 + +在俄罗斯 VPS 选择可用的 VLESS REALITY TCP 或旧式 XHTTP 入站,要求 `decryption=none` 且 VLESS `fallbacks` 列表为空。新安装上预留空闲模板端口,并在服务商防火墙中保持关闭。运行 `sudo xrayebator profile-create --name private-cascade-template --transport xhttp --without-pq --port 15442`,确认 `names` 包含模板且 `errors` 为空。这会在主配置中创建 `inbound-15442`。独立服务使用自己的端口,此例为 `15443`。 + +用 `uuidgen` 为独立入口生成新 UUID。在 root 专属目录(例如 `/root/xrayebator-private-cascade/`)中创建两个 root 所有、权限为 `0600` 的文件。将唯一上游 URI 写入 `upstream.txt`,按下例填写 `policy.json`,替换入站 tag、UUID 和示例目标。 + +```json +{ + "inbound_tag": "inbound-15442", + "client_id": "", + "listen": "0.0.0.0", + "port": 15443, + "udp_relay_port": 15444, + "udp_dispatch_port": 15445, + "russia_only_domains": ["geosite:available-only-in-ru"], + "blocked_domains": ["ext:refilter-geosite.dat:refilter"], + "blocked_ips": ["ext:refilter-geoip.dat:refilter"], + "russian_domains": ["domain:ru", "domain:su", "domain:xn--p1ai", "geosite:category-ru"], + "russian_ips": ["geoip:ru"] +} +``` + +选择空闲 TCP 端口,并在主机和服务商防火墙上向所需客户端开放。`blocked_domains`、`blocked_ips` 必须是数组,两者至少有一个非空。可选数组 `russia_only_domains`、`russian_domains`、`russian_ips` 定义直连规则,后两者默认覆盖 `.ru`/`.рф` 和 `geoip:ru`。使用已安装数据支持的 Xray selector。`ext:` 需要对应本地数据文件。生成器只读取 VPS 上的数据。 + +使用空数组禁用某个可选列表。省略字段时使用默认值。 + +`udp_relay_port` 和 `udp_dispatch_port` 默认分别为 `15444` 和 `15445`。在俄罗斯 VPS 预留两个空闲非特权 TCP 端口,三个端口必须互不相同。本地端口仅绑定 `127.0.0.1`,保持其仅回环可达。生成器在受保护配置中创建独立辅助程序密码和分类器 UUID。仅在服务器本地保管这些内部凭据。 + +入口按 IP 规则阻止私有和 IPv6 目标。Sniffing 保留客户端传入的禁止地址。其他 TCP 连接使用嗅探到的名称作为 Xray 实际连接目标。识别出的仅限俄罗斯名称优先于封锁列表,无论客户端最初传入的是名称还是对应公网 IP。封锁列表优先于普通俄罗斯规则。直连出站仅解析 IPv4,并在拨号时复查目标 IP。`russian_ips` 路由只能连接该列表中的 IP。后续 DNS 查询结果若与所选直连策略冲突,连接会失败。 + +对 UDP,公网入站先将每个数据报发给认证回环辅助程序,包括虚拟 DNS 和禁止目标尝试。XUDP 在一个会话内可以改变目标,因此辅助程序为原会话的每个目标分别开启固定目标的 VLESS UDP 流。Xray 再对流执行 DNS 截获、目标禁止和五条有序策略。辅助程序复用 Xray 的域名/IP 策略,互联网连接由 Xray 发起。本地 Trojan 帧格式仅用于内部传输,客户端仍使用 VLESS REALITY。 + +识别出的俄罗斯 UDP 可以直接从俄罗斯出站。境外节点故障会停止境外 TCP/UDP,保持俄罗斯直连 TCP/UDP 和入口 DNS 可用。辅助程序故障会停止应用 UDP 和虚拟 UDP DNS,TCP 保留其路由。辅助程序拒绝大于 8190 字节的负载。Xray 的 8 KiB 帧缓冲区还可能因地址和头部开销降低可用大小。需要大型数据报的应用应另行验证。连接、流、队列和空闲时间限制用于控制资源消耗,达到限制时丢弃数据或关闭相关流。 + +分流键是原会话内的目标地址和端口。Sniffing 在固定目标流的起始执行。共享同一目标端点的不同 QUIC 连接沿用该流的分类,需要对这类应用另行确认。 + +入口使用服务 DoH,并以本机解析器作为备用。在 VLESS 内将客户端 DNS 指向 `192.0.2.53:53`。该虚拟地址专供 53 端口 DNS。关闭客户端自动切换到直连或其他配置档。 + +```bash +sudo xrayebator private-cascade render \ + --policy-file /root/xrayebator-private-cascade/policy.json \ + --upstream-file /root/xrayebator-private-cascade/upstream.txt \ + --output /root/xrayebator-private-cascade/ingress.json +``` + +已安装管理器较旧时,从已审核源码目录运行带相同参数的 `sudo bash ./xrayebator private-cascade render`。 + +生成器为公网客户端创建新 UUID,并采用模板首个客户端的 flow,同时生成内部回环分类器和辅助程序凭据。它保留公网传输及 REALITY 参数,使用 `xray run -test` 验证后写入 root 所有、权限为 `0600` 的新文件。辅助程序服务可用性需要单独检查。首次安装选用空闲服务目录。 + +```bash +sudo install -d -o root -g xray -m 0750 /etc/xray-private-cascade +sudo install -o root -g xray -m 0640 /root/xrayebator-private-cascade/ingress.json \ + /etc/xray-private-cascade/config.json +sudo install -d -o root -g root -m 0755 /usr/local/libexec +sudo install -o root -g root -m 0755 libexec/private_cascade_udp.py \ + /usr/local/libexec/xrayebator-private-udp.py +command -v python3 +``` + +从已审核源码目录安装辅助程序。启动前确认 `/usr/bin/python3` 存在,支持的 Debian/Ubuntu 上缺失时安装 `python3` 软件包。配置保留 root 所有、仅 `xray` 组可读(`0640`),两个服务都需要读取。 + +以 root 创建 `/etc/systemd/system/xray-private-cascade-udp.service`。 + +```ini +[Unit] +Description=Xray private cascade UDP destination splitter +PartOf=xray-private-cascade.service + +[Service] +User=xray +Group=xray +NoNewPrivileges=true +ExecStart=/usr/bin/python3 /usr/local/libexec/xrayebator-private-udp.py --config /etc/xray-private-cascade/config.json +Restart=on-failure +``` + +以 root 创建 `/etc/systemd/system/xray-private-cascade.service`。`Wants` 启动辅助程序,辅助程序故障时 TCP 仍可工作。`PartOf` 让辅助程序随入口停止或重启。绑定能力也支持空闲特权端口(例如 443)。两个本地端口保持大于 1023。以下使用标准 Xrayebator 二进制和数据路径。 + +```ini +[Unit] +Description=Xray private cascade ingress +Wants=network-online.target xray-private-cascade-udp.service +After=network-online.target xray-private-cascade-udp.service + +[Service] +User=xray +Group=xray +AmbientCapabilities=CAP_NET_BIND_SERVICE +CapabilityBoundingSet=CAP_NET_BIND_SERVICE +NoNewPrivileges=true +Environment=XRAY_LOCATION_ASSET=/usr/local/share/xray +ExecStart=/usr/local/bin/xray run -config /etc/xray-private-cascade/config.json +Restart=on-failure + +[Install] +WantedBy=multi-user.target +``` + +```bash +sudo systemctl daemon-reload +sudo systemctl start xray-private-cascade.service +sudo systemctl status --no-pager xray-private-cascade.service xray-private-cascade-udp.service +ss -ltn 'sport = :15443' +ss -ltn 'sport = :15444 or sport = :15445' +``` + +确认两个本地监听都使用 `127.0.0.1`。通过实际 UDP 请求验证辅助程序。更新时保护配置、辅助程序和两个 unit 的备份,验证候选配置后重启入口,让 `PartOf` 辅助程序加载匹配凭据。验证或验收失败时一起恢复这些文件。 + +私下以模板首个客户端 URI 为参考,替换 UUID、拨号地址和独立监听端口。保留 REALITY 字段、flow、指纹和传输选项,包括 XHTTP 的 host、path、mode。作为独立测试配置档导入。轮换时更新独立配置中的 UUID 并重新发放链接。 + +## 更新与卸载 + +独立级联采用手动生命周期。更新前备份配置、已安装辅助程序和两个 unit 文件。将源码切换到已审核修订版,在新输出路径生成并验证候选配置,再安装匹配配置,并重新将 `libexec/private_cascade_udp.py` 复制到 `/usr/local/libexec/xrayebator-private-udp.py`。对照指南更新两个 unit 文件。单元改变后运行 `sudo systemctl daemon-reload`,再重启 `xray-private-cascade.service`,让辅助程序重读相同凭据。重复验收,失败时整体恢复备份。 + +运行通用 `uninstall.sh` 前,按下文回滚。先停止入口和辅助程序,再移除 `/etc/systemd/system/xray-private-cascade.service`、`/etc/systemd/system/xray-private-cascade-udp.service`、`/etc/xray-private-cascade/` 及已安装辅助程序。运行 `systemctl daemon-reload`,关闭级联公网端口,移除境外配置档及其限定路由。保留受保护输入和备份,直至不再需要回滚。使用常规安装、更新或卸载程序时,这些独立文件和单元由运营者手动维护。 + +## 验收或回滚级联 + +1. 从所需网络上的桌面或命令行客户端验证 REALITY,发送少量 HTTPS 和 DNS 请求。用可控目标日志确认俄罗斯规则显示俄罗斯源 IP,未匹配规则显示境外源 IP。为一个仅限俄罗斯名称配置也命中 `blocked_ips` 的公网 IPv4,分别按名称及带相同 SNI 的 IP 连接,两者应直达实际俄罗斯目标。普通俄罗斯名称若解析到封锁 IP,应走境外。 +2. 在同一个真实 XUDP 会话中依次向可控俄罗斯、境外、封锁目标及俄罗斯目标发送小型 UDP 包。确认每次源地址和响应,再反向重复并以虚拟 DNS 查询开头重复。即使封锁目标 IP 属于俄罗斯,也应走境外。私有和 IPv6 目标应收不到包。 +3. 维护窗口中只停止专用境外链路,再开启新连接。俄罗斯直连 TCP/UDP 和虚拟 DNS 应继续工作,境外 TCP/UDP 应失败且不会从俄罗斯出口发出。恢复链路并检查恢复。另行仅停止 `xray-private-cascade-udp.service`,应用 UDP 和虚拟 UDP DNS 应停止,TCP 保留其路由。重启辅助程序并复查。 +4. 对照操作前状态检查原 Xray 服务、配置档、订阅、Hysteria 2 和 AmneziaWG。验收通过后只启用入口开机启动,运行 `sudo systemctl enable xray-private-cascade.service`,其 `Wants` 会启动辅助程序。 +5. 回滚时,断开客户端级联配置档,运行 `sudo systemctl disable --now xray-private-cascade.service`,再运行 `sudo systemctl stop xray-private-cascade-udp.service`。确认入口三个监听均已停止。移除两个专用 unit 和安装配置,仅在辅助程序专用于此级联时删除其安装文件。运行 `sudo systemctl daemon-reload`。仅关闭两端专用公网端口,回环端口保持本地限制。在境外 VPS 运行 `sudo xrayebator profile-delete --name private-cascade-egress`,再移除其路由规则和 `private-cascade-exit` 出站。若创建了 `private-cascade-template`,在俄罗斯 VPS 按名称删除。复查原服务。 diff --git a/docs/zh-CN/testing.md b/docs/zh-CN/testing.md index 5443eedf..44a52f21 100644 --- a/docs/zh-CN/testing.md +++ b/docs/zh-CN/testing.md @@ -13,9 +13,11 @@ for test_file in validation/*.sh; do bash "$test_file" || exit; done 这是本地检查的最小门槛。`shellcheck` 可以额外运行,但不是 CI 的必要 gate(见下文)。 +UDP 辅助程序的测试和真实 Xray 运行时测试需要 `python3`。直接运行后者前,先执行 `command -v python3`。缺少解释器时,Bash 测试入口会报告跳过。 + ## 测试覆盖范围 -`validation/` 中有 49 个静态与本地回归测试: +`validation/` 中有 51 个静态与本地回归测试: | 测试 | 检查内容 | |---|---| @@ -49,6 +51,8 @@ for test_file in validation/*.sh; do bash "$test_file" || exit; done | `test-secret-argv.sh` | 密钥不进入进程参数(`/proc//cmdline` 对所有用户可读,`/proc//environ` 不可读):桩 `curl` 证明机器人令牌与 `sub_token` 通过 stdin 配置(`-K -`)传入且不出现在 `argv`;`--secret-file`/`--secret-stdin` 载荷解析(单行令牌、AWS 对、显式标志优先、垃圾输入)、拒绝宽于 `0600` 的文件、读取后删除、`--token` 在 stderr 打印警告而 stdout 仍是纯 JSON、jq 读取 `$ENV.XRAYEBATOR_JQ_SECRET` | | `test-awg-lifecycle.sh` | AmneziaWG 后端:Amnezia 默认 junk 方言(Jc=5、Jmin=10、Jmax=50、H1–H4=1..4、S1–S4 互不相同)、密钥生成、服务端配置渲染(PostUp MASQUERADE、安装时无 peer)、peer 地址分配、客户端 `.conf` 内容、revoke/expire/restore 事件、预删除配置档后的 deleted 重生成、created 为无操作(不自动签发)、CLI 分发、`/etc/modules-load.d` 的开机模块登记(仅在模块可用时写入)、`backend-start`(「已安装」≠「正在运行」)、以及安装成功判定:内核模块必须针对**当前**内核(`AWG_MODULES_ROOT` 为测试接缝) | | `test-main-readiness-regressions.sh` | 审计后的 readiness 回归:certbot manifest、UFW manifest、nginx 回滚、权限与 SSH 端口 | +| `test-private-cascade-udp.sh` | Python 标准库 UDP 辅助程序测试:认证、报文边界、目标隔离、响应、清理和资源限制 | +| `test-profile-create-without-pq.sh` | 旧式 XHTTP 配置档的创建与 URI 导出、保留 PQ 默认值、不兼容端口和后端生命周期事件 | | `test-sni-change-cli.sh` | `sni-change` CLI:JSON 输出、Reality、XHTTP host、配置档同步与回滚 | | `test-bypass-cli.sh` | `bypass` CLI:JSON 输出、路由规则更新、带 SNI 探测的 add | | `test-port-change-cli.sh` | `port-change` CLI:unit/shared/move 入站场景、无效端口、缺少配置档、多线路 `--route` | @@ -70,6 +74,8 @@ for test_file in validation/*.sh; do bash "$test_file" || exit; done | `test-sni-reachability.sh` | 默认 SNI 的选择:不可达的默认值(或 `sni_list.txt` 首行)被第一个可达候选替换、全部不可达时回退到原默认值(不让探测破坏隔离主机上的部署)、结果按 SNI 缓存;同时覆盖探针判据(完整 TLS 1.3 + 已验证证书 + HTTP 应答)与候选顺序的上限 | > 静态测试不能替代一次性 VPS 上的实测:创建与删除配置档、校验配置、重启服务、回滚以及真实客户端连接。 + +`udp-runtime` CI 任务会使用 SHA-256 校验后的官方 Xray 26.6.27 和 26.10.31 运行 `test-private-cascade-udp-runtime.py`。本地接收端和严格限定的测试例外用于检查真实 UDP 出站源地址、同一 XUDP 会话内的目标切换、响应、QUIC 目标改写和故障行为。在 Linux 上运行 `python3 validation/test-private-cascade-udp-runtime.py --repo "$PWD" --xray /path/to/xray --local-ip 127.0.0.2`,二进制文件旁需有 geo 数据。在其他系统上使用已有的非 `127.0.0.1` 本机 IPv4,通过 `--bash` 指定 Bash 4+,并将 GNU coreutils 放入 PATH。保持现有网络地址配置。另行验证服务商防火墙和真实客户端。 > > 该测试集并非自封闭的——请在一次性主机或容器中运行。以下两点来自在真实服务器上的运行: > `test-ssh-protect.sh` 会走真实的 `--disable` 路径,即停止并禁用 `fail2ban`(跑完请重新启用); @@ -177,7 +183,7 @@ npm test # Vitest 单元测试 三个独立 workflow: -- **ci-linux.yml** — Bash validation:在 ubuntu-24.04 上对所有脚本执行 `bash -n`,并运行全部 49 个 +- **ci-linux.yml** — Bash validation:在 ubuntu-24.04 上对所有脚本执行 `bash -n`,并运行全部 51 个 `validation/test-*.sh`;在 push 到 `main`、`dev`、`experimental` 以及 pull request 时运行。 - **release.yml** — Electron 构建(Windows/macOS/Linux)。只在 `v*` tag 和手动触发时运行;先由 `preflight` 检查发布说明 `docs/releases/.en.md` 是否存在,以及仓库密钥 `AP3X0`(若已设置) @@ -186,4 +192,4 @@ npm test # Vitest 单元测试 `npm test`、`npm run build`,再在三种平台执行 `electron-builder --publish never`。若 `preflight` 确认 `AP3X0` 可用,release 以该 token 所有者名义发布,否则以 `github-actions[bot]` 通过内置 `GITHUB_TOKEN` 发布:GitHub release 的作者在创建时即固定,事后无法改换。 -- **gui-release.yml** — legacy PySide6 GUI:ruff、pytest 和 wheel 构建;在 PR 与 `gui-v*` tag 上运行。 \ No newline at end of file +- **gui-release.yml** — legacy PySide6 GUI:ruff、pytest 和 wheel 构建;在 PR 与 `gui-v*` tag 上运行。 diff --git a/libexec/private_cascade_udp.py b/libexec/private_cascade_udp.py new file mode 100644 index 00000000..741fb00b --- /dev/null +++ b/libexec/private_cascade_udp.py @@ -0,0 +1,333 @@ +#!/usr/bin/env python3 +"""Split authenticated loopback Trojan UDP into immutable local VLESS streams.""" + +import argparse +import asyncio +import hashlib +import hmac +import json +import os +import signal +import stat +import struct +import sys +import uuid +from dataclasses import dataclass + +MAX_SESSIONS = 64 +MAX_FLOWS = 256 +MAX_SESSION_FLOWS = 32 +QUEUE_SIZE = 32 +MAX_PAYLOAD = 8190 # Xray's bare VLESS packet writer reserves two bytes of its 8K buffer. +IO_TIMEOUT = 5 +IDLE_TIMEOUT = 120 + + +class ProtocolError(ValueError): + """Identify malformed or unsupported relay protocol data.""" + pass + + +@dataclass(frozen=True) +class Config: + """Hold local endpoints and independent credentials from renderer output.""" + listen_port: int + dispatch_port: int + password: str + client_id: uuid.UUID + + @classmethod + def from_file(cls, path): + """Read protected secrets and require authenticated, loopback-only endpoints.""" + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + with os.fdopen(fd) as file: + info = os.fstat(file.fileno()) + if (not stat.S_ISREG(info.st_mode) or info.st_uid not in (0, os.geteuid()) + or info.st_mode & 0o027): + raise ProtocolError("Config must be protected and owned by root or the caller") + data = json.load(file) + relays = [o for o in data.get("outbounds", []) if o.get("tag") == "private-cascade-udp-relay"] + dispatchers = [i for i in data.get("inbounds", []) if i.get("tag") == "private-cascade-udp-dispatch"] + if len(relays) != 1 or len(dispatchers) != 1: + raise ProtocolError("Expected one UDP relay and dispatcher") + relay, dispatch = relays[0], dispatchers[0] + servers = relay.get("settings", {}).get("servers", []) + clients = dispatch.get("settings", {}).get("clients", []) + if len(servers) != 1 or len(clients) != 1: + raise ProtocolError("Expected one local server and credential") + server = servers[0] + password = server.get("password") + if (relay.get("protocol") != "trojan" or server.get("address") != "127.0.0.1" + or dispatch.get("protocol") != "vless" or dispatch.get("listen") != "127.0.0.1" + or dispatch.get("settings", {}).get("decryption") != "none" + or dispatch.get("settings", {}).get("fallbacks") + or clients[0].get("flow") + or any(item.get("streamSettings", {}).get("network") != "tcp" + or item.get("streamSettings", {}).get("security") != "none" + for item in (relay, dispatch)) + or not isinstance(password, str) or not 16 <= len(password.encode()) <= 255): + raise ProtocolError("UDP relay requires authenticated loopback-only TCP endpoints") + ports = server.get("port"), dispatch.get("port") + if any(type(p) is not int or not 1024 <= p <= 65535 for p in ports) or ports[0] == ports[1]: + raise ProtocolError("UDP relay ports must be distinct valid ports") + return cls(*ports, password, uuid.UUID(clients[0]["id"])) + + +@dataclass(frozen=True) +class Destination: + """Retain exact Trojan identity and port-first VLESS framing without DNS.""" + wire: bytes + vless: bytes + + +async def read_destination(reader): + """Decode an address without resolving it or merging distinct flow keys.""" + kind = await reader.readexactly(1) + if kind == b"\x01": + address = await reader.readexactly(4) + vless_kind = b"\x01" + elif kind == b"\x04": + address = await reader.readexactly(16) + vless_kind = b"\x03" + elif kind == b"\x03": + size = await reader.readexactly(1) + if not size[0]: + raise ProtocolError("Empty domain") + name = await reader.readexactly(size[0]) + if any(c < 33 or c > 126 for c in name): + raise ProtocolError("Invalid domain encoding") + address = size + name + vless_kind = b"\x02" + else: + raise ProtocolError("Unknown address type") + port = await reader.readexactly(2) + if port == b"\0\0": + raise ProtocolError("Invalid destination port") + return Destination(kind + address + port, port + vless_kind + address) + + +async def read_packet(reader): + """Read a complete datagram, rejecting lengths that exceed Xray's framing budget.""" + destination = await read_destination(reader) + size = struct.unpack("!H", await reader.readexactly(2))[0] + if not 1 <= size <= min(MAX_PAYLOAD, 8192 - len(destination.wire) - 4) or await reader.readexactly(2) != b"\r\n": + raise ProtocolError("Invalid UDP frame") + return destination, await reader.readexactly(size) + + +async def close_writer(writer): + """Release a local stream within the I/O deadline, including failed connections.""" + if writer is not None: + writer.close() + try: + await asyncio.wait_for(writer.wait_closed(), IO_TIMEOUT) + except (OSError, asyncio.TimeoutError): + pass + + +class Flow: + """Confine one destination to one backend stream with bounded pending packets.""" + + def __init__(self, session, destination): + """Create a bounded queue and schedule its immutable-destination stream.""" + self.session = session + self.destination = destination + self.queue = asyncio.Queue(QUEUE_SIZE) + self.last_active = asyncio.get_running_loop().time() + self.task = asyncio.create_task(self.run()) + self.task.add_done_callback(self.finished) + + def finished(self, task): + """Release capacity even when cancellation preceded the flow's first execution.""" + self.session.flows.pop(self.destination.wire, None) + self.session.relay.flow_count -= 1 + if not task.cancelled() and task.exception() is not None: + print("UDP relay flow failed unexpectedly", file=sys.stderr) + self.session.writer.close() + + async def send(self, writer): + """Preserve datagram boundaries while bounding stalled backend writes.""" + while True: + payload = await self.queue.get() + writer.write(struct.pack("!H", len(payload)) + payload) + await asyncio.wait_for(writer.drain(), IO_TIMEOUT) + + async def receive(self, reader): + """Restore original reply labels and serialize writes to the frontend stream.""" + if await reader.readexactly(2) != b"\0\0": + raise ProtocolError("Unexpected local VLESS response") + while True: + size = struct.unpack("!H", await reader.readexactly(2))[0] + if not 1 <= size <= min(MAX_PAYLOAD, 8192 - len(self.destination.wire) - 4): + raise ProtocolError("Invalid local VLESS packet length") + payload = await reader.readexactly(size) + self.last_active = self.session.last_active = asyncio.get_running_loop().time() + frame = self.destination.wire + struct.pack("!H", size) + b"\r\n" + payload + async with self.session.write_lock: + self.session.writer.write(frame) + await asyncio.wait_for(self.session.writer.drain(), IO_TIMEOUT) + + async def idle(self): + """Expire an inactive backend flow without switching its selected exit.""" + while True: + await asyncio.sleep(min(1, IDLE_TIMEOUT / 2)) + if asyncio.get_running_loop().time() - self.last_active >= IDLE_TIMEOUT: + return + + async def run(self): + """Own one fixed VLESS stream and cancel all directions when any task ends.""" + writer = None + tasks = [] + try: + config = self.session.relay.config + reader, writer = await asyncio.wait_for( + asyncio.open_connection("127.0.0.1", config.dispatch_port), IO_TIMEOUT) + # Send the first packet before waiting for Xray's buffered response header. + writer.write(b"\0" + config.client_id.bytes + b"\0\x02" + self.destination.vless) + tasks = [asyncio.create_task(self.send(writer)), asyncio.create_task(self.receive(reader)), + asyncio.create_task(self.idle())] + done, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) + for task in done: + task.result() + except (ProtocolError, asyncio.IncompleteReadError, OSError, asyncio.TimeoutError): + pass + finally: + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + await close_writer(writer) + + +class Session: + """Keep each authenticated client's destination map and replies isolated.""" + + def __init__(self, relay, reader, writer): + """Allocate client-local flow identity, response ordering and idle state.""" + self.relay, self.reader, self.writer = relay, reader, writer + self.flows = {} + self.write_lock = asyncio.Lock() + self.last_active = asyncio.get_running_loop().time() + + async def read(self): + """Split destinations into bounded flows and drop overload without rerouting.""" + while True: + destination, payload = await read_packet(self.reader) + self.last_active = asyncio.get_running_loop().time() + flow = self.flows.get(destination.wire) + if flow is None: + if len(self.flows) >= MAX_SESSION_FLOWS or self.relay.flow_count >= MAX_FLOWS: + continue + flow = self.flows[destination.wire] = Flow(self, destination) + self.relay.flow_count += 1 + flow.last_active = self.last_active + try: + flow.queue.put_nowait(payload) + except asyncio.QueueFull: + pass + + async def idle(self): + """End a session after both client packets and backend replies become inactive.""" + while True: + await asyncio.sleep(min(1, IDLE_TIMEOUT / 2)) + if asyncio.get_running_loop().time() - self.last_active >= IDLE_TIMEOUT: + return + + async def run(self): + """Tie every backend socket and task to the frontend connection lifetime.""" + tasks = [asyncio.create_task(self.read()), asyncio.create_task(self.idle())] + try: + done, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) + for task in done: + task.result() + finally: + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + flows = [flow.task for flow in self.flows.values()] + for task in flows: + task.cancel() + await asyncio.gather(*flows, return_exceptions=True) + + +class Relay: + """Authenticate local Trojan streams before allowing per-destination splitting.""" + + def __init__(self, config): + """Track authentication and global capacity without logging credentials or data.""" + self.config = config + self.key = hashlib.sha224(config.password.encode()).hexdigest().encode() + self.clients = set() + self.handlers = set() + self.flow_count = 0 + self.server = None + + async def authenticate(self, reader): + """Accept only the configured password hash and Trojan UDP request command.""" + if not hmac.compare_digest(await reader.readexactly(56), self.key): + raise ProtocolError("Authentication failed") + if await reader.readexactly(3) != b"\r\n\x03": + raise ProtocolError("Only UDP is supported") + await read_destination(reader) + if await reader.readexactly(2) != b"\r\n": + raise ProtocolError("Invalid request header") + + async def handle(self, reader, writer): + """Enforce admission and handshake limits before allocating client flows.""" + task = asyncio.current_task() + self.handlers.add(task) + try: + if writer.get_extra_info("peername")[0] != "127.0.0.1" or len(self.clients) >= MAX_SESSIONS: + return + self.clients.add(writer) + await asyncio.wait_for(self.authenticate(reader), IO_TIMEOUT) + await Session(self, reader, writer).run() + except (ProtocolError, asyncio.IncompleteReadError, OSError, asyncio.TimeoutError): + pass + finally: + self.clients.discard(writer) + await close_writer(writer) + self.handlers.discard(task) + + async def start(self): + """Expose the authenticated relay only on IPv4 loopback.""" + self.server = await asyncio.start_server(self.handle, "127.0.0.1", self.config.listen_port) + + async def close(self): + """Stop admission and await cleanup of every accepted client.""" + if self.server is not None: + self.server.close() + await self.server.wait_closed() + tasks = list(self.handlers) + for task in tasks: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + + +async def serve(config): + """Install termination hooks and release all clients before process exit.""" + relay = Relay(config) + stopped = asyncio.Event() + loop = asyncio.get_running_loop() + for sig in (signal.SIGINT, signal.SIGTERM): + loop.add_signal_handler(sig, stopped.set) + try: + await relay.start() + await stopped.wait() + finally: + await relay.close() + + +def main(): + """Load renderer output and report startup failures without disclosing secrets.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--config", required=True) + args = parser.parse_args() + try: + config = Config.from_file(args.config) + asyncio.run(serve(config)) + except (OSError, ValueError, KeyError, TypeError, AttributeError): + parser.exit(1, "UDP relay could not read its protected configuration or bind its listener.\n") + + +if __name__ == "__main__": + main() diff --git a/validation/test-cascade-routing.sh b/validation/test-cascade-routing.sh index 418d380b..24b56b29 100644 --- a/validation/test-cascade-routing.sh +++ b/validation/test-cascade-routing.sh @@ -126,4 +126,148 @@ _cascade_apply_current_upstream "cascade_test_reapply" >/dev/null 2>&1 \ [[ "$(jq '[.outbounds[]? | select(.tag == "cascade-fragment")] | length' "$CONFIG_FILE")" == "1" ]] \ || fail "cascade re-apply duplicated cascade-fragment outbound" -echo "OK: cascade routing (real _cascade_* functions)" \ No newline at end of file +echo "OK: cascade routing (real _cascade_* functions)" + +# Private render is opt-in and leaves the running config and its other profiles alone. +jq '.inbounds = [ + {tag:"legacy-inbound", protocol:"vless"}, + {tag:"private-template", protocol:"vless", listen:"0.0.0.0", port:443, + settings:{clients:[{id:"33333333-3333-4333-8333-333333333333",email:"template"}],decryption:"none"}, + streamSettings:{network:"xhttp",security:"reality", + xhttpSettings:{path:"/fixture",mode:"stream-one"}, + realitySettings:{dest:"127.0.0.1:9444",serverNames:["ingress.example.net"]}}} +]' "$CONFIG_FILE" > "$WORKDIR/template.json" +CONFIG_FILE="$WORKDIR/template.json" +cp "$CONFIG_FILE" "$WORKDIR/template.before" + +cat > "$WORKDIR/policy.json" <<'JSON' +{ + "inbound_tag": "private-template", + "client_id": "22222222-2222-4222-8222-222222222222", + "listen": "0.0.0.0", + "port": 15443, + "russia_only_domains": ["full:only.example"], + "blocked_domains": ["domain:blocked.example"], + "blocked_ips": ["198.51.100.0/24"] +} +JSON +printf '%s\n' 'vless://11111111-1111-4111-8111-111111111111@[2001:db8::10]:25443?security=reality&type=xhttp&sni=egress.example.net&pbk=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN&sid=abcd1234&mode=stream-one&path=%2Ffixture' > "$WORKDIR/upstream.uri" +chmod 600 "$WORKDIR/policy.json" "$WORKDIR/upstream.uri" + +XRAY_BIN="$WORKDIR/xray-test" +cat > "$XRAY_BIN" <<'BASH' +#!/usr/bin/env bash +if [[ "$1" == "version" ]]; then + printf 'Xray %s (Xray, Penetrates Everything.) fixture\n' "${XRAY_TEST_VERSION:-26.6.27}" + exit 0 +fi +[[ "${XRAY_TEST_REJECT_CONFIG:-0}" == 0 && + "$1" == "run" && "$2" == "-test" && "$3" == "-config" && "$4" == *.json ]] && + jq -e '.outbounds[0].protocol == "blackhole"' "$4" >/dev/null +BASH +chmod +x "$XRAY_BIN" +output="$WORKDIR/private.json" +render() { + private_cascade_command render --policy-file "${1:-$WORKDIR/policy.json}" \ + --upstream-file "$WORKDIR/upstream.uri" --output "$output" +} +render >/dev/null || fail "private cascade render failed" +cmp -s "$CONFIG_FILE" "$WORKDIR/template.before" || fail "live config changed" +[[ "$(stat -c %a "$output")" == 600 ]] || fail "candidate is not private" +jq -e ' + def outbound($tag): first(.outbounds[] | select(.tag == $tag)); + ["192.0.2.53","geoip:private","::/0"] as $denied_ips | + ($denied_ips + ["198.51.100.0/24"]) as $protected_ips | + .routing.rules as $rules | + (.inbounds | length) == 2 and + .inbounds[0].port == 15443 and .inbounds[0].sniffing.routeOnly == false and + .inbounds[0].settings.clients == [{id:"22222222-2222-4222-8222-222222222222"}] and + .dns.servers[-1] == "localhost" and + .routing.domainStrategy == "IPOnDemand" and + ($rules | map(.outboundTag)) == [ + "private-cascade-udp-relay", "block", "private-cascade-dns", "block", "direct-russia-only", "cascade-upstream", + "cascade-upstream", "direct", "direct-russian-ip", "cascade-upstream" + ] and + $rules[0] == {type:"field", inboundTag:["private-cascade-entry"], network:"udp", outboundTag:"private-cascade-udp-relay"} and + $rules[1] == {type:"field", inboundTag:["private-cascade-udp-dispatch"], network:"tcp", outboundTag:"block"} and + $rules[2] == {type:"field", ip:["192.0.2.53"], port:53, network:"tcp,udp", outboundTag:"private-cascade-dns"} and + $rules[3] == {type:"field", ip:$denied_ips, outboundTag:"block"} and + $rules[-1] == {type:"field", network:"tcp,udp", outboundTag:"cascade-upstream"} and + .inbounds[0].sniffing.ipsExcluded == $denied_ips and + .inbounds[1].tag == "private-cascade-udp-dispatch" and + .inbounds[1].listen == "127.0.0.1" and .inbounds[1].port == 15445 and + .inbounds[1].protocol == "vless" and .inbounds[1].settings.decryption == "none" and + .inbounds[1].settings.clients[0].id != .inbounds[0].settings.clients[0].id and + .inbounds[1].streamSettings == {network:"tcp", security:"none"} and + .inbounds[1].sniffing == {enabled:true, destOverride:["quic"], routeOnly:false, ipsExcluded:$denied_ips} and + $rules[7].domain == ["domain:ru","domain:xn--p1ai"] and $rules[8].ip == ["geoip:ru"] and + .outbounds[0].protocol == "blackhole" and + all(.outbounds[] | select(.tag | startswith("direct")); + .protocol == "freedom" and .settings.domainStrategy == "ForceIPv4" and + .streamSettings.sockopt.domainStrategy == "ForceIPv4") and + outbound("direct").settings.finalRules == [{action:"block", ip:$protected_ips}] and + outbound("direct-russia-only").settings.finalRules == [{action:"block", ip:$denied_ips}] and + outbound("direct-russian-ip").settings.finalRules == [ + {action:"block", ip:$protected_ips}, {action:"allow", ip:["geoip:ru"]}, {action:"block"} + ] and + (outbound("private-cascade-udp-relay") | .protocol == "trojan" and + .streamSettings == {network:"tcp",security:"none"} and + .settings.servers[0].address == "127.0.0.1" and .settings.servers[0].port == 15444 and + (.settings.servers[0].password | test("^[a-f0-9]{48}$"))) and + (outbound("cascade-upstream") | .settings.vnext[0].address == "2001:db8::10" + and .settings.vnext[0].users[0].id == "11111111-1111-4111-8111-111111111111" + and .streamSettings.realitySettings.shortId == "abcd1234" + and .streamSettings.xhttpSettings.mode == "stream-one") +' "$output" >/dev/null || fail "private cascade routing or ingress mismatch" +cp "$output" "$WORKDIR/private.before" +if render >/dev/null 2>&1; then fail "private cascade overwrote existing output"; fi +cmp -s "$output" "$WORKDIR/private.before" || fail "existing candidate changed" + +output="$WORKDIR/empty-selectors.json" +jq '.russia_only_domains = [] | .russian_domains = [] | .russian_ips = []' \ + "$WORKDIR/policy.json" > "$WORKDIR/optional-selectors.json" +chmod 600 "$WORKDIR/optional-selectors.json" +render "$WORKDIR/optional-selectors.json" >/dev/null || fail "private cascade rejected empty optional selectors" +jq -e 'all(.routing.rules[]; .outboundTag | startswith("direct") | not) and + all(.outbounds[]; .tag != "direct-russian-ip" and .tag != "direct-russia-only")' "$output" >/dev/null \ + || fail "empty optional selectors enabled direct routes" + +output="$WORKDIR/rejected.json" +for field in udp_relay_port udp_dispatch_port; do + for value in 0 -1 1023 65536 15443 false null '"15446"'; do + jq --arg field "$field" --argjson value "$value" '.[$field] = $value' \ + "$WORKDIR/policy.json" > "$WORKDIR/bad-port.json" + chmod 600 "$WORKDIR/bad-port.json" + if render "$WORKDIR/bad-port.json" >/dev/null 2>&1; then + fail "private cascade accepted $field=$value" + fi + [[ ! -e "$output" ]] || fail "invalid local port left a candidate" + done +done +jq '.udp_relay_port=15445' "$WORKDIR/policy.json" > "$WORKDIR/bad-port.json" +if render "$WORKDIR/bad-port.json" >/dev/null 2>&1; then fail "private cascade accepted colliding local ports"; fi +for field in russia_only_domains russian_domains russian_ips; do + for value in false null; do + jq --arg field "$field" --argjson value "$value" '.[$field] = $value' \ + "$WORKDIR/policy.json" > "$WORKDIR/optional-selectors.json" + if render "$WORKDIR/optional-selectors.json" >/dev/null 2>&1; then + fail "private cascade accepted $field=$value" + fi + [[ ! -e "$output" ]] || fail "invalid optional selector left a candidate" + done +done +if XRAY_TEST_VERSION=26.3.27 render >/dev/null 2>&1; then fail "private cascade accepted old Xray"; fi +[[ ! -e "$output" ]] || fail "old Xray left a candidate" + +jq '.client_id = "33333333-3333-4333-8333-333333333333"' "$WORKDIR/policy.json" > "$WORKDIR/reused.json" +chmod 600 "$WORKDIR/reused.json" +if render "$WORKDIR/reused.json" >/dev/null 2>&1; then + fail "private cascade reused an existing client" +fi +if XRAY_TEST_REJECT_CONFIG=1 render >/dev/null 2>&1; then fail "private cascade accepted rejected Xray config"; fi +[[ ! -e "$output" ]] || fail "failed render left a candidate" +chmod 644 "$WORKDIR/upstream.uri" +if render >/dev/null 2>&1; then fail "private cascade accepted exposed URI file"; fi +[[ ! -e "$output" ]] || fail "bad permissions left a candidate" + +echo "OK: private cascade routing, isolation, permissions and atomic validation" diff --git a/validation/test-private-cascade-udp-runtime.py b/validation/test-private-cascade-udp-runtime.py new file mode 100644 index 00000000..97c108f3 --- /dev/null +++ b/validation/test-private-cascade-udp-runtime.py @@ -0,0 +1,481 @@ +#!/usr/bin/env python3 +"""Isolated PR36 UDP check: real renderer, raw XUDP, relay and VLESS classifier. + +No router, VPS, interface, firewall or routing-table changes. The only fixture +exceptions allow two local UDP sink addresses and one local TCP sink port. +Branch evidence is recvfrom's actual source IPv4, not the Xray log label. +""" +import argparse +import contextlib +import json +import os +import pathlib +import queue +import socket +import struct +import subprocess +import sys +import tempfile +import threading +import time +import uuid +import urllib.parse + +IDENTITY = uuid.UUID('22222222-2222-4222-8222-222222222222') +# Official Xray v26.10.31 common/protocol/quic/sniff_test.go, TestSniffQUIC. +# Decryptable Initial with SNI www.google.com, used only against local sinks. +QUIC = bytes.fromhex('cd0000000108f1fb7bcc78aa5e7203a8f86400421531fe825b19541876db6c55c38890cd73149d267a084afee6087304095417a3033df6a81bbb71d8512e7a3e16df1e277cae5df3182cb214b8fe982ba3fdffbaa9ffec474547d55945f0fddbeadfb0b5243890b2fa3da45169e2bd34ec04b2e29382f48d612b28432a559757504d158e9e505407a77dd34f4b60b8d3b555ee85aacd6648686802f4de25e7216b19e54c5f78e8a5963380c742d861306db4c16e4f7fc94957aa50b9578a0b61f1e406b2ad5f0cd3cd271c4d99476409797b0c3cb3efec256118912d4b7e4fd79d9cb9016b6e5eaa4f5e57b637b217755daf8968a4092bed0ed5413f5d04904b3a61e4064f9211b2629e5b52a89c7b19f37a713e41e27743ea6dfa736dfa1bb0a4b2bc8c8dc632c6ce963493a20c550e6fdb2475213665e9a85cfc394da9cec0cf41f0c8abed3fc83be5245b2b5aa5e825d29349f721d30774ef5bf965b540f3d8d98febe20956b1fc8fa047e10e7d2f921c9c6622389e02322e80621a1cf5264e245b7276966eb02932584e3f7038bd36aa908766ad3fb98344025dec18670d6db43a1c5daac00937fce7b7c7d61ff4e6efd01a2bdee0ee183108b926393df4f3d74bbcbb015f240e7e346b7d01c41111a401225ce3b095ab4623a5836169bf9599eeca79d1d2e9b2202b5960a09211e978058d6fc0484eff3e91ce4649a5e3ba15b906d334cf66e28d9ff575406e1ae1ac2febafd72870b6f5d58fc5fb949cb1f40feb7c1d9ce5e71b') + + +def free_port(): + """Find an unused loopback TCP port without changing network configuration.""" + with socket.socket() as s: + s.bind(('127.0.0.1', 0)) + return s.getsockname()[1] + + +def address(host): + """Encode a VLESS address without resolving a domain name.""" + for family, kind in ((socket.AF_INET, 1), (socket.AF_INET6, 3)): + try: + return bytes([kind]) + socket.inet_pton(family, host) + except OSError: + pass + data = host.encode('ascii') + return bytes([2, len(data)]) + data + + +def frame(status, host, port, payload, global_id): + """Encode an XUDP frame whose explicit destination may differ from earlier frames.""" + meta = struct.pack('>HBBB', 1, status, 1, 2) + meta += struct.pack('>H', port) + address(host) + if status == 1: + meta += global_id + return struct.pack('>H', len(meta)) + meta + struct.pack('>H', len(payload)) + payload + + +def exact(sock, n): + """Read a complete protocol field and reject an early connection close.""" + result = b'' + while len(result) < n: + chunk = sock.recv(n - len(result)) + if not chunk: + raise EOFError('closed before complete response') + result += chunk + return result + + +class Association: + def __init__(self, port): + """Open one authenticated raw VLESS mux association for destination changes.""" + self.sock = socket.create_connection(('127.0.0.1', port), timeout=4) + self.sock.settimeout(4) + self.sock.sendall(b'\x00' + IDENTITY.bytes + b'\x00\x03') + self.first = True + self.response_header = False + self.global_id = os.urandom(8) + + def send(self, host, port, payload): + """Keep every new destination inside the original XUDP association.""" + self.sock.sendall(frame(1 if self.first else 2, host, port, payload, self.global_id)) + self.first = False + + def response(self): + """Decode one returned data frame while skipping mux control frames.""" + if not self.response_header: + header = exact(self.sock, 2) + assert header[0] == 0, header + exact(self.sock, header[1]) + self.response_header = True + for _ in range(20): + length = struct.unpack('>H', exact(self.sock, 2))[0] + meta = exact(self.sock, length) + if meta[3] & 1: + size = struct.unpack('>H', exact(self.sock, 2))[0] + return exact(self.sock, size) + raise AssertionError('no data response frame') + + def close(self): + """Release only this fixture's client connection.""" + self.sock.close() + + +def stop(process): + """Stop a captured fixture process with a bounded termination fallback.""" + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=2) + + +def ready(process, port, log): + """Wait for a listener or report its fixture log if startup fails.""" + for _ in range(80): + if process.poll() is not None: + log.flush() + raise RuntimeError(pathlib.Path(log.name).read_text()) + try: + with socket.create_connection(('127.0.0.1', port), timeout=.1): + return + except OSError: + time.sleep(.05) + raise TimeoutError(f'listener {port} not ready') + + +def sink_thread(sock, events, stopped): + """Record the real UDP source and destination before echoing the exact payload.""" + sock.settimeout(.1) + while not stopped.is_set(): + try: + data, peer = sock.recvfrom(65535) + except socket.timeout: + continue + except OSError: + return + events.put((sock.getsockname()[0], peer[0], data)) + sock.sendto(data, peer) + + +def tcp_sink_thread(sock, stopped): + """Return the observed TCP source address for independent routing canaries.""" + sock.settimeout(.1) + while not stopped.is_set(): + try: + conn, peer = sock.accept() + except socket.timeout: + continue + except OSError: + return + with conn: + conn.settimeout(3) + if conn.recv(4096): + conn.sendall(b'tcp-source:' + peer[0].encode()) + + +def dns_a_response(packet, identifier): + """Validate a test DNS response and extract its IPv4 answers.""" + ident, flags, questions, answers, _, _ = struct.unpack('>HHHHHH', packet[:12]) + assert ident == identifier and flags & 0x8000 and flags & 15 == 0, packet.hex() + + def skip_name(offset): + """Skip a DNS name or compression pointer without following arbitrary offsets.""" + for _ in range(128): + size = packet[offset] + if size & 0xc0 == 0xc0: + return offset + 2 + offset += 1 + if size == 0: + return offset + offset += size + raise AssertionError('invalid DNS name') + + offset = 12 + for _ in range(questions): + offset = skip_name(offset) + 4 + result = [] + for _ in range(answers): + offset = skip_name(offset) + kind, cls, _, length = struct.unpack('>HHIH', packet[offset:offset + 10]) + offset += 10 + if kind == 1 and cls == 1 and length == 4: + result.append(socket.inet_ntop(socket.AF_INET, packet[offset:offset + length])) + offset += length + return result + + +def local_ip(): + """Select an existing local IPv4 without adding an interface or address.""" + if sys.platform == 'darwin': + return subprocess.check_output(['/usr/sbin/ipconfig', 'getifaddr', 'en0'], text=True).strip() + for ip in socket.gethostbyname_ex(socket.gethostname())[2]: + if not ip.startswith('127.'): + return ip + raise RuntimeError('Pass --local-ip with an existing local IPv4 address') + + +def run(binary, relay_script, source_ip, keep, repo, bash, transport, decoy_name, decoy_target, empty_ips=False): + """Check real-core delivery using narrowly scoped local destination exceptions.""" + version = subprocess.check_output([binary, 'version'], text=True).splitlines()[0].split()[1] + profile = 'unmatched' if empty_ips else 'full' + directory = pathlib.Path(tempfile.mkdtemp(prefix='udp-split-' + version + '-' + transport + '-' + profile + '-')) + print(version, transport, profile, 'fixture', directory, flush=True) + with contextlib.ExitStack() as stack: + if not keep: + import shutil + stack.callback(shutil.rmtree, directory) + events = queue.Queue() + stopped = threading.Event() + stack.callback(stopped.set) + sinks = [] + for target in ('127.0.0.1', source_ip): + sock = stack.enter_context(socket.socket(socket.AF_INET, socket.SOCK_DGRAM)) + sock.bind((target, 0 if not sinks else sinks[0].getsockname()[1])) + threading.Thread(target=sink_thread, args=(sock, events, stopped), daemon=True).start() + sinks.append(sock) + sink_port = sinks[0].getsockname()[1] + sink6 = stack.enter_context(socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)) + sink6.bind(('::1', sink_port)) + threading.Thread(target=sink_thread, args=(sink6, events, stopped), daemon=True).start() + prohibited = stack.enter_context(socket.socket(socket.AF_INET, socket.SOCK_DGRAM)) + prohibited.bind(('127.0.0.1', 0)) + threading.Thread(target=sink_thread, args=(prohibited, events, stopped), daemon=True).start() + tcp_sink = stack.enter_context(socket.socket()) + tcp_sink.bind(('127.0.0.1', 0)) + tcp_sink.listen(8) + tcp_port = tcp_sink.getsockname()[1] + threading.Thread(target=tcp_sink_thread, args=(tcp_sink, stopped), daemon=True).start() + ports = [free_port() for _ in range(5)] + assert len(set(ports)) == len(ports) + public_port, relay_port, dispatch_port, foreign_port, front_port = ports + keys = dict(line.split(': ', 1) for line in subprocess.check_output([binary, 'x25519'], text=True).splitlines() if ': ' in line) + public_key = next(v for k, v in keys.items() if 'Public' in k or 'Password' in k) + network = 'xhttp' if transport == 'plain' else transport + def reality_stream(outgoing=False): + """Build matching REALITY settings for the selected trusted TLS target.""" + reality = ({'serverName': decoy_name, 'fingerprint': 'chrome', + 'publicKey': public_key, 'shortId': 'ab12'} if outgoing else + {'target': decoy_target, 'serverNames': [decoy_name], + 'privateKey': keys['PrivateKey'], 'shortIds': ['ab12']}) + result = {'network': network, 'security': 'reality', 'realitySettings': reality} + if network == 'xhttp': + result['xhttpSettings'] = {'host': decoy_name, 'path': '/fixture', 'mode': 'stream-one'} + return result + + template_user = {'id': str(uuid.uuid4())} + if network == 'tcp': + template_user['flow'] = 'xtls-rprx-vision' + template = {'inbounds': [{'tag': 'template', 'port': 15442, 'protocol': 'vless', + 'settings': {'decryption': 'none', 'clients': [template_user]}, + 'streamSettings': reality_stream()}]} + policy = {'inbound_tag': 'template', 'listen': '127.0.0.1', 'port': public_port, + 'client_id': str(IDENTITY), 'udp_relay_port': relay_port, 'udp_dispatch_port': dispatch_port, + 'russia_only_domains': ['full:inside.test', 'full:www.google.com'], + 'blocked_domains': ['full:blocked.ru'], 'blocked_ips': [source_ip + '/32'], + 'russian_domains': ['domain:ru'], 'russian_ips': [] if empty_ips else ['127.0.0.1/32']} + files = {name: directory / name for name in ('source.json', 'policy.json', 'upstream.txt', 'candidate.json')} + files['source.json'].write_text(json.dumps(template)) + files['policy.json'].write_text(json.dumps(policy)) + uri = {'security': 'reality', 'type': network, 'sni': decoy_name, + 'fp': 'chrome', 'pbk': public_key, 'sid': 'ab12'} + if network == 'tcp': + uri['flow'] = 'xtls-rprx-vision' + else: + uri.update({'host': decoy_name, 'path': '/fixture', 'mode': 'stream-one'}) + files['upstream.txt'].write_text('vless://11111111-1111-4111-8111-111111111111@203.0.113.8:25443?' + urllib.parse.urlencode(uri) + '\n') + env = dict(os.environ, XRAY_LOCATION_ASSET=str(binary.parent)) + command = [str(bash), '-c', + 'source ./xrayebator; CONFIG_FILE=$1; XRAY_BIN=$2; shift 2; private_cascade_command "$@"', + 'bash', files['source.json'], binary, 'render', '--policy-file', files['policy.json'], + '--upstream-file', files['upstream.txt'], '--output', files['candidate.json']] + rendered = subprocess.run(command, cwd=repo, env=env, text=True, capture_output=True) + assert rendered.returncode == 0, rendered.stderr + config = json.loads(files['candidate.json'].read_text()) + config['log'] = {'loglevel': 'debug'} + hosts = {'inside.test': source_ip, 'ordinary.ru': '127.0.0.1', 'blocked.ru': '127.0.0.1', + 'other.test': source_ip, 'www.google.com': source_ip, 'only6.test': '::1'} + config['dns'] = {'hosts': hosts, 'queryStrategy': 'UseIPv4'} + if transport == 'plain': + config['inbounds'][0]['streamSettings'] = {'network': 'tcp', 'security': 'none'} + # Permit exactly our two fixture addresses in classification; finalRules + # still allow only the exact sink port, not the prohibited local socket. + for inbound in config['inbounds']: + excluded = inbound.get('sniffing', {}).get('ipsExcluded', []) + inbound.get('sniffing', {})['ipsExcluded'] = [x if x != 'geoip:private' else '10.231.254.253/32' for x in excluded] + for rule in config['routing']['rules']: + if 'ip' in rule: + rule['ip'] = [x if x != 'geoip:private' else '10.231.254.253/32' for x in rule['ip']] + for outbound in config['outbounds']: + tag = outbound['tag'] + if tag.startswith('direct'): + outbound['sendThrough'] = '127.0.0.1' + ips = ['127.0.0.1/32'] + ([source_ip + '/32'] if tag == 'direct-russia-only' else []) + outbound['settings']['finalRules'].insert(0, {'action': 'allow', 'network': 'udp', 'ip': ips, 'port': str(sink_port)}) + outbound['settings']['finalRules'].insert(0, {'action': 'allow', 'network': 'tcp', 'ip': ['127.0.0.1/32'], 'port': str(tcp_port)}) + if tag == 'cascade-upstream': + if transport == 'plain': + outbound.clear() + outbound.update({'tag': tag, 'protocol': 'vless', + 'settings': {'vnext': [{'address': '127.0.0.1', 'port': foreign_port, + 'users': [{'id': '11111111-1111-4111-8111-111111111111', 'encryption': 'none'}]}]}, + 'streamSettings': {'network': 'tcp', 'security': 'none'}}) + else: + outbound['settings']['vnext'][0].update({'address': '127.0.0.1', 'port': foreign_port}) + if tag == 'cascade-fragment' and transport != 'plain': + outbound['settings']['finalRules'] = [{'action': 'allow', 'network': 'tcp', 'ip': ['127.0.0.1/32'], 'port': str(foreign_port)}] + files['candidate.json'].write_text(json.dumps(config)) + foreign = {'log': {'loglevel': 'debug'}, 'dns': {'hosts': hosts, 'queryStrategy': 'UseIPv4'}, + 'inbounds': [{'tag': 'foreign-in', 'listen': '127.0.0.1', 'port': foreign_port, 'protocol': 'vless', + 'settings': {'clients': [{'id': '11111111-1111-4111-8111-111111111111'}], 'decryption': 'none'}, + 'streamSettings': {'network': 'tcp', 'security': 'none'}}], + 'outbounds': [{'tag': 'foreign-exit', 'protocol': 'freedom', 'sendThrough': source_ip, + 'settings': {'domainStrategy': 'ForceIPv4', 'finalRules': [ + {'action': 'allow', 'network': 'udp', 'ip': ['127.0.0.1/32', source_ip + '/32'], 'port': str(sink_port)}, + {'action': 'allow', 'network': 'tcp', 'ip': ['127.0.0.1/32'], 'port': str(tcp_port)}, + {'action': 'block', 'ip': ['geoip:private', '::/0']}]}, + 'streamSettings': {'sockopt': {'domainStrategy': 'ForceIPv4'}}}]} + if transport != 'plain': + foreign['inbounds'][0]['streamSettings'] = reality_stream() + if network == 'tcp': + foreign['inbounds'][0]['settings']['clients'][0]['flow'] = 'xtls-rprx-vision' + foreign_file = directory / 'foreign.json' + foreign_file.write_text(json.dumps(foreign)) + foreign_log = stack.enter_context((directory / 'foreign.log').open('w')) + foreign_process = subprocess.Popen([binary, 'run', '-config', foreign_file], env=env, stdout=foreign_log, stderr=subprocess.STDOUT) + stack.callback(stop, foreign_process) + ready(foreign_process, foreign_port, foreign_log) + core_log = stack.enter_context((directory / 'ingress.log').open('w')) + core = subprocess.Popen([binary, 'run', '-config', files['candidate.json']], env=env, stdout=core_log, stderr=subprocess.STDOUT) + stack.callback(stop, core) + ready(core, public_port, core_log) + relay_log = stack.enter_context((directory / 'relay.log').open('w')) + relay = subprocess.Popen([sys.executable, relay_script, '--config', files['candidate.json']], env=env, stdout=relay_log, stderr=subprocess.STDOUT) + stack.callback(stop, relay) + ready(relay, relay_port, relay_log) + connection_port = public_port + if transport != 'plain': + front_user = {'id': str(IDENTITY), 'encryption': 'none', 'packetEncoding': 'xudp'} + if network == 'tcp': + front_user['flow'] = 'xtls-rprx-vision' + front_config = {'log': {'loglevel': 'debug'}, 'inbounds': [{'listen': '127.0.0.1', + 'port': front_port, 'protocol': 'vless', 'settings': {'decryption': 'none', 'clients': [{'id': str(IDENTITY)}]}, + 'streamSettings': {'network': 'tcp', 'security': 'none'}}], + 'outbounds': [{'protocol': 'vless', 'settings': {'vnext': [{'address': '127.0.0.1', + 'port': public_port, 'users': [front_user]}]}, 'streamSettings': reality_stream(True), + 'mux': {'enabled': True, 'concurrency': -1, 'xudpConcurrency': 1, 'xudpProxyUDP443': 'allow'}}]} + front_file = directory / 'front.json' + front_file.write_text(json.dumps(front_config)) + front_log = stack.enter_context((directory / 'front.log').open('w')) + front = subprocess.Popen([binary, 'run', '-config', front_file], env=env, stdout=front_log, stderr=subprocess.STDOUT) + stack.callback(stop, front) + ready(front, front_port, front_log) + connection_port = front_port + + def tcp_canary(host, expected_branch): + """Verify TCP routing independently of whether the UDP helper is running.""" + with socket.create_connection(('127.0.0.1', connection_port), timeout=8) as client: + client.settimeout(8) + request = b'\x00' + IDENTITY.bytes + b'\x00\x01' + struct.pack('>H', tcp_port) + address(host) + request += f'GET / HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n'.encode() + client.sendall(request) + header = exact(client, 2) + assert header[0] == 0, header + exact(client, header[1]) + expected = b'tcp-source:' + ('127.0.0.1' if expected_branch == 'RU' else source_ip).encode() + assert exact(client, len(expected)) == expected + print(version, 'TCP canary', host, '->', expected_branch, flush=True) + + def observed(client, host, expected_branch, target=None, payload=None): + """Assert the actual UDP target, source address and byte-exact response.""" + target = target or hosts.get(host, host) + data = payload if payload is not None else (host + ':' + uuid.uuid4().hex[:8]).encode() + client.send(host, sink_port, data) + event = events.get(timeout=5) + expected = (target, '127.0.0.1' if expected_branch == 'RU' else source_ip, data) + assert event == expected, (host, expected_branch, event, expected) + assert client.response() == data, ('return payload changed', host) + print(version, host, '->', expected_branch, 'actual source', event[1], 'target', event[0], flush=True) + + def denied(client, host, port, payload=None): + """Require that a prohibited datagram reaches none of the controlled sinks.""" + marker = payload if payload is not None else ('denied-' + uuid.uuid4().hex).encode() + client.send(host, port, marker) + try: + event = events.get(timeout=.55) + except queue.Empty: + return + raise AssertionError(('prohibited packet reached local sink', host, event)) + + tcp_canary('ordinary.ru', 'RU') + tcp_canary('blocked.ru', 'FOREIGN') + # Service DNS first must not pin the whole association to the DNS exit. + with contextlib.closing(Association(connection_port)) as client: + identifier = 0x2468 + qname = b''.join(bytes([len(part)]) + part.encode() for part in 'ordinary.ru'.split('.')) + b'\0' + query = struct.pack('>HHHHHH', identifier, 0x0100, 1, 0, 0, 0) + qname + struct.pack('>HH', 1, 1) + client.send('192.0.2.53', 53, query) + answer = client.response() + assert '127.0.0.1' in dns_a_response(answer, identifier), answer.hex() + assert events.empty(), 'DNS query leaked to an application sink' + observed(client, 'ordinary.ru', 'RU') + observed(client, 'other.test', 'FOREIGN') + print(version, 'same association DNS-first actual A answer -> RU -> foreign', flush=True) + # One association repeatedly changes routing category, including overlap. + with contextlib.closing(Association(connection_port)) as client: + observed(client, 'ordinary.ru', 'RU') + observed(client, 'other.test', 'FOREIGN') + observed(client, source_ip, 'FOREIGN', source_ip) + observed(client, 'blocked.ru', 'FOREIGN') + observed(client, 'inside.test', 'RU', source_ip) + observed(client, '127.0.0.1', 'FOREIGN' if empty_ips else 'RU') + denied(client, '127.0.0.1', prohibited.getsockname()[1]) + denied(client, '::1', sink_port) + denied(client, 'only6.test', sink_port) + observed(client, 'ordinary.ru', 'RU') + with contextlib.closing(Association(connection_port)) as client: + observed(client, 'other.test', 'FOREIGN') + observed(client, 'ordinary.ru', 'RU') + observed(client, 'other.test', 'FOREIGN') + # QUIC SNI must change the real destination, not merely the route label. + with contextlib.closing(Association(connection_port)) as client: + observed(client, '127.0.0.1', 'RU', source_ip, QUIC) + with contextlib.closing(Association(connection_port)) as client: + denied(client, '::1', sink_port, QUIC) + observed(client, 'ordinary.ru', 'RU') + if transport == 'plain': + # Offline CI also checks a policy change with fresh core listeners. + stop(core) + config['routing']['rules'] = [r for r in config['routing']['rules'] + if not (r.get('outboundTag') == 'direct-russian-ip' and r.get('ip') == ['127.0.0.1/32'])] + files['candidate.json'].write_text(json.dumps(config)) + core = subprocess.Popen([binary, 'run', '-config', files['candidate.json']], env=env, stdout=core_log, stderr=subprocess.STDOUT) + stack.callback(stop, core) + ready(core, public_port, core_log) + tcp_canary('ordinary.ru', 'RU') + tcp_canary('blocked.ru', 'FOREIGN') + print(version, 'variant without Russian-IP route: unmatched literal follows foreign default', flush=True) + with contextlib.closing(Association(connection_port)) as client: + observed(client, '127.0.0.1', 'FOREIGN') + observed(client, 'ordinary.ru', 'RU') + # Foreign failure must not convert subsequent traffic into direct output. + stop(foreign_process) + with contextlib.closing(Association(connection_port)) as client: + denied(client, 'other.test', sink_port) + observed(client, 'ordinary.ru', 'RU') + stop(relay) + with contextlib.closing(Association(connection_port)) as client: + denied(client, 'ordinary.ru', sink_port) + tcp_canary('ordinary.ru', 'RU') + foreign_process = subprocess.Popen([binary, 'run', '-config', foreign_file], env=env, stdout=foreign_log, stderr=subprocess.STDOUT) + stack.callback(stop, foreign_process) + ready(foreign_process, foreign_port, foreign_log) + tcp_canary('blocked.ru', 'FOREIGN') + print(version, transport, profile, 'PASS UDP split, DNS-first, TCP canaries, bidirectional payloads, destination changes, prohibited targets, foreign/relay failure', directory if keep else '', flush=True) + + +if __name__ == '__main__': + os.umask(0o077) + parser = argparse.ArgumentParser() + parser.add_argument('--repo', type=pathlib.Path, default=pathlib.Path.cwd()) + parser.add_argument('--bash', type=pathlib.Path, default=pathlib.Path('/bin/bash')) + parser.add_argument('--relay-script', type=pathlib.Path) + parser.add_argument('--xray', '--binary', dest='binary', type=pathlib.Path, action='append', required=True) + parser.add_argument('--local-ip') + parser.add_argument('--keep', action='store_true') + parser.add_argument('--transport', choices=['plain', 'tcp', 'xhttp'], default='plain', + help='tcp/xhttp additionally exercise real REALITY on both hops; plain bypasses outer transport') + parser.add_argument('--decoy-name', default='www.cloudflare.com', + help='TLS name and XHTTP host of the REALITY decoy for full transport checks') + parser.add_argument('--decoy-target', default='www.cloudflare.com:443', + help='reachable HOST:PORT of the valid TLS decoy; may be a local SSH forward') + args = parser.parse_args() + ip = args.local_ip or local_ip() + relay_script = args.relay_script or args.repo / 'libexec/private_cascade_udp.py' + for binary in args.binary: + run(binary, relay_script, ip, args.keep, args.repo, args.bash, args.transport, args.decoy_name, args.decoy_target) + if args.transport != 'plain': + # A distinct cold configuration tests unmatched routing without + # conflating this policy test with live HTTP/2 restart recovery. + run(binary, relay_script, ip, args.keep, args.repo, args.bash, args.transport, args.decoy_name, args.decoy_target, True) diff --git a/validation/test-private-cascade-udp.sh b/validation/test-private-cascade-udp.sh new file mode 100644 index 00000000..86940ac2 --- /dev/null +++ b/validation/test-private-cascade-udp.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +if ! command -v python3 >/dev/null 2>&1; then + printf '%s\n' 'SKIP: python3 not installed' + exit 0 +fi +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +python3 -m unittest discover -s "$repo_root/validation" -p test_private_cascade_udp.py -v diff --git a/validation/test-profile-create-without-pq.sh b/validation/test-profile-create-without-pq.sh new file mode 100644 index 00000000..5493b89c --- /dev/null +++ b/validation/test-profile-create-without-pq.sh @@ -0,0 +1,92 @@ +#!/usr/bin/env bash +# Local CLI contract: opt-in legacy XHTTP, unchanged PQ default and backend grants. +set -euo pipefail + +fail() { echo "FAIL: $*" >&2; exit 1; } +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +WORKDIR=$(mktemp -d /tmp/xrayebator-create-without-pq.XXXXXX) +trap 'rm -rf "$WORKDIR"' EXIT +source "$REPO_ROOT/xrayebator" + +CONFIG_FILE="$WORKDIR/config.json" +PROFILES_DIR="$WORKDIR/profiles" +PUBLIC_KEY_FILE="$WORKDIR/public-key" +PRIVATE_KEY_FILE="$WORKDIR/private-key" +VLESS_ENCRYPTION_FILE="$WORKDIR/pq-encryption" +VLESS_DECRYPTION_FILE="$WORKDIR/pq-decryption" +SERVER_COUNTRY_FILE="$WORKDIR/country" +XRAYEBATOR_SERVER_ADDR_OVERRIDE="203.0.113.10" +PRIVATE_KEY="test-private-key" +printf '%s' "$PRIVATE_KEY" > "$PRIVATE_KEY_FILE" +printf '%s' 'test-public-key' > "$PUBLIC_KEY_FILE" +mkdir -p "$PROFILES_DIR" +printf '%s\n' '{"inbounds":[]}' > "$CONFIG_FILE" +: > "$WORKDIR/events" + +# Keep real profile/inbound creation, metadata validation, URI and backend dispatch. +# Only host-dependent operations are replaced; no network, firewall or service calls. +_default_sni_for_transport() { echo "example.com"; } +_reality_dest_for_sni() { echo "$1:443"; } +backup_config() { cp "$CONFIG_FILE" "$WORKDIR/backup.json"; printf -v "$2" '%s' "$WORKDIR/backup.json"; } +safe_restart_xray() { echo restart >> "$WORKDIR/events"; } +fix_xray_permissions() { return 0; } +open_firewall_port() { echo "open:$1" >> "$WORKDIR/events"; } +close_firewall_port() { echo "close:$1" >> "$WORKDIR/events"; } +_profile_cli_subscription_url() { return 1; } +_backend_installed() { return 0; } +_hysteria2_on_profile_event() { echo "hy2:$1:$2" >> "$WORKDIR/events"; } +_awg_on_profile_event() { echo "awg:$1:$2" >> "$WORKDIR/events"; } + +out=$(profile_create_command --name legacy --transport xhttp --port 34001 --without-pq) +jq -e '.ok and .names == ["legacy"] and .errors == []' <<< "$out" >/dev/null || fail "legacy creation: $out" +jq -e '.pq_enabled == false and .schema_version == 2 and .xhttp_path == "/xhttp"' \ + "$PROFILES_DIR/legacy.json" >/dev/null || fail "legacy metadata" +jq -e '.inbounds[0].settings.decryption == "none" and .inbounds[0].streamSettings.network == "xhttp"' \ + "$CONFIG_FILE" >/dev/null || fail "legacy inbound" +uri=$(_generate_vless_url_pure "$PROFILES_DIR/legacy.json") || fail "legacy URI export without PQ keys" +[[ "$uri" == vless://*'encryption=none&'*'type=xhttp&'* ]] || fail "legacy URI: $uri" + +# A compatible shared legacy inbound works for every member of a batch. +out=$(profile_create_command --name shared --port 34001 --count 2 --without-pq) +jq -e '.names == ["shared", "shared-2"] and .errors == []' <<< "$out" >/dev/null || fail "legacy batch: $out" +jq -e '.inbounds | length == 1 and (.[0].settings.clients | length == 3)' \ + "$CONFIG_FILE" >/dev/null || fail "legacy shared inbound" + +# Normal XHTTP still requires PQ keys; the failed profile leaves config untouched. +before=$(cat "$CONFIG_FILE") +out=$(profile_create_command --name missing-keys --transport xhttp --port 34002) +jq -e '.names == [] and (.errors | length == 1)' <<< "$out" >/dev/null || fail "default PQ must require keys" +[[ ! -e "$PROFILES_DIR/missing-keys.json" && "$(cat "$CONFIG_FILE")" == "$before" ]] || fail "missing keys changed state" +printf '%s' 'mlkem768x25519plus.native.test-encryption' > "$VLESS_ENCRYPTION_FILE" +printf '%s' 'mlkem768x25519plus.native.test-decryption' > "$VLESS_DECRYPTION_FILE" +out=$(profile_create_command --name pq --port 34002) +jq -e '.names == ["pq"] and .errors == []' <<< "$out" >/dev/null || fail "PQ default: $out" +jq -e '.pq_enabled == true' "$PROFILES_DIR/pq.json" >/dev/null || fail "PQ default metadata" +jq -e '.inbounds[] | select(.port == 34002) | .settings.decryption == "mlkem768x25519plus.native.test-decryption"' \ + "$CONFIG_FILE" >/dev/null || fail "PQ default inbound" +uri=$(_generate_vless_url_pure "$PROFILES_DIR/pq.json") || fail "PQ URI export" +[[ "$uri" == *'encryption=mlkem768x25519plus.native.test-encryption&'* ]] || fail "PQ URI encryption" + +# Reject a PQ/legacy port collision without changing the existing inbound. +before=$(cat "$CONFIG_FILE") +out=$(profile_create_command --name collision --port 34002 --without-pq) +jq -e '.names == [] and (.errors | length == 1)' <<< "$out" >/dev/null || fail "PQ/legacy collision accepted" +[[ ! -e "$PROFILES_DIR/collision.json" && "$(cat "$CONFIG_FILE")" == "$before" ]] || fail "collision changed state" + +for transport in tcp tcp-utls tcp-xudp tcp-mux grpc; do + events_before=$(cat "$WORKDIR/events") + if out=$(profile_create_command --name invalid --transport "$transport" --port 34003 --without-pq); then + fail "--without-pq accepted for $transport" + fi + jq -e '.ok == false and (.error | contains("--without-pq"))' <<< "$out" >/dev/null || fail "invalid-transport JSON" + [[ ! -e "$PROFILES_DIR/invalid.json" && "$(cat "$CONFIG_FILE")" == "$before" && "$(cat "$WORKDIR/events")" == "$events_before" ]] \ + || fail "invalid transport had side effects" +done +out=$(profile_create_command --name tcp --transport tcp --port 34003) +jq -e '.names == ["tcp"] and .errors == []' <<< "$out" >/dev/null || fail "normal TCP creation" +uri=$(_generate_vless_url_pure "$PROFILES_DIR/tcp.json") || fail "normal TCP URI" +[[ "$uri" == *'encryption=none&flow=xtls-rprx-vision&'*'type=tcp&'* ]] || fail "normal TCP changed" +[[ "$(grep -c '^hy2:.*:created$' "$WORKDIR/events")" == 5 && "$(grep -c '^awg:.*:created$' "$WORKDIR/events")" == 5 ]] \ + || fail "successful creations must preserve optional backend grants" + +echo "PASS: profile-create legacy XHTTP opt-in, PQ default, compatibility guards and backend grants" diff --git a/validation/test_private_cascade_udp.py b/validation/test_private_cascade_udp.py new file mode 100644 index 00000000..d8002ba3 --- /dev/null +++ b/validation/test_private_cascade_udp.py @@ -0,0 +1,342 @@ +#!/usr/bin/env python3 +"""Local wire-level regression checks; no external connections or host mutations.""" + +import asyncio +import contextlib +import hashlib +import importlib.util +import ipaddress +import io +import json +import pathlib +import struct +import sys +import tempfile +import unittest +import uuid +from unittest.mock import patch + +ROOT = pathlib.Path(__file__).resolve().parents[1] +SPEC = importlib.util.spec_from_file_location("private_cascade_udp", ROOT / "libexec/private_cascade_udp.py") +relay = importlib.util.module_from_spec(SPEC) +sys.modules[SPEC.name] = relay +SPEC.loader.exec_module(relay) + +PASSWORD = "only-local-test-password" +CLIENT_ID = uuid.UUID("11111111-2222-4333-8444-555555555555") + + +def destination(host, port): + """Build independent IPv4, IPv6 or domain wire addresses for protocol probes.""" + try: + address = ipaddress.ip_address(host) + except ValueError: + name = host.encode() + wire = b"\x03" + bytes([len(name)]) + name + else: + wire = (b"\x01" if address.version == 4 else b"\x04") + address.packed + return wire + struct.pack("!H", port) + + +def packet(target, payload): + """Frame test datagrams independently of the relay's decoder.""" + return target + struct.pack("!H", len(payload)) + b"\r\n" + payload + + +async def eventually(condition): + """Await asynchronous cleanup with a finite polling budget.""" + for _ in range(100): + if condition(): + return + await asyncio.sleep(.01) + raise AssertionError("State did not settle") + + +class WireTests(unittest.IsolatedAsyncioTestCase): + """Exercise authenticated splitting against an isolated bare VLESS echo peer.""" + + async def asyncSetUp(self): + """Start temporary loopback peers without touching host routing or services.""" + self.records = [] + self.backend_tasks = set() + self.backend = await asyncio.start_server(self.backend_client, "127.0.0.1", 0) + port = self.backend.sockets[0].getsockname()[1] + self.proxy = relay.Relay(relay.Config(0, port, PASSWORD, CLIENT_ID)) + await self.proxy.start() + self.port = self.proxy.server.sockets[0].getsockname()[1] + self.writers = [] + + async def asyncTearDown(self): + """Close fixture peers and require complete relay capacity and task release.""" + for writer in self.writers: + writer.close() + await asyncio.gather(*(writer.wait_closed() for writer in self.writers), + return_exceptions=True) + await self.proxy.close() + self.backend.close() + for task in list(self.backend_tasks): + task.cancel() + await asyncio.gather(*self.backend_tasks, return_exceptions=True) + await self.backend.wait_closed() + self.assertEqual(self.proxy.flow_count, 0) + self.assertFalse(self.proxy.clients) + self.assertFalse(self.proxy.handlers) + + async def backend_client(self, reader, writer): + """Observe fixed VLESS targets and inject bounded response failures on request.""" + task = asyncio.current_task() + self.backend_tasks.add(task) + record = None + try: + prefix = await reader.readexactly(19) + self.assertEqual(prefix, b"\0" + CLIENT_ID.bytes + b"\0\x02") + port = await reader.readexactly(2) + kind = await reader.readexactly(1) + if kind == b"\x01": + address, label = await reader.readexactly(4), b"\x01" + elif kind == b"\x03": + address, label = await reader.readexactly(16), b"\x04" + elif kind == b"\x02": + size = await reader.readexactly(1) + address, label = size + await reader.readexactly(size[0]), b"\x03" + else: + self.fail("Unexpected VLESS address family") + record = {"target": label + address + port, "payloads": [], "closed": False} + self.records.append(record) + first = True + while True: + size = struct.unpack("!H", await reader.readexactly(2))[0] + payload = await reader.readexactly(size) + record["payloads"].append(payload) + if first: + writer.write(b"\x01\0" if payload == b"wrong-version" else b"\0\0") + first = False + if payload == b"oversize-reply": + writer.write(struct.pack("!H", relay.MAX_PAYLOAD + 1)) + else: + writer.write(struct.pack("!H", size) + payload) + await writer.drain() + except (asyncio.IncompleteReadError, OSError): + pass + finally: + if record is not None: + record["closed"] = True + writer.close() + await writer.wait_closed() + self.backend_tasks.discard(task) + + async def connect(self, password=PASSWORD, command=b"\x03"): + """Open a test frontend with selectable credentials and command.""" + reader, writer = await asyncio.open_connection("127.0.0.1", self.port) + self.writers.append(writer) + key = hashlib.sha224(password.encode()).hexdigest().encode() + writer.write(key + b"\r\n" + command + destination("192.0.2.1", 4000) + b"\r\n") + await writer.drain() + return reader, writer + + async def response(self, reader): + """Require a complete frontend reply within the fixture deadline.""" + return await asyncio.wait_for(relay.read_packet(reader), 1) + + async def test_one_authenticated_stream_splits_and_reuses_exact_destinations(self): + """Require independent backend targets while reusing only identical endpoints.""" + reader, writer = await self.connect() + targets = [destination("192.0.2.1", 4000), destination("example.ru", 4000), + destination("192.0.2.1", 4001), destination("2001:db8::1", 4000)] + for n, target in enumerate(targets): + payload = ("payload-%d" % n).encode() + writer.write(packet(target, payload)) + await writer.drain() + response, data = await self.response(reader) + self.assertEqual((response.wire, data), (target, payload)) + writer.write(packet(targets[0], b"again")) + self.assertEqual((await self.response(reader))[1], b"again") + self.assertEqual(len(self.records), 4) + self.assertEqual(self.records[0]["payloads"], [b"payload-0", b"again"]) + self.assertEqual({r["target"] for r in self.records}, set(targets)) + + async def test_two_clients_same_destination_are_isolated(self): + """Keep equal destinations and one client's disconnect isolated across clients.""" + a, aw = await self.connect() + b, bw = await self.connect() + target = destination("192.0.2.1", 4000) + aw.write(packet(target, b"alice")) + bw.write(packet(target, b"bob")) + self.assertEqual((await self.response(a))[1], b"alice") + self.assertEqual((await self.response(b))[1], b"bob") + self.assertEqual(len(self.records), 2) + self.assertNotEqual(self.records[0]["payloads"], self.records[1]["payloads"]) + aw.close() + await eventually(lambda: self.proxy.flow_count == 1) + bw.write(packet(target, b"bob-still")) + self.assertEqual((await self.response(b))[1], b"bob-still") + + async def test_wrong_auth_and_tcp_or_mux_commands_never_reach_classifier(self): + """Reject unauthorized or non-UDP traffic before any backend connection.""" + for password, command in [("wrong-test-password", b"\x03"), (PASSWORD, b"\x01"), + (PASSWORD, b"\x7f")]: + reader, writer = await self.connect(password, command) + writer.write(packet(destination("192.0.2.1", 4000), b"rejected")) + self.assertEqual(await asyncio.wait_for(reader.read(), 1), b"") + self.assertEqual(self.records, []) + + async def test_malformed_and_oversize_packets_close_without_destination_dial(self): + """Reject invalid frames, zero ports and oversized lengths before forwarding.""" + malformed = [b"\x09", destination("192.0.2.1", 4000) + b"\0\0\r\n", + destination("192.0.2.1", 4000) + struct.pack("!H", relay.MAX_PAYLOAD + 1), + destination("192.0.2.1", 4000) + b"\0\x01xxz", b"\x03\0", + destination("192.0.2.1", 0) + b"\0\x01\r\nz"] + for bad in malformed: + reader, writer = await self.connect() + writer.write(bad) + self.assertEqual(await asyncio.wait_for(reader.read(), 1), b"") + self.assertEqual(self.records, []) + + async def test_control_disconnect_cleans_all_backend_flows(self): + """Require frontend EOF to close every destination stream and return capacity.""" + reader, writer = await self.connect() + for port in range(4000, 4003): + writer.write(packet(destination("192.0.2.1", port), b"ok")) + await self.response(reader) + writer.close() + await eventually(lambda: self.proxy.flow_count == 0) + await eventually(lambda: all(r["closed"] for r in self.records)) + + async def test_payload_boundary_is_byte_exact_and_oversize_never_truncated(self): + """Echo the largest IPv4 frame intact and reject one extra byte entirely.""" + reader, writer = await self.connect() + target = destination("192.0.2.1", 4000) + largest = bytes(range(251)) * 32 + b"x" * 149 # 8181 bytes: exact IPv4 Trojan frame capacity. + self.assertEqual(len(largest), 8192 - len(target) - 4) + writer.write(packet(target, largest)) + self.assertEqual((await self.response(reader))[1], largest) + writer.write(packet(target, largest + b"x")) + self.assertEqual(await asyncio.wait_for(reader.read(), 1), b"") + self.assertEqual(self.records[0]["payloads"], [largest]) + + async def test_limits_drop_new_destinations_but_existing_flow_continues(self): + """Keep established flows usable when a client reaches its destination cap.""" + with patch.object(relay, "MAX_SESSION_FLOWS", 1), patch.object(relay, "MAX_FLOWS", 1): + reader, writer = await self.connect() + target = destination("192.0.2.1", 4000) + writer.write(packet(target, b"first")) + await self.response(reader) + writer.write(packet(destination("192.0.2.2", 4000), b"over-limit")) + writer.write(packet(target, b"still-good")) + self.assertEqual((await self.response(reader))[1], b"still-good") + self.assertEqual(len(self.records), 1) + self.assertEqual(self.proxy.flow_count, 1) + + async def test_idle_expiry_and_invalid_backend_response_release_resources(self): + """Reclaim capacity after idle expiry or invalid VLESS reply framing.""" + with patch.object(relay, "IDLE_TIMEOUT", .06): + reader, writer = await self.connect() + writer.write(packet(destination("192.0.2.1", 4000), b"idle")) + await self.response(reader) + self.assertEqual(await asyncio.wait_for(reader.read(), 1), b"") + for payload in [b"wrong-version", b"oversize-reply"]: + _, writer = await self.connect() + writer.write(packet(destination("192.0.2.1", 4000), payload)) + await eventually(lambda: any(payload in r["payloads"] for r in self.records)) + await eventually(lambda: self.proxy.flow_count == 0) + + async def test_global_capacity_is_shared_and_released_for_other_clients(self): + """Enforce the shared cap and make released slots available to another client.""" + with patch.object(relay, "MAX_SESSION_FLOWS", 2), patch.object(relay, "MAX_FLOWS", 1): + a, aw = await self.connect() + b, bw = await self.connect() + aw.write(packet(destination("192.0.2.1", 4000), b"occupy")) + await self.response(a) + target = destination("192.0.2.2", 4000) + bw.write(packet(target, b"over-limit")) + await asyncio.sleep(.02) + self.assertEqual(len(self.records), 1) + aw.close() + await eventually(lambda: self.proxy.flow_count == 0) + bw.write(packet(target, b"capacity-returned")) + self.assertEqual((await self.response(b))[1], b"capacity-returned") + self.assertEqual(self.records[-1]["payloads"], [b"capacity-returned"]) + + async def test_pending_queue_is_bounded_without_losing_other_destinations(self): + """Drop excess queued packets while preserving admitted packets and new flows.""" + gate = asyncio.Event() + original = relay.Flow.send + + async def delayed_send(flow, writer): + """Hold the backend sender so the fixture can saturate its pending queue.""" + await gate.wait() + await original(flow, writer) + + with patch.object(relay, "QUEUE_SIZE", 3), patch.object(relay.Flow, "send", delayed_send): + reader, writer = await self.connect() + target = destination("192.0.2.1", 4000) + writer.write(b"".join(packet(target, bytes([n])) for n in range(10))) + await eventually(lambda: len(self.records) == 1) + gate.set() + values = [(await self.response(reader))[1] for _ in range(3)] + self.assertEqual(values, [b"\0", b"\1", b"\2"]) + other = destination("192.0.2.2", 4000) + writer.write(packet(other, b"other")) + response, payload = await self.response(reader) + self.assertEqual((response.wire, payload), (other, b"other")) + self.assertEqual(self.records[0]["payloads"], values) + + async def test_unauthenticated_connection_limit_and_handshake_timeout(self): + """Bound clients before authentication and expire incomplete handshakes.""" + with patch.object(relay, "MAX_SESSIONS", 1), patch.object(relay, "IO_TIMEOUT", .06): + reader, writer = await asyncio.open_connection("127.0.0.1", self.port) + self.writers.append(writer) + await eventually(lambda: len(self.proxy.clients) == 1) + other, ow = await asyncio.open_connection("127.0.0.1", self.port) + self.writers.append(ow) + self.assertEqual(await asyncio.wait_for(other.read(), 1), b"") + self.assertEqual(await asyncio.wait_for(reader.read(), 1), b"") + await eventually(lambda: not self.proxy.clients) + + async def test_unexpected_flow_failure_closes_client_without_logging_data(self): + """Close faulty clients while keeping exception details and payloads out of logs.""" + async def failed_send(flow, writer): + """Inject a private exception string to exercise sanitized error reporting.""" + raise RuntimeError("must-not-be-logged-payload") + + errors = io.StringIO() + with patch.object(relay.Flow, "send", failed_send), contextlib.redirect_stderr(errors): + reader, writer = await self.connect() + writer.write(packet(destination("example.ru", 4000), b"private-payload")) + self.assertEqual(await asyncio.wait_for(reader.read(), 1), b"") + await eventually(lambda: self.proxy.flow_count == 0) + self.assertEqual(errors.getvalue(), "UDP relay flow failed unexpectedly\n") + + +class ConfigTests(unittest.TestCase): + """Check file protection and local endpoint restrictions without opening sockets.""" + + def test_protected_exact_local_schema(self): + """Accept protected local settings and reject public, exposed or symlink inputs.""" + data = {"outbounds": [{"tag": "private-cascade-udp-relay", "protocol": "trojan", + "settings": {"servers": [{"address": "127.0.0.1", "port": 30001, "password": PASSWORD}]}, + "streamSettings": {"network": "tcp", "security": "none"}}], + "inbounds": [{"tag": "private-cascade-udp-dispatch", "protocol": "vless", + "listen": "127.0.0.1", "port": 30002, "settings": {"clients": [{"id": str(CLIENT_ID)}], + "decryption": "none"}, "streamSettings": {"network": "tcp", "security": "none"}}]} + with tempfile.TemporaryDirectory() as tmp: + path = pathlib.Path(tmp) / "config.json" + path.write_text(json.dumps(data)) + path.chmod(0o640) + self.assertEqual(relay.Config.from_file(path), relay.Config(30001, 30002, PASSWORD, CLIENT_ID)) + path.chmod(0o644) + with self.assertRaises(relay.ProtocolError): + relay.Config.from_file(path) + path.chmod(0o600) + link = pathlib.Path(tmp) / "link.json" + link.symlink_to(path) + with self.assertRaises(OSError): + relay.Config.from_file(link) + data["outbounds"][0]["settings"]["servers"][0]["address"] = "example.com" + path.write_text(json.dumps(data)) + with self.assertRaises(relay.ProtocolError): + relay.Config.from_file(path) + + +if __name__ == "__main__": + unittest.main() diff --git a/xrayebator b/xrayebator index ad5b2156..2c388cb2 100755 --- a/xrayebator +++ b/xrayebator @@ -6828,18 +6828,16 @@ _cascade_parse_vless_uri() { return 1 fi - jq -n \ + XRAYEBATOR_CASCADE_UUID="$uuid" XRAYEBATOR_CASCADE_SHORT_ID="$short_id" \ + XRAYEBATOR_CASCADE_PATH="$xhttp_path" jq -n \ --arg address "$address" \ --argjson port "$port" \ - --arg uuid "$uuid" \ --arg transport "$transport" \ --arg sni "$sni" \ --arg fingerprint "$fingerprint" \ --arg public_key "$public_key" \ - --arg short_id "$short_id" \ --arg flow "$flow" \ --arg packet_encoding "$packet_encoding" \ - --arg xhttp_path "$xhttp_path" \ --arg xhttp_host "$xhttp_host" \ --arg xhttp_mode "$xhttp_mode" ' { @@ -6847,19 +6845,19 @@ _cascade_parse_vless_uri() { tag: "cascade-upstream", address: $address, port: $port, - uuid: $uuid, + uuid: $ENV.XRAYEBATOR_CASCADE_UUID, transport: $transport, sni: $sni, fingerprint: $fingerprint, public_key: $public_key, - short_id: $short_id + short_id: $ENV.XRAYEBATOR_CASCADE_SHORT_ID } + (if $transport == "tcp" then (if $flow == "" then {} else {flow: $flow} end) + (if $packet_encoding == "" then {} else {packet_encoding: $packet_encoding} end) else { - xhttp_path: $xhttp_path, + xhttp_path: $ENV.XRAYEBATOR_CASCADE_PATH, xhttp_host: $xhttp_host, xhttp_mode: $xhttp_mode } @@ -7014,6 +7012,180 @@ _cascade_build_fragment_outbound_json() { }' } +private_cascade_command() ( + local usage='Usage: xrayebator private-cascade render --policy-file FILE --upstream-file FILE --output FILE' + local policy="" upstream="" output="" workdir relay_password dispatch_id + local -a links=() + if [[ "$#" -eq 1 && "$1" == "--help" ]]; then + printf '%s\n' "$usage" + return 0 + fi + if [[ "${1:-}" != "render" ]]; then + printf '%s\n' "$usage" >&2 + return 1 + fi + shift + while [[ $# -ge 2 ]]; do + case "$1" in + --policy-file) [[ -z "$policy" ]] || break; policy=$2 ;; + --upstream-file) [[ -z "$upstream" ]] || break; upstream=$2 ;; + --output) [[ -z "$output" ]] || break; output=$2 ;; + *) break ;; + esac + shift 2 + done + if [[ $# -ne 0 || -z "$policy" || -z "$upstream" || "$output" != *.json ]]; then + printf '%s\n' "$usage" >&2 + return 1 + fi + local input + for input in "$policy" "$upstream"; do + if [[ ! -f "$input" || -L "$input" || "$(stat -c '%a:%u' -- "$input" 2>/dev/null)" != "600:$EUID" ]]; then + printf 'Private cascade inputs must be regular mode-0600 files owned by the caller.\n' >&2 + return 1 + fi + done + if [[ -e "$output" || -L "$output" ]]; then + printf 'Private cascade output already exists.\n' >&2 + return 1 + fi + local min_xray_version="26.6.27" xray_version + if ! xray_version=$("$XRAY_BIN" version 2>/dev/null) || + ! [[ $xray_version =~ ^Xray[[:blank:]]+([0-9]+\.[0-9]+\.[0-9]+)([[:space:]]|$) ]] || + ! _xray_version_at_least_pure "${BASH_REMATCH[1]}" "$min_xray_version"; then + printf 'Private cascade requires Xray-core %s or newer.\n' "$min_xray_version" >&2 + return 1 + fi + mapfile -t links < "$upstream" || return 1 + if [[ "${#links[@]}" -ne 1 ]]; then + printf 'The upstream file must contain exactly one VLESS link.\n' >&2 + return 1 + fi + umask 077 + workdir=$(mktemp -d "$(dirname -- "$output")/.xrayebator-private-cascade.XXXXXX") || return 1 + trap 'rm -rf -- "$workdir"' EXIT + _cascade_parse_vless_uri "${links[0]%$'\r'}" > "$workdir/upstream.json" || return 1 + _cascade_build_outbound_json "$workdir/upstream.json" > "$workdir/outbound.json" || return 1 + _cascade_build_fragment_outbound_json > "$workdir/fragment.json" || return 1 + + relay_password=$(openssl rand -hex 24) || return 1 + dispatch_id=$(uuidgen) || return 1 + [[ "$relay_password" =~ ^[a-f0-9]{48}$ && "$dispatch_id" =~ ^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$ ]] || return 1 + + CASCADE_RELAY_PASSWORD="$relay_password" CASCADE_DISPATCH_ID="$dispatch_id" \ + jq -e --slurpfile policies "$policy" --slurpfile upstream "$workdir/outbound.json" \ + --slurpfile fragment "$workdir/fragment.json" ' + def selectors: type == "array" and all(.[]; type == "string" and length > 0); + def optional_selectors($key): (has($key) | not) or (.[$key] | selectors); + def port_number: type == "number" and floor == . and . >= 1 and . <= 65535; + def optional_port($key): (has($key) | not) or (.[$key] | port_number and . >= 1024); + def ipv4: + type == "string" and (split(".") | + length == 4 and all(.[]; test("^(0|[1-9][0-9]{0,2})$") and tonumber <= 255)); + def valid_policy: + type == "object" and + ((keys - ["inbound_tag", "client_id", "listen", "port", "russia_only_domains", + "blocked_domains", "blocked_ips", "russian_domains", "russian_ips", + "udp_relay_port", "udp_dispatch_port"]) | length == 0) and + (.inbound_tag | type == "string" and length > 0) and + (.client_id | type == "string" and test("^[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$")) and + (.listen | ipv4) and + (.port | port_number) and + optional_port("udp_relay_port") and optional_port("udp_dispatch_port") and + (.udp_relay_port // 15444 | port_number) and + (.udp_dispatch_port // 15445 | port_number) and + ([.port, (.udp_relay_port // 15444), (.udp_dispatch_port // 15445)] | unique | length == 3) and + (.blocked_domains | selectors) and (.blocked_ips | selectors) and + ((.blocked_domains + .blocked_ips) | length > 0) and + optional_selectors("russia_only_domains") and + optional_selectors("russian_domains") and optional_selectors("russian_ips"); + def rule($field; $values; $target): + if ($values | length) == 0 then empty + else {type:"field", ($field):$values, outboundTag:$target} end; + def direct($tag; $final_rules): + # Older cores resolve Freedom destinations before applying sockopt. + {tag:$tag, protocol:"freedom", + settings:{domainStrategy:"ForceIPv4", finalRules:$final_rules}, + streamSettings:{sockopt:{domainStrategy:"ForceIPv4"}}}; + + if ($policies | length) != 1 or ($policies[0] | valid_policy | not) + then error("Invalid private cascade policy") else . end | + ($policies[0] | .udp_relay_port //= 15444 | .udp_dispatch_port //= 15445) as $p | + [.inbounds[]? | select(.tag == $p.inbound_tag)] as $matches | + if ($matches | length) != 1 then error("Select one configured ingress inbound") else . end | + $matches[0] as $in | + ($in.settings.clients[0] // {}) as $template_client | + ($p.client_id | ascii_downcase) as $client_id | + any(.inbounds[]?.settings.clients[]?; (.id // "" | ascii_downcase) == $client_id) as $client_exists | + if $in.protocol != "vless" or $in.streamSettings.security != "reality" or + (($in.streamSettings.network // "tcp") | IN("tcp","raw","xhttp") | not) or + ($in.settings.decryption // "none") != "none" or + (($in.settings.fallbacks // []) | length) != 0 or + $client_exists or + (($in.streamSettings.realitySettings.serverNames // []) | length) == 0 + then error("Ingress needs standard VLESS Reality TCP/XHTTP and a new private client UUID") + else . end | + ["192.0.2.53"] as $dns_ips | + ($dns_ips + ["geoip:private","::/0"]) as $denied_ips | + ($denied_ips + $p.blocked_ips) as $protected_ips | + ($p.russia_only_domains // []) as $russia_only | + ($p.russian_ips // ["geoip:ru"]) as $russian_ips | + { + log:{loglevel:"warning", access:"none"}, + dns:{servers:["https+local://1.1.1.1/dns-query","localhost"], queryStrategy:"UseIPv4"}, + inbounds: [($in | .listen=$p.listen | .port=$p.port | .tag="private-cascade-entry" | + .settings.clients=[($template_client | {id:$client_id} + (if .flow then {flow} else {} end))] | + .sniffing={enabled:true, destOverride:["http","tls","quic"], routeOnly:false, + ipsExcluded:$denied_ips}), + {tag:"private-cascade-udp-dispatch", listen:"127.0.0.1", port:$p.udp_dispatch_port, + protocol:"vless", settings:{decryption:"none", clients:[{id:env.CASCADE_DISPATCH_ID}]}, + streamSettings:{network:"tcp", security:"none"}, + sniffing:{enabled:true, destOverride:["quic"], routeOnly:false, ipsExcluded:$denied_ips}} + ], + outbounds:[ + {tag:"block",protocol:"blackhole"}, + {tag:"private-cascade-dns",protocol:"dns"}, + direct("direct"; [{action:"block", ip:$protected_ips}]), + (if ($russia_only | length) > 0 + then direct("direct-russia-only"; [{action:"block", ip:$denied_ips}]) + else empty end), + (if ($russian_ips | length) > 0 + then direct("direct-russian-ip"; [ + {action:"block", ip:$protected_ips}, + {action:"allow", ip:$russian_ips}, + {action:"block"} + ]) + else empty end), + {tag:"private-cascade-udp-relay", protocol:"trojan", + settings:{servers:[{address:"127.0.0.1", port:$p.udp_relay_port, password:env.CASCADE_RELAY_PASSWORD}]}, + streamSettings:{network:"tcp", security:"none"}}, + $fragment[0], $upstream[0] + ], + routing:{domainStrategy:"IPOnDemand",rules:[ + # Split mutable public XUDP before DNS or any destination-based route. + {type:"field", inboundTag:["private-cascade-entry"], network:"udp",outboundTag:"private-cascade-udp-relay"}, + {type:"field", inboundTag:["private-cascade-udp-dispatch"], network:"tcp",outboundTag:"block"}, + {type:"field", ip:$dns_ips, port:53, network:"tcp,udp",outboundTag:"private-cascade-dns"}, + {type:"field", ip:$denied_ips,outboundTag:"block"}, + rule("domain"; $russia_only; "direct-russia-only"), + rule("domain"; $p.blocked_domains; "cascade-upstream"), + rule("ip"; $p.blocked_ips; "cascade-upstream"), + rule("domain"; $p.russian_domains // ["domain:ru","domain:xn--p1ai"]; "direct"), + rule("ip"; $russian_ips; "direct-russian-ip"), + {type:"field",network:"tcp,udp",outboundTag:"cascade-upstream"} + ]} + } + ' "$CONFIG_FILE" > "$workdir/config.json" || return 1 + + if ! XRAY_LOCATION_ASSET="${XRAY_LOCATION_ASSET:-/usr/local/share/xray}" \ + "$XRAY_BIN" run -test -config "$workdir/config.json" > "$workdir/xray-test.log" 2>&1; then + printf 'Xray rejected the private cascade candidate. Verify the selected inbound and installed geo assets.\n' >&2 + return 1 + fi + ln -T -- "$workdir/config.json" "$output" || return 1 + printf 'Private cascade config validated and written: %s\n' "$output" +) + _cascade_apply_current_upstream() { local reason=${1:-cascade_apply} local upstream_file outbound_json fragment_json address old_address had_active=false @@ -8050,7 +8222,7 @@ probe_test_command() { # xrayebator на каждый HTTP-request — лишние сетевые вызовы под xray:xray неприемлемы). # В source-режиме SERVER_IP инициализируется пустым; pure-функции берут публичный # адрес из HAPP markers, а get_server_ip() используют только как fallback. -if [[ "$XRAYEBATOR_SOURCED" -eq 0 ]]; then +if [[ "$XRAYEBATOR_SOURCED" -eq 0 && "${1:-}" != "private-cascade" ]]; then SERVER_IP=$(get_server_ip) else SERVER_IP="" @@ -16145,7 +16317,7 @@ profiles_command() { return 0 } -# xrayebator profile-create --name NAME [--transport T] [--port P] [--count N] +# xrayebator profile-create --name NAME [--transport T] [--port P] [--count N] [--without-pq] # T: tcp|tcp-utls|tcp-xudp|tcp-mux|grpc|xhttp (по умолчанию xhttp) # N: количество копий (по умолчанию 1); имена: name, name-2, name-3, ... # При N>1 каждый профиль получает отдельный случайный порт (или заданный --port). @@ -16154,7 +16326,7 @@ profile_create_command() { export DEBIAN_FRONTEND=noninteractive export XRAYEBATOR_NONINTERACTIVE=1 - local name="" transport="xhttp" port="" count=1 expire_raw="" + local name="" transport="xhttp" port="" count=1 expire_raw="" pq_enabled=true while [[ $# -gt 0 ]]; do case "$1" in --name) name="$2"; shift 2 ;; @@ -16162,6 +16334,7 @@ profile_create_command() { --port) port="$2"; shift 2 ;; --count) count="$2"; shift 2 ;; --expire) expire_raw="$2"; shift 2 ;; + --without-pq) pq_enabled=false; shift ;; *) shift ;; esac done @@ -16177,6 +16350,10 @@ profile_create_command() { return 1 ;; esac + if [[ "$pq_enabled" == "false" && "$transport" != "xhttp" ]]; then + echo '{"ok":false,"error":"--without-pq допустим только для транспорта xhttp"}' + return 1 + fi if ! [[ "$count" =~ ^[0-9]+$ ]] || [[ "$count" -lt 1 ]] || [[ "$count" -gt 50 ]]; then echo '{"ok":false,"error":"Некорректное количество (1-50)"}' return 1 @@ -16235,7 +16412,7 @@ profile_create_command() { errors+=("$pname: уже существует") continue fi - if _profile_cli_create_one "$pname" "$transport" "$port" "$results_file" "$expire_value"; then + if _profile_cli_create_one "$pname" "$transport" "$port" "$results_file" "$expire_value" "$pq_enabled"; then created_names+=("$pname") else errors+=("$pname: не удалось создать") @@ -16255,9 +16432,10 @@ profile_create_command() { # Один профиль: файл JSON + inbound + safe_restart_xray. Возвращает 0/1. # $5 — expire (epoch-секунды, 0 = бессрочный). +# $6 — PQ для XHTTP (по умолчанию true). _profile_cli_create_one() { - local pname="$1" transport="$2" fixed_port="${3:-}" results_file="${4:-}" expire_value="${5:-0}" - local uuid sub_token grpc_service_name xhttp_path port default_sni + local pname="$1" transport="$2" fixed_port="${3:-}" results_file="${4:-}" expire_value="${5:-0}" pq_enabled="${6:-true}" + local uuid sub_token grpc_service_name="" xhttp_path="" port default_sni uuid=$(uuidgen) sub_token=$(openssl rand -hex 16) if [[ ! "$sub_token" =~ ^[a-f0-9]{32}$ ]]; then @@ -16303,7 +16481,7 @@ _profile_cli_create_one() { elif [[ "$transport" == "xhttp" ]]; then jq_args+=(--arg xhttp_path "$xhttp_path") jq_expr+=', xhttp_path: $xhttp_path' - jq_args+=(--argjson schema_v 2 --argjson pq_enabled true) + jq_args+=(--argjson schema_v 2 --argjson pq_enabled "$pq_enabled") jq_expr+=', schema_version: $schema_v, pq_enabled: $pq_enabled' fi jq_expr+=', sub_token: $sub_token, created: $created' @@ -16324,7 +16502,7 @@ _profile_cli_create_one() { return 1 fi - if ! add_inbound "$uuid" "$transport" "$port" "$default_sni" "$fingerprint" "$grpc_service_name" "$xhttp_path"; then + if ! add_inbound "$uuid" "$transport" "$port" "$default_sni" "$fingerprint" "$grpc_service_name" "$xhttp_path" "$pq_enabled"; then rm -f "$PROFILES_DIR/$pname.json" echo -e "${RED}✗ Inbound не создан — профиль удалён${NC}" >&2 return 1 @@ -20276,6 +20454,10 @@ if [[ "$XRAYEBATOR_SOURCED" -eq 0 ]]; then shift bypass_command "$@" ;; + private-cascade) + shift + private_cascade_command "$@" + ;; backend-status) _backend_status_json ;; @@ -20342,8 +20524,8 @@ if [[ "$XRAYEBATOR_SOURCED" -eq 0 ]]; then echo -e " ${CYAN}sudo xrayebator happ-setup${NC} — создать/переиспользовать HAPP multi-route профиль" echo -e " ${CYAN}sudo xrayebator probe-test${NC} — проверить доступность SNI с VPS" echo -e " ${CYAN}sudo xrayebator profiles${NC} — JSON-список профилей" - echo -e " ${CYAN}sudo xrayebator profile-create --name N [--transport T] [--port P] [--count N] [--expire 2006-12-31]${NC}" - echo -e " — создать профиль/семейство профилей (JSON)" + echo -e " ${CYAN}sudo xrayebator profile-create --name N [--transport T] [--port P] [--count N] [--expire 2006-12-31] [--without-pq]${NC}" + echo -e " — создать профиль/семейство профилей (JSON); --without-pq: только XHTTP, encryption=none" echo -e " ${CYAN}sudo xrayebator profile-delete --name N${NC} — удалить профиль (JSON)" echo -e " ${CYAN}sudo xrayebator fp-change --name N [--route R] --fp FINGERPRINT${NC} — сменить fingerprint (JSON)" echo -e " ${CYAN}sudo xrayebator profile-revoke --name N [--full]${NC} — новый sub_token; --full: и новый uuid, старые клиенты отваливаются (JSON)" @@ -20370,6 +20552,7 @@ if [[ "$XRAYEBATOR_SOURCED" -eq 0 ]]; then echo -e " ${CYAN}sudo xrayebator sni-change --name N [--route R] --sni S${NC} — сменить SNI (JSON; обновит все профили на порту)" echo -e " ${CYAN}sudo xrayebator port-change --name N [--route R] --port P|random${NC} — сменить порт (JSON; reconnect клиентов)" echo -e " ${CYAN}sudo xrayebator bypass list${NC} — список доменов в обходе (JSON)" + echo -e " ${CYAN}sudo xrayebator private-cascade render --policy-file F --upstream-file U --output O.json${NC} — отдельный конфиг каскада" echo -e " ${CYAN}sudo xrayebator bypass add --domain D${NC} — добавить домен в обход (JSON)" echo -e " ${CYAN}sudo xrayebator bypass remove --domain D${NC} — убрать домен из обхода (JSON)" echo -e " ${CYAN}sudo xrayebator bypass reset${NC} — сбросить все bypass-правила (JSON)"