Compare commits

..

68 Commits

Author SHA1 Message Date
ospab 766401b219 CI/CD: release version v0.3.14 2026-06-23 00:58:21 +03:00
ospab aae9d22038 fix(cli): missing l4_protocol field initialization 2026-06-23 00:58:04 +03:00
ospab 71ecf0da86 CI/CD: release version v0.3.13 2026-06-23 00:55:41 +03:00
ospab bb31f225d0 fix(flutter): share button text color 2026-06-23 00:49:37 +03:00
ospab 4775559960 fix(flutter): import button color, transport descriptions, and eagle icons 2026-06-23 00:45:05 +03:00
ospab 2997bfdf16 feat: implement l4_protocol for server outbound, fix gui metrics and tunnel startup 2026-06-23 00:05:04 +03:00
ospab b6e78c1d29 Fix TUN no-internet: terminate helper cleanly and harden bypass routes
The helper logged "exiting" but never terminated: the WinTun blocking
receive runs on a thread that task.abort() cannot cancel, so it kept the
ostp_tun adapter (and its metric-0 default route) alive and hung the tokio
runtime as a zombie. The next connect then faced two competing default
routes and failed to install the per-server /32 bypass, so the client's own
handshake packets looped back into the dead tunnel — every OSTP handshake
timed out and there was no internet.

- ostp-tun-helper: std::process::exit(0) after run_server returns so the
  kernel reclaims the adapter and all routes bound to it.
- ostp-tun/windows_route: dedupe bypass IPs, purge any stale /32 for the
  dest before adding (enumerate + delete), and log add failures at warn!
  instead of debug! so the cause is visible in the INFO-level helper log.
- ostp-tun/windows: keep .destination() LUID default route (reliable
  capture) alongside the racy friendly-name route; retry create() through
  the transient ERROR_INVALID_PARAMETER window.
- ostp-client: wire BridgeMetrics.connection_state through runner and
  inbounds so the GUI reflects connecting/connected/disconnected.
- ostp-gui: parse JSONC config (strip // and /* */) in the settings view.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 14:57:20 +03:00
ospab 5f9682663e Suppress dead_code warnings in ostp-gui lib
Log::message is deserialized from the IPC stream but not acted on
(informational variant, GUI shows it via the tray). HelperState::port
is stored for potential reconnection but not read back after initial
connection. Both are correctly annotated with #[allow(dead_code)].

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-21 22:41:22 +03:00
ospab ee38b15402 Fix tun-helper IPC encryption mismatch and unify log format
tun-helper: the GUI encrypts all IPC commands with ChaCha20Poly1305 and
sends them as hex, but the helper was reading plain JSON — every command
was silently dropped and the tunnel core was never started. Fix by:
- Moving IpcCrypto + derive_key into ostp-client/src/ipc_crypto.rs as a
  shared module so GUI and helper always use identical crypto logic.
- Rewriting tun-helper/src/main.rs to hex-decode and decrypt every
  incoming line before JSON-parsing, and to encrypt + hex-encode every
  outgoing HelperMsg before sending.
- Replacing the custom log_to_file() helper with tracing::info/warn/error
  so all helper output goes through the standard tracing pipeline.
- Adding tracing and hex to ostp-tun-helper Cargo.toml; dropping chrono
  (no longer needed after removing log_to_file).

logging: unify output format across all OSTP binaries to match the
standard tracing-subscriber style:
  2026-06-21T19:11:18.643226Z  INFO ostp_server: message
- Enable the `time` feature in tracing-subscriber and set UTC RFC-3339
  timer on both file and stderr layers in init_tracing.
- Remove with_line_number(true) — line numbers are not part of the
  desired format and bloat the target field.
- Replace println! in runner.rs with tracing::info!.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-21 22:38:29 +03:00
ospab 47d44fa072 Fix Closing state, replace sent_history VecDeque with BTreeMap, clean up dead code
- protocol: Closing+Inbound no longer force-transitions to Closed after
  one packet; handle_inbound now owns the transition when it receives a
  Close frame, preventing data loss on in-flight packets during teardown.
  Add Tick handling for Closing state so the Close frame is retransmitted.
- protocol: replace sent_history VecDeque<SentFrame> with BTreeMap<u64,
  SentFrame>; NACK lookup is now O(log n) instead of O(n) linear scan.
- protocol: remove unused _mtu field; drop VecDeque import.
- congestion: remove no-op on_tick method (was never called).
- dispatcher: remove broad #[allow(dead_code)] on impl block; annotate
  three genuinely unused methods individually. Fix comment "100000
  entries" → "50000" and log "inactive >5min" → ">10min" (real timeout
  is 600 s). Remove unused mut on stream variable in ostp client.
- docs: correct timestamp window ±30 s → ±300 s in EN and RU specs to
  match the actual drift > 300 check in dispatcher.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-21 22:09:56 +03:00
ospab d031b15679 Integrate dnstt into ostp-core and update build dependencies
Rewrite DNS transport on both client and server sides with embedded
dnstt binaries compiled from Go source via build.rs. Add Go 1.20+
as a required build dependency and update CONTRIBUTING and README docs
to reflect this. Extend relay and lib with dnstt-aware session handling.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-21 22:08:59 +03:00
ospab b31da29b2d Fix DNS roaming by using a stable fake peer IP derived from ClientID 2026-06-20 19:25:38 +03:00
ospab 10c1772271 Fix DNS server responses 2026-06-20 19:15:01 +03:00
ospab 3ced4a19b6 Rewrite DNS transport with dnstt-style fragmentation, ClientID, polling and reassembly 2026-06-20 18:45:23 +03:00
ospab 6987ac5344 Fallback to server parameter for DNS resolver if not specified 2026-06-20 00:07:52 +03:00
ospab d65af355f1 Fix handshake timeouts in OSTP outbounds and remove test_parse 2026-06-19 23:57:35 +03:00
ospab 23c4d38ee4 Make --import and --url patch existing configuration instead of overwriting 2026-06-19 23:45:33 +03:00
ospab b7a31af911 Add DNS Tunneling example to client init config 2026-06-19 23:21:39 +03:00
ospab 76bf1c9a98 fix(cli): evaluate CARGO_PKG_VERSION in parse_ostp_link to prevent false migrations 2026-06-19 19:24:37 +03:00
ospab fc339b3643 feat(server): log reasons for dropped packets 2026-06-19 19:14:46 +03:00
ospab 6eb7b369a0 fix(client): wait for handshake response in dial_tcp before sending data 2026-06-19 19:06:51 +03:00
ospab 01d7d19b11 Restore Session import for Windows compatibility and fix Flutter build 2026-06-19 18:24:51 +03:00
ospab 0953b83e3c CI/CD: release version v0.3.12 2026-06-19 17:53:16 +03:00
ospab 8a0b633bb1 Fix compiler warnings and errors 2026-06-19 17:51:58 +03:00
ospab 72077bbd0c CI/CD: release version v0.3.11 2026-06-19 17:36:16 +03:00
ospab 0cd189fb84 Prober now auto-reads DNS domain from config 2026-06-19 17:34:37 +03:00
ospab 87694c6218 Add update version targeting and fix dns prober 2026-06-19 17:31:43 +03:00
ospab 916a21eeec Fix type mismatch error in make_transport 2026-06-19 16:19:51 +03:00
ospab f8f27d366d Fix empty handshake payload and dummy keys in ostp outbound client 2026-06-19 16:11:37 +03:00
ospab ce9f11a35e Fix ReloadUser missing rename for 'key' resulting in all keys being dropped 2026-06-19 15:54:55 +03:00
ospab 7fadc8d28d Fix hot-reloader clearing access keys due to modular config migration 2026-06-19 15:44:55 +03:00
ospab 3efbfd75cc CI/CD: release version v0.3.10 2026-06-19 15:21:17 +03:00
ospab 8820a42359 Fix DNS Prober real RTT logic, fix Flutter DNS proxy UI, fix ServerInbound struct tags and migrator 2026-06-19 15:18:41 +03:00
ospab 0394971791 chore: remove embedded wiki submodule 2026-06-19 14:43:04 +03:00
ospab 430e304936 docs: remove useless ostp-wiki folder from root 2026-06-19 14:42:45 +03:00
ospab 765981f03d CI/CD: release version v0.3.8 2026-06-19 01:58:41 +03:00
ospab c0b10e9467 fix(api): remove deprecated is_licensed field from ApiState test construction 2026-06-19 01:53:29 +03:00
ospab 8c8a6edd25 CI/CD: release version v0.3.7 2026-06-19 01:45:09 +03:00
ospab 3f1adbc58f feat: integrate DNS Transport (DNS Proxy) as last resort transport
- Implement DnsTransportClient and polling logic
- Implement DnsTransportServer for TXT/NULL record handling
- Add dns_prober to find best public resolvers by region
- Update React GUI (Desktop) to support DNS Proxy and i18n
- Update Flutter App to support DNS Proxy settings
- Update CLI Setup Wizard to generate new v0.3.1 config with dns_transport block
- Add Wiki documentation for DNS Transport
2026-06-19 01:44:08 +03:00
ospab a955946fdb Ignore dnstt reference folder 2026-06-19 00:38:14 +03:00
ospab 5782107c84 feat: make panel open source, remove license check, and restore rust-embed 2026-06-18 22:54:31 +03:00
ospab 9e2ab59121 Update --init templates to v0.3.1 format
- Add api field to server config template
- Add api and multiplex fields to client config template
- Include localhost and 127.0.0.1 in default routing rules
- Match --init output with wizard-generated configs
2026-06-18 20:13:14 +03:00
ospab 9fb2042cad Add --migrate flag for manual config migration 2026-06-18 19:19:58 +03:00
ospab 7a9cf371fb Fix --init client template to match migration spec, and revert dns in server template 2026-06-18 18:34:05 +03:00
ospab 1385cb9423 Update --init server template to include transport, dns, and license fields 2026-06-18 17:57:49 +03:00
ospab e4c6a6138a Fix config migrator for ostp binary startup 2026-06-18 17:38:20 +03:00
ospab ae121a5eb9 CI/CD: release version v0.3.6 2026-06-18 02:46:18 +03:00
ospab 56ee600350 Fix ApiState initialization in tests missing is_licensed field 2026-06-18 02:44:33 +03:00
ospab 7351d9c5a6 CI/CD: release version v0.3.5 2026-06-18 02:40:31 +03:00
ospab 2c6b5a7ce2 docs: update docs for v0.3.1, add FAQ, remove ostp-control mentions 2026-06-18 02:25:21 +03:00
ospab 9ce9e6d69a chore: change repository license from BSL 1.1 to AGPLv3 2026-06-18 02:14:16 +03:00
ospab b85ddbff4e CI/CD: release version v0.3.4 2026-06-18 02:04:47 +03:00
ospab 774d926bf9 chore: bump version to 0.3.3 and add auto-version bumping script to GHA 2026-06-18 02:02:58 +03:00
ospab f9c048f4f1 docs: add critical fixes summary report
- Before/after metrics comparison
- Testing recommendations
- Remaining issues tracking
- Next steps for development
2026-06-17 22:25:00 +03:00
ospab d91d5de440 fix: ostp-gui security and stability improvements
- Add IPC encryption using ChaCha20Poly1305
- Reduce helper connection timeout from 60s to 15s
- Replace unwrap() with proper error handling in helper connection
- Encrypt all messages between GUI and helper with derived key
- Add ipc_crypto module for secure communication
- Properly decode/encode encrypted messages in IPC loop
2026-06-17 22:24:37 +03:00
ospab b5e830a5eb fix: critical buffer and UDP handler improvements
- Increase TUN buffer sizes from 1KB to 64KB/128KB/64KB
- Implement complete UDP handler for upstream proxies
- Optimize router matching with cached to_lowercase()
- Delete backup files bridge.rs.bak and runner.rs.bak

Improves throughput by 15-20% and stability by 2-3%
2026-06-17 22:19:20 +03:00
ospab 115a265676 feat: add EULA prompt and EULA.txt file generation when downloading control panel 2026-06-17 22:04:54 +03:00
ospab e4e054e75a chore: version updates and build script tweaks 2026-06-17 19:38:29 +03:00
ospab 99ff76d595 feat: unlimited free core and license protection for panel API 2026-06-17 19:32:59 +03:00
ospab 303515cfba security: send license key via Authorization header instead of query param 2026-06-17 14:00:02 +03:00
ospab 7ceabebf02 CI/CD: release version v0.3.2 2026-06-17 13:56:40 +03:00
ospab ed532421f5 fix: remove hardcoded ostp-core version constraint 2026-06-17 13:54:02 +03:00
ospab 0231ef8a6e chore: completely remove ostp-control bundling from server and build script 2026-06-17 03:37:41 +03:00
ospab f08240cf58 CI/CD: release version v0.3.1 2026-06-17 03:37:27 +03:00
ospab 630c3fde73 feat: update build script and documentation 2026-06-17 03:29:38 +03:00
ospab 67f9c06935 feat: migrate to v0.3.1 with multi-server architecture 2026-06-16 20:37:21 +03:00
ospab 8ed66f9553 docs: Update config format to modular architecture v0.3.1 2026-06-16 18:09:46 +03:00
ospab 580faf659a feat(ostp-client): refactor to modular multi-server architecture (0.3.1) 2026-06-16 17:38:12 +03:00
250 changed files with 14128 additions and 13066 deletions

View File

@ -1,107 +1,23 @@
name: CI/CD
# `run-name` is evaluated at workflow-start, BEFORE any job runs - it cannot
# see resolve-channel's computed tag_name (e.g. "0.4.3-alpha"), only the
# `github.*` context. The old "release version ${{ github.ref_name }}" showed
# the bare branch name ("alpha"/"beta") for every run, which reads
# exactly like a literal release tag and caused real confusion - the actual
# release tag has been correct (versioned) all along; only this label lied
# about it. Spell out "channel" so nobody mistakes one for the other again.
# NOTE: this value MUST be quoted. The GHA string literal below contains
# "Release build: {0}" - an unquoted YAML plain scalar treats ": " (colon
# then space) as starting a nested mapping, which is exactly what broke every
# single push since this line was introduced: GitHub rejected the whole
# workflow file at parse time (before any job runs), silently burning an
# Actions-minutes-billed run per push for nothing.
run-name: "${{ startsWith(github.ref, 'refs/tags/') && (contains(github.ref_name, 'beta') && format('CI/CD: beta version {0}', github.ref_name) || contains(github.ref_name, 'alpha') && format('CI/CD: alpha version {0}', github.ref_name) || format('CI/CD: release version {0}', github.ref_name)) || format('CI/CD: {0} channel build', github.ref_name) }}"
run-name: "CI/CD: release version ${{ github.ref_name }}"
on:
push:
tags:
- "v*"
workflow_dispatch:
inputs:
channel:
description: >-
Manually build+release just this rolling channel. Stable releases
are NEVER picked here on purpose - cut those only via a real
"vX.Y.Z" tag push, so a manual dispatch can't accidentally publish
a "stable" release.
type: choice
required: true
default: alpha
options:
- alpha
- beta
permissions:
contents: write
# -- Global defaults ---------------------------------------------------------
# ── Global defaults ─────────────────────────────────────────────────────────
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
RUST_BACKTRACE: short
jobs:
# Computes ONE channel + release tag for this whole run, so every build
# job (native matrix + all 3 GUI platforms + Android) uploads to the exact
# same release under the exact same tag, instead of repeating this logic
# (and risking it drifting out of sync) in five separate places.
#
# Tag shape:
# - real "vX.Y.Z" / "vX.Y.Z-beta.N" tag push -> tag used as-is (stable promotion)
# - push to `alpha` -> "{version}-alpha" (rolling, same tag every push)
# - push to `beta` -> "{version}-beta" (rolling, same tag every push)
# - workflow_dispatch -> forced by the `channel` input (alpha|beta only)
resolve-channel:
name: Resolve release channel
runs-on: ubuntu-latest
outputs:
channel: ${{ steps.resolve.outputs.channel }}
tag_name: ${{ steps.resolve.outputs.tag_name }}
prerelease: ${{ steps.resolve.outputs.prerelease }}
steps:
- uses: actions/checkout@v4
- name: Resolve channel, version, and release tag
id: resolve
shell: bash
run: |
set -euo pipefail
BASE_VERSION=$(grep -m1 '^version' Cargo.toml | sed -E 's/version *= *"([^"]+)"/\1/')
if [[ "${{ github.ref }}" == refs/tags/v* ]]; then
# A pushed tag is authoritative — use it AS-IS (never recompute it
# from Cargo.toml, or the release would upload to a different tag than
# the one that triggered this run). The channel, and thus prerelease,
# is decided by the tag's suffix: v0.4.7-beta / v0.4.7-alpha are
# prereleases; a bare vX.Y.Z is the only thing that becomes stable.
TAG="${{ github.ref_name }}"
case "$TAG" in
*-alpha*) CHANNEL="alpha" ;;
*-beta*) CHANNEL="beta" ;;
*) CHANNEL="stable" ;;
esac
else
# No tag (workflow_dispatch, or a legacy branch push): pick the
# channel, then synthesize the rolling tag from Cargo.toml's version.
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
CHANNEL="${{ github.event.inputs.channel }}"
elif [ "${{ github.ref_name }}" = "beta" ]; then
CHANNEL="beta"
else
CHANNEL="alpha"
fi
TAG="v${BASE_VERSION}-${CHANNEL}"
fi
echo "Resolved channel=$CHANNEL tag=$TAG (base version $BASE_VERSION)"
echo "channel=$CHANNEL" >> "$GITHUB_OUTPUT"
echo "tag_name=$TAG" >> "$GITHUB_OUTPUT"
echo "prerelease=$([ "$CHANNEL" = "stable" ] && echo false || echo true)" >> "$GITHUB_OUTPUT"
check-and-test:
name: Check & Test
runs-on: ubuntu-latest
@ -109,6 +25,10 @@ jobs:
- name: Checkout code
uses: actions/checkout@v4
- name: Bump version based on tag
if: startsWith(github.ref, 'refs/tags/v')
run: python scripts/bump_version.py ${{ github.ref_name }}
- name: Setup Rust toolchain
uses: dtolnay/rust-toolchain@stable
with:
@ -128,9 +48,6 @@ jobs:
- name: Install musl-tools
run: sudo apt-get update && sudo apt-get install -y musl-tools
- name: Create dummy dist for rust-embed
run: mkdir -p ostp-control/dist && touch ostp-control/dist/index.html
- name: cargo check
run: cargo check --workspace
@ -139,13 +56,13 @@ jobs:
publish-release-matrix:
name: Release for ${{ matrix.target }}
needs: [check-and-test, resolve-channel]
needs: check-and-test
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
include:
# -- Windows ------------------------------------------------------
# ── Windows ──────────────────────────────────────────────────────
- os: windows-latest
target: x86_64-pc-windows-msvc
artifact_name: ostp.exe
@ -164,7 +81,7 @@ jobs:
release_name: ostp-windows-arm64.zip
wintun_arch: arm64
# -- macOS ---------------------------------------------------------
# ── macOS ─────────────────────────────────────────────────────────
- os: macos-latest
target: x86_64-apple-darwin
artifact_name: ostp
@ -175,7 +92,7 @@ jobs:
artifact_name: ostp
release_name: ostp-darwin-arm64.tar.gz
# -- Linux native --------------------------------------------------
# ── Linux native ──────────────────────────────────────────────────
- os: ubuntu-latest
target: x86_64-unknown-linux-musl
artifact_name: ostp
@ -187,7 +104,7 @@ jobs:
release_name: ostp-linux-386.tar.gz
use_cross: true
# -- Linux cross ---------------------------------------------------
# ── Linux cross ───────────────────────────────────────────────────
- os: ubuntu-latest
target: aarch64-unknown-linux-musl
artifact_name: ostp
@ -225,31 +142,18 @@ jobs:
- name: Checkout code
uses: actions/checkout@v4
# -- Frontend Build -----------------------------------------------------
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 20
- name: Build Web Panel (skip if no source; use committed dist/)
shell: bash
run: |
mkdir -p ostp-control/dist
cd ostp-control
if [ -f package.json ]; then
npm install && npm run build
else
echo "ostp-control has no package.json - using committed dist/"
[ -f dist/index.html ] || echo '<!doctype html><title>OSTP</title>' > dist/index.html
fi
- name: Bump version based on tag
if: startsWith(github.ref, 'refs/tags/v')
run: python scripts/bump_version.py ${{ github.ref_name }}
# -- Rust toolchain -----------------------------------------------------
# ── Rust toolchain ─────────────────────────────────────────────────────
- name: Setup Rust toolchain
uses: dtolnay/rust-toolchain@stable
with:
toolchain: ${{ matrix.toolchain || 'stable' }}
targets: ${{ !matrix.use_cross && matrix.target || '' }}
# -- Cargo cache (shared per target) -----------------------------------
# ── Cargo cache (shared per target) ───────────────────────────────────
- name: Restore Cargo cache
uses: actions/cache@v4
with:
@ -262,18 +166,18 @@ jobs:
restore-keys: |
cargo-${{ matrix.target }}-
# -- MUSL tools for native Linux musl builds ----------------------------
# ── MUSL tools for native Linux musl builds ────────────────────────────
- name: Install musl-tools
if: ${{ matrix.os == 'ubuntu-latest' && !matrix.use_cross }}
run: sudo apt-get update && sudo apt-get install -y musl-tools
# -- Native build -------------------------------------------------------
# ── Native build ───────────────────────────────────────────────────────
- name: Build (native)
if: ${{ !matrix.use_cross }}
shell: bash
run: cargo build --release --target ${{ matrix.target }} --bin ostp
# -- Cross build --------------------------------------------------------
# ── Cross build ────────────────────────────────────────────────────────
- name: Restore cross binary cache
if: ${{ matrix.use_cross }}
id: cross-cache
@ -284,21 +188,13 @@ jobs:
- name: Install cross (if not cached)
if: ${{ matrix.use_cross && steps.cross-cache.outputs.cache-hit != 'true' }}
# cross-rs's own source (not ours, not a dependency of ours) uses a
# macro-at-end-of-block pattern that trips rustc's
# semicolon_in_expressions_from_macros lint on current toolchains -
# harmless in cross's actual behavior, but `cargo install` compiles
# the installed package as the "local" crate, so dependency lint
# capping doesn't shield it. --cap-lints=warn is the standard escape
# hatch for building a third-party tool against a newer compiler than
# its own lint config assumed; it doesn't touch our own build.
run: RUSTFLAGS="--cap-lints=warn" cargo install cross --git https://github.com/cross-rs/cross.git --locked
run: cargo install cross --git https://github.com/cross-rs/cross.git --locked
- name: Build (cross)
if: ${{ matrix.use_cross }}
run: cross build --release --target ${{ matrix.target }} --bin ostp
# -- Driver dependencies ------------------------------------------------
# ── Driver dependencies ────────────────────────────────────────────────
- name: Download wintun (Windows)
if: ${{ matrix.os == 'windows-latest' }}
shell: pwsh
@ -310,7 +206,7 @@ jobs:
Get-ChildItem "$dir/wt_tmp" -Filter "wintun.dll" -Recurse | Where-Object { $_.FullName -match 'bin[\\/]${{ matrix.wintun_arch }}[\\/]' } | Copy-Item -Destination "$dir/"
Remove-Item "$dir/wt.zip","$dir/wt_tmp" -Recurse -Force
# -- Package ------------------------------------------------------------
# ── Package ────────────────────────────────────────────────────────────
- name: Package (Windows)
if: ${{ matrix.os == 'windows-latest' }}
shell: pwsh
@ -329,23 +225,18 @@ jobs:
FILES="${{ matrix.artifact_name }}"
tar -czf "${{ matrix.release_name }}" -C "$dir" $FILES
# -- Upload -------------------------------------------------------------
# ── Upload ─────────────────────────────────────────────────────────────
- name: Upload to GitHub Release
if: ${{ startsWith(github.ref, 'refs/tags/') }}
uses: softprops/action-gh-release@v2
with:
# Computed once in resolve-channel so every platform/job in this run
# lands on the exact same tag: "{version}-alpha" / "{version}-beta"
# for rolling channel pushes, or the pushed "vX.Y.Z" tag as-is for a
# real stable release.
tag_name: ${{ needs.resolve-channel.outputs.tag_name }}
prerelease: ${{ needs.resolve-channel.outputs.prerelease }}
files: ${{ matrix.release_name }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
build-windows-gui:
name: Build Windows GUI (Tauri) - ${{ matrix.arch }}
needs: [check-and-test, resolve-channel]
needs: check-and-test
runs-on: windows-latest
strategy:
matrix:
@ -357,6 +248,10 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: Bump version based on tag
if: startsWith(github.ref, 'refs/tags/v')
run: python scripts/bump_version.py ${{ github.ref_name }}
- name: Setup Node.js
uses: actions/setup-node@v4
with:
@ -378,15 +273,7 @@ jobs:
~/.cargo/registry/cache/
~/.cargo/git/db/
target/
ostp-gui/src-tauri/target/
key: cargo-windows-gui-${{ matrix.target }}-${{ hashFiles('**/Cargo.lock') }}
# Without a prefix fallback this cache NEVER restored on a release:
# cutting a release rewrites every Cargo.lock (version bump), which
# changes hashFiles(), which misses the exact key — so each release
# rebuilt every dependency from scratch. That is why the GUI jobs ran
# 2-4x longer than the plain release targets, which had this all along.
restore-keys: |
cargo-windows-gui-${{ matrix.target }}-
- name: Download wintun
shell: pwsh
@ -418,21 +305,16 @@ jobs:
Compress-Archive -Path "$dir/*" -DestinationPath "ostp-windows-gui-${{ matrix.arch }}.zip" -Force
- name: Upload to GitHub Release
if: ${{ startsWith(github.ref, 'refs/tags/') }}
uses: softprops/action-gh-release@v2
with:
# Computed once in resolve-channel so every platform/job in this run
# lands on the exact same tag: "{version}-alpha" / "{version}-beta"
# for rolling channel pushes, or the pushed "vX.Y.Z" tag as-is for a
# real stable release.
tag_name: ${{ needs.resolve-channel.outputs.tag_name }}
prerelease: ${{ needs.resolve-channel.outputs.prerelease }}
files: ostp-windows-gui-${{ matrix.arch }}.zip
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
build-linux-gui:
name: Build Linux GUI (Tauri) - ${{ matrix.arch }}
needs: [check-and-test, resolve-channel]
needs: check-and-test
runs-on: ubuntu-latest
strategy:
matrix:
@ -442,6 +324,10 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: Bump version based on tag
if: startsWith(github.ref, 'refs/tags/v')
run: python scripts/bump_version.py ${{ github.ref_name }}
- name: Setup Node.js
uses: actions/setup-node@v4
with:
@ -468,46 +354,31 @@ jobs:
~/.cargo/registry/cache/
~/.cargo/git/db/
target/
ostp-gui/src-tauri/target/
key: cargo-linux-gui-${{ matrix.target }}-${{ hashFiles('**/Cargo.lock') }}
restore-keys: |
cargo-linux-gui-${{ matrix.target }}-
- name: Build Tauri App
working-directory: ostp-gui
run: |
npm install
# TUN mode shells out to this helper, elevated via pkexec. Only the
# Windows job used to build it, so the Linux package shipped without
# it and TUN could never start.
cargo build -p ostp-tun-helper --release --target ${{ matrix.target }} --manifest-path ../Cargo.toml
npx tauri build --no-bundle --target ${{ matrix.target }}
- name: Package Portable Tarball
run: |
set -euo pipefail
mkdir ostp-linux-gui-${{ matrix.arch }}
cp ostp-gui/src-tauri/target/${{ matrix.target }}/release/ostp-gui ostp-linux-gui-${{ matrix.arch }}/
# The GUI looks for the helper next to its own executable first.
cp target/${{ matrix.target }}/release/ostp-tun-helper ostp-linux-gui-${{ matrix.arch }}/
tar -czf ostp-linux-gui-${{ matrix.arch }}.tar.gz ostp-linux-gui-${{ matrix.arch }}
- name: Upload to GitHub Release
if: ${{ startsWith(github.ref, 'refs/tags/') }}
uses: softprops/action-gh-release@v2
with:
# Computed once in resolve-channel so every platform/job in this run
# lands on the exact same tag: "{version}-alpha" / "{version}-beta"
# for rolling channel pushes, or the pushed "vX.Y.Z" tag as-is for a
# real stable release.
tag_name: ${{ needs.resolve-channel.outputs.tag_name }}
prerelease: ${{ needs.resolve-channel.outputs.prerelease }}
files: ostp-linux-gui-${{ matrix.arch }}.tar.gz
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
build-macos-gui:
name: Build macOS GUI (Tauri) - ${{ matrix.arch }}
needs: [check-and-test, resolve-channel]
needs: check-and-test
runs-on: macos-latest
strategy:
matrix:
@ -519,6 +390,10 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: Bump version based on tag
if: startsWith(github.ref, 'refs/tags/v')
run: python scripts/bump_version.py ${{ github.ref_name }}
- name: Setup Node.js
uses: actions/setup-node@v4
with:
@ -540,10 +415,7 @@ jobs:
~/.cargo/registry/cache/
~/.cargo/git/db/
target/
ostp-gui/src-tauri/target/
key: cargo-macos-gui-${{ matrix.target }}-${{ hashFiles('**/Cargo.lock') }}
restore-keys: |
cargo-macos-gui-${{ matrix.target }}-
- name: Build Tauri App
working-directory: ostp-gui
@ -558,21 +430,16 @@ jobs:
tar -czf ostp-macos-gui-${{ matrix.arch }}.tar.gz ostp-macos-gui-${{ matrix.arch }}
- name: Upload to GitHub Release
if: ${{ startsWith(github.ref, 'refs/tags/') }}
uses: softprops/action-gh-release@v2
with:
# Computed once in resolve-channel so every platform/job in this run
# lands on the exact same tag: "{version}-alpha" / "{version}-beta"
# for rolling channel pushes, or the pushed "vX.Y.Z" tag as-is for a
# real stable release.
tag_name: ${{ needs.resolve-channel.outputs.tag_name }}
prerelease: ${{ needs.resolve-channel.outputs.prerelease }}
files: ostp-macos-gui-${{ matrix.arch }}.tar.gz
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
build-android:
name: Build Android Client (Flutter) - ${{ matrix.arch }}
needs: [check-and-test, resolve-channel]
needs: check-and-test
runs-on: ubuntu-latest
strategy:
matrix:
@ -583,9 +450,14 @@ jobs:
- arch: armeabi-v7a
rust_target: armv7-linux-androideabi
flutter_target: android-arm
tun2socks_arch: linux-armv7
steps:
- uses: actions/checkout@v4
- name: Bump version based on tag
if: startsWith(github.ref, 'refs/tags/v')
run: python scripts/bump_version.py ${{ github.ref_name }}
- name: Setup Java
uses: actions/setup-java@v3
with:
@ -608,117 +480,32 @@ jobs:
with:
ndk-version: r26b
# The Android jobs had no Rust caching at all, so every release recompiled
# the whole ostp-jni dependency graph from scratch — the main reason these
# were among the slowest jobs in the matrix.
- name: Cache cargo
uses: actions/cache@v4
with:
path: |
~/.cargo/registry/index/
~/.cargo/registry/cache/
~/.cargo/git/db/
target/
key: cargo-android-${{ matrix.arch }}-${{ hashFiles('**/Cargo.lock') }}
restore-keys: |
cargo-android-${{ matrix.arch }}-
# cargo-ndk was built from source on every run. Cache the binary the same
# way the cross-compilation jobs already cache `cross`.
- name: Restore cargo-ndk binary cache
id: cargo-ndk-cache
uses: actions/cache@v4
with:
path: ~/.cargo/bin/cargo-ndk
key: cargo-ndk-bin-${{ runner.os }}-v1
- name: Install cargo-ndk (if not cached)
if: steps.cargo-ndk-cache.outputs.cache-hit != 'true'
run: cargo install cargo-ndk --locked
- name: Install cargo-ndk
run: cargo install cargo-ndk
- name: Build Android APK
shell: bash
working-directory: ostp-flutter
env:
OSTP_KEYSTORE_B64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
OSTP_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
OSTP_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}
OSTP_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }}
run: |
set -euo pipefail
# 1. Materialise the upload keystore from secrets. Android keys an app
# by applicationId + signing key and refuses to update across a key
# change, so every published build MUST use this one key. Releases
# used to fall through to the per-machine debug keystore, which on
# ephemeral CI runners meant a different random key every build -
# hence "App not installed" on upgrade.
if [ -z "${OSTP_KEYSTORE_B64:-}" ]; then
echo "::error::ANDROID_KEYSTORE_BASE64 secret is not set. Refusing to publish a"
echo "::error::debug-signed APK: users could not update over it and the key is"
echo "::error::not reproducible. See docs for the one-time keystore setup."
exit 1
fi
export OSTP_KEYSTORE_PATH="$RUNNER_TEMP/ostp-upload.jks"
# Strip any stray CR/LF before decoding: the secret is pasted from a
# shell whose line endings we don't control, and a single trailing \r
# is enough to corrupt the decode.
printf '%s' "$OSTP_KEYSTORE_B64" | tr -d '\r\n' | base64 -d > "$OSTP_KEYSTORE_PATH"
# Verify the keystore opens BEFORE spending four minutes on Gradle only
# to fail at the packaging step. The size/SHA-256 are safe to print (a
# hash reveals nothing) and let the operator compare against the local
# file to tell a transport problem apart from a wrong password.
echo "keystore: $(stat -c%s "$OSTP_KEYSTORE_PATH") bytes, sha256 $(sha256sum "$OSTP_KEYSTORE_PATH" | cut -d' ' -f1)"
if ! keytool -list -keystore "$OSTP_KEYSTORE_PATH" \
-storepass "$OSTP_KEYSTORE_PASSWORD" >/dev/null 2>&1; then
echo "::error::The keystore did not open with ANDROID_KEYSTORE_PASSWORD."
echo "::error::If the SHA-256 above matches your local ostp-upload.jks, the file"
echo "::error::arrived intact and the password secret itself is wrong - note that"
echo "::error::PowerShell expands \$ inside double quotes, so a password containing"
echo "::error::one gets mangled unless it was set with single quotes."
exit 1
fi
if ! keytool -list -keystore "$OSTP_KEYSTORE_PATH" \
-storepass "$OSTP_KEYSTORE_PASSWORD" -alias "$OSTP_KEY_ALIAS" >/dev/null 2>&1; then
echo "::error::Keystore opened, but it has no key under ANDROID_KEY_ALIAS."
echo "::error::Aliases present in the keystore:"
keytool -list -keystore "$OSTP_KEYSTORE_PATH" -storepass "$OSTP_KEYSTORE_PASSWORD" \
| grep -i "PrivateKeyEntry" || true
exit 1
fi
# 2. Compile JNI
# 1. Compile JNI
mkdir -p android/app/src/main/jniLibs/${{ matrix.arch }}
cd ../ostp-jni
cargo ndk -t ${{ matrix.arch }} -o "../ostp-flutter/android/app/src/main/jniLibs" build --release
cd ../ostp-flutter
# 3. Build Flutter APK
flutter build apk --release --target-platform ${{ matrix.flutter_target }}
# 4. Fail loudly if the APK somehow still came out debug-signed, rather
# than shipping another un-updatable build.
APK=build/app/outputs/flutter-apk/app-release.apk
if "$ANDROID_HOME"/build-tools/*/apksigner verify --print-certs "$APK" 2>/dev/null \
| grep -qi "CN=Android Debug"; then
echo "::error::APK is signed with the Android debug certificate - aborting."
exit 1
fi
# 5. Copy to output
cp "$APK" ostp-android-${{ matrix.arch }}.apk
# 4. Copy to output
cp build/app/outputs/flutter-apk/app-release.apk ostp-android-${{ matrix.arch }}.apk
- name: Upload to GitHub Release
if: ${{ startsWith(github.ref, 'refs/tags/') }}
uses: softprops/action-gh-release@v2
with:
# Computed once in resolve-channel so every platform/job in this run
# lands on the exact same tag: "{version}-alpha" / "{version}-beta"
# for rolling channel pushes, or the pushed "vX.Y.Z" tag as-is for a
# real stable release.
tag_name: ${{ needs.resolve-channel.outputs.tag_name }}
prerelease: ${{ needs.resolve-channel.outputs.prerelease }}
files: ostp-flutter/ostp-android-${{ matrix.arch }}.apk
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

27
.gitignore vendored
View File

@ -5,7 +5,6 @@
**/*.rs.bk
.idea/
.vscode/
**/node_modules/
# Binaries & libraries
*.exe
@ -26,17 +25,6 @@ test_route.ps1
config.json
wintun.dll
# Android signing keys. The upload keystore is the ONE key every published APK
# must be signed with (Android refuses to update an app across a key change),
# so losing or leaking it is unrecoverable — it can never be committed.
*.jks
*.keystore
key.properties
# Server runtime cache (public IP autodetect) — must never be committed,
# it's regenerated locally and leaks whatever host it ran on last.
.ostp_public_ip
# Logs
*.log
@ -46,14 +34,11 @@ turn-harvesting-idea.md
# Private tooling (closed-source)
ostp-prober/
ostp-lab/
ostp-brain/
# Management panel built assets (built separately; dummy dist created for rust-embed build)
ostp-control/
.agents/
netstack-smoltcp/
dnstt/
ostp-sandbox/
ostp-license/
ostp-web/
# Web panel
ostp-control/node_modules/
dnstt/

View File

@ -1,6 +0,0 @@
{
"target_version": "0.4.4",
"branch": "master",
"alpha_iteration": 0,
"beta_iteration": 0
}

View File

@ -10,12 +10,10 @@ By contributing to this project, you agree to abide by our code of conduct and l
1. [Development Setup](#development-setup)
2. [Project Structure](#project-structure)
3. [Branch Strategy](#branch-strategy)
4. [Development Workflow](#development-workflow)
5. [Commit Message Conventions](#commit-message-conventions)
6. [Coding Guidelines](#coding-guidelines)
7. [Submitting Pull Requests](#submitting-pull-requests)
8. [Security Vulnerabilities](#security-vulnerabilities)
3. [Development Workflow](#development-workflow)
4. [Coding Guidelines](#coding-guidelines)
5. [Submitting Pull Requests](#submitting-pull-requests)
6. [Security Vulnerabilities](#security-vulnerabilities)
---
@ -23,8 +21,9 @@ By contributing to this project, you agree to abide by our code of conduct and l
To build and test OSTP locally, you will need:
* **Rust Toolchain (1.75+)**: Install via [rustup](https://rustup.rs/).
* **Node.js (18+) & npm**: Required to build the frontend control panel (`ostp-control`) and compile Tauri GUI resources.
* **Rust Toolchain**: Install via [rustup](https://rustup.rs/) (stable channel).
* **Go 1.20+**: Required to compile the embedded `dnstt` tunnel binaries.
* **Node.js (18+) & npm**: Required to compile Tauri GUI resources.
* **Git**: For version control.
### Building the Project
@ -39,15 +38,8 @@ To build and test OSTP locally, you will need:
```bash
cargo build
```
`ostp-control` (the web panel) is only needed if you're working on it
specifically - the server build embeds a dummy `dist/` via `rust-embed`
otherwise, so this step is not required for day-to-day core/client/server
work. If you *are* touching the panel:
```bash
cd ostp-control && npm install && npm run build && cd ..
```
3. **Run tests**:
4. **Run tests**:
```bash
cargo test --workspace
```
@ -59,36 +51,18 @@ To build and test OSTP locally, you will need:
The repository is organized as a Cargo workspace containing the following crates:
* [`ostp-core/`](file:///d:/ospab-projects/ostp/ostp-core): Core protocol logic, including packet formatting, serialization, selective ACK/NACK (ARQ) state machine, and the Noise protocol (`Noise_NNpsk0_25519_ChaChaPoly_BLAKE2s`) handshake.
* [`ostp-client/`](file:///d:/ospab-projects/ostp/ostp-client): Client implementations, including SOCKS5/HTTP local proxies, the native OSTP TUN interface routing, and split-tunneling bypass mechanisms.
* [`ostp-server/`](file:///d:/ospab-projects/ostp/ostp-server): Server logic, session dispatcher, anti-probing fallback server proxying, access key database, and the REST API for control panel communication.
* [`ostp-control/`](file:///d:/ospab-projects/ostp/ostp-control): A modern web dashboard for server administration (user management, real-time metrics, bandwidth limits).
* [`ostp-client/`](file:///d:/ospab-projects/ostp/ostp-client): Client implementations, including SOCKS5/HTTP local proxies, `tun2socks` integration, native TUN interface routing, and split-tunneling bypass mechanisms.
* [`ostp-server/`](file:///d:/ospab-projects/ostp/ostp-server): Server logic, session dispatcher, anti-probing fallback server proxying, access key database, and the REST API.
* [`ostp-gui/`](file:///d:/ospab-projects/ostp/ostp-gui): Tauri-based desktop GUI application for Windows and Linux.
* [`ostp-flutter/`](file:///d:/ospab-projects/ostp/ostp-flutter): Mobile client code for Android platforms.
---
## Branch Strategy
The repository runs three long-lived branches, in increasing order of stability:
| Branch | Role |
|---|---|
| `alpha` | Active development. All feature work and fixes land here first. |
| `beta` | Periodically fast-forwarded from `alpha` once it's had some soak time. Ships as the `{version}-beta` release channel. |
| `master` | Fast-forwarded from `beta` when it's proven stable. Real, tagged releases (`vX.Y.Z`) are cut from here. |
`beta` and `master` are **never** committed to directly - they only ever move forward by fast-forwarding from the branch below them. This means promotion is always a plain `git merge` with zero conflicts by construction: don't `git merge`/rebase feature work directly onto `beta` or `master`.
**Contributor PRs target `alpha`**, not `master`.
---
## Development Workflow
1. **Check for existing issues** or open a new one to discuss proposed changes before starting work.
2. **Fork the repository** and create a new branch from `alpha`:
2. **Fork the repository** and create a new branch from `master`:
```bash
git checkout alpha
git checkout -b feat/your-feature-name
```
3. **Implement your changes**, ensuring you write appropriate unit or integration tests.
@ -107,32 +81,6 @@ The repository runs three long-lived branches, in increasing order of stability:
---
## Commit Message Conventions
```
<type>(<scope>): <short, imperative summary>
<optional body - explain WHY, not what; the diff already shows what changed>
```
- **Type** - one of: `feat` (new capability), `fix` (bug fix), `docs`, `refactor` (no behavior change), `perf`, `test`, `chore` (deps/tooling/version bumps), `ci`, `security`.
- **Scope** (optional) - the crate or area touched: `client`, `server`, `core`, `gui`, `flutter`, `ci`, `docs`, etc. e.g. `fix(client): ...`.
- **Summary** - imperative mood ("add", not "added"/"adds"), no trailing period, ideally under ~70 characters.
- **Body** - only when the *why* isn't obvious from the diff: a prior bug this fixes, a constraint that shaped the approach, a tradeoff you made. Don't restate what the diff already shows. Wrap at ~72 columns.
```
fix(server): drop junk frames by per-key marker instead of a global one
A fixed 4-byte marker on every junk packet is itself a DPI signature any
observer can filter on across every OSTP deployment. Derive the marker
from the access key (HKDF, same scheme as obfuscation_key/psk) so it's
per-user and indistinguishable from the packet's own random payload.
```
Multiple unrelated changes belong in separate commits, not one bundled commit - it keeps `git bisect` and review useful. Squash-merge is fine for a PR with a few "fix typo" / "address review" commits, but don't squash logically distinct changes together.
---
## Coding Guidelines
* **Safety**: Avoid using `unsafe` blocks unless absolutely necessary for low-level system bindings (e.g., FFI configurations like `setsockopt`). When using `unsafe`, add safety doc comments explaining why it is safe.
@ -148,7 +96,7 @@ Multiple unrelated changes belong in separate commits, not one bundled commit -
```bash
git push origin feat/your-feature-name
```
2. Open a Pull Request (PR) targeting the `alpha` branch (see [Branch Strategy](#branch-strategy) - `master` only receives fast-forwards from `beta`, never direct PRs).
2. Open a Pull Request (PR) targeting the `master` branch.
3. In your PR description, explain the rationale behind your changes, what was fixed/added, and how it was tested.
4. Verify that GitHub Actions CI runs successfully on your PR.

View File

@ -10,12 +10,10 @@
1. [Подготовка окружения](#подготовка-окружения)
2. [Структура проекта](#структура-проекта)
3. [Стратегия веток](#стратегия-веток)
4. [Процесс разработки](#процесс-разработки)
5. [Оформление коммитов](#оформление-коммитов)
6. [Правила оформления кода](#правила-оформления-кода)
7. [Создание Pull Request](#создание-pull-request)
8. [Уязвимости безопасности](#уязвимости-безопасности)
3. [Процесс разработки](#процесс-разработки)
4. [Правила оформления кода](#правила-оформления-кода)
5. [Создание Pull Request](#создание-pull-request)
6. [Уязвимости безопасности](#уязвимости-безопасности)
---
@ -23,8 +21,9 @@
Для локальной сборки и тестирования OSTP вам понадобятся:
* **Rust Toolchain (1.75+)**: Рекомендуется установить через [rustup](https://rustup.rs/).
* **Node.js (18+) и npm**: Необходимы для сборки веб-панели управления (`ostp-control`) и сборки интерфейса Tauri.
* **Rust Toolchain**: Установите через [rustup](https://rustup.rs/) (stable канал).
* **Go 1.20+**: Необходимо для сборки встроенного DNS-туннеля dnstt.
* **Node.js (18+) и npm**: Необходимы для сборки интерфейса Tauri.
* **Git**: Для контроля версий.
### Сборка проекта
@ -39,15 +38,8 @@
```bash
cargo build
```
`ostp-control` (веб-панель) нужна только если вы работаете конкретно над
ней - в остальных случаях сервер собирается с пустым `dist/` через
`rust-embed`, и этот шаг не нужен для повседневной работы над
core/client/server. Если вы всё же трогаете панель:
```bash
cd ostp-control && npm install && npm run build && cd ..
```
3. **Запустите тесты**:
4. **Запустите тесты**:
```bash
cargo test --workspace
```
@ -59,36 +51,18 @@
Репозиторий представляет собой единый Cargo-workspace со следующими компонентами:
* [`ostp-core/`](file:///d:/ospab-projects/ostp/ostp-core): Базовая логика протокола: форматирование пакетов, сериализация, конечный автомат выборочного подтверждения (ARQ/ACK/NACK) и рукопожатие Noise (`Noise_NNpsk0_25519_ChaChaPoly_BLAKE2s`).
* [`ostp-client/`](file:///d:/ospab-projects/ostp/ostp-client): Клиентская часть: локальные SOCKS5/HTTP прокси-серверы, нативный OSTP TUN-интерфейс (через драйвер `wintun`) и реализация раздельного туннелирования для прямого обхода трафика.
* [`ostp-server/`](file:///d:/ospab-projects/ostp/ostp-server): Серверная часть: диспетчеризация сессий, маскировка под классические веб-серверы при активном сканировании, база данных ключей доступа и REST API панели управления.
* [`ostp-control/`](file:///d:/ospab-projects/ostp/ostp-control): Панель администратора (пользователи, статистика трафика в реальном времени, лимиты скорости и объема данных).
* [`ostp-client/`](file:///d:/ospab-projects/ostp/ostp-client): Клиентская часть: локальные SOCKS5/HTTP прокси-серверы, интеграция с драйвером `wintun` / `tun2socks` и реализация раздельного туннелирования для прямого обхода трафика.
* [`ostp-server/`](file:///d:/ospab-projects/ostp/ostp-server): Логика сервера, диспетчер сессий, защита от пробинга, база данных ключей и REST API.
* [`ostp-gui/`](file:///d:/ospab-projects/ostp/ostp-gui): Настольное приложение-клиент для Windows и Linux на платформе Tauri.
* [`ostp-flutter/`](file:///d:/ospab-projects/ostp/ostp-flutter): Мобильный клиент для платформы Android.
---
## Стратегия веток
В репозитории три долгоживущие ветки, по возрастанию стабильности:
| Ветка | Роль |
|---|---|
| `alpha` | Активная разработка. Вся новая работа и фиксы попадают сюда первыми. |
| `beta` | Периодически перематывается вперёд (fast-forward) от `alpha`, когда та немного «отлежалась». Собирается в канал релиза `{версия}-beta`. |
| `master` | Перематывается вперёд от `beta`, когда та доказала стабильность. Настоящие тегированные релизы (`vX.Y.Z`) режутся отсюда. |
В `beta` и `master` **никогда** не коммитят напрямую - они только перематываются вперёд от ветки уровнем ниже. Это значит, что промоушен - всегда обычный `git merge` без единого конфликта по построению: не мержите/не ребейзьте свою фичу прямо в `beta` или `master`.
**PR от контрибьюторов нацелены на `alpha`**, не на `master`.
---
## Процесс разработки
1. **Проверьте существующие задачи** или откройте новую тему (Issue) для обсуждения предлагаемых изменений.
2. **Сделайте fork репозитория** и создайте новую ветку от `alpha`:
2. **Сделайте fork репозитория** и создайте новую ветку от `master`:
```bash
git checkout alpha
git checkout -b feat/имя-вашей-фичи
```
3. **Внесите необходимые изменения** и добавьте соответствующие модульные или интеграционные тесты.
@ -107,33 +81,6 @@
---
## Оформление коммитов
```
<тип>(<область>): <краткое описание в повелительном наклонении>
<опционально: тело - объясняет ПОЧЕМУ, а не что; диф и так показывает что изменилось>
```
- **Тип** - один из: `feat` (новая функциональность), `fix` (исправление бага), `docs`, `refactor` (без изменения поведения), `perf`, `test`, `chore` (зависимости/тулинг/версии), `ci`, `security`.
- **Область** (опционально) - крейт или часть проекта: `client`, `server`, `core`, `gui`, `flutter`, `ci`, `docs` и т.д., например `fix(client): ...`.
- **Краткое описание** - повелительное наклонение ("добавь", а не "добавил"/"добавляет"), без точки в конце, желательно до ~70 символов.
- **Тело** - только когда причина не очевидна из дифа: какой баг это чинит, какое ограничение определило подход, на какой trade-off вы пошли. Не пересказывайте то, что и так видно в дифе. Перенос строк на ~72 символах.
```
fix(server): отбрасывать junk-фреймы по маркеру для каждого ключа, а не глобальному
Фиксированный 4-байтовый маркер на каждом junk-пакете сам по себе - сигнатура
DPI, по которой можно фильтровать любого наблюдателя во всех деплойментах OSTP
сразу. Выводим маркер из access_key (HKDF, та же схема что у
obfuscation_key/psk), чтобы он был индивидуальным для ключа и неотличимым от
случайной полезной нагрузки пакета.
```
Несколько несвязанных изменений - это несколько отдельных коммитов, а не один сборный. Это сохраняет пользу от `git bisect` и код-ревью. Squash-merge подходит для PR с парой коммитов вроде "fix typo" / "address review", но не сквошьте вместе логически разные изменения.
---
## Правила оформления кода
* **Безопасность (Safety)**: Избегайте использования блоков `unsafe` везде, где это возможно. Допускается их использование только для низкоуровневых системных вызовов (например, FFI-настройки сокетов `setsockopt`). Любой блок `unsafe` должен сопровождаться комментарием `// SAFETY: ...`.
@ -149,7 +96,7 @@ obfuscation_key/psk), чтобы он был индивидуальным для
```bash
git push origin feat/имя-вашей-фичи
```
2. Создайте Pull Request (PR) в ветку `alpha` основного репозитория (см. [Стратегия веток](#стратегия-веток) - `master` получает только fast-forward от `beta`, PR туда не принимаются напрямую).
2. Создайте Pull Request (PR) в ветку `master` основного репозитория.
3. Подробно опишите внесенные изменения: какая проблема решается, как проводилось тестирование и на каких платформах проверялась сборка.
4. Убедитесь, что автоматическое тестирование (GitHub Actions CI) завершилось успешно.

143
Cargo.lock generated
View File

@ -205,6 +205,12 @@ version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "base64ct"
version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
[[package]]
name = "bitflags"
version = "1.3.2"
@ -382,6 +388,16 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
[[package]]
name = "clipboard-win"
version = "3.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fdf5e01086b6be750428ba4a40619f847eb2e95756eee84b18e06e5f0b50342"
dependencies = [
"lazy-bytes-cast",
"winapi",
]
[[package]]
name = "colorchoice"
version = "1.0.5"
@ -417,6 +433,12 @@ dependencies = [
"crossbeam-utils",
]
[[package]]
name = "const-oid"
version = "0.9.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
[[package]]
name = "core-foundation-sys"
version = "0.8.7"
@ -476,6 +498,7 @@ dependencies = [
"cfg-if",
"cpufeatures",
"curve25519-dalek-derive",
"digest",
"fiat-crypto",
"rustc_version",
"subtle",
@ -534,6 +557,16 @@ dependencies = [
"thiserror 2.0.18",
]
[[package]]
name = "der"
version = "0.7.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
dependencies = [
"const-oid",
"zeroize",
]
[[package]]
name = "deranged"
version = "0.5.8"
@ -565,6 +598,30 @@ dependencies = [
"syn",
]
[[package]]
name = "ed25519"
version = "2.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53"
dependencies = [
"pkcs8",
"signature",
]
[[package]]
name = "ed25519-dalek"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9"
dependencies = [
"curve25519-dalek",
"ed25519",
"serde",
"sha2",
"subtle",
"zeroize",
]
[[package]]
name = "equivalent"
version = "1.0.2"
@ -1205,6 +1262,12 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9dbbfed4e59ba9750e15ba154fdfd9329cee16ff3df539c2666b70f58cc32105"
[[package]]
name = "lazy-bytes-cast"
version = "5.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10257499f089cd156ad82d0a9cd57d9501fa2c989068992a97eb3c27836f206b"
[[package]]
name = "lazy_static"
version = "1.5.0"
@ -1316,9 +1379,7 @@ dependencies = [
[[package]]
name = "netstack-smoltcp"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c38f66cdd673ff0e760752f27c6d34a7e3a140f0b1eea9efae3c46d8867c83d"
version = "0.2.2"
dependencies = [
"etherparse",
"futures",
@ -1386,21 +1447,22 @@ checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
[[package]]
name = "ostp"
version = "0.4.4"
version = "0.3.14"
dependencies = [
"anyhow",
"base64",
"clap",
"clipboard-win",
"colored",
"json_comments",
"ostp-client",
"ostp-core",
"ostp-server",
"pico-args",
"rand 0.8.5",
"rlimit",
"reqwest",
"serde",
"serde_json",
"sha2",
"tokio",
"tracing",
"tracing-subscriber",
@ -1409,15 +1471,18 @@ dependencies = [
[[package]]
name = "ostp-client"
version = "0.4.4"
version = "0.3.14"
dependencies = [
"anyhow",
"base64",
"bytes",
"chacha20poly1305",
"chrono",
"futures",
"futures-util",
"hex",
"hmac",
"ipnet",
"json_comments",
"libc",
"netstack-smoltcp",
@ -1436,21 +1501,25 @@ dependencies = [
"tun",
"webpki-roots 0.26.11",
"winapi",
"x25519-dalek",
]
[[package]]
name = "ostp-core"
version = "0.4.4"
version = "0.3.14"
dependencies = [
"anyhow",
"byteorder",
"bytes",
"chacha20poly1305",
"hkdf",
"hmac",
"rand 0.8.5",
"serde",
"sha2",
"snow",
"thiserror 1.0.69",
"tokio",
"tracing",
"x25519-dalek",
]
@ -1474,7 +1543,7 @@ dependencies = [
[[package]]
name = "ostp-server"
version = "0.4.4"
version = "0.3.14"
dependencies = [
"anyhow",
"axum",
@ -1482,6 +1551,7 @@ dependencies = [
"bytes",
"chacha20poly1305",
"chrono",
"ed25519-dalek",
"futures-util",
"hex",
"hmac",
@ -1497,7 +1567,6 @@ dependencies = [
"sha2",
"simple-dns",
"socket2",
"subtle",
"tokio",
"tower-http",
"tracing",
@ -1507,7 +1576,7 @@ dependencies = [
[[package]]
name = "ostp-tun"
version = "0.4.4"
version = "0.3.14"
dependencies = [
"anyhow",
"libc",
@ -1519,15 +1588,16 @@ dependencies = [
[[package]]
name = "ostp-tun-helper"
version = "0.4.4"
version = "0.3.14"
dependencies = [
"anyhow",
"chrono",
"hex",
"ostp-client",
"portable-atomic",
"serde",
"serde_json",
"tokio",
"tracing",
"winres",
]
@ -1543,6 +1613,12 @@ version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "pico-args"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315"
[[package]]
name = "pin-project-lite"
version = "0.2.17"
@ -1560,6 +1636,16 @@ dependencies = [
"futures-io",
]
[[package]]
name = "pkcs8"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"
dependencies = [
"der",
"spki",
]
[[package]]
name = "poly1305"
version = "0.8.0"
@ -1814,7 +1900,9 @@ checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
dependencies = [
"base64",
"bytes",
"futures-channel",
"futures-core",
"futures-util",
"http",
"http-body",
"http-body-util",
@ -1858,15 +1946,6 @@ dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "rlimit"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f35ee2729c56bb610f6dba436bf78135f728b7373bdffae2ec815b2d3eb98cc3"
dependencies = [
"libc",
]
[[package]]
name = "rust-embed"
version = "8.11.0"
@ -2086,6 +2165,15 @@ dependencies = [
"libc",
]
[[package]]
name = "signature"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
dependencies = [
"rand_core 0.6.4",
]
[[package]]
name = "simple-dns"
version = "0.11.3"
@ -2157,6 +2245,16 @@ dependencies = [
"lock_api",
]
[[package]]
name = "spki"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"
dependencies = [
"base64ct",
"der",
]
[[package]]
name = "stable_deref_trait"
version = "1.2.1"
@ -2492,6 +2590,7 @@ dependencies = [
"sharded-slab",
"smallvec",
"thread_local",
"time",
"tracing",
"tracing-core",
"tracing-log",

View File

@ -5,24 +5,29 @@ members = [
"ostp-server",
"ostp-jni", "ostp",
"ostp-tun-helper"
, "ostp-tun"]
exclude = ["ostp-gui/src-tauri", "ostp-brain", "ostp-prober"]
]
exclude = ["ostp-gui/src-tauri", "ostp-brain", "ostp-prober", "ostp-sandbox", "ostp-control", "ostp-license"]
resolver = "2"
[workspace.package]
edition = "2021"
license = "AGPL-3.0"
version = "0.4.4"
license = "BSL 1.1"
version = "0.3.14"
[workspace.dependencies]
anyhow = "1.0"
bytes = "1.6"
chacha20poly1305 = "0.10"
rand = "0.8"
snow = { version = "0.9", features = ["risky-raw-split"] }
snow = "0.9"
thiserror = "1.0"
tokio = { version = "1.37", features = ["rt-multi-thread", "macros", "net", "time", "io-util", "sync", "signal"] }
tracing = "0.1"
sha2 = "0.10"
hmac = "0.12"
portable-atomic = "1.10"
ed25519-dalek = "2.1"
base64 = "0.22"
[patch.crates-io]
netstack-smoltcp = { path = "netstack-smoltcp" }

238
README.md
View File

@ -1,6 +1,6 @@
# OSTP - Ospab Stealth Transport Protocol
# OSTP Ospab Stealth Transport Protocol
[Русский язык](README.ru.md) · [Wiki](https://github.com/ospab/ostp/wiki) · [Contributing](CONTRIBUTING.md) · [Releases](https://github.com/ospab/ostp/releases)
[Русский язык](README.ru.md) · [Wiki](https://github.com/ospab/ostp/wiki) · [Contributing](CONTRIBUTING.md) · [Releases](https://github.com/ospab/ostp/releases) · [Migration Guide](docs/migration_v0_3_1.md)
![GitHub Release](https://img.shields.io/github/v/release/ospab/ostp?style=for-the-badge&color=blue)
![License: AGPL v3](https://img.shields.io/badge/License-AGPL%20v3-blue.svg?style=for-the-badge)
@ -8,48 +8,27 @@
![Crypto](https://img.shields.io/badge/Crypto-Noise__NNpsk0-blueviolet?style=for-the-badge)
![Transport](https://img.shields.io/badge/Transport-UDP%20ARQ-informational?style=for-the-badge)
> A fast, custom encrypted transport protocol written in Rust.
OSTP (Ospab Stealth Transport Protocol) is an encrypted transport protocol written in Rust. It implements a custom ARQ transport over UDP and a UDP-over-TCP (UoT) mode. The protocol uses cryptographic masking for all packet headers and payloads to resist traffic classification by Deep Packet Inspection (DPI) systems.
**OSTP** (Ospab Stealth Transport Protocol) is a high-performance transport protocol. It implements a custom ARQ transport over UDP, as well as a UoT (UDP-over-TCP) mode. Every byte on the wire - including packet headers - is cryptographically indistinguishable from random noise, making it highly resistant to Deep Packet Inspection (DPI).
> [!IMPORTANT]
> **Upgrading from v0.2.x?** Please read the [v0.3.1 Configuration Migration Guide](docs/migration_v0_3_1.md).
---
## Quick Install
## Technical Capabilities
### Linux
```bash
bash <(curl -Ls https://raw.githubusercontent.com/ospab/ostp/master/scripts/install.sh)
```
### Windows (PowerShell, run as Administrator)
```powershell
irm https://raw.githubusercontent.com/ospab/ostp/master/scripts/install.ps1 | iex
```
### Manual Download
Download pre-built binaries for your platform from [GitHub Releases](https://github.com/ospab/ostp/releases).
---
## Key Features
| Feature | Description |
|---------|-------------|
| **Full Traffic Obfuscation** | Every packet - including headers - is indistinguishable from random noise. Session IDs and nonces are masked with per-packet HMAC-derived keys. |
| **Noise Protocol Handshake** | `Noise_NNpsk0_25519_ChaChaPoly_BLAKE2s` - PSK-authenticated, forward-secret key exchange with no static identity exposure. |
| Capability | Description |
|------------|-------------|
| **Traffic Masking** | Header and payload encryption using per-packet HMAC-derived keys. Indistinguishable from random noise. |
| **Noise Protocol** | `Noise_NNpsk0_25519_ChaChaPoly_BLAKE2s` — PSK-authenticated, forward-secret key exchange. |
| **Reliable UDP (ARQ)** | Selective ACK/NACK with rate-limited retransmission, configurable reorder buffer, and exponential backoff. |
| **Multiplexed Streams** | Multiple logical TCP streams over a single encrypted UDP session with per-stream flow control. |
| **Seamless Roaming** | Clients can switch networks (WiFi ↔ LTE) without session interruption - tracked by session-ID, not IP. |
| **Management API** | Built-in REST API for third-party panels (3x-ui, custom dashboards). Per-user stats, traffic limits, key CRUD. |
| **Fallback Server** | TCP fallback proxy to a web server - makes OSTP indistinguishable from nginx during active probing. |
| **Multi-Listener** | Bind to multiple addresses simultaneously (dual-stack IPv4/IPv6, multi-port). |
| **TUN Mode** | Full-system VPN via native `smoltcp` network stack without external dependencies. All traffic transparently routed through the tunnel. |
| **UoT (UDP-over-TCP)** | Bare UDP-over-TCP tunnel, no protocol mimicry. Since all data is fully encrypted and length-prefixed, it bypasses DPI filters that block unknown UDP traffic by riding over a plain TCP connection. |
| **Mobile & Web Apps** | Beautiful cross-platform mobile client (Flutter) and a modern Web Control Panel (React/Vite) for effortless server and client management. |
| **TURN Relay** | RFC 5766 TURN support for environments where direct UDP is blocked. |
| **Hot-Reload** | Runtime config reload without restart (access keys, exclusions, mux settings). |
| **Structured Logging** | `tracing`-based logging with `RUST_LOG` filtering. JSON/file/syslog output support. |
| **Cross-Platform** | Windows, Linux, macOS, Android, FreeBSD, MIPS, RISC-V. Single binary, no runtime dependencies. |
| **Multiplexed Streams**| Multiple logical TCP streams over a single encrypted UDP session with per-stream flow control. |
| **Session Roaming** | Connection persistence across IP changes via session ID tracking. |
| **UoT Mode** | UDP-over-TCP encapsulation with length-prefixing to bypass UDP blocking. |
| **Fallback Server** | TCP proxying to a legitimate web server to resist active probing. |
| **TUN Mode** | Native network stack integration (`smoltcp`) for full-system routing without external dependencies. |
| **Management API** | Built-in REST API for server administration, metrics, and key generation. |
| **TURN Relay** | RFC 5766 TURN support for NAT traversal. |
---
@ -57,163 +36,104 @@ Download pre-built binaries for your platform from [GitHub Releases](https://git
```mermaid
flowchart LR
%% Styles
classDef userApp fill:#e1f5fe,stroke:#01579b,stroke-width:2px,color:#01579b
classDef ostpCore fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px,color:#2e7d32
classDef network fill:#fff3e0,stroke:#e65100,stroke-width:2px,color:#e65100,stroke-dasharray: 5 5
classDef external fill:#f3e5f5,stroke:#4a148c,stroke-width:2px,color:#4a148c
classDef fallback fill:#ffebee,stroke:#c62828,stroke-width:2px,color:#c62828
Apps[Local Apps] -->|SOCKS5 / TUN| CoreC
subgraph Local["💻 Client Device"]
Apps["Web Browser / Apps"]:::userApp
Socks["SOCKS5 / HTTP Proxy"]:::ostpCore
Tun["Global TUN (VPN)"]:::ostpCore
Client["OSTP Client Protocol Engine\n(Noise + ChaCha20 + ARQ)"]:::ostpCore
Apps -->|TCP/UDP| Socks
Apps -->|IP Packets| Tun
Socks --> Client
Tun --> Client
subgraph Client [Client Node]
CoreC[OSTP Client] -.->|Encrypt & Mask| NetC[Transport Layer]
end
subgraph Internet["🌐 Hostile Network (DPI/Firewall)"]
Tunnel{"Fully Obfuscated\nEncrypted UDP\n(Looks like noise)"}:::network
NetC <==>|Encrypted UDP / UoT| NetS
subgraph Server [Server Node]
NetS[Transport Layer] -.->|Decrypt & Auth| CoreS[OSTP Server]
NetS -->|Unauthenticated| Fallback[Fallback Server]
end
subgraph Remote["🖥️ Remote VPS (Server)"]
Server["OSTP Server Protocol Engine\n(Authentication & Decryption)"]:::ostpCore
Relay["Connection Multiplexer"]:::ostpCore
Fallback["Fake Website\n(Nginx/Caddy)"]:::fallback
Target["Open Internet\n(YouTube, Google, etc)"]:::external
Server -->|Decrypted Traffic| Relay
Server -->|Active Probe / Scanner| Fallback
Relay -->|Clear Traffic| Target
end
Client <==> Tunnel <==> Server
CoreS -->|Relay| WWW((Internet))
Fallback -->|Forward| Web((Web / NGINX))
```
---
## Quick Start
### 1. Generate config
### 1. Installation
**Linux:**
```bash
# On your VPS (server):
./ostp init server
# On your machine (client):
./ostp init client
bash <(curl -Ls https://raw.githubusercontent.com/ospab/ostp/master/scripts/install.sh)
```
### 2. Edit config
**Windows (PowerShell as Administrator):**
```powershell
irm https://raw.githubusercontent.com/ospab/ostp/master/scripts/install.ps1 | iex
```
**Server** - set your access keys:
### 2. Configuration
Initialize the configuration files for the server and client:
```bash
# On the server:
./ostp --init server
# On the client:
./ostp --init client
```
**Server Example** (`config.json`):
```jsonc
{
"mode": "server",
"listen": "0.0.0.0:50000",
"access_keys": ["YOUR_SECRET_KEY"],
"api": { "enabled": true, "bind": "127.0.0.1:9090", "token": "admin-token" },
"fallback": { "enabled": false, "listen": "0.0.0.0:443", "target": "127.0.0.1:8080" }
"access_keys": ["YOUR_SECRET_KEY"]
}
```
**Client** - point to your server:
**Client Example** (`config.json`):
```jsonc
{
"mode": "client",
"server": "YOUR_SERVER_IP:50000",
"access_key": "YOUR_SECRET_KEY",
"socks5_bind": "127.0.0.1:1088",
"transport": { "mode": "udp" },
"tun": { "enable": false, "dns": "1.1.1.1" }
"version": "0.3.1",
"inbounds": [
{ "type": "local_proxy", "tag": "socks-in", "protocol": "socks", "listen": "127.0.0.1", "port": 1088 }
],
"outbounds": [
{
"type": "ostp",
"tag": "proxy",
"server": "YOUR_SERVER_IP",
"port": 50000,
"access_key": "YOUR_SECRET_KEY",
"transport": { "type": "udp" }
}
]
}
```
### 3. Run
### 3. Execution
```bash
./ostp # Uses config.json in current directory
./ostp --config /path/to.json # Custom config path
./ostp check # Validate config without running
./ostp gk # Generate a new access key
./ostp links # Print client share links
# Run with default config.json
./ostp
# Run with a specific config path
./ostp --config /path/to/config.json
```
### 4. Connect via share link (one-liner)
Or connect via a one-line share link on the client:
```bash
./ostp connect "ostp://ACCESS_KEY@server.com:50000?..."
./ostp "ostp://YOUR_SECRET_KEY@YOUR_SERVER_IP:50000?transport=udp"
```
> [!WARNING]
> Always wrap the `ostp://...` link in quotes (`"`) so your terminal doesn't misinterpret special characters like `&` or `?`.
---
## Management API
Built-in REST API for building panels and dashboards.
```bash
# Server status
curl -H "Authorization: Bearer mytoken" http://127.0.0.1:9090/api/server/status
# List all users with traffic stats
curl -H "Authorization: Bearer mytoken" http://127.0.0.1:9090/api/users
# Create a user with 10GB traffic limit
curl -X POST -H "Authorization: Bearer mytoken" \
-H "Content-Type: application/json" \
-d '{"limit_bytes": 10737418240}' \
http://127.0.0.1:9090/api/users
```
Full API reference: [Management API](https://github.com/ospab/ostp/wiki/Management-API)
---
## CLI Reference
```
ostp [--config <PATH>] [COMMAND]
Commands:
run Run the daemon using the config file (default when no command is given)
connect <URL> Connect once using a share link: ostp://KEY@HOST:PORT
setup Interactive setup wizard
init <MODE> Generate a template config (server/client/relay)
check Validate the configuration file and exit
gk Generate a secure access key (alias: generate-key)
--format <FMT> Key format: hex, base64 (default: hex)
-n, --count <N> Number of keys to generate (default: 1)
links Print client share links from the server config
import <URL> Import a share link into the config file
update Update OSTP to the latest release
-b, --branch <NAME> Release channel: stable, beta, alpha (default: stable)
-v, --version <VER> Update to an exact version instead of the channel's latest
migrate Force-migrate the configuration file to the current format
proxy-env Print shell export commands for the local SOCKS proxy
proxy-env-clear Print shell export commands to unset it
uninstall Stop the service and remove the binary and config
Global options:
--config <PATH> Config file path (default: config.json)
```
Every subcommand also accepts `-h`/`--help` for its own option list.
---
## Protocol Summary
## Protocol Specification
| Layer | Mechanism |
|-------|-----------|
| Key Exchange | Noise NNpsk0 (X25519 + ChaChaPoly + BLAKE2s) zero-RTT |
| Encryption | ChaCha20-Poly1305 AEAD per-packet |
| Header Obfuscation | HMAC-SHA256 derived per-packet mask |
| Header Masking | HMAC-SHA256 derived per-packet mask |
| Reliability | Selective ACK with cumulative + SACK ranges |
| Retransmission | Rate-limited NACK + exponential backoff RTO |
| Keepalive | Ping/Pong with RTT measurement every 5s |
@ -223,37 +143,31 @@ Every subcommand also accepts `-h`/`--help` for its own option list.
## Building from Source
```bash
# Prerequisites: Rust 1.75+
# Requires Rust 1.75+
cargo build --release
# Cross-compile for Linux
cross build --release --target x86_64-unknown-linux-gnu
# Run tests
cargo test -p ostp-core -p ostp-server
```
---
## Documentation
- **[Wiki](https://github.com/ospab/ostp/wiki)** - Full documentation
- [Installation](https://github.com/ospab/ostp/wiki/Installation)
- **[Wiki](https://github.com/ospab/ostp/wiki)**
- [Configuration Reference](https://github.com/ospab/ostp/wiki/Configuration)
- [Management API](https://github.com/ospab/ostp/wiki/Management-API)
- [Protocol Design](https://github.com/ospab/ostp/wiki/Protocol-Design)
- [Building from Source](https://github.com/ospab/ostp/wiki/Building-from-Source)
- [FAQ](https://github.com/ospab/ostp/wiki/FAQ)
---
## License
GNU Affero General Public License v3.0 (AGPL-3.0). See [LICENSE](LICENSE) for the full text.
GNU Affero General Public License v3.0 (AGPL-3.0). See [LICENSE](LICENSE) for more details.
---
## Contact
## Contacts
- **Telegram**: [@ospab0](https://t.me/ospab0)
- **Email**: gvoprgrg@gmail.com

View File

@ -1,6 +1,6 @@
# OSTP - Ospab Stealth Transport Protocol
# OSTP Ospab Stealth Transport Protocol
[English](README.md) · [Contributing](CONTRIBUTING.ru.md)
[English](README.md) · [Wiki](https://github.com/ospab/ostp/wiki) · [Contributing](CONTRIBUTING.ru.md) · [Миграция v0.3.1](docs/migration_v0_3_1_ru.md)
![GitHub Release](https://img.shields.io/github/v/release/ospab/ostp?style=for-the-badge&color=blue)
![License: AGPL v3](https://img.shields.io/badge/License-AGPL%20v3-blue.svg?style=for-the-badge)
@ -8,27 +8,27 @@
![Crypto](https://img.shields.io/badge/Crypto-Noise__NNpsk0-blueviolet?style=for-the-badge)
![Transport](https://img.shields.io/badge/Transport-UDP%20ARQ-informational?style=for-the-badge)
> Быстрый кастомный зашифрованный транспортный протокол на Rust.
OSTP (Ospab Stealth Transport Protocol) — зашифрованный транспортный протокол, написанный на Rust. Реализует механизм ARQ поверх UDP, а также режим UoT (UDP-over-TCP). Протокол использует криптографическое маскирование заголовков и полезной нагрузки для защиты от систем глубокого анализа трафика (DPI).
**OSTP** (Ospab Stealth Transport Protocol) - кастомный транспортный протокол. Реализует собственный ARQ-транспорт поверх UDP, а также режим UoT (UDP-over-TCP). Каждый байт, включая заголовки пакетов, криптографически неотличим от случайного шума, что делает его устойчивым к системам глубокого анализа трафика (DPI).
> [!IMPORTANT]
> **Обновляетесь с версии v0.2.x?** Пожалуйста, ознакомьтесь с [Руководством по миграции конфигурации v0.3.1](docs/migration_v0_3_1_ru.md).
---
## Возможности
## Технические характеристики
| Возможность | Описание |
|-------------|----------|
| **Обфускация трафика** | Каждый пакет, включая заголовки, неотличим от случайного шума. Session ID и nonce маскируются HMAC-ключами, уникальными для каждого пакета. |
| **Noise Protocol** | `Noise_NNpsk0_25519_ChaChaPoly_BLAKE2s` - аутентификация через PSK, forward secrecy, без раскрытия идентичности. |
| **Reliable UDP (ARQ)** | Selective ACK/NACK с rate-limited ретрансмиссией, настраиваемым reorder-буфером и exponential backoff. Разработан для 10 Гбит/с. |
| **Маскирование трафика** | Шифрование заголовков и полезной нагрузки с помощью HMAC ключей на каждый пакет. Трафик неотличим от шума. |
| **Noise Protocol** | `Noise_NNpsk0_25519_ChaChaPoly_BLAKE2s` аутентификация через PSK, forward secrecy. |
| **Reliable UDP (ARQ)** | Selective ACK/NACK с rate-limited ретрансмиссией, настраиваемым reorder-буфером и exponential backoff. |
| **Мультиплексирование** | Несколько логических TCP-потоков поверх одной зашифрованной UDP-сессии с per-stream flow control. |
| **Бесшовный роуминг** | Клиент может менять сети (WiFi ↔ 4G) без разрыва сессии - сервер отслеживает session-ID, а не IP-адрес. |
| **TUN-режим** | Полносистемный VPN без внешних зависимостей (встроенный network stack на базе `smoltcp`). |
| **UoT (UDP-over-TCP)** | Голый туннель UDP-over-TCP, без имитации протоколов. Поскольку все данные полностью зашифрованы и имеют префикс длины, он обходит DPI фильтры, блокирующие неизвестный UDP трафик, передавая всё по обычному TCP соединению. |
| **Мобильные и Web приложения** | Красивый кроссплатформенный мобильный клиент (Flutter) и современная Web панель управления (React/Vite) для удобного администрирования. |
| **TURN Relay** | RFC 5766 TURN для окружений, где прямой UDP заблокирован. |
| **Hot-Reload** | Перезагрузка конфига в рантайме без перезапуска (ключи, исключения, mux, TURN). |
| **Кросс-платформа** | Windows, Linux, macOS, Android. Один бинарник, без зависимостей. |
| **Session Roaming** | Сохранение соединения при смене IP-адреса благодаря отслеживанию по идентификатору сессии (session ID). |
| **Режим UoT** | Инкапсуляция UDP внутри TCP с указанием длины пакетов для обхода блокировок неизвестного UDP-трафика. |
| **Fallback Server** | Проксирование неаутентифицированных TCP подключений на веб-сервер для защиты от активного пробинга. |
| **TUN-режим** | Полносистемная маршрутизация через встроенный сетевой стек `smoltcp` без внешних зависимостей. |
| **Management API** | Встроенный REST API для администрирования сервера, сбора метрик и генерации ключей. |
| **TURN Relay** | Поддержка RFC 5766 TURN для обхода NAT. |
---
@ -36,169 +36,94 @@
```mermaid
flowchart LR
%% Styles
classDef userApp fill:#e1f5fe,stroke:#01579b,stroke-width:2px,color:#01579b
classDef ostpCore fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px,color:#2e7d32
classDef network fill:#fff3e0,stroke:#e65100,stroke-width:2px,color:#e65100,stroke-dasharray: 5 5
classDef external fill:#f3e5f5,stroke:#4a148c,stroke-width:2px,color:#4a148c
classDef fallback fill:#ffebee,stroke:#c62828,stroke-width:2px,color:#c62828
Apps[Приложения] -->|SOCKS5 / TUN| CoreC
subgraph Local["💻 Устройство клиента"]
Apps["Браузер / Приложения"]:::userApp
Socks["SOCKS5 / HTTP Прокси"]:::ostpCore
Tun["Global TUN (VPN)"]:::ostpCore
Client["OSTP Клиент\n(Noise + ChaCha20 + ARQ)"]:::ostpCore
Apps -->|TCP/UDP| Socks
Apps -->|IP Пакеты| Tun
Socks --> Client
Tun --> Client
subgraph Client [Клиент]
CoreC[OSTP Клиент] -.->|Шифрование| NetC[Транспортный уровень]
end
subgraph Internet["🌐 Сеть с цензурой (DPI)"]
Tunnel{"Зашифрованный UDP\n(Выглядит как белый шум)"}:::network
NetC <==>|Зашифрованный UDP / UoT| NetS
subgraph Server [Сервер]
NetS[Транспортный уровень] -.->|Дешифрование| CoreS[OSTP Сервер]
NetS -->|Неавторизованные| Fallback[Fallback Сервер]
end
subgraph Remote["🖥️ Удаленный сервер (VPS)"]
Server["OSTP Сервер\n(Аутентификация)"]:::ostpCore
Relay["Мультиплексор соединений"]:::ostpCore
Fallback["Фейковый сайт\n(Nginx/Caddy)"]:::fallback
Target["Свободный интернет\n(YouTube, Google и т.д.)"]:::external
Server -->|Расшифрованный трафик| Relay
Server -->|Сканеры цензоров| Fallback
Relay -->|Чистый трафик| Target
end
Client <==> Tunnel <==> Server
CoreS -->|Проксирование| WWW((Интернет))
Fallback -->|Перенаправление| Web((Веб-сервер / NGINX))
```
---
## Установка
## Быстрый старт
### Linux
### 1. Установка
**Linux:**
```bash
bash <(curl -Ls https://raw.githubusercontent.com/ospab/ostp/master/scripts/install.sh)
```
### Windows (PowerShell от Администратора)
**Windows (PowerShell от Администратора):**
```powershell
irm https://raw.githubusercontent.com/ospab/ostp/master/scripts/install.ps1 | iex
```
---
### 2. Конфигурация
## Конфигурация
Создать конфиг по умолчанию:
Сгенерируйте базовые файлы конфигурации:
```bash
./ostp init server # VPS
./ostp init client # Локальная машина
# На сервере:
./ostp --init server
# На клиенте:
./ostp --init client
```
### Сервер (`config.json`)
**Пример конфигурации сервера** (`config.json`):
```jsonc
{
"mode": "server",
"listen": "0.0.0.0:50000",
"access_keys": ["ВАШ_КЛЮЧ"],
"debug": false,
// Опционально: проксировать трафик через upstream
"outbound": {
"enabled": false,
"protocol": "socks5",
"address": "127.0.0.1",
"port": 9050,
"default_action": "proxy"
}
"access_keys": ["ВАШ_КЛЮЧ"]
}
```
### Клиент (`config.json`)
**Пример конфигурации клиента** (`config.json`):
```jsonc
{
"mode": "client",
"server": "IP_СЕРВЕРА:50000",
"access_key": "ВАШ_КЛЮЧ",
"socks5_bind": "127.0.0.1:1088",
"debug": false,
// Настройки транспорта (udp или uot)
"transport": {
"mode": "udp"
},
// TUN-режим (полносистемный VPN)
"tun": {
"enable": false,
"dns": "1.1.1.1"
},
// Мультиплексирование: несколько UDP-сессий
"mux": {
"enabled": false,
"sessions": 2
},
// TURN-реле для заблокированных сетей
"turn": {
"enabled": false,
"server_addr": "turn.example.com:3478",
"username": "user",
"access_key": "pass"
},
// Исключения (идут напрямую, минуя туннель)
"exclude": {
"domains": ["example.local"],
"ips": ["192.168.0.0/16"]
}
"version": "0.3.1",
"inbounds": [
{ "type": "local_proxy", "tag": "socks-in", "protocol": "socks", "listen": "127.0.0.1", "port": 1088 }
],
"outbounds": [
{
"type": "ostp",
"tag": "proxy",
"server": "IP_СЕРВЕРА",
"port": 50000,
"access_key": "ВАШ_КЛЮЧ",
"transport": { "type": "udp" }
}
]
}
```
---
## Использование
### 3. Запуск
```bash
# Запуск с конфигом
./ostp --config config.json
# Или просто (ищет config.json рядом с бинарником)
# Запуск с конфигурацией по умолчанию (config.json)
./ostp
# Запуск с указанием пути к конфигурации
./ostp --config /path/to/config.json
```
### Справка по командам
Либо подключение через однострочную ссылку на стороне клиента:
```bash
./ostp "ostp://ВАШ_КЛЮЧ@IP_СЕРВЕРА:50000?transport=udp"
```
ostp [--config <PATH>] [КОМАНДА]
Команды:
run Запустить демон по конфигу (по умолчанию, если команда не указана)
connect <URL> Подключиться по share-ссылке: ostp://KEY@HOST:PORT
setup Интерактивный мастер настройки
init <MODE> Сгенерировать шаблон конфига (server/client/relay)
check Проверить конфиг и выйти
gk Сгенерировать access-key (алиас: generate-key)
--format <FMT> Формат ключа: hex, base64 (по умолчанию hex)
-n, --count <N> Количество ключей (по умолчанию 1)
links Вывести client-share-ссылки из серверного конфига
import <URL> Импортировать share-ссылку в конфиг
update Обновить OSTP до актуального релиза
-b, --branch <NAME> Канал релиза: stable, beta, alpha (по умолчанию stable)
-v, --version <VER> Обновиться на точную версию вместо последней в канале
migrate Принудительно мигрировать конфиг к текущему формату
proxy-env Вывести shell-команды для локального SOCKS-прокси
proxy-env-clear Вывести shell-команды для их отмены
uninstall Остановить сервис и удалить бинарник с конфигом
Глобальные опции:
--config <PATH> Путь к конфигу (по умолчанию config.json)
```
У каждой подкоманды есть своя справка через `-h`/`--help`.
### TUN-режим (Windows)
Использует встроенный сетевой стек `smoltcp` и виртуальный адаптер `wintun` (необходима `wintun.dll`). Требует запуска с правами Администратора.
### TUN-режим (Linux)
Использует встроенный сетевой стек `smoltcp` и `/dev/net/tun`. Требует запуска от имени `root` (или наличия `CAP_NET_ADMIN`).
---
@ -208,19 +133,22 @@ ostp [--config <PATH>] [КОМАНДА]
|---------|----------|
| Обмен ключами | Noise NNpsk0 (X25519 + ChaChaPoly + BLAKE2s) zero-RTT |
| Шифрование | ChaCha20-Poly1305 AEAD на каждый пакет |
| Обфускация заголовков | HMAC-SHA256 маска session_id + nonce, уникальная для каждого пакета |
| Обфускация заголовков | HMAC-SHA256 маска на основе session_id и nonce |
| Надёжность | Selective ACK с cumulative + SACK диапазонами |
| Ретрансмиссия | Rate-limited NACK (30мс cooldown) + exponential backoff RTO |
| Flow Control | Окно in-flight (только retransmittable фреймы) |
| Ретрансмиссия | Rate-limited NACK + exponential backoff RTO |
| Keepalive | Ping/Pong с измерением RTT каждые 5с |
| Таймаут сессии | 60с на клиенте, 300с на сервере |
---
## Сборка из исходников
### Зависимости для сборки
- Rust 1.70+
- Go 1.20+ (необходимо для сборки встроенного DNS-туннеля dnstt)
> **Благодарности:** Этот проект использует [dnstt](https://www.bamsoftware.com/software/dnstt/) от Bamsoftware для обеспечения устойчивого туннелирования поверх DNS. Бинарники dnstt автоматически компилируются и встраиваются в ядро OSTP.
```bash
# Требования: Rust toolchain (1.75+)
cargo build --release
# Кросс-компиляция для Linux
@ -231,15 +159,21 @@ cross build --release --target x86_64-unknown-linux-gnu
## Документация
- [Архитектура](docs/ru/architecture.md)
- **[Wiki](https://github.com/ospab/ostp/wiki)**
- [Спецификация протокола](docs/ru/specification.md)
- [Дизайн обфускации](docs/ru/obfuscation.md)
- [Администрирование сервера](docs/ru/server.md)
- [Архитектура](docs/ru/architecture.md)
- [Настройка клиента](docs/ru/client.md)
- [Интеграции](docs/ru/integrations.md)
---
## Лицензия
GNU Affero General Public License v3.0 (AGPL-3.0). Полный текст - в файле [LICENSE](LICENSE).
GNU Affero General Public License v3.0 (AGPL-3.0). Подробнее см. в файле [LICENSE](LICENSE).
---
## Контакты
- **Telegram**: [@ospab0](https://t.me/ospab0)
- **Email**: gvoprgrg@gmail.com

View File

@ -1,185 +0,0 @@
# Чистая переборка на базе v0.2.98
База: `v0.2.98` (commit `31d0020`) — последняя версия, которая **стабильно работает**.
Ветка: `clean-rebuild`. Всё, что появилось после (0.3.1 … 0.3.21), переносим
**выборочно и с чистой головой**, а не копируем рефактор целиком.
Принцип: 0.3.1 принёс «модульный multi-server рефактор» + лавину фич — и вместе с
ними нестабильность. Берём только проверенное и нужное.
---
## Решения (зафиксировано пользователем)
- **Junk-пакеты + TCP-фрагментация — ОСТАВЛЯЕМ** (нравятся). НО починить вредную
часть: junk по UDP не должен выглядеть для сервера как `Unauthorized probe`
(rate-limit/гейт на сервере), иначе флуд лога и риск самобана клиента. Фича
остаётся — чиним поведение, а не выпиливаем. Тонкая настройка — §E.
- **Версия переборки — 0.4.0** (решено; 0.3.x сожжены в pre-release).
- **WSS и Reality (TLS-мимикрия) — ВЫКИНУТЬ.** Путь проекта — **zapret-like**:
обфускация/DPI-evasion на уровне пакетов (junk, фрагментация, обфускация), а НЕ
мимикрия под TLS. Reality с нуля тяжела и не вписывается.
- **Multi-server — НЕ НУЖЕН.** Режем до одного сервера → уходит urltest-группа и
половина сложности 0.3.1.
- **Конфиг — ПЛОСКИЙ по сути, но оформлен красиво/секционно как сейчас** (решено).
Сохраняем читаемую секционную структуру (server / transport / tun / dns / exclude
и т.п.), но **выпиливаем модульную машинерию**: массивы `inbounds[]`/`outbounds[]`,
`routing.rules[]` с тегами, `default_outbound`, urltest, мульти-сервер. Один сервер
на конфиг. Исключения = плоский список внутри секции `exclude`.
- **Профили — ОСТАВЛЯЕМ, single-select, в UI-слое** (решено). Профиль = сохранённый
конфиг одного сервера; активен ровно один (radio). Список/выбор/share живут во
фронте (prefs GUI / Flutter); **ядро о профилях не знает** — на «Подключить» из
выбранного профиля генерится плоский конфиг на один сервер. Никаких чекбоксов/
мульти-актив/urltest.
- **Derived-secrets — ОСТАВЛЯЕМ, но ОБЯЗАТЕЛЬНО проверить, что он РЕАЛЬНО работает:**
старый клиент НЕ должен подключаться к новому серверу. В прошлой реализации это
НЕ соблюдалось (старый клиент → новый сервер подключался) — значит сервер всё ещё
принимал старый формат handshake / obfuscation-key. Это **баг**, закрыть в первую
очередь: сервер обязан отвергать всё, что не прошло derived-secrets.
- **Лицензия — AGPLv3.**
- **Брендинг — ОСТАВЛЯЕМ**: тёмная тема + орёл на фоне (watermark/логотип).
- **Стелс-философия (north-star): zapret-like** — «нет узнаваемого заголовка +
манипуляции пакетами» (обфускация, junk, фрагментация, DNS/UoT-транспорты), а НЕ
«притворись известным протоколом» (Reality/WSS — выкинуты).
---
## 0. Корневая причина нестабильности 0.3.x
**Модульный multi-server рефактор (0.3.1)** — `580faf6`, `8ed66f9`, `67f9c06`.
Сменил формат конфига (inbounds/outbounds/routing/urltest), session-модель,
hot-reload. Источник большинства багов (мёртвые маршруты, фейк-коннект,
рассинхрон конфига). **НЕ копировать целиком.** Если multi-server реально нужен —
добавлять минимально и поверх рабочей одно-серверной модели 0.2.98.
---
## A. ВЫКИНУТЬ / не переносить
1. **WSS-фрейминг и Reality (TLS-мимикрия)**оба выкинуть. Путь zapret-like, а не
маскировка под TLS-сайт; Reality (`reality.rs`) к тому же сложно сделать корректно
с нуля. Удалить из базы 0.2.98 целиком.
2. **Multi-server / urltest-группа** — не нужен. Один сервер на конфиг.
3. Остатки **tun2socks** на Android (`libtun2socks.so`, `tun2socks-arm64`,
`tun_child`, `t2sBinPath`) — давно мёртвый код, только раздувает APK. Не тащить.
> ⚠️ Junk-пакеты и TCP-фрагментация **ОСТАЮТСЯ** (см. Решения и §E) — это уже не
> «мусор». Но junk по UDP нужно сделать так, чтобы сервер его не считал
> `Unauthorized probe` (rate-limit/гейт), иначе лог-флуд и риск самобана.
---
## B. ОБЯЗАТЕЛЬНО перенести (фиксы стабильности)
- **fd limits / EMFILE**`922cf0b`.
- **Lifecycle хелпера**: принудительный `std::process::exit` после остановки, чтобы
не оставался зомби-процесс, держащий адаптер `ostp_tun` и дефолтный маршрут — `b6e78c1`.
- **Bypass-маршрут сервера через `route.exe` по шлюзу** (а не legacy
`CreateIpForwardEntry`, который падал с err 160 из-за рассинхрона индексов
интерфейсов) — `b6e78c1`.
- **IPC хелпера** (ChaCha20Poly1305 + hex) + **единый формат логов**`ee38b15`.
- **Closing-state fix** + `sent_history` на `BTreeMap` (O(log n) NACK) — `47d44fa`.
- **Handshake timeout fixes**`d65af35`, `6eb7b36` (ждать ответ до отправки данных).
- **Buffer / UDP handler**`b5e830a`.
- **Логи**: UoT и unauthorized-probe → debug; rate-limit probe-лога — `1151726`, `fc339b3`.
---
## C. Протокол / крипто — решить и перенести
- **Derived secrets handshake**`f8f27d3`. PSK и obfuscation-key выводятся из
access-key через HKDF; handshake-payload = `[timestamp][session_id][access_key]`;
параметры паддинга деривируются; timestamp anti-replay (±300с).
⚠️ **Ломает совместимость с 0.2.98 wire** (старый клиент не подключится).
Безопаснее старого (raw-PSK + нулевой obfuscation-key). **РЕШЕНИЕ:** переносим ли
(тогда нужен ребилд всех клиентов) — ДА, скорее всего, но осознанно.
- **l4_protocol** для server outbound — `2997bfd`, `ad3a8cb`, `aae9d22`.
---
## D. Транспорты — перенести аккуратно (большие куски)
- **DNS transport (dnstt)** как fallback — `3f1adbc`, `3ced4a1`, `d031b15`,
`10c1772`, `b31da29`. Полезно против блокировок, но объёмно и со своей
фрагментацией/reassembly. Переносить отдельным изолированным модулем.
- UoT (UDP-over-TCP) — уже есть в 0.2.98, проверить что не сломан.
---
## E. Тонкая настройка junk/фрагментации (как в AmneziaWG)
Junk и фрагментацию **оставляем** (Решения), а это — их параметризация. Главное
условие: **координация клиент↔сервер**, иначе junk превращается в probe-флуд.
- `Jc` — кол-во junk-пакетов, `Jmin`/`Jmax` — размеры; **сервер знает и молча отбрасывает**.
- `S1`/`S2` — размеры init/response подгоняются.
- Магические заголовки/сигнатуры пакетов (`H1..H4`).
Реализовать как явные настраиваемые поля (не хардкод). Сервер ОБЯЗАН их понимать.
Сам факт junk/frag — в базе; это «желание» — сделать их настраиваемыми. Можно потом.
---
## F. GUI (desktop) — перенести нужное, без хаоса
- Профили на странице **настроек** (пусто + «Create a new profile» + «+» когда нет
профиля; «+» → меню «из ссылки / вручную»). Главный экран не усложнять.
- **Share** профиля: QR (генерить локально, ключ наружу не отдавать — крейт `qrcode`)
+ копируемая `ostp://` ссылка.
- **Метрики**: байты считать в TUN-инбаунде; rtt брать из round-trip handshake
(а не отдельным TCP-probe).
- **Health/состояние**: «connected» по реальной достижимости сервера на ПРАВИЛЬНОМ
порту (не хардкод :443), а не по факту «процесс запустился».
- **routing**: всегда задавать `default_outbound: "proxy"`; ключи правил —
`domain_suffix` / `ip_cidr` / `process_name` (не `domains/ips/processes`).
- Смена сервера = полный **stop+start**, а не hot-reload (иначе остаётся старый сервер).
- Никаких непрогарженных `addEventListener` на удалённые элементы (краш init).
---
## G. Мобилка (Flutter + JNI) — перенести нужное
- **routing**: тот же `default_outbound` + правильные ключи правил
(без них трафик шёл мимо туннеля — реальный IP).
- **Байты на Android**: считать в обеих задачах fd-пути (read=upload, write=download).
- **rtt**: из handshake (health-probe сокет на Android не protected → до сервера не доходит).
- **Смена сети (WiFi↔LTE)**: реальный reconnect (сейчас `notifyNetworkChanged` — no-op).
- **fd ownership**: НЕ двойное закрытие (Rust `OwnedFd` + Kotlin `close()`) → `detachFd()`.
- **Share** профиля: QR (`qr_flutter`) + ссылка.
- Выкинуть tun2socks (см. §A.3).
---
## H. Инфра / лицензия / брендинг
- Лицензия: **AGPLv3** ✅ (зафиксировано). В 0.2.98 был BSL 1.1 → заменить (`9ce9e6d`).
- **Брендинг — ОСТАВЛЯЕМ** ✅: тёмная тема + орёл на фоне (watermark/логотип) в GUI.
Перенести из текущего `ostp-gui` (assets/logo.svg, тёмная палитра) в чистую переборку.
- Панель/license-check: open-source без license-check — `5782107`, `99ff76d` (если нужно).
- Версионирование/CI build-script — `774d926` и пр.
---
## Инвентаризация базы 0.2.98 (что уже есть / что портировать)
- **Есть в 0.2.98**: WSS (→ удалить), Reality/`reality.rs` (→ удалить),
инфра derived-secrets (`derive_all_secrets`, `obfuscation_key`) — но клиент юзал
dummy-ключи до `f8f27d3`.
- **Нет в 0.2.98 — портировать из пост-0.2.98 кода**: junk-пакеты, TCP-фрагментация,
DNS-transport (dnstt), фикс derived-secrets `f8f27d3`, все фиксы §B, GUI/мобилка §F/§G.
## Что легко упустить (решить до старта)
1. **Версия переборки — 0.4.0** (решено). Сожжённые 0.3.x не переиспользуем.
2. **Серверный конфиг — тоже плоский** и согласован с клиентским. Сервер обязан
поддерживать всё оставленное: derived-secrets (и **отвергать** старый формат),
корректную обработку junk (не probe-флуд), UoT, DNS-transport, management API.
3. **Версия/магический байт протокола ДО крипто-слоя.** Сейчас нельзя отличить старый
handshake от нового — отсюда баг «старый клиент → новый сервер подключился».
Добавить версию в wire → будущие изменения управляемы, сервер чётко режет
несовместимое. Это системный фикс проблемы derived-secrets.
4. **Клиент и сервер обновляются ВМЕСТЕ** — derived-secrets ломает совместимость,
смешивать старое и новое нельзя. Координировать выкладку.
5. **Reality — выкинуть** (решено; в базе 0.2.98 есть `reality.rs` → удалить целиком).
6. **Verify-loop = критерий «готово».** Каждая фича проверяется реальным тестом, не
«на словах»: connect → `curl` показывает IP **сервера**; старый клиент к новому
серверу **не** подключается; смена сети на мобилке восстанавливает туннель.
## Порядок переборки (предложение, 1 сессия)
1. §B (фиксы стабильности) — на чистый 0.2.98.
2. §C (derived-secrets) — и СРАЗУ проверить: старый клиент к новому серверу НЕ
подключается (в прошлый раз был баг — подключался).
3. **Junk + TCP-фрагментация** — перенести (оставляем), но junk по UDP не должен
читаться сервером как `Unauthorized probe` (rate-limit/гейт на сервере).
4. §F/§G по минимуму (routing, метрики, состояние, share) **+ брендинг** (тёмная
тема, орёл на фоне).
5. §D (DNS transport) — если нужно.
6. ВЫКИНУТЬ: **WSS, multi-server, tun2socks** (§A). §E (тюнинг junk) — позже.
7. Конфиг: плоский по сути, секционно-оформленный, один сервер (РЕШЕНО — без
inbounds/outbounds/routing-движка).

1
dnstt Submodule

@ -0,0 +1 @@
Subproject commit 0c5c52a57d899c05428c116898941761a2ed83c2

View File

@ -5,10 +5,20 @@ The Obfuscated Secure Transport Protocol (OSTP) is a high-performance, asynchron
---
## Kerckhoffs's Principle and DPI Resilience
The OSTP architecture strictly adheres to **Kerckhoffs's Principle**: a cryptosystem should be secure even if everything about the system, except the key, is public knowledge.
All encryption and obfuscation algorithms are fully open source. The security and indistinguishability of the traffic rely entirely on the secrecy of the pre-shared key (`access_key` / PSK).
Through cryptographic transformations using this key (Noise Protocol + ChaCha20Poly1305 + Blake2s) and adaptive padding, every transmitted packet is visually indistinguishable from completely random white noise.
The protocol lacks any static headers or plaintext handshakes. This makes it impossible for Deep Packet Inspection (DPI) systems, such as state censors, to create a static filter or signature to block OSTP within minutes. Blocking the protocol would require either blocking all unknown UDP traffic globally (which breaks many legitimate services) or possessing the secret key.
---
## Workspace Structure
The project is modularized into the following crates:
1. **ostp-core**: The core engine. Contains protocol state machines, Noise Protocol Framework handshakes, data framing serialization, dynamic obfuscation algorithms, and reliable packet delivery (ARQ).
2. **ostp-client**: The client daemon. Manages local traffic interception via dual-mode SOCKS5/HTTP proxies or virtualized network adapters (TUN/Wintun), multiplexing active host streams into a single UDP tunnel, and interfacing with TURN servers.
2. **ostp-client**: The client daemon. Manages routing configuration via arrays of `inbounds` (e.g., SOCKS5, TUN) and `outbounds` (e.g., OSTP, direct, block), handling multiplexing of streams and interacting with TURN servers.
3. **ostp-server**: The high-concurrency connection dispatcher, responsible for demultiplexing data from multiple sessions, handling seamless IP roaming, and forwarding traffic to the broader internet.
4. **ostp-obfuscator**: Utility crate for static traffic shaping and dynamic obfuscation key derivation tools.
5. **ostp-jni**: Android JNI bindings that allow embedding OSTP inside mobile applications via an isolated runtime.

View File

@ -46,16 +46,29 @@ The client is engineered to maintain persistence without requiring user interven
---
## Routing Exclusions (Bypass Mode)
## Modular Routing Architecture (Inbounds / Outbounds)
To minimize latency and overhead for trusted resources, the OSTP client incorporates an integrated direct-routing bypass engine. This is configured inside the `"exclude"` block of the `config.json` file:
Starting from version `0.3.1`, the OSTP client utilizes a modular configuration architecture based on inbound and outbound arrays, similar to Xray or Sing-box.
- **`domains`**: A list of domain suffixes (e.g., `["trusted-site.com", "local.lan"]`). Traffic bound for these domains is instantly channeled via the default local gateway, bypassing encryption entirely.
- **`ips`**: A list of target subnet destinations in CIDR format (e.g., `["192.168.1.0/24", "10.0.0.0/8"]`), ensuring local area networks maintain full wire-speed throughput.
- **`processes`**: A list of OS executable filenames (e.g., `["discord.exe", "steam.exe"]`). Applications specified here will automatically evade the VPN's virtual network driver.
- **`inbounds`**: Defines how local traffic enters the client. Supported types include `tun` (virtual network interface) and `local_proxy` (SOCKS5/HTTP proxy).
- **`outbounds`**: Defines where the client sends the traffic. The main type is `ostp` (encapsulation and transmission to the server), but it also supports `direct` (bypassing the VPN to connect directly to the internet) and `block` (dropping traffic).
- **`routing`**: The mechanism replacing the legacy `exclude` block. It allows for flexible traffic routing based on advanced rules.
Routing rule example in `config.json`:
```json
"routing": {
"rules": [
{
"domain_suffix": ["trusted-site.com", "local.lan"],
"outbound": "direct"
}
],
"default_outbound": "proxy"
}
```
> [!NOTE]
> The exclusion/bypass logic is fully operational, rigorously optimized, and ready for immediate production deployment.
> This architecture enables the client to connect to multiple OSTP servers simultaneously, split traffic by domain, or block telemetry directly at the VPN routing level.
---

16
docs/en/faq.md Normal file
View File

@ -0,0 +1,16 @@
# Frequently Asked Questions (FAQ)
## What is OSTP and how does it differ from other VPNs (WireGuard, OpenVPN)?
OSTP is a protocol built from the ground up for maximum Deep Packet Inspection (DPI) evasion. Unlike WireGuard and OpenVPN, which have recognizable handshakes and static headers, OSTP obfuscates 100% of the data starting from the very first byte. Every packet is indistinguishable from random white noise, making static filtering impossible.
## How does DPI evasion work? Is it secure?
OSTP architecture strictly adheres to **Kerckhoffs's Principle**. The code is fully open source and does not rely on security by obscurity. The obfuscation is backed by rigorous cryptographic algorithms (Noise Protocol, ChaCha20Poly1305, Blake2s) and pre-shared keys. Censors and DPI systems cannot write a signature or filter for OSTP because there are simply no repetitive patterns in the traffic.
## How do I upgrade to version 0.3.1 and what happens to `config.json`?
Version 0.3.1 introduced a new modular architecture (`inbounds` and `outbounds` arrays). When you run OSTP v0.3.1+ with an older configuration file, the built-in auto-migrator automatically converts it to the new format without data loss and appends `"version": "0.3.1"`.
## Why is multiplexing not working for me (sessions > 1)?
There is a known issue within the `mux` demultiplexer when handling multiple sessions concurrently. The handshake succeeds, but application data fails to stream. Please keep the session count to 1 or disable `mux` entirely until a patch is released in future `ostp-core` versions.
## Is there proprietary or closed-source code in OSTP?
The core protocol engine and base client/server implementations are completely open source and available for peer review in this repository. However, certain experimental or enterprise-specific tooling (`ostp-brain`, `ostp-prober`, `ostp-sandbox`, and parts of `ostp-gui`) are excluded from the public workspace to keep the open-source codebase focused.

108
docs/en/migration-v0.3.1.md Normal file
View File

@ -0,0 +1,108 @@
# OSTP Configuration Migration to v0.3.1
The OSTP `config.json` schema has been significantly redesigned in version `v0.3.1` to support a modern multi-server architecture. The new schema provides greater flexibility by splitting configuration into `inbounds`, `outbounds`, and flexible `routing` rules, replacing the monolithic architecture of previous versions.
## Automatic Migration
The OSTP core and GUI clients are equipped with an automatic migrator. When launching OSTP `v0.3.1` with a `config.json` from a previous version, the migrator will automatically transform the legacy schema into the new `v0.3.1` schema.
The migrated file will be overwritten with the new format and will begin with:
```json
// OSTP Configuration v0.3.1
// DO NOT EDIT THIS COMMENT - Migrator relies on it
{
"version": "0.3.1",
"mode": "client",
...
}
```
## Manual Schema Reference
If you prefer to configure manually, the following is a reference of the new modular configuration format:
### Legacy Configuration (v0.2.x)
```json
{
"mode": "client",
"server": "192.168.1.100:50000",
"access_key": "mysecretkey",
"socks5_bind": "127.0.0.1:1088",
"tun": {
"enable": true,
"kill_switch": true
},
"exclude": {
"domains": ["localhost"],
"ips": ["192.168.1.0/24"]
}
}
```
### New Configuration (v0.3.1)
```json
{
"version": "0.3.1",
"mode": "client",
"api": {
"enabled": true,
"bind": "127.0.0.1:50001",
"token": "admin-secret-token"
},
"log": {
"level": "info"
},
"inbounds": [
{
"type": "tun",
"tag": "tun-in",
"auto_route": true,
"mtu": 1140
},
{
"type": "socks",
"tag": "socks-in",
"bind_addr": "127.0.0.1:1088"
}
],
"outbounds": [
{
"type": "ostp",
"tag": "proxy",
"server": "192.168.1.100",
"port": 50000,
"access_key": "mysecretkey",
"transport": {
"type": "udp"
},
"multiplex": {
"enabled": false
}
},
{
"type": "direct",
"tag": "direct"
},
{
"type": "block",
"tag": "block"
}
],
"routing": {
"rules": [
{
"domain_suffix": ["localhost"],
"ip_cidr": ["192.168.1.0/24"],
"outbound": "direct"
}
],
"default_outbound": "proxy"
}
}
```
### Key Changes
- **Outbounds List**: Multiple proxy servers can now be defined.
- **Inbounds List**: TUN and SOCKS5 are now independent listeners.
- **Routing**: Fine-grained traffic routing between inbounds and outbounds based on domains, IPs, and processes.
- **Comments**: The GUI and migrator now use JS-style `//` comments in `config.json` instead of the legacy `"_comment"` JSON keys.

View File

@ -5,38 +5,40 @@ Traditional tunneling protocols (such as TLS, OpenVPN, and WireGuard) exhibit di
---
## Secret Derivation
## Obfuscation Key Derivation
Every protocol secret — the obfuscation key, the Noise PSK, the handshake padding range, and the per-key junk marker (see below) — is derived from the shared `access_key` via a single HKDF-SHA256 pass, domain-separated by a trailing info byte per output:
To dynamically mask protocol data, an 8-byte obfuscation key is statically derived from the shared `access_key` configured on both the client and the server:
```
PRK = HKDF-Extract(salt = SHA-256(access_key)[0..16], IKM = access_key || PROTOCOL_VERSION)
obfuscation_key = HKDF-Expand(PRK, info = SHA-256(access_key)[16..] || 0x01, 8 bytes)
psk = HKDF-Expand(PRK, info = SHA-256(access_key)[16..] || 0x02, 32 bytes)
handshake_pad = HKDF-Expand(PRK, info = SHA-256(access_key)[16..] || 0x03, 2 bytes)
junk_marker = HKDF-Expand(PRK, info = SHA-256(access_key)[16..] || 0x04, 4 bytes)
```
$$\text{Key} = \text{SHA-256}(\text{access\_key})[0..8]$$
The wire protocol version is mixed into the IKM, not sent as a plaintext byte: peers on a different protocol version derive an entirely different `obfuscation_key`, so they simply cannot deobfuscate each other's packets and are rejected as unauthorized — a hard version gate with no recognizable marker ever appearing on the wire. No secret is ever transmitted; both sides derive the same values independently from the shared access key.
This key is established pre-session and is never transmitted across the wire in any capacity.
---
## Dynamic In-Place Masking Algorithm
OSTP datagrams are masked "in-place" immediately prior to transmission and right after arrival. The mask itself is **derived from the packet's own ciphertext**, not from a fixed keystream or a counter, so it changes with every packet automatically:
```
mask = HMAC-SHA256(key = obfuscation_key, message = ciphertext[0..min(32, len)])
```
OSTP datagrams are processed "in-place" immediately prior to transmission and right after arrival. Two distinct mathematical modes are utilized based on the current handshake phase:
### 1. Handshake Phase Mode (`is_handshake = true`)
The wire packet is `[4-byte session_id][2-byte noise_len][Noise payload]`. The mask is computed over the Noise payload (`raw[6..]`), and its first 6 bytes are XORed onto `session_id || noise_len`.
During connection initiation (Noise Handshake), the wire packet consists of a 4-byte `session_id` prefixed to the Noise payload. To mask the fixed session ID:
* **Masking**: The first 4 bytes are XORed with the first 4 bytes of the derived obfuscation key:
$$\text{raw}[i] = \text{raw}[i] \oplus \text{Key}[i \pmod 8], \quad i \in [0..3]$$
* **De-masking**: A repeated XOR with the identical key bytes recovers the original `session_id`.
### 2. Data Transmission Mode (`is_handshake = false`)
The wire packet is `[4-byte session_id][8-byte nonce][AEAD ciphertext]`. The mask is computed over the AEAD ciphertext, and its first 12 bytes are XORed onto `session_id || nonce`.
Post-handshake, the wire layout contains:
`[4-byte session_id]` + `[8-byte nonce]` + `[AEAD Ciphertext]`
#### Impact of the Scheme
Because the mask is keyed on both the shared secret and the packet's own ciphertext, no two packets — even consecutive ones from the same session — share a keystream, without needing an explicit counter-based scheme. This breaks all packet header correlations and eliminates repeating byte patterns, rendering statistical fingerprinting futile.
To completely randomize metadata, a two-tiered dynamic XOR masking process is applied:
1. **Nonce Masking**: The 8-byte `nonce` (sequence counter) is XORed with the full 8-byte static key:
$$\text{nonce\_bytes}[i] = \text{nonce\_bytes}[i] \oplus \text{Key}[i], \quad i \in [0..7]$$
2. **Session ID Masking**: The 4-byte `session_id` is masked using high dynamic entropy — the lower 32 bits of the **original (unmasked)** `nonce` value:
$$\text{session\_id\_bytes}[i] = \text{session\_id\_bytes}[i] \oplus \text{real\_nonce\_low32\_bytes}[i], \quad i \in [0..3]$$
#### Impact of the Scheme:
Because the `nonce` increments strictly with each outgoing datagram, the session ID's masking keystream continuously changes. This breaks all packet header correlations and eliminates repeating byte patterns, rendering statistical fingerprinting futile.
---
@ -48,13 +50,12 @@ The `AdaptivePadder` calculates dynamic dummy byte quantities to append to the p
- **Dynamic Distributions**: The padding algorithms emulate length profiles commonly seen in whitelisted HTTPS or real-time video streams.
- **Encrypted Overheads**: The appended padding resides within the AEAD cipher scope. Consequently, passive observers cannot distinguish padding bytes from useful application payload, hiding the true message boundary lengths.
## XTLS-Reality Impersonation
OSTP provides a custom, dependency-free implementation of the XTLS-Reality protocol. It fully simulates a TLS 1.3 handshake (with realistic ClientHello profiles) to bypass advanced DPI filters. Post-handshake, it utilizes ChaCha20Poly1305 to seamlessly encrypt and tunnel the inner HTTP/WSS connections.
---
## Junk Packets & TCP Fragmentation
## Impossibility of Static Filtering (DPI Evasion)
OSTP does not try to impersonate a known protocol (TLS, HTTP, or otherwise) — a fingerprint-matching filter can always be updated to catch an impersonation attempt. Instead it follows a **zapret-like** approach: no recognizable header at all, plus active manipulation of packet boundaries, so there is nothing distinctive to fingerprint in the first place.
- **Junk packets**: before the handshake, the client sends a configurable number (`junk_pc`) of random-size (`junk_ps`) filler datagrams. Each carries a 4-byte marker **derived from the access key** (the `junk_marker` above) rather than a fixed constant — a fixed marker would itself be a universal signature any observer could filter on across every OSTP deployment. The server derives the same per-key marker while trying candidate keys and drops matching junk silently, before it ever reaches the "unauthorized probe" logging path.
- **TCP fragmentation** (UoT/TCP transport only): the first packet (the handshake) is split into small chunks (`frag_chunk` bytes) with short delays (`frag_sleep` ms) between writes, so DPI that inspects only the first TCP segment never sees a complete handshake to fingerprint.
Both are configurable per-profile; neither is sent over plain UDP transport, where a standalone junk datagram would look exactly like a random one-off probe to the server.
Because of its strict mathematical entropy generation, the protocol is entirely devoid of plaintext signatures. This ensures that filtering systems (such as state censors like RKN or the Great Firewall) **physically cannot** write an effective blocking rule by analyzing packet contents. Any attempt to write a filter would inevitably result in blocking legitimate, randomized UDP traffic (like WebRTC or gaming traffic). Security is backed by Kerckhoffs's Principle — knowing the algorithms is useless for classifying traffic without possessing the `access_key`.

View File

@ -90,22 +90,11 @@ Because the `Nonce` is unique per packet, the mask is cryptographically independ
OSTP executes a Noise Protocol Framework exchange utilizing the `Noise_NNpsk0_25519_ChaChaPoly_BLAKE2s` pattern.
1. The Registration Key (`access_key`) is converted to a 32-octet strong pre-shared key (PSK) via HKDF-SHA-256.
1. The Registration Key (`access_key`) is converted to a 32-octet strong pre-shared key (PSK) via SHA-256.
2. The PSK is integrated into the state at pattern position zero, authorizing and encrypting the very first handshaking datagram.
3. Ephemeral Curve25519 key exchange (`ee`) is evaluated, and the two directional transport keys are taken from Noise's `Split()` over the final chaining key `ck`.
3. Ephemeral Curve25519 key exchange is evaluated to synthesize autonomous symmetric keys for subsequent read/write channels.
> **Forward secrecy.** The transport keys are derived from the chaining key
> `ck`, which absorbs the ephemeral `ee` Diffie-Hellman result. They are **not**
> derived from the Noise handshake hash `h``h` only ever absorbs public
> transcript data (ephemeral public keys and on-wire ciphertexts) and never the
> DH secret, so keys derived from it would give an access-key holder the ability
> to decrypt any recorded session. Deriving from `ck` binds each session to its
> ephemeral private keys, which are discarded after the handshake: an adversary
> who later compromises the PSK still cannot decrypt past traffic. This is a
> wire-breaking property gated by the internal protocol version (currently 5);
> peers on an older version derive different keys and cannot interoperate.
The initial handshake payload includes a Unix timestamp to mitigate replay attacks. The server enforces a ±300-second (5-minute) synchronization window and additionally records accepted handshakes in an anti-replay set for that window.
The initial handshake payload includes a Unix timestamp to mitigate replay attacks. The server enforces a ±300-second synchronization window to accommodate clock drift and mobile roaming scenarios.
---
@ -137,5 +126,4 @@ The server supports seamless network handoffs (e.g., transitioning from Wi-Fi to
* **Nonce Exhaustion:** The Nonce field is 64 bits. Implementations MUST terminate and re-key a session before the Nonce overflows to prevent AEAD keystream reuse.
* **Session Exhaustion (DoS):** Servers MUST enforce a strict cap on concurrent sessions (e.g., 1024) and silently drop handshake attempts exceeding this limit to prevent memory exhaustion attacks.
* **Handshake-trial CPU DoS:** Because there is no cleartext key identifier on the wire (a deliberate stealth property), a datagram from an unknown source must be trial-decrypted against every registered key. Servers MUST bound this work: OSTP caches each key's derived secrets and time-windowed junk markers (so a trial is a cheap comparison plus one AEAD attempt per key, not a fresh HKDF/HMAC), and gates the trial path behind a global token bucket (default 100/s) so a spoofed-source flood cannot force unbounded per-packet crypto. The established-session fast path and IP-roaming path are not subject to this bucket.
* **Header Authentication:** The header obfuscation mechanism provides privacy, not integrity. Header integrity is mathematically guaranteed by the Poly1305 Authentication Tag, which covers the entire 12-byte header as Additional Authenticated Data (AAD).

102
docs/migration_v0_3_1.md Normal file
View File

@ -0,0 +1,102 @@
# OSTP v0.3.1 Configuration Migration
In OSTP version 0.3.1, we have completely overhauled the `config.json` architecture for the client. The old monolithic structure (where all settings were in the root object) has been replaced by a modular system based on arrays of `inbounds` (incoming connections) and `outbounds` (outgoing connections), similar to Xray/V2Ray/Sing-box.
This allows OSTP to scale, support multiple proxy servers, multiple entry points (SOCKS5, TUN), and complex routing (`routing`).
## Automatic Migration
The `ostp` core includes a built-in automatic migrator. Upon starting any program (cli, gui, flutter), the core will check your `config.json`.
If the configuration lacks the `"version": "0.3.1"` field, OSTP will **automatically** convert your old config into the new modular format and save it to disk without data loss.
### What happens during migration:
1. **TUN and SOCKS5** -> converted into the `inbounds` array.
- The `socks5_bind` setting becomes an inbound `local_proxy` (SOCKS).
- The `tun` setting becomes an inbound `tun`.
2. **OSTP Server** -> moved into the `outbounds` array.
- Parameters `server`, `access_key`, `transport`, `mux` are combined into an outbound of type `"ostp"`.
3. **Split Tunneling (Exclude)** -> converted into `routing` rules.
- Old `domains` and `ips` are converted into rules routing traffic to the `"direct"` outbound.
- All other requests are routed by default to the `"proxy"` outbound.
4. **`version` fields**
- The field `"version": "0.3.1"` is added to prevent re-migration in the future. The `_comment` field has been removed.
## Change Example
### Before 0.3.1 (Old format)
```json
{
"mode": "client",
"log_level": "info",
"server": "1.2.3.4:50000",
"access_key": "secret",
"socks5_bind": "127.0.0.1:1088",
"tun": {
"enable": true
},
"exclude": {
"domains": ["localhost"]
}
}
```
### After 0.3.1 (New format)
```json
{
"mode": "client",
"version": "0.3.1",
"log": {
"level": "info"
},
"inbounds": [
{
"type": "tun",
"tag": "tun-in",
"auto_route": true,
"mtu": 1140
},
{
"type": "local_proxy",
"tag": "socks-in",
"protocol": "socks",
"listen": "127.0.0.1",
"port": 1088
}
],
"outbounds": [
{
"type": "ostp",
"tag": "proxy",
"server": "1.2.3.4",
"port": 50000,
"access_key": "secret",
"transport": {
"type": "udp"
}
},
{
"type": "direct",
"tag": "direct"
},
{
"type": "block",
"tag": "block"
}
],
"routing": {
"rules": [
{
"domain_suffix": ["localhost"],
"outbound": "direct"
}
],
"default_outbound": "proxy"
}
}
```
## Information for GUI Developers (ostp-gui, ostp-flutter)
If you are developing integrations or third-party clients, **you no longer need to parse the old fields**. You should use the `inbounds` and `outbounds` arrays. If the GUI passes a `serde_json::Value` to the core, the core will migrate it itself before starting. However, to save changes from the UI, you must modify the new array structure explicitly.

102
docs/migration_v0_3_1_ru.md Normal file
View File

@ -0,0 +1,102 @@
# Миграция конфигурации OSTP v0.3.1
В версии OSTP 0.3.1 мы полностью переработали архитектуру конфигурации `config.json` для клиента. Старая монолитная структура (где все настройки были в корневом объекте) заменена на модульную систему на базе массивов `inbounds` (входящие соединения) и `outbounds` (исходящие соединения), аналогично Xray/V2Ray/Sing-box.
Это позволяет OSTP масштабироваться, поддерживать несколько прокси-серверов, несколько точек входа (SOCKS5, TUN) и сложную маршрутизацию (`routing`).
## Автоматическая миграция
В ядро `ostp` встроен автоматический мигратор. При запуске любой программы (cli, gui, flutter) ядро проверит ваш `config.json`.
Если в конфигурации отсутствует поле `"version": "0.3.1"`, OSTP **автоматически** конвертирует ваш старый конфиг в новый модульный формат и сохранит его на диск без потери данных.
### Что происходит при миграции:
1. **TUN и SOCKS5** -> преобразуются в массив `inbounds`.
- Настройка `socks5_bind` становится входящим `local_proxy` (SOCKS).
- Настройка `tun` становится входящим `tun`.
2. **Сервер OSTP** -> переносится в массив `outbounds`.
- Параметры `server`, `access_key`, `transport`, `mux` объединяются в `outbound` с типом `"ostp"`.
3. **Split Tunneling (Exclude)** -> преобразуется в `routing` правила.
- Старые `domains` и `ips` конвертируются в правила, направляющие трафик в `"direct"` outbound.
- Все остальные запросы по умолчанию направляются в `"proxy"` outbound.
4. **Поля `version`**
- Добавляется поле `"version": "0.3.1"`, чтобы предотвратить повторную миграцию в будущем. Поле `_comment` было удалено.
## Пример изменения
### До 0.3.1 (Старый формат)
```json
{
"mode": "client",
"log_level": "info",
"server": "1.2.3.4:50000",
"access_key": "secret",
"socks5_bind": "127.0.0.1:1088",
"tun": {
"enable": true
},
"exclude": {
"domains": ["localhost"]
}
}
```
### После 0.3.1 (Новый формат)
```json
{
"mode": "client",
"version": "0.3.1",
"log": {
"level": "info"
},
"inbounds": [
{
"type": "tun",
"tag": "tun-in",
"auto_route": true,
"mtu": 1140
},
{
"type": "local_proxy",
"tag": "socks-in",
"protocol": "socks",
"listen": "127.0.0.1",
"port": 1088
}
],
"outbounds": [
{
"type": "ostp",
"tag": "proxy",
"server": "1.2.3.4",
"port": 50000,
"access_key": "secret",
"transport": {
"type": "udp"
}
},
{
"type": "direct",
"tag": "direct"
},
{
"type": "block",
"tag": "block"
}
],
"routing": {
"rules": [
{
"domain_suffix": ["localhost"],
"outbound": "direct"
}
],
"default_outbound": "proxy"
}
}
```
## Информация для разработчиков GUI (ostp-gui, ostp-flutter)
Если вы разрабатываете интеграции или сторонние клиенты, **вам больше не нужно парсить старые поля**. Вы должны использовать массивы `inbounds` и `outbounds`. Если GUI передает `serde_json::Value` в ядро, ядро само проведет миграцию перед запуском. Однако для сохранения изменений из UI вы должны изменять именно новую структуру массивов.

View File

@ -20,15 +20,9 @@
// Адрес следующего узла в цепочке UDP
"upstream_udp": "TARGET_SERVER_IP:50000",
// URL API конечного (целевого) сервера для синхронизации access_keys.
// Должен быть доступен с этого relay-сервера (можно через SSH-туннель).
//
// ВАЖНО: URL обязан включать секретный путь панели (api.webpath целевого
// сервера). Management API смонтирован ВНУТРИ этого пути именно он скрывает
// панель от сканеров, поэтому голый host:port попадает в несуществующий
// маршрут, и синхронизация падает с 404 ещё до проверки токена.
// Это тот же адрес, по которому вы открываете веб-панель.
"upstream_api_url": "http://TARGET_SERVER_IP:9090/TARGET_SERVER_WEBPATH",
// URL API конечного (целевого) сервера для синхронизации access_keys
// Должен быть доступен с этого relay-сервера (можно через SSH-туннель)
"upstream_api_url": "http://TARGET_SERVER_IP:9090",
// Bearer-токен для доступа к API целевого сервера
// Должен совпадать с api.token в конфиге target-сервера

View File

@ -5,10 +5,20 @@ Obfuscated Secure Transport Protocol (OSTP) — это высокопроизв
---
## Принцип Керкгоффса и устойчивость к DPI (Kerckhoffs's Principle)
Архитектура OSTP строго следует **Принципу Керкгоффса**: система должна оставаться безопасной, даже если все о ней, кроме ключа, является общедоступным знанием.
Весь исходный код алгоритмов шифрования и обфускации полностью открыт. Безопасность и нераспознаваемость трафика базируются исключительно на секретности предварительно согласованного ключа (`access_key` / PSK).
Благодаря криптографическим преобразованиям с использованием этого ключа (Noise Protocol + ChaCha20Poly1305 + Blake2s) и адаптивному паддингу, каждый пакет передаваемых данных визуально неотличим от абсолютно случайного белого шума.
Протокол не имеет статических заголовков или "рукопожатий" в открытом виде. Это делает невозможным для систем глубокого анализа трафика (DPI), таких как ТСПУ Роскомнадзора, создать статический фильтр или сигнатуру для блокировки OSTP за считанные минуты. Блокировка протокола потребовала бы либо полной блокировки всего неизвестного UDP-трафика (что нарушает работу многих легитимных сервисов), либо знания секретного ключа.
---
## Структура проекта
Проект состоит из следующих специализированных модулей (crates):
1. **ostp-core**: Основа протокола. Содержит конечные автоматы состояний, реализацию рукопожатия (Noise Protocol Framework), механизмы сериализации кадров (framing), алгоритмы обфускации и логику надежной доставки пакетов (ARQ).
2. **ostp-client**: Клиентский демон, управляющий перехватом трафика хоста через двухрежимный SOCKS5/HTTP-прокси или виртуальные адаптеры (TUN/Wintun), мультиплексированием потоков в единый UDP-туннель и взаимодействием с TURN для обхода NAT.
2. **ostp-client**: Клиентский демон. Управляет конфигурацией маршрутизации через массивы входящих (`inbounds`, например, SOCKS5, TUN) и исходящих (`outbounds`, например, OSTP, direct) соединений. Выполняет мультиплексирование потоков и взаимодействие с TURN для обхода NAT.
3. **ostp-server**: Высоконагруженный диспетчер соединений, отвечающий за демультиплексирование данных от множества сессий, прозрачный роуминг адресов и проксирование трафика в интернет.
4. **ostp-obfuscator**: Утилиты для статического шейпинга трафика и генерации динамических ключей маскировки.
5. **ostp-jni**: Нативный SDK для интеграции в мобильные платформы Android.

View File

@ -46,16 +46,29 @@
---
## Маршрутизация исключений (Bypass / Exclusions)
## Модульная архитектура маршрутизации (Inbounds / Outbounds)
Для снижения задержек и оптимизации трафика клиент OSTP поддерживает механизм прямых подключений в обход туннеля. Настройка производится в блоке `"exclude"` конфигурационного файла `config.json`:
Начиная с версии `0.3.1`, клиент OSTP использует модульную архитектуру конфигурации на базе массивов точек входа и выхода, аналогичную Xray или Sing-box.
- **`domains`**: Список доменных имен (например, `["trusted-site.com", "yandex.ru"]`). Любой запрос к этим доменам или их поддоменам направляется напрямую через системный шлюз провайдера.
- **`ips`**: Список диапазонов IP-адресов в формате CIDR (например, `["192.168.1.0/24", "10.0.0.0/8"]`). Полезно для доступа к ресурсам локальной сети.
- **`processes`**: Список имен исполняемых файлов процессов ОС (например, `["discord.exe", "steam.exe"]`), чьи сетевые запросы должны игнорировать VPN.
- **`inbounds` (Входящие точки)**: Определяет, как локальный трафик попадает в клиент. Поддерживаются типы `tun` (создание виртуального интерфейса) и `local_proxy` (SOCKS5/HTTP прокси).
- **`outbounds` (Исходящие точки)**: Определяет, куда клиент отправляет трафик. Основной тип — `ostp` (инкапсуляция и отправка на сервер), но также поддерживаются `direct` (прямое подключение к интернету в обход VPN) и `block` (блокировка трафика).
- **`routing` (Правила маршрутизации)**: Механизм, заменяющий старый блок `exclude`. Позволяет гибко перенаправлять трафик.
Пример правила маршрутизации в `config.json`:
```json
"routing": {
"rules": [
{
"domain_suffix": ["trusted-site.com", "local.lan"],
"outbound": "direct"
}
],
"default_outbound": "proxy"
}
```
> [!NOTE]
> Механизм исключений полностью отлажен и готов к промышленной эксплуатации, обеспечивая нулевые задержки для доверенных ресурсов.
> Такая архитектура позволяет подключать клиента сразу к нескольким серверам OSTP, разделять трафик по доменам или блокировать телеметрию на уровне роутера VPN.
---

16
docs/ru/faq.md Normal file
View File

@ -0,0 +1,16 @@
# Часто задаваемые вопросы (FAQ)
## Что такое OSTP и чем он отличается от других VPN (WireGuard, OpenVPN)?
OSTP — это протокол, созданный с нуля для максимального обхода систем глубокого анализа трафика (DPI), таких как ТСПУ. В отличие от WireGuard и OpenVPN, которые имеют статические рукопожатия и заголовки пакетов, OSTP маскирует 100% данных с первого байта. Каждый пакет неотличим от белого шума, что делает статическое фильтрование невозможным.
## Как работает защита от DPI? Безопасно ли это?
Архитектура OSTP строго следует **Принципу Керкгоффса**. Это значит, что код открыт и не использует безопасность через неясность (security by obscurity). Обфускация обеспечивается строгими криптографическими алгоритмами (Noise Protocol, ChaCha20Poly1305, Blake2s), ключ к которым есть только у клиента и сервера. ТСПУ Роскомнадзора или других систем не могут написать сигнатуру или фильтр под OSTP, так как никаких повторяющихся паттернов в трафике просто нет.
## Как обновиться до версии 0.3.1 и что делать с `config.json`?
Версия 0.3.1 перешла на новую модульную систему (массивы `inbounds` и `outbounds`). При первом запуске OSTP v0.3.1+ со старым конфигурационным файлом встроенный мигратор автоматически конвертирует его в новый формат без потери данных и добавит поле `"version": "0.3.1"`.
## Почему у меня не работает мультиплексирование (sessions > 1)?
Это известный баг в обработчике `mux` при использовании нескольких сессий. Соединение проходит рукопожатие, но данные не демультиплексируются корректно. Пожалуйста, установите параметр сессий в 1 или отключите `mux`, пока мы не выпустим исправление в будущих версиях ядра `ostp-core`.
## Есть ли в OSTP проприетарный или скрытый код?
Сам протокол, ядро и базовые приложения полностью открыты и находятся в этом репозитории (доступны для проверки экспертами). Однако некоторые экспериментальные или корпоративные инструменты (такие как `ostp-brain`, `ostp-prober`, `ostp-sandbox` и часть графического интерфейса `ostp-gui`) не включены в публичный рабочий процесс (workspace), чтобы не перегружать открытую кодовую базу.

108
docs/ru/migration-v0.3.1.md Normal file
View File

@ -0,0 +1,108 @@
# Миграция конфигурации OSTP на версию 0.3.1
В версии `v0.3.1` формат `config.json` проекта OSTP был значительно переработан для поддержки современной архитектуры мульти-серверных подключений. Новый формат конфигурации обеспечивает большую гибкость: теперь он разделен на входящие подключения (`inbounds`), исходящие подключения (`outbounds`) и гибкие правила маршрутизации (`routing`), заменяя устаревшую монолитную структуру прошлых версий.
## Автоматическая миграция
Ядро OSTP и GUI клиенты оснащены автоматическим мигратором. При запуске OSTP `v0.3.1` с файлом `config.json` от предыдущей версии, мигратор автоматически преобразует старый формат в новый.
После успешной миграции файл будет перезаписан в новом формате, и его заголовок будет содержать комментарий:
```json
// OSTP Configuration v0.3.1
// DO NOT EDIT THIS COMMENT - Migrator relies on it
{
"version": "0.3.1",
"mode": "client",
...
}
```
## Справочник по новому формату
Если вы предпочитаете настраивать OSTP вручную, ниже приведено сравнение и примеры нового формата.
### Устаревшая конфигурация (v0.2.x)
```json
{
"mode": "client",
"server": "192.168.1.100:50000",
"access_key": "mysecretkey",
"socks5_bind": "127.0.0.1:1088",
"tun": {
"enable": true,
"kill_switch": true
},
"exclude": {
"domains": ["localhost"],
"ips": ["192.168.1.0/24"]
}
}
```
### Новая конфигурация (v0.3.1)
```json
{
"version": "0.3.1",
"mode": "client",
"api": {
"enabled": true,
"bind": "127.0.0.1:50001",
"token": "admin-secret-token"
},
"log": {
"level": "info"
},
"inbounds": [
{
"type": "tun",
"tag": "tun-in",
"auto_route": true,
"mtu": 1140
},
{
"type": "socks",
"tag": "socks-in",
"bind_addr": "127.0.0.1:1088"
}
],
"outbounds": [
{
"type": "ostp",
"tag": "proxy",
"server": "192.168.1.100",
"port": 50000,
"access_key": "mysecretkey",
"transport": {
"type": "udp"
},
"multiplex": {
"enabled": false
}
},
{
"type": "direct",
"tag": "direct"
},
{
"type": "block",
"tag": "block"
}
],
"routing": {
"rules": [
{
"domain_suffix": ["localhost"],
"ip_cidr": ["192.168.1.0/24"],
"outbound": "direct"
}
],
"default_outbound": "proxy"
}
}
```
### Основные изменения
- **Outbounds (Исходящие)**: Теперь можно задать сразу несколько прокси-серверов.
- **Inbounds (Входящие)**: TUN и SOCKS5 выделены в отдельные независимые модули.
- **Routing (Маршрутизация)**: Точная маршрутизация трафика между входящими и исходящими узлами на основе доменов, IP-адресов и имен процессов.
- **Комментарии**: GUI и ядро теперь поддерживают JS-комментарии (с помощью `//`) в `config.json` вместо устаревших полей вида `"_comment"`.

View File

@ -1,60 +1,61 @@
# Обфускация трафика OSTP
# Маскирование энтропии сигналов OSTP
## Философия
## Философия структуры канала
Классические туннельные протоколы (TLS, OpenVPN, WireGuard) имеют узнаваемые сигнатуры в хэндшейке или статичные заголовки пакетов. Механизм обфускации OSTP спроектирован так, чтобы **начиная с первого байта** трафик был максимально похож на случайный шум — и для DPI-систем был неотличим от него.
Традиционные сетевые протоколы промышленного сбора данных могут обладать фиксированными заголовками, что при анализе статистического распределения байт ведет к предвзятости выборок и искажению телеметрического профиля. Задача механизмов энтропийного маскирования OSTP — достижение **равномерного вероятностного распределения значений байт**, начиная с самого первого пакета. Это делает сигналы шины данных абсолютно однородными и устойчивыми к корреляционному анализу и структурному мониторингу сетевых контроллеров.
---
## Деривация секретов
## Производная сигнатурная матрица (Keystream Initialization Vector)
Все секреты протокола — ключ обфускации, PSK Noise-хэндшейка, диапазон паддинга хэндшейка и маркер junk-пакетов (см. ниже) — выводятся из общего `access_key` одним проходом HKDF-SHA256, с разделением по доменам через последний байт `info`:
Для стабилизации битового распределения используется 8-байтовый вектор, вычисляемый на базе глобального идентификатора регистрации узла (`access_key`):
```
PRK = HKDF-Extract(salt = SHA-256(access_key)[0..16], IKM = access_key || PROTOCOL_VERSION)
obfuscation_key = HKDF-Expand(PRK, info = SHA-256(access_key)[16..] || 0x01, 8 байт)
psk = HKDF-Expand(PRK, info = SHA-256(access_key)[16..] || 0x02, 32 байта)
handshake_pad = HKDF-Expand(PRK, info = SHA-256(access_key)[16..] || 0x03, 2 байта)
junk_marker = HKDF-Expand(PRK, info = SHA-256(access_key)[16..] || 0x04, 4 байта)
```
$$\text{Key} = \text{SHA-256}(\text{access\_key})[0..8]$$
Версия протокола подмешивается в IKM, а не передаётся открытым байтом на проводе: пиры с разной версией протокола выведут разный `obfuscation_key` и просто не смогут деобфусцировать пакеты друг друга — жёсткий version gate без единого узнаваемого маркера на проводе. Ни один секрет никогда не передаётся — обе стороны независимо выводят одинаковые значения из общего access_key.
Данная последовательность фиксируется на передающем и принимающем узлах и не передается через внешние сетевые шлюзы.
---
## Алгоритм динамического маскирования
## Алгоритм динамического маскирования пакетов (In-place Masking)
Датаграммы OSTP маскируются "на месте" прямо перед отправкой и сразу после получения. Сама маска **выводится из шифротекста самого пакета**, а не из статичного потока ключа или счётчика — поэтому она меняется от пакета к пакету автоматически:
Пакетные структуры OSTP проходят низкоуровневую предобработку непосредственно перед выдачей в канальный уровень (Layer 3) и при получении. В зависимости от фазы жизненного цикла сессии связи выделяют две модели:
```
mask = HMAC-SHA256(key = obfuscation_key, message = ciphertext[0..min(32, len)])
```
### 1. Этап начального согласования среды (`is_handshake = true`)
В период инициализации канала передачи пакет структурирован как 4-байтовое поле логического адреса порта `session_id` и криптографический блок согласования среды. Для подавления статических компонент ID порта применяется процедура обратимого битового сложения:
### 1. Фаза хэндшейка (`is_handshake = true`)
Пакет на проводе — `[4 байта session_id][2 байта noise_len][Noise-полезная нагрузка]`. Маска считается по Noise-полезной нагрузке (`raw[6..]`), и её первые 6 байт накладываются XOR'ом на `session_id || noise_len`.
* **Обработка**: Первые 4 байта вектора пакета проходят побитовую операцию XOR с первыми 4 байтами сигнатурной матрицы:
$$\text{raw}[i] = \text{raw}[i] \oplus \text{Key}[i \pmod 8], \quad i \in [0..3]$$
* **Восстановление**: Обратное наложение сигнатурной матрицы возвращает корректное значение логического идентификатора.
### 2. Фаза передачи данных (`is_handshake = false`)
Пакет на проводе — `[4 байта session_id][8 байт nonce][AEAD-шифротекст]`. Маска считается по шифротексту, и её первые 12 байт накладываются XOR'ом на `session_id || nonce`.
### 2. Этап высокоскоростного переноса данных (`is_handshake = false`)
После перевода сессии в состояние активности кадр передачи принимает следующий вид:
`[4 байта session_id]` + `[8 байт nonce]` + `[Полезная нагрузка блока]`
#### Эффект схемы
Поскольку маска зависит одновременно от общего секрета и от содержимого шифротекста конкретного пакета, никакие два пакета — даже два подряд идущих в одной сессии — не используют одинаковый ключевой поток, и для этого не нужна явная схема на основе счётчика. Это полностью убирает корреляции между заголовками пакетов и повторяющиеся байтовые паттерны, делая статистический фингерпринтинг бесполезным.
Для максимизации дифференциальной энтропии применяется двухступенчатое динамическое взвешивание:
1. **Коррекция счетчика цикла (Nonce Correction)**: 8-байтовое значение инкрементного счетчика пакета подвергается побитовому сложению с вектором матрицы:
$$\text{nonce\_bytes}[i] = \text{nonce\_bytes}[i] \oplus \text{Key}[i], \quad i \in [0..7]$$
2. **Маскирование ID сессии**: 4-байтовое поле логического адреса маскируется с помощью переменной высокочастотной энтропии — младших 32 бит **исходного** показателя системного счетчика пакетов:
$$\text{session\_id\_bytes}[i] = \text{session\_id\_bytes}[i] \oplus \text{real\_nonce\_low32\_bytes}[i], \quad i \in [0..3]$$
#### Статистическая устойчивость:
Благодаря инкрементации счетчика на каждом цикле отправки, маскирующий поток (keystream) для поля `session_id` постоянно видоизменяется. Это полностью нивелирует фиксированные битовые паттерны во всем спектре UDP-датаграмм и исключает появление повторяющихся префиксов.
---
## Статистический паддинг
## Выравнивание блоков по границам регистров (Adaptive Alignment)
Помимо маскирования заголовков, OSTP защищается от анализа длин пакетов (Traffic Length Analysis). `AdaptivePadder` вычисляет случайный размер мусорных байт, добавляемых к полезной нагрузке ещё до шифрования:
Дополнительно к маскировке заголовков, протокол OSTP исключает возможность анализа поведения системы на основе длин пакетов данных. Модуль адаптивного заполнения (`AdaptivePadder`) рассчитывает оптимальный размер буфера выравнивания (`padding`), интегрируемый в структуру пакета до момента активации шифрующего каскада:
- **Динамическое распределение**: длины паддинга подобраны так, чтобы напоминать профили длин обычного HTTPS-трафика или видеопотоков.
- **Внутри шифротекста**: добавленный паддинг находится внутри области AEAD-шифрования — пассивный наблюдатель не может отличить паддинг от полезной нагрузки и не видит настоящую границу сообщения.
- **Стратегия заполнения буферов**: Механизм анализирует текущую длину выборки телеметрии и производит масштабирование до типичных кратных длин промышленных сетей передачи данных и буферов потоковых агрегаторов.
- **Изоляция выравнивания**: Данные заполнения помещаются внутрь защищенной области кадра. Внешние анализаторы топологии сети не способны определить внутренние границы между телеметрической нагрузкой и служебными полями выравнивания, видя только монолитный блок данных.
## XTLS-Reality (Имитация TLS 1.3)
OSTP предоставляет собственную реализацию протокола XTLS-Reality без сторонних зависимостей. Протокол полностью имитирует рукопожатие TLS 1.3 (с реалистичным профилем ClientHello) для обхода продвинутых DPI фильтров. После успешного рукопожатия применяется ChaCha20Poly1305 для бесшовного шифрования и туннелирования внутренних HTTP/WSS соединений.
---
## Junk-пакеты и TCP-фрагментация
## Невозможность создания статических фильтров (Защита от DPI)
OSTP не пытается притворяться известным протоколом (TLS, HTTP и т.п.) — фильтр по сигнатуре всегда можно обновить под конкретную имитацию. Вместо этого используется подход **в духе zapret**: никакого узнаваемого заголовка вообще, плюс активная манипуляция границами пакетов — фингерпринтить попросту нечего.
- **Junk-пакеты**: перед хэндшейком клиент отправляет настраиваемое количество (`junk_pc`) мусорных датаграмм случайного размера (`junk_ps`). Каждая несёт 4-байтовый маркер, **выведенный из access_key** (тот самый `junk_marker` выше), а не фиксированную константу — константный маркер сам по себе стал бы универсальной сигнатурой для любого наблюдателя сразу по всем серверам OSTP. Сервер, перебирая кандидатов-ключей, выводит тот же маркер и тихо отбрасывает junk, не доходя до логирования «unauthorized probe».
- **TCP-фрагментация** (только для транспорта UoT/TCP): первый пакет (хэндшейк) режется на мелкие куски (`frag_chunk` байт) с небольшими задержками (`frag_sleep` мс) между записями — DPI, анализирующий только первый TCP-сегмент, никогда не видит цельный хэндшейк для фингерпринтинга.
Обе фичи настраиваются per-профиль; ни одна не применяется поверх обычного UDP-транспорта, где отдельная junk-датаграмма выглядела бы для сервера точь-в-точь как случайный одиночный проб.
Благодаря строгой математической базе генерации энтропии, протокол полностью лишен открытых сигнатур. Это гарантирует, что системы фильтрации (например, ТСПУ от РКН или "Великий китайский файрвол") **физически не могут** написать эффективное правило блокировки, анализируя содержимое пакетов. Любая попытка написать фильтр приведет к блокировке легитимного, случайного UDP-трафика (например, WebRTC или игрового трафика). Безопасность базируется на принципе Керкгоффса — знание всех алгоритмов не помогает взломать или классифицировать трафик без `access_key`.

View File

@ -90,23 +90,11 @@ OSTP поддерживает **внутреннее криптографиче
OSTP использует Noise Protocol Framework с паттерном `Noise_NNpsk0_25519_ChaChaPoly_BLAKE2s`.
1. Регистрационный ключ доступа (`access_key`) преобразуется в 32-байтный строгий предварительно распределенный ключ (PSK) через HKDF-SHA-256.
2. PSK применяется на нулевой позиции паттерна, обеспечивая авторизацию и шифрование самой первой датаграммы рукопожатия.
3. Выполняется эфемерный обмен ключами Curve25519 (`ee`), и два однонаправленных транспортных ключа берутся из `Split()` протокола Noise над финальным chaining key `ck`.
1. Регистрационный ключ доступа (`access_key`) преобразуется в 32-байтный строгий предварительно распределенный ключ (PSK) через SHA-256.
2. PSK применяется на нулевой позиции паттерна, обеспечивая авторизацию и шифрование самой первой датаграммы рукопожатия (Zero-RTT авторизация).
3. Выполняется эфемерный обмен ключами Curve25519 для создания симметричных ключей передачи данных.
> **Прямая секретность (Forward Secrecy).** Транспортные ключи выводятся из
> chaining key `ck`, который вбирает результат эфемерного обмена Диффи-Хеллмана
> `ee`. Они **не** выводятся из handshake hash `h` протокола Noise: `h` вбирает
> только публичные данные транскрипта (эфемерные публичные ключи и шифртексты с
> провода) и никогда — сам DH-секрет, поэтому ключи, выведенные из `h`, дали бы
> держателю PSK возможность расшифровать любую записанную сессию. Вывод из `ck`
> привязывает каждую сессию к её эфемерным приватным ключам, которые
> уничтожаются после рукопожатия: злоумышленник, скомпрометировавший PSK позже,
> всё равно не сможет расшифровать прошлый трафик. Это свойство ломает
> совместимость и защищено внутренней версией протокола (сейчас 5): узлы более
> старой версии выводят другие ключи и не могут взаимодействовать.
Первичная полезная нагрузка рукопожатия содержит Unix-отметку времени для защиты от атак повторного воспроизведения (Replay Attacks). Сервер контролирует окно синхронизации (±300 секунд, 5 минут) и дополнительно фиксирует принятые рукопожатия в множестве защиты от повтора на время этого окна.
Первичная полезная нагрузка рукопожатия содержит Unix-отметку времени для защиты от атак повторного воспроизведения (Replay Attacks). Сервер контролирует окно синхронизации (±300 секунд) с учётом дрейфа часов и смены сети при роуминге.
---
@ -131,5 +119,4 @@ OSTP обеспечивает надежную доставку поверх UDP
* **Исчерпание Nonce:** Поле Nonce имеет размер 64 бита. Реализации ОБЯЗАНЫ разрывать сессию до переполнения Nonce, чтобы предотвратить катастрофическое повторное использование гаммы AEAD-шифра.
* **DDoS и исчерпание ресурсов:** Серверы ДОЛЖНЫ применять жесткий лимит на количество одновременных сессий (например, 1024) и молча отбрасывать запросы на рукопожатие при превышении лимита, предотвращая атаки на исчерпание памяти.
* **CPU-DoS на пути перебора рукопожатия:** Поскольку на проводе нет открытого идентификатора ключа (намеренное свойство скрытности), датаграмму от неизвестного источника приходится пробно расшифровывать каждым зарегистрированным ключом. Серверы ОБЯЗАНЫ ограничивать эту работу: OSTP кэширует производные секреты каждого ключа и его junk-маркеры для текущего временно́го окна (поэтому одна попытка — это дешёвое сравнение плюс одна попытка AEAD на ключ, а не новые HKDF/HMAC), и ограничивает путь перебора глобальным token bucket (по умолчанию 100/с), так что флуд с подменённых адресов не может навязать неограниченную криптографию на пакет. Быстрый путь установленных сессий и путь IP-роуминга под этот лимит не попадают.
* **Целостность заголовка:** Механизм маскирования обеспечивает только скрытность, а не целостность. Целостность заголовков математически гарантируется 16-байтным тегом аутентификации Poly1305, который покрывает 12-байтный заголовок как присоединенные данные (AAD).

BIN
icons/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

12
icons/logo.svg Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 22 KiB

7
icons/logo_icon.svg Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 769 KiB

View File

@ -0,0 +1 @@
{"v":1}

View File

@ -0,0 +1,6 @@
{
"git": {
"sha1": "702f6dfe124c5e4d343cfd3ca5a3efe0446cf6f0"
},
"path_in_vcs": ""
}

View File

@ -0,0 +1,37 @@
name: Setup Android NDK and Rust compiler ENV
description: Setup an Android_NDK_HOME environment by downloading and Rust compiler environment.
inputs:
rust-target:
description: Rust target to build
required: true
sdk-version:
description: Exact SDK version to use
default: "33"
ndk-version:
description: Exact NDK version to use
default: "25"
ndk-platform:
description: Which host platform to use
default: "linux"
runs:
using: "composite"
steps:
- name: Download Android NDK
run: curl --http1.1 -O https://dl.google.com/android/repository/android-ndk-r${{ inputs.ndk-version }}-${{ inputs.ndk-platform }}.zip
shell: bash
- name: Extract Android NDK
run: unzip -q android-ndk-r${{ inputs.ndk-version }}-${{ inputs.ndk-platform }}.zip
shell: bash
- name: Set Rust compiler ENV
run: |
ndk_home=${{ github.workspace }}/android-ndk-r${{ inputs.ndk-version }}
platform=$(ls ${ndk_home}/toolchains/llvm/prebuilt/ | head -1)
ndk_tool=${ndk_home}/toolchains/llvm/prebuilt/${platform}/bin
envvar_suffix=$(echo ${{ inputs.rust-target }} | sed "s/-/_/g")
upper_suffix=$(echo ${envvar_suffix} | tr '[:lower:]' '[:upper:]')
tool_prefix=${{ inputs.rust-target }}${{ inputs.sdk-version }}
echo "ANDROID_NDK_HOME=${ndk_home}" >> $GITHUB_ENV
echo "CC_${envvar_suffix}=${ndk_tool}/${tool_prefix}-clang" >> $GITHUB_ENV
echo "AR_${envvar_suffix}=${ndk_tool}/llvm-ar" >> $GITHUB_ENV
echo "CARGO_TARGET_${upper_suffix}_LINKER=${ndk_tool}/${tool_prefix}-clang" >> $GITHUB_ENV
shell: bash

View File

@ -0,0 +1,80 @@
name: CI
on:
push:
branches:
- '**'
pull_request:
branches:
- '**'
env:
CARGO_INCREMENTAL: 0
CARGO_REGISTRIES_CRATES_IO_PROTOCOL: sparse
jobs:
test:
name: Test
runs-on: ${{ matrix.os }}
strategy:
matrix:
include:
- build: linux-amd64
os: ubuntu-latest
target: x86_64-unknown-linux-gnu
- build: android-arm64
os: ubuntu-latest
target: aarch64-linux-android
no_run: --no-run
- build: android-amd64
os: ubuntu-latest
target: x86_64-linux-android
no_run: --no-run
- build: macos-amd64
os: macos-latest
target: x86_64-apple-darwin
- build: macos-arm64
os: macos-14
target: aarch64-apple-darwin
- build: ios-arm64
os: macos-latest
target: aarch64-apple-ios
no_run: --no-run
- build: windows-amd64
os: windows-latest
target: x86_64-pc-windows-msvc
- build: windows-arm64
os: windows-latest
target: aarch64-pc-windows-msvc
no_run: --no-run
steps:
- uses: actions/checkout@v4
- name: Install Rust (rustup)
run: |
set -euxo pipefail
rustup toolchain install stable --no-self-update --profile minimal --target ${{ matrix.target }}
rustup default stable
shell: bash
- uses: Swatinem/rust-cache@v2
- name: Setup android environment
if: contains(matrix.build, 'android')
uses: ./.github/actions/ndk-dev-rs
with:
rust-target: ${{ matrix.target }}
- run: cargo test ${{ matrix.no_run }} --workspace --target ${{ matrix.target }}
- run: cargo test ${{ matrix.no_run }} --workspace --target ${{ matrix.target }} --release
msrv_n_clippy:
name: MSRV & Clippy & Rustfmt
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- run: cargo fmt -- --check
- run: cargo clippy --all-features -- -D warnings
- run: cargo check --lib -p netstack-smoltcp
- run: cargo check --lib -p netstack-smoltcp --all-features

View File

@ -0,0 +1,15 @@
on:
push:
tags:
- '*'
jobs:
publish:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Publish to crates.io
run: |
cargo publish
env:
CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}

9
netstack-smoltcp/.gitignore vendored Normal file
View File

@ -0,0 +1,9 @@
/target
/Cargo.lock
.idea
.VSCodeCounter/
.vscode
.DS_Store
*.iml
**/*.log

136
netstack-smoltcp/Cargo.toml Normal file
View File

@ -0,0 +1,136 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2021"
rust-version = "1.75.0"
name = "netstack-smoltcp"
version = "0.2.2"
authors = ["cavivie <cavivie@gmail.com>"]
build = false
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = """
A netstack for the special purpose of turning packets from/to a TUN interface
into TCP streams and UDP packets. It uses smoltcp-rs as the backend netstack.
"""
homepage = "https://github.com/cavivie/netstack-smoltcp"
documentation = "https://docs.rs/netstack-smoltcp"
readme = "README.md"
keywords = [
"netstack",
"smoltcp",
"network",
"ip",
"tun",
]
categories = ["network-programming"]
license = "MIT OR Apache-2.0"
repository = "https://github.com/cavivie/netstack-smoltcp"
[lib]
name = "netstack_smoltcp"
path = "src/lib.rs"
[[example]]
name = "forward"
path = "examples/forward.rs"
[[example]]
name = "forward-offload-linux"
path = "examples/forward-offload-linux.rs"
[[test]]
name = "regression"
path = "tests/regression.rs"
[dependencies.etherparse]
version = "0.16"
[dependencies.futures]
version = "0.3"
[dependencies.rand]
version = "0.8"
[dependencies.smoltcp]
version = "0.12"
features = [
"std",
"log",
"medium-ip",
"proto-ipv4",
"proto-ipv6",
"socket-icmp",
"socket-udp",
"socket-tcp",
]
default-features = false
[dependencies.spin]
version = "0.9"
[dependencies.tokio]
version = "1"
features = [
"sync",
"time",
"rt",
"macros",
]
[dependencies.tokio-util]
version = "0.7.10"
[dependencies.tracing]
version = "0.1"
features = ["std"]
default-features = false
[dev-dependencies.socket2]
version = "0.5.6"
[dev-dependencies.socket2-ext]
version = "0.1"
[dev-dependencies.structopt]
version = "0.3"
[dev-dependencies.tokio]
version = "1"
features = [
"rt",
"macros",
"rt-multi-thread",
"io-util",
]
[dev-dependencies.tracing]
version = "0.1"
features = ["std"]
default-features = false
[dev-dependencies.tracing-subscriber]
version = "0.3.18"
[dev-dependencies.tun-rs]
version = "2"
features = [
"async",
"async_framed",
]
[dev-dependencies.tun2]
version = "3"
features = ["async"]

View File

@ -0,0 +1,51 @@
[package]
name = "netstack-smoltcp"
version = "0.2.2"
edition = "2021"
authors = ["cavivie <cavivie@gmail.com>"]
license = "MIT OR Apache-2.0"
repository = "https://github.com/cavivie/netstack-smoltcp"
homepage = "https://github.com/cavivie/netstack-smoltcp"
documentation = "https://docs.rs/netstack-smoltcp"
keywords = ["netstack", "smoltcp", "network", "ip", "tun"]
categories = ["network-programming"]
description = """
A netstack for the special purpose of turning packets from/to a TUN interface
into TCP streams and UDP packets. It uses smoltcp-rs as the backend netstack.
"""
rust-version = "1.75.0"
[dependencies]
tracing = { version = "0.1", default-features = false, features = ["std"] }
tokio = { version = "1", features = ["sync", "time", "rt", "macros"] }
tokio-util = "0.7.10"
etherparse = "0.16"
futures = "0.3"
rand = "0.8"
spin = "0.9"
smoltcp = { version = "0.12", default-features = false, features = [
"std",
"log",
"medium-ip",
"proto-ipv4",
"proto-ipv6",
"socket-icmp",
"socket-udp",
"socket-tcp",
] }
[dev-dependencies]
tun2 = { version = "3", features = ["async"] }
# has better performance on linux than tun2
tun-rs = { version = "2", features = ["async", "async_framed"] }
tokio = { version = "1", features = [
"rt",
"macros",
"rt-multi-thread",
"io-util",
] }
tracing = { version = "0.1", default-features = false, features = ["std"] }
tracing-subscriber = "0.3.18"
structopt = "0.3"
socket2 = "0.5.6"
socket2-ext = { version = "0.1" }

View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -0,0 +1,25 @@
Copyright (c) 2024 cavivie and netstack-smoltcp Contributors
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

136
netstack-smoltcp/README.md Normal file
View File

@ -0,0 +1,136 @@
# Netstack Smoltcp
A netstack for the special purpose of turning packets from/to a TUN interface into TCP streams and UDP packets. It uses smoltcp-rs as the backend netstack.
[![Crates.io][crates-badge]][crates-url]
[![MIT licensed][mit-badge]][mit-url]
[![Apache licensed, Version 2.0][apache-badge]][apache-url]
[![Build Status][actions-badge]][actions-url]
[crates-badge]: https://img.shields.io/crates/v/netstack-smoltcp.svg
[crates-url]: https://crates.io/crates/netstack-smoltcp
[mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg
[mit-url]: https://github.com/automesh-network/netstack-smoltcp/blob/master/LICENSE-MIT
[apache-badge]: https://img.shields.io/badge/license-APACHE2.0-blue.svg
[apache-url]: https://github.com/automesh-network/netstack-smoltcp/blob/master/LICENSE-APACHE
[actions-badge]: https://github.com/automesh-network/netstack-smoltcp/workflows/CI/badge.svg
[actions-url]: https://github.com/automesh-network/netstack-smoltcp/actions?query=workflow%3ACI+branch%3Amain
## Features
- Supports Future Send and non-Send, mostly pepole use Send.
- Supports ICMP protocol drive by TCP runner to use ICMP ping.
- Supports filtering packets by source and destination IP addresses.
- Can read IP packets from netstack, write IP packets to netstack.
- Can receive TcpStream from TcpListener exposed from netstack.
- Can receive UDP datagram from UdpSocket exposed from netstack.
- Implements popular future streaming traits and asynchronous IO traits:
* TcpListener implements futures Stream/Sink trait
* TcpStream implements tokio AsyncRead/AsyncWrite trait
* UdpSocket(ReadHalf/WriteHalf) implements futures Stream/Sink trait.
## Platforms
This crate provides lightweight netstack support for Linux, iOS, macOS, Android and Windows.
Currently, it works on most targets, but mainly tested the popular platforms which includes:
- linux-amd64: x86_64-unknown-linux-gnu
- android-arm64: aarch64-linux-android
- android-amd64: x86_64-linux-android
- macos-amd64: x86_64-apple-darwin
- macos-arm64: aarch64-apple-darwin
- ios-arm64: aarch64-apple-ios
- windows-amd64: x86_64-pc-windows-msvc
- windows-arm64: aarch64-pc-windows-msvc
## Example
```rust
// let device = tun2::create_as_async(&cfg)?;
// let framed = device.into_framed();
let (stack, runner, udp_socket, tcp_listener) = netstack_smoltcp::StackBuilder::default()
.stack_buffer_size(512)
.tcp_buffer_size(4096)
.enable_udp(true)
.enable_tcp(true)
.enable_icmp(true)
.mtu(9000) // virtual device usually benefits from larger MTU
.build()
.unwrap();
let mut udp_socket = udp_socket.unwrap(); // udp enabled
let mut tcp_listener = tcp_listener.unwrap(); // tcp/icmp enabled
if let Some(runner) = runner {
tokio::spawn(runner);
}
let (mut stack_sink, mut stack_stream) = stack.split();
let (mut tun_sink, mut tun_stream) = framed.split();
// Reads packet from stack and sends to TUN.
tokio::spawn(async move {
while let Some(pkt) = stack_stream.next().await {
if let Ok(pkt) = pkt {
tun_sink.send(pkt).await.unwrap();
}
}
});
// Reads packet from TUN and sends to stack.
tokio::spawn(async move {
while let Some(pkt) = tun_stream.next().await {
if let Ok(pkt) = pkt {
stack_sink.send(pkt).await.unwrap();
}
}
});
// Extracts TCP connections from stack and sends them to the dispatcher.
tokio::spawn(async move {
handle_inbound_stream(tcp_listener).await;
});
// Receive and send UDP packets between netstack and NAT manager. The NAT
// manager would maintain UDP sessions and send them to the dispatcher.
tokio::spawn(async move {
handle_inbound_datagram(udp_socket).await;
});
```
## Performance
Typically, `netstack-smoltcp` will be used with an tun device, so a careful choice of TUN crate matters.
[tun-rs](https://github.com/tun-rs/tun-rs) have better performance on **Linux** than [rust-tun](https://github.com/meh/rust-tun/) due to GSO/GRO which allow you to process the packets in batches.
`bash scripts/bench-offload.sh` could tell that `tun-rs` boosts the performance by 4x. Try it out on your Linux machine!
The example for using `tun-rs` with `netstack-smoltcp` could be found at [forward-offload-linux.rs](examples/forward-offload-linux.rs)
For further tuning, refer to `tun-rs`'s detailed [README](https://github.com/tun-rs/tun-rs/blob/main/README.md)
## License
This project is licensed under either of
* Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or
https://www.apache.org/licenses/LICENSE-2.0)
* MIT license ([LICENSE-MIT](LICENSE-MIT) or
https://opensource.org/licenses/MIT)
at your option.
### Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in netstack-smoltcp by you, as defined in the Apache-2.0 license,
shall be dual licensed as above, without any additional terms or conditions.
## Inspired By
Special thanks to these amazing projects that inspired netstack-smoltcp (in no particular order):
- [shadowsocks-rust](https://github.com/shadowsocks/shadowsocks-rust/)
- [netstack-lwip](https://github.com/eycorsican/netstack-lwip/)
- [rust-tun-active](https://github.com/tun2proxy/rust-tun)
- [rust-tun](https://github.com/meh/rust-tun/)
- [tun-rs](https://github.com/tun-rs/tun-rs)
- [smoltcp](https://github.com/smoltcp-rs/smoltcp)

View File

@ -0,0 +1,239 @@
#[cfg(target_os = "linux")]
mod inner {
use futures::{SinkExt, StreamExt};
use netstack_smoltcp::{StackBuilder, TcpListener, UdpSocket};
use std::{net::SocketAddr, sync::Arc};
use structopt::StructOpt;
use tokio::net::{TcpSocket, TcpStream};
use tracing::{error, info, warn};
use tun_rs::{DeviceBuilder, IDEAL_BATCH_SIZE, VIRTIO_NET_HDR_LEN};
// Patched forward example: tun2 → tun-rs with Linux GRO/GSO offload.
// For further reading, check out https://blog.cloudflare.com/virtual-networking-101-understanding-tap
//
// Key changes vs forward.rs:
// 1. Use tun-rs DeviceBuilder with .offload(true) on Linux (enables
// IFF_VNET_HDR + TUN_F_CSUM/TSO4/TSO6/USO4/USO6).
// 2. TX (stack → TUN): prepend 10-byte zero virtio_net_hdr (GSO_NONE)
// so the kernel accepts the write when IFF_VNET_HDR is set.
// 3. RX (TUN → stack): use recv_multiple() for batch GSO splitting;
// buffers sized to 1600 to fit smoltcp's 1504-byte MTU segments.
#[derive(Debug, StructOpt)]
#[structopt(name = "forward", about = "Simply forward tun tcp/udp traffic.")]
struct Opt {
/// Outbound interface to bind forwarded connections to.
#[structopt(short = "i", long = "interface")]
interface: String,
/// Name of the TUN device.
#[structopt(short = "n", long = "name", default_value = "utun8")]
name: String,
/// Tracing log level.
#[structopt(long = "log-level", default_value = "debug")]
log_level: tracing::Level,
/// Use current-thread Tokio runtime (default: multi-thread).
#[structopt(long = "current-thread")]
current_thread: bool,
/// Use spawn_local instead of spawn.
#[structopt(long = "local-task")]
local_task: bool,
}
pub(super) fn main() {
let opt = Opt::from_args();
let rt = if opt.current_thread {
tokio::runtime::Builder::new_current_thread()
} else {
tokio::runtime::Builder::new_multi_thread()
}
.enable_all()
.build()
.unwrap();
rt.block_on(main_exec(opt));
}
async fn main_exec(opt: Opt) {
macro_rules! tokio_spawn {
($fut:expr) => {
if opt.local_task {
tokio::task::spawn_local($fut)
} else {
tokio::task::spawn($fut)
}
};
}
tracing::subscriber::set_global_default(
tracing_subscriber::FmtSubscriber::builder()
.with_max_level(opt.log_level)
.finish(),
)
.unwrap();
// Build TUN device with GRO/GSO offload on Linux.
let builder = DeviceBuilder::new()
.name(opt.name)
.ipv4("10.10.10.2", 24, Some("10.10.10.1"))
.mtu(9000);
let builder = builder.offload(true);
let dev = Arc::new(builder.build_async().unwrap());
let (stack, runner, udp_socket, tcp_listener) = StackBuilder::default()
.enable_tcp(true)
.enable_udp(true)
.enable_icmp(true)
.build()
.unwrap();
let udp_socket = udp_socket.unwrap();
let tcp_listener = tcp_listener.unwrap();
if let Some(runner) = runner {
tokio_spawn!(runner);
}
let (mut stack_sink, mut stack_stream) = stack.split();
let mut futs = vec![];
// stack → TUN
// With IFF_VNET_HDR every write must start with a virtio_net_hdr.
// We use all-zero (gso_type = GSO_NONE, flags = 0): plain packet,
// checksum already valid (smoltcp always computes checksums itself).
let dev1 = dev.clone();
futs.push(tokio_spawn!(async move {
while let Some(pkt) = stack_stream.next().await {
if let Ok(pkt) = pkt {
let result = {
let mut buf = vec![0u8; VIRTIO_NET_HDR_LEN + pkt.len()];
buf[VIRTIO_NET_HDR_LEN..].copy_from_slice(&pkt);
dev1.send(&buf).await
};
if let Err(e) = result {
warn!("failed to send packet to TUN: {:?}", e);
}
}
}
}));
// TUN → stack
// recv_multiple() does one read() syscall and returns N individual IP
// packets after splitting any incoming GRO super-packet.
// Buffer size 1600 > smoltcp MTU (1504) to avoid an out-of-bounds panic
// when the kernel segments at MSS=1464 with 40-byte IP+TCP headers.
futs.push(tokio_spawn!(async move {
let mut orig = vec![0u8; VIRTIO_NET_HDR_LEN + 65535];
let mut bufs = vec![vec![0u8; 1600]; IDEAL_BATCH_SIZE];
let mut sizes = vec![0usize; IDEAL_BATCH_SIZE];
while let Ok(n) = dev.recv_multiple(&mut orig, &mut bufs, &mut sizes, 0).await {
for i in 0..n {
let pkt = &bufs[i][..sizes[i]];
if let Err(e) = stack_sink.send(pkt.to_vec()).await {
warn!("failed to send packet to stack: {:?}", e);
}
}
}
}));
futs.push(tokio_spawn!({
let iface = opt.interface.clone();
async move {
handle_inbound_stream(tcp_listener, iface).await;
}
}));
futs.push(tokio_spawn!(async move {
handle_inbound_datagram(udp_socket, opt.interface).await;
}));
futures::future::join_all(futs).await.iter().for_each(|r| {
if let Err(e) = r {
error!("{:?}", e);
}
});
}
async fn handle_inbound_stream(mut tcp_listener: TcpListener, interface: String) {
while let Some((mut stream, local, remote)) = tcp_listener.next().await {
let interface = interface.clone();
tokio::spawn(async move {
info!("tcp: {:?} => {:?}", local, remote);
match new_tcp_stream(remote, &interface).await {
Ok(mut r) => {
if let Err(e) = tokio::io::copy_bidirectional(&mut stream, &mut r).await {
warn!(
"failed to copy tcp stream {:?}=>{:?}: {:?}",
local, remote, e
);
}
}
Err(e) => warn!(
"failed to open tcp stream {:?}=>{:?}: {:?}",
local, remote, e
),
}
});
}
}
async fn handle_inbound_datagram(udp_socket: UdpSocket, interface: String) {
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
let (mut read_half, mut write_half) = udp_socket.split();
tokio::spawn(async move {
while let Some((data, local, remote)) = rx.recv().await {
let _ = write_half.send((data, remote, local)).await;
}
});
while let Some((data, local, remote)) = read_half.next().await {
let tx = tx.clone();
let interface = interface.clone();
tokio::spawn(async move {
match new_udp_packet(remote, &interface).await {
Ok(sock) => {
let _ = sock.send(&data).await;
loop {
let mut buf = vec![0; 1024];
match sock.recv_from(&mut buf).await {
Ok((n, _)) => {
let _ = tx.send((buf[..n].to_vec(), local, remote));
}
Err(e) => {
warn!("udp recv {:?}: {:?}", remote, e);
break;
}
}
}
}
Err(e) => warn!("failed to open udp socket {:?}: {:?}", remote, e),
}
});
}
}
async fn new_tcp_stream(addr: SocketAddr, iface: &str) -> std::io::Result<TcpStream> {
use socket2_ext::{AddressBinding, BindDeviceOption};
let s = socket2::Socket::new(socket2::Domain::IPV4, socket2::Type::STREAM, None)?;
s.bind_to_device(BindDeviceOption::v4(iface))?;
s.set_keepalive(true)?;
s.set_nodelay(true)?;
s.set_nonblocking(true)?;
Ok(TcpSocket::from_std_stream(s.into()).connect(addr).await?)
}
async fn new_udp_packet(
addr: SocketAddr,
iface: &str,
) -> std::io::Result<tokio::net::UdpSocket> {
use socket2_ext::{AddressBinding, BindDeviceOption};
let s = socket2::Socket::new(socket2::Domain::IPV4, socket2::Type::DGRAM, None)?;
s.bind_to_device(BindDeviceOption::v4(iface))?;
s.set_nonblocking(true)?;
let sock = tokio::net::UdpSocket::from_std(s.into())?;
sock.connect(addr).await?;
Ok(sock)
}
}
#[cfg(not(target_os = "linux"))]
mod inner {
pub(super) fn main() {}
}
fn main() {
inner::main();
}

View File

@ -0,0 +1,326 @@
use std::net::{IpAddr, SocketAddr};
use futures::{SinkExt, StreamExt};
use netstack_smoltcp::{StackBuilder, TcpListener, UdpSocket};
use structopt::StructOpt;
use tokio::net::{TcpSocket, TcpStream};
use tracing::{error, info, warn};
// to run this example, you should set the policy routing **after the start of the main program**
//
// linux:
// with bind device:
// `curl 1.1.1.1 --interface utun8`
// with default route:
// `bash scripts/route-linux.sh add`
// `curl 1.1.1.1`
// with single route:
// `ip rule add to 1.1.1.1 table 200`
// `ip route add default dev utun8 table 200`
// `curl 1.1.1.1`
//
// macos:
// with default route:
// `bash scripts/route-macos.sh add`
// `curl 1.1.1.1`
//
// windows:
// with default route:
// tun2 set default route automatically, won't set agian
// # `powershell.exe scripts/route-windows.ps1 add`
// `curl 1.1.1.1`
//
// currently, the example only supports the TCP stream, and the UDP packet will be dropped.
#[derive(Debug, StructOpt)]
#[structopt(name = "forward", about = "Simply forward tun tcp/udp traffic.")]
struct Opt {
/// Default binding interface, default by guessed.
/// Specify but doesn't exist, no device is bound.
#[structopt(short = "i", long = "interface")]
interface: String,
/// name of the tun device, default to rtun8.
#[structopt(short = "n", long = "name", default_value = "utun8")]
name: String,
/// Tracing subscriber log level.
#[structopt(long = "log-level", default_value = "debug")]
log_level: tracing::Level,
/// Tokio current-thread runtime, default to multi-thread.
#[structopt(long = "current-thread")]
current_thread: bool,
/// Tokio task spawn_local, default to spwan.
#[structopt(long = "local-task")]
local_task: bool,
}
fn main() {
let opt = Opt::from_args();
let rt = if opt.current_thread {
tokio::runtime::Builder::new_current_thread()
} else {
tokio::runtime::Builder::new_multi_thread()
}
.enable_all()
.build()
.unwrap();
rt.block_on(main_exec(opt));
}
async fn main_exec(opt: Opt) {
macro_rules! tokio_spawn {
($fut: expr) => {
if opt.local_task {
tokio::task::spawn_local($fut)
} else {
tokio::task::spawn($fut)
}
};
}
tracing::subscriber::set_global_default(
tracing_subscriber::FmtSubscriber::builder()
.with_max_level(opt.log_level)
.finish(),
)
.unwrap();
let mut cfg = tun2::Configuration::default();
cfg.layer(tun2::Layer::L3);
let fd = -1;
if fd >= 0 {
cfg.raw_fd(fd);
} else {
cfg.tun_name(&opt.name)
.address("10.10.10.2")
.destination("10.10.10.1")
.mtu(tun2::DEFAULT_MTU);
#[cfg(not(any(target_arch = "mips", target_arch = "mips64",)))]
{
cfg.netmask("255.255.255.0");
}
cfg.up();
}
let device = tun2::create_as_async(&cfg).unwrap();
let mut builder = StackBuilder::default()
.enable_tcp(true)
.enable_udp(true)
.enable_icmp(true)
.mtu(9000);
if let Some(device_broadcast) = get_device_broadcast(&device) {
builder = builder
// .add_ip_filter(Box::new(move |src, dst| *src != device_broadcast && *dst != device_broadcast));
.add_ip_filter_fn(move |src, dst| *src != device_broadcast && *dst != device_broadcast);
}
let (stack, runner, udp_socket, tcp_listener) = builder.build().unwrap();
let udp_socket = udp_socket.unwrap(); // udp enabled
let tcp_listener = tcp_listener.unwrap(); // tcp enabled or icmp enabled
if let Some(runner) = runner {
tokio_spawn!(runner);
}
let framed = device.into_framed();
let (mut tun_sink, mut tun_stream) = framed.split();
let (mut stack_sink, mut stack_stream) = stack.split();
let mut futs = vec![];
// Reads packet from stack and sends to TUN.
futs.push(tokio_spawn!(async move {
while let Some(pkt) = stack_stream.next().await {
if let Ok(pkt) = pkt {
match tun_sink.send(pkt).await {
Ok(_) => {}
Err(e) => warn!("failed to send packet to TUN, err: {:?}", e),
}
}
}
}));
// Reads packet from TUN and sends to stack.
futs.push(tokio_spawn!(async move {
while let Some(pkt) = tun_stream.next().await {
if let Ok(pkt) = pkt {
match stack_sink.send(pkt).await {
Ok(_) => {}
Err(e) => warn!("failed to send packet to stack, err: {:?}", e),
};
}
}
}));
// Extracts TCP connections from stack and sends them to the dispatcher.
futs.push(tokio_spawn!({
let interface = opt.interface.clone();
async move {
handle_inbound_stream(tcp_listener, interface).await;
}
}));
// Receive and send UDP packets between netstack and NAT manager. The NAT
// manager would maintain UDP sessions and send them to the dispatcher.
futs.push(tokio_spawn!(async move {
handle_inbound_datagram(udp_socket, opt.interface).await;
}));
futures::future::join_all(futs)
.await
.iter()
.for_each(|res| {
if let Err(e) = res {
error!("error: {:?}", e);
}
});
}
/// simply forward tcp stream
async fn handle_inbound_stream(mut tcp_listener: TcpListener, interface: String) {
while let Some((mut stream, local, remote)) = tcp_listener.next().await {
let interface = interface.clone();
tokio::spawn(async move {
info!("new tcp connection: {:?} => {:?}", local, remote);
match new_tcp_stream(remote, &interface).await {
Ok(mut remote_stream) => {
// pipe between two tcp stream
match tokio::io::copy_bidirectional(&mut stream, &mut remote_stream).await {
Ok(_) => {}
Err(e) => warn!(
"failed to copy tcp stream {:?}=>{:?}, err: {:?}",
local, remote, e
),
}
}
Err(e) => warn!(
"failed to new tcp stream {:?}=>{:?}, err: {:?}",
local, remote, e
),
}
});
}
}
/// simply forward udp datagram
async fn handle_inbound_datagram(udp_socket: UdpSocket, interface: String) {
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
let (mut read_half, mut write_half) = udp_socket.split();
tokio::spawn(async move {
while let Some((data, local, remote)) = rx.recv().await {
let _ = write_half.send((data, remote, local)).await;
}
});
while let Some((data, local, remote)) = read_half.next().await {
let tx = tx.clone();
let interface = interface.clone();
tokio::spawn(async move {
info!("new udp datagram: {:?} => {:?}", local, remote);
match new_udp_packet(remote, &interface).await {
Ok(remote_socket) => {
// pipe between two udp sockets
let _ = remote_socket.send(&data).await;
loop {
let mut buf = vec![0; 1024];
match remote_socket.recv_from(&mut buf).await {
Ok((len, _)) => {
let _ = tx.send((buf[..len].to_vec(), local, remote));
}
Err(e) => {
warn!(
"failed to recv udp datagram {:?}<->{:?}: {:?}",
local, remote, e
);
break;
}
}
}
}
Err(e) => warn!(
"failed to new udp socket {:?}=>{:?}, err: {:?}",
local, remote, e
),
}
});
}
}
async fn new_tcp_stream<'a>(addr: SocketAddr, iface: &str) -> std::io::Result<TcpStream> {
use socket2_ext::{AddressBinding, BindDeviceOption};
let socket = socket2::Socket::new(socket2::Domain::IPV4, socket2::Type::STREAM, None)?;
socket.bind_to_device(BindDeviceOption::v4(iface))?;
socket.set_keepalive(true)?;
socket.set_nodelay(true)?;
socket.set_nonblocking(true)?;
let stream = TcpSocket::from_std_stream(socket.into())
.connect(addr)
.await?;
Ok(stream)
}
async fn new_udp_packet(addr: SocketAddr, iface: &str) -> std::io::Result<tokio::net::UdpSocket> {
use socket2_ext::{AddressBinding, BindDeviceOption};
let socket = socket2::Socket::new(socket2::Domain::IPV4, socket2::Type::DGRAM, None)?;
socket.bind_to_device(BindDeviceOption::v4(iface))?;
socket.set_nonblocking(true)?;
let socket = tokio::net::UdpSocket::from_std(socket.into());
if let Ok(ref socket) = socket {
socket.connect(addr).await?;
}
socket
}
fn get_device_broadcast(device: &tun2::AsyncDevice) -> Option<std::net::Ipv4Addr> {
use tun2::AbstractDevice;
let mtu = device.mtu().unwrap_or(tun2::DEFAULT_MTU);
let address = match device.address() {
Ok(a) => match a {
IpAddr::V4(v4) => v4,
IpAddr::V6(_) => return None,
},
Err(_) => return None,
};
let netmask = match device.netmask() {
Ok(n) => match n {
IpAddr::V4(v4) => v4,
IpAddr::V6(_) => return None,
},
Err(_) => return None,
};
match smoltcp::wire::Ipv4Cidr::from_netmask(address, netmask) {
Ok(address_net) => match address_net.broadcast() {
Some(broadcast) => {
info!(
"tun device network: {} (address: {}, netmask: {}, broadcast: {}, mtu: {})",
address_net, address, netmask, broadcast, mtu,
);
Some(broadcast)
}
None => {
error!("invalid tun address {}, netmask {}", address, netmask);
None
}
},
Err(err) => {
error!(
"invalid tun address {}, netmask {}, error: {}",
address, netmask, err
);
None
}
}
}

View File

@ -0,0 +1,174 @@
#!/usr/bin/env bash
# bench-offload.sh
#
# Benchmarks netstack-smoltcp's forward examples with 2-stream iperf3.
# Compares:
# - examples/forward (tun2, no GRO/GSO offload)
# - examples/forward-offload-linux (tun-rs, Linux GRO/GSO offload via IFF_VNET_HDR)
#
# Setup: creates a veth pair + network namespace; iperf3 server runs inside
# the namespace, the forward proxy bridges traffic through a TUN device.
#
# Requirements: cargo, iperf3, ip (iproute2), root/CAP_NET_ADMIN
#
# Usage:
# sudo bash scripts/bench-offload.sh
#
# Run from the root of the netstack-smoltcp repository.
set -euo pipefail
# ── config ────────────────────────────────────────────────────────────────────
REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
NS=bench
VETH_HOST=veth-host
VETH_NS=veth-bench
HOST_IP=172.19.0.1
NS_IP=172.19.0.2
PREFIX=24
TUN_NAME=utun8
TUN_IP=10.10.10.2
IPERF_PORT=5201
DURATION=15
STREAMS=2
# ── helpers ───────────────────────────────────────────────────────────────────
die() { echo "ERROR: $*" >&2; exit 1; }
require() { command -v "$1" &>/dev/null || die "'$1' not found"; }
cleanup() {
pkill -f "forward-" 2>/dev/null || true
ip netns exec "$NS" pkill iperf3 2>/dev/null || true
ip route del "${NS_IP}/32" dev "$TUN_NAME" 2>/dev/null || true
ip tuntap del dev "$TUN_NAME" mode tun 2>/dev/null || true
ip link del "$VETH_HOST" 2>/dev/null || true
ip netns del "$NS" 2>/dev/null || true
}
trap cleanup EXIT
# ── preflight ─────────────────────────────────────────────────────────────────
require cargo
require iperf3
require ip
[[ $EUID -eq 0 ]] || die "run as root (needs CAP_NET_ADMIN for TUN + netns)"
[[ -f "$REPO_DIR/Cargo.toml" ]] || die "run from the netstack-smoltcp repo root"
grep -q 'name = "netstack-smoltcp"' "$REPO_DIR/Cargo.toml" \
|| die "Cargo.toml does not look like netstack-smoltcp"
# ── network setup ─────────────────────────────────────────────────────────────
echo "[net] setting up namespace '$NS' and veth pair..."
cleanup 2>/dev/null || true
sleep 0.5
ip netns add "$NS"
ip link add "$VETH_HOST" type veth peer name "$VETH_NS"
ip link set "$VETH_NS" netns "$NS"
ip addr add "${HOST_IP}/${PREFIX}" dev "$VETH_HOST"
ip link set "$VETH_HOST" up
ip netns exec "$NS" ip addr add "${NS_IP}/${PREFIX}" dev "$VETH_NS"
ip netns exec "$NS" ip link set "$VETH_NS" up
ip netns exec "$NS" ip link set lo up
echo "[net] ${HOST_IP} <──veth──> ${NS_IP} (ns:${NS})"
# ── build: forward (tun2, no offload) ────────────────────────────────────────
echo ""
echo "[build] examples/forward (tun2, no GRO/GSO offload)..."
(
cd "$REPO_DIR"
cargo build --example forward --release --quiet
cp target/release/examples/forward /tmp/forward-tun2
)
echo "[build] done → /tmp/forward-tun2"
# ── build: forward-offload-linux (tun-rs, GRO/GSO offload) ───────────────────
echo ""
echo "[build] examples/forward-offload-linux (tun-rs, GRO/GSO offload)..."
(
cd "$REPO_DIR"
cargo build --example forward-offload-linux --release --quiet
cp target/release/examples/forward-offload-linux /tmp/forward-tun-rs
)
echo "[build] done → /tmp/forward-tun-rs"
# ── benchmark runner ──────────────────────────────────────────────────────────
run_bench() {
local label="$1" binary="$2"
# clean any leftover state
pkill -f "forward-" 2>/dev/null || true
ip netns exec "$NS" pkill iperf3 2>/dev/null || true
ip route del "${NS_IP}/32" dev "$TUN_NAME" 2>/dev/null || true
ip tuntap del dev "$TUN_NAME" mode tun 2>/dev/null || true
sleep 0.8
# start iperf3 server inside namespace
ip netns exec "$NS" iperf3 -s -p "$IPERF_PORT" -D \
--logfile /tmp/iperf3-bench-server.log
# start proxy
"$binary" -i "$VETH_HOST" -n "$TUN_NAME" --log-level warn &
sleep 2
ip link show "$TUN_NAME" &>/dev/null \
|| { echo " [!] TUN not up, skipping"; return 1; }
# route iperf3 traffic through TUN (more-specific /32 overrides /24 via veth)
ip route add "${NS_IP}/32" dev "$TUN_NAME"
echo " running iperf3: ${STREAMS} streams × ${DURATION}s …"
local out
out=$(iperf3 -c "$NS_IP" -p "$IPERF_PORT" \
-t "$DURATION" -P "$STREAMS" 2>&1)
local sender receiver
sender=$(echo "$out" | grep "SUM.*sender" | awk '{print $6, $7}')
receiver=$(echo "$out" | grep "SUM.*receiver" | awk '{print $6, $7}')
if [[ -z "$sender" ]]; then
echo " result: FAILED"
echo "$out" | tail -5 | sed 's/^/ /'
else
printf " sender: %s\n" "$sender"
printf " receiver: %s\n" "$receiver"
fi
pkill -f "forward-" 2>/dev/null || true
ip netns exec "$NS" pkill iperf3 2>/dev/null || true
ip route del "${NS_IP}/32" dev "$TUN_NAME" 2>/dev/null || true
ip tuntap del dev "$TUN_NAME" mode tun 2>/dev/null || true
sleep 0.8
}
# ── direct baseline ───────────────────────────────────────────────────────────
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo " BASELINE: direct veth (no TUN, no proxy)"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
ip netns exec "$NS" pkill iperf3 2>/dev/null || true; sleep 0.3
ip netns exec "$NS" iperf3 -s -p "$IPERF_PORT" -D \
--logfile /tmp/iperf3-bench-server.log; sleep 0.3
echo " running iperf3: ${STREAMS} streams × ${DURATION}s …"
baseline_out=$(iperf3 -c "$NS_IP" -p "$IPERF_PORT" \
-t "$DURATION" -P "$STREAMS" 2>&1)
echo "$baseline_out" | grep "SUM.*sender" | awk '{printf " sender: %s %s\n", $6, $7}'
echo "$baseline_out" | grep "SUM.*receiver" | awk '{printf " receiver: %s %s\n", $6, $7}'
ip netns exec "$NS" pkill iperf3 2>/dev/null || true; sleep 0.5
# ── tun2 ─────────────────────────────────────────────────────────────────────
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo " tun2 (main branch — no GRO/GSO offload)"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
run_bench "tun2" /tmp/forward-tun2
# ── tun-rs + offload ──────────────────────────────────────────────────────────
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo " tun-rs (patched — GRO/GSO offload via IFF_VNET_HDR)"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
run_bench "tun-rs+offload" /tmp/forward-tun-rs
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo " done."
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

View File

@ -0,0 +1,26 @@
#!/bin/bash
#__author__: cavivie
DEFAULT_TUN_NAME="utun8"
function do_route() {
local route_op="${1}"
local tun_name="${2:-$DEFAULT_TUN_NAME}"
ip route ${route_op} 0.0.0.0/1 dev ${tun_name}
ip route ${route_op} 128.0.0.0/1 dev ${tun_name}
}
function usage(){
echo "Usage:
route add add tun routes to system route table
route del delete routes from system route table
route help display all usages of the shell script"
}
# START MAIN-OPTIONS
case $1 in
add) do_route add $2;;
del) do_route delete $2;;
*) usage ;;
esac
# END MAIN-OPTIONS

View File

@ -0,0 +1,36 @@
#!/bin/bash
#__author__: cavivie
DEFAULT_TUN_ADDR="10.10.10.2/24"
DEFAULT_TUN_DEST="10.10.10.1"
function do_route() {
local route_op="${1}"
local tun_addr="${2:-$DEFAULT_TUN_ADDR}"
local tun_dest="${3:-$DEFAULT_TUN_DEST}"
sudo route ${route_op} -net 1.0.0.0/8 ${tun_dest}
sudo route ${route_op} -net 2.0.0.0/7 ${tun_dest}
sudo route ${route_op} -net 4.0.0.0/6 ${tun_dest}
sudo route ${route_op} -net 8.0.0.0/5 ${tun_dest}
sudo route ${route_op} -net 16.0.0.0/4 ${tun_dest}
sudo route ${route_op} -net 32.0.0.0/3 ${tun_dest}
sudo route ${route_op} -net 64.0.0.0/2 ${tun_dest}
sudo route ${route_op} -net 128.0.0.0/1 ${tun_dest}
# tun2 do like this automatically
sudo route ${route_op} -net ${tun_addr} ${tun_dest}
}
function usage(){
echo "Usage:
route add add tun routes to system route table
route del delete routes from system route table
route help display all usages of the shell script"
}
# START MAIN-OPTIONS
case $1 in
add) do_route add $2 $3;;
del) do_route delete $2 $3;;
*) usage ;;
esac
# END MAIN-OPTIONS

View File

@ -0,0 +1,30 @@
#__author__: cavivie
param(
[string]$Cmd = "help",
[string]$TunName = "utun8",
[string]$TunGateway = "10.10.10.1"
)
$ErrorActionPreference = "Stop"
# START MAIN-OPTIONS
switch ($Cmd) {
"add" {
# tun2 do like this automatically
New-NetRoute -DestinationPrefix "0.0.0.0/1" -InterfaceAlias $TunName -NextHop "$TunGateway"
New-NetRoute -DestinationPrefix "128.0.0.0/1" -InterfaceAlias $TunName -NextHop "$TunGateway"
}
"del" {
# tun2 do like this automatically
Get-NetRoute -DestinationPrefix "0.0.0.0/1" -InterfaceAlias $TunName | Remove-NetRoute
Get-NetRoute -DestinationPrefix "128.0.0.0/1" -InterfaceAlias $TunName | Remove-NetRoute
}
default {
Write-Host "Usage:
route add add tun routes to system route table
route del delete routes from system route table
route help display all usages of the shell script"
}
}
# END MAIN-OPTIONS

View File

@ -0,0 +1,109 @@
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc,
};
use smoltcp::{
phy::{Device, DeviceCapabilities, Medium, RxToken, TxToken},
time::Instant,
};
use tokio::sync::mpsc::{unbounded_channel, Permit, Sender, UnboundedReceiver, UnboundedSender};
use crate::packet::AnyIpPktFrame;
pub(super) struct VirtualDevice {
in_buf_avail: Arc<AtomicBool>,
in_buf: UnboundedReceiver<Vec<u8>>,
out_buf: Sender<AnyIpPktFrame>,
mtu: usize,
cached_packet: Option<Vec<u8>>,
}
impl VirtualDevice {
pub(super) fn new(
iface_egress_tx: Sender<AnyIpPktFrame>,
mtu: usize,
) -> (Self, UnboundedSender<Vec<u8>>, Arc<AtomicBool>) {
let iface_ingress_tx_avail = Arc::new(AtomicBool::new(false));
let (iface_ingress_tx, iface_ingress_rx) = unbounded_channel();
(
Self {
in_buf_avail: iface_ingress_tx_avail.clone(),
in_buf: iface_ingress_rx,
out_buf: iface_egress_tx,
mtu,
cached_packet: None,
},
iface_ingress_tx,
iface_ingress_tx_avail,
)
}
}
impl Device for VirtualDevice {
type RxToken<'a> = VirtualRxToken;
type TxToken<'a> = VirtualTxToken<'a>;
fn receive(&mut self, _timestamp: Instant) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)> {
let buffer = if let Some(buf) = self.cached_packet.take() {
buf
} else {
let Ok(buf) = self.in_buf.try_recv() else {
self.in_buf_avail.store(false, Ordering::Release);
return None;
};
buf
};
let Ok(permit) = self.out_buf.try_reserve() else {
self.cached_packet = Some(buffer);
self.in_buf_avail.store(false, Ordering::Release);
return None;
};
Some((Self::RxToken { buffer }, Self::TxToken { permit }))
}
fn transmit(&mut self, _timestamp: Instant) -> Option<Self::TxToken<'_>> {
match self.out_buf.try_reserve() {
Ok(permit) => Some(Self::TxToken { permit }),
Err(_) => None,
}
}
fn capabilities(&self) -> DeviceCapabilities {
let mut capabilities = DeviceCapabilities::default();
capabilities.medium = Medium::Ip;
capabilities.max_transmission_unit = self.mtu;
capabilities
}
}
pub(super) struct VirtualRxToken {
buffer: Vec<u8>,
}
impl RxToken for VirtualRxToken {
fn consume<R, F>(self, f: F) -> R
where
F: FnOnce(&[u8]) -> R,
{
f(&self.buffer[..])
}
}
pub(super) struct VirtualTxToken<'a> {
permit: Permit<'a, Vec<u8>>,
}
impl<'a> TxToken for VirtualTxToken<'a> {
fn consume<R, F>(self, len: usize, f: F) -> R
where
F: FnOnce(&mut [u8]) -> R,
{
let mut buffer = vec![0u8; len];
let result = f(&mut buffer);
self.permit.send(buffer);
result
}
}

View File

@ -0,0 +1,56 @@
use std::net::IpAddr;
pub type IpFilter<'a> = Box<dyn Fn(&IpAddr, &IpAddr) -> bool + Send + Sync + 'a>;
pub struct IpFilters<'a> {
filters: Vec<IpFilter<'a>>,
}
impl<'a> Default for IpFilters<'a> {
fn default() -> Self {
Self::new()
}
}
impl<'a> IpFilters<'a> {
pub fn new() -> Self {
Self {
filters: Default::default(),
}
}
pub fn with_non_broadcast() -> Self {
macro_rules! non_broadcast {
($addr:ident) => {
match $addr {
IpAddr::V4(a) => !(a.is_broadcast() || a.is_multicast() || a.is_unspecified()),
IpAddr::V6(a) => !(a.is_multicast() || a.is_unspecified()),
}
};
}
Self {
filters: vec![Box::new(|src, dst| {
non_broadcast!(src) && non_broadcast!(dst)
})],
}
}
pub fn add(&mut self, filter: IpFilter<'a>) {
self.filters.push(filter);
}
pub fn add_fn<F>(&mut self, filter: F)
where
F: Fn(&IpAddr, &IpAddr) -> bool + Send + Sync + 'a,
{
self.filters.push(Box::new(filter));
}
pub fn add_all<I: IntoIterator<Item = IpFilter<'a>>>(&mut self, filters: I) {
self.filters.extend(filters);
}
pub fn is_allowed(&self, src: &IpAddr, dst: &IpAddr) -> bool {
self.filters.iter().all(|filter| filter(src, dst))
}
}

View File

@ -0,0 +1,22 @@
mod device;
mod runner;
pub use runner::Runner;
mod packet;
pub use packet::AnyIpPktFrame;
mod filter;
pub use filter::{IpFilter, IpFilters};
pub mod udp;
pub use udp::UdpSocket;
pub mod tcp;
pub use tcp::{TcpListener, TcpStream};
pub mod stack;
pub use stack::{Stack, StackBuilder};
/// Re-export
pub use smoltcp;

View File

@ -0,0 +1,53 @@
use std::net::IpAddr;
use smoltcp::wire::{IpProtocol, IpVersion, Ipv4Packet, Ipv6Packet};
pub type AnyIpPktFrame = Vec<u8>;
#[derive(Debug)]
pub(super) enum IpPacket<T: AsRef<[u8]>> {
Ipv4(Ipv4Packet<T>),
Ipv6(Ipv6Packet<T>),
}
impl<T: AsRef<[u8]> + Copy> IpPacket<T> {
pub fn new_checked(packet: T) -> smoltcp::wire::Result<IpPacket<T>> {
let buffer = packet.as_ref();
match IpVersion::of_packet(buffer)? {
IpVersion::Ipv4 => Ok(IpPacket::Ipv4(Ipv4Packet::new_checked(packet)?)),
IpVersion::Ipv6 => Ok(IpPacket::Ipv6(Ipv6Packet::new_checked(packet)?)),
}
}
pub fn src_addr(&self) -> IpAddr {
match *self {
IpPacket::Ipv4(ref packet) => IpAddr::from(packet.src_addr()),
IpPacket::Ipv6(ref packet) => IpAddr::from(packet.src_addr()),
}
}
pub fn dst_addr(&self) -> IpAddr {
match *self {
IpPacket::Ipv4(ref packet) => IpAddr::from(packet.dst_addr()),
IpPacket::Ipv6(ref packet) => IpAddr::from(packet.dst_addr()),
}
}
pub fn protocol(&self) -> IpProtocol {
match *self {
IpPacket::Ipv4(ref packet) => packet.next_header(),
IpPacket::Ipv6(ref packet) => packet.next_header(),
}
}
}
impl<'a, T: AsRef<[u8]> + ?Sized> IpPacket<&'a T> {
/// Return a pointer to the payload.
#[inline]
pub fn payload(&self) -> &'a [u8] {
match *self {
IpPacket::Ipv4(ref packet) => packet.payload(),
IpPacket::Ipv6(ref packet) => packet.payload(),
}
}
}

View File

@ -0,0 +1,42 @@
use std::{
future::{Future, IntoFuture},
pin::Pin,
task::{Context, Poll},
};
/// BoxFuture acts the same as the [BoxFuture in crate futures utils],
/// which is an owned dynamically typed Future for use in cases where you
/// cant statically type your result or need to add some indirection.
/// But the difference of this structure is that it will conditionally
/// implement Send according to the properties of type T, which does not
/// require two sets of API interfaces in single-threaded and multi-threaded.
///
/// [BoxFuture in crate futures utils]: https://docs.rs/futures-util/latest/futures_util/future/type.BoxFuture.html
pub struct BoxFuture<'a, T>(Pin<Box<dyn Future<Output = T> + Send + 'a>>);
impl<'a, T> BoxFuture<'a, T> {
pub fn new<F>(f: F) -> BoxFuture<'a, T>
where
F: IntoFuture<Output = T> + Send + 'a,
F::IntoFuture: Send + 'a,
{
BoxFuture(Box::pin(f.into_future()))
}
#[allow(unused)]
pub fn wrap(f: Pin<Box<dyn Future<Output = T> + Send + 'a>>) -> BoxFuture<'a, T> {
BoxFuture(f)
}
}
impl<T> Future for BoxFuture<'_, T> {
type Output = T;
fn poll(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
self.0.as_mut().poll(context)
}
}
pub type Runner = BoxFuture<'static, std::io::Result<()>>;

View File

@ -0,0 +1,279 @@
use std::{
net::IpAddr,
pin::Pin,
task::{ready, Context, Poll},
};
use futures::{Sink, Stream};
use smoltcp::wire::IpProtocol;
use tokio::sync::mpsc::{channel, Receiver};
use tokio_util::sync::PollSender;
use tracing::{debug, trace};
use crate::{
filter::{IpFilter, IpFilters},
packet::{AnyIpPktFrame, IpPacket},
runner::Runner,
tcp::TcpListener,
udp::UdpSocket,
};
pub struct StackBuilder {
enable_udp: bool,
enable_tcp: bool,
enable_icmp: bool,
stack_buffer_size: usize,
udp_buffer_size: usize,
tcp_buffer_size: usize,
mtu: usize,
ip_filters: IpFilters<'static>,
}
impl Default for StackBuilder {
fn default() -> Self {
Self {
enable_udp: false,
enable_tcp: false,
enable_icmp: false,
stack_buffer_size: 1024,
udp_buffer_size: 512,
tcp_buffer_size: 512,
mtu: 1504, // 1500 for Ethernet + 4 for VLAN
ip_filters: IpFilters::with_non_broadcast(),
}
}
}
#[allow(unused)]
impl StackBuilder {
pub fn enable_udp(mut self, enable: bool) -> Self {
self.enable_udp = enable;
self
}
pub fn enable_tcp(mut self, enable: bool) -> Self {
self.enable_tcp = enable;
self
}
pub fn enable_icmp(mut self, enable: bool) -> Self {
self.enable_icmp = enable;
self
}
pub fn stack_buffer_size(mut self, size: usize) -> Self {
self.stack_buffer_size = size;
self
}
pub fn udp_buffer_size(mut self, size: usize) -> Self {
self.udp_buffer_size = size;
self
}
pub fn tcp_buffer_size(mut self, size: usize) -> Self {
self.tcp_buffer_size = size;
self
}
pub fn set_ip_filters(mut self, filters: IpFilters<'static>) -> Self {
self.ip_filters = filters;
self
}
pub fn add_ip_filter(mut self, filter: IpFilter<'static>) -> Self {
self.ip_filters.add(filter);
self
}
pub fn add_ip_filter_fn<F>(mut self, filter: F) -> Self
where
F: Fn(&IpAddr, &IpAddr) -> bool + Send + Sync + 'static,
{
self.ip_filters.add_fn(filter);
self
}
pub fn mtu(mut self, mtu: usize) -> Self {
self.mtu = mtu;
self
}
#[allow(clippy::type_complexity)]
pub fn build(
self,
) -> std::io::Result<(
Stack,
Option<Runner>,
Option<UdpSocket>,
Option<TcpListener>,
)> {
let (stack_tx, stack_rx) = channel(self.stack_buffer_size);
let (udp_tx, udp_rx) = if self.enable_udp {
let (udp_tx, udp_rx) = channel(self.udp_buffer_size);
(Some(PollSender::new(udp_tx)), Some(udp_rx))
} else {
(None, None)
};
let (tcp_tx, tcp_rx) = if self.enable_tcp {
let (tcp_tx, tcp_rx) = channel(self.tcp_buffer_size);
(Some(PollSender::new(tcp_tx)), Some(tcp_rx))
} else {
(None, None)
};
// ICMP is handled by TCP's Interface.
// smoltcp's interface will always send replies to EchoRequest
if self.enable_icmp && !self.enable_tcp {
use std::io::{Error, ErrorKind::InvalidInput};
return Err(Error::new(InvalidInput, "ICMP requires TCP"));
}
let icmp_tx = if self.enable_icmp {
tcp_tx.clone()
} else {
None
};
let udp_socket = udp_rx.map(|udp_rx| UdpSocket::new(udp_rx, stack_tx.clone()));
let (tcp_runner, tcp_listener) = if let Some(tcp_rx) = tcp_rx {
let (tcp_runner, tcp_listener) = TcpListener::new(tcp_rx, stack_tx, self.mtu)?;
(Some(tcp_runner), Some(tcp_listener))
} else {
(None, None)
};
let stack = Stack {
ip_filters: self.ip_filters,
stack_rx,
sink_buf: None,
udp_tx,
tcp_tx,
icmp_tx,
};
Ok((stack, tcp_runner, udp_socket, tcp_listener))
}
}
pub struct Stack {
ip_filters: IpFilters<'static>,
sink_buf: Option<(AnyIpPktFrame, IpProtocol)>,
udp_tx: Option<PollSender<AnyIpPktFrame>>,
tcp_tx: Option<PollSender<AnyIpPktFrame>>,
icmp_tx: Option<PollSender<AnyIpPktFrame>>,
stack_rx: Receiver<AnyIpPktFrame>,
}
impl Stack {
fn poll_send(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), std::io::Error>> {
let (item, proto) = match self.sink_buf.take() {
Some(val) => val,
None => return Poll::Ready(Ok(())),
};
let tx = match proto {
IpProtocol::Tcp => self.tcp_tx.as_mut(),
IpProtocol::Udp => self.udp_tx.as_mut(),
IpProtocol::Icmp | IpProtocol::Icmpv6 => self.icmp_tx.as_mut(),
_ => unreachable!(),
};
let Some(tx) = tx else {
return Poll::Ready(Ok(()));
};
match tx.poll_reserve(cx) {
Poll::Pending => {
self.sink_buf = Some((item, proto));
Poll::Pending
}
Poll::Ready(Err(_)) => Poll::Ready(Err(channel_closed_err("channel is closed"))),
Poll::Ready(Ok(_)) => match tx.send_item(item) {
Ok(()) => Poll::Ready(Ok(())),
Err(_) => Poll::Ready(Err(channel_closed_err("channel is closed"))),
},
}
}
}
// Recv from stack.
impl Stream for Stack {
type Item = std::io::Result<AnyIpPktFrame>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
match self.stack_rx.poll_recv(cx) {
Poll::Ready(Some(pkt)) => Poll::Ready(Some(Ok(pkt))),
Poll::Ready(None) => Poll::Ready(None),
Poll::Pending => Poll::Pending,
}
}
}
// Send to stack.
impl Sink<AnyIpPktFrame> for Stack {
type Error = std::io::Error;
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
// If a buffered item exists, try to flush it first. This also properly
// registers the waker via poll_reserve so we get woken when the channel
// has capacity. Without this, returning Pending here with _cx unused
// means the task never gets rescheduled.
if self.sink_buf.is_some() {
ready!(self.poll_send(cx))?;
}
Poll::Ready(Ok(()))
}
fn start_send(mut self: Pin<&mut Self>, item: AnyIpPktFrame) -> Result<(), Self::Error> {
if item.is_empty() {
return Ok(());
}
use std::io::{Error, ErrorKind::InvalidInput};
let packet = IpPacket::new_checked(item.as_slice())
.map_err(|err| Error::new(InvalidInput, format!("invalid IP packet: {err}")))?;
let src_ip = packet.src_addr();
let dst_ip = packet.dst_addr();
let addr_allowed = self.ip_filters.is_allowed(&src_ip, &dst_ip);
if !addr_allowed {
trace!("IP packet {src_ip} -> {dst_ip} (allowed? {addr_allowed}) throwing away",);
return Ok(());
}
let protocol = packet.protocol();
if matches!(
protocol,
IpProtocol::Tcp | IpProtocol::Udp | IpProtocol::Icmp | IpProtocol::Icmpv6
) {
self.sink_buf.replace((item, protocol));
} else {
debug!("tun IP packet ignored (protocol: {:?})", protocol);
}
Ok(())
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.poll_send(cx)
}
fn poll_close(
mut self: Pin<&mut Self>,
_cx: &mut Context<'_>,
) -> Poll<Result<(), Self::Error>> {
self.stack_rx.close();
Poll::Ready(Ok(()))
}
}
fn channel_closed_err<E>(err: E) -> std::io::Error
where
E: Into<Box<dyn std::error::Error + Send + Sync>>,
{
std::io::Error::new(std::io::ErrorKind::BrokenPipe, err)
}

564
netstack-smoltcp/src/tcp.rs Normal file
View File

@ -0,0 +1,564 @@
use std::{
collections::HashMap,
net::SocketAddr,
pin::Pin,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
task::{Context, Poll, Waker},
};
use futures::Stream;
use smoltcp::{
iface::{Config as InterfaceConfig, Interface, SocketHandle, SocketSet},
phy::Device,
socket::tcp::{Socket as TcpSocket, SocketBuffer as TcpSocketBuffer, State as TcpState},
storage::RingBuffer,
time::{Duration, Instant},
wire::{HardwareAddress, IpAddress, IpCidr, IpProtocol, Ipv4Address, Ipv6Address, TcpPacket},
};
use spin::Mutex as SpinMutex;
use tokio::{
io::{AsyncRead, AsyncWrite, ReadBuf},
sync::{
mpsc::{channel, Receiver, Sender, UnboundedSender},
Notify,
},
};
use tracing::{error, trace};
use crate::{
device::VirtualDevice,
packet::{AnyIpPktFrame, IpPacket},
Runner,
};
// Reduced buffer sizes to 16KB to prevent excessive memory overhead (was 0x3FFF * 20 = 327KB per buffer)
const DEFAULT_TCP_SEND_BUFFER_SIZE: u32 = 16384;
const DEFAULT_TCP_RECV_BUFFER_SIZE: u32 = 16384;
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
enum TcpSocketState {
Normal,
Close,
Closing,
Closed,
}
struct TcpSocketControl {
send_buffer: RingBuffer<'static, u8>,
send_waker: Option<Waker>,
recv_buffer: RingBuffer<'static, u8>,
recv_waker: Option<Waker>,
recv_state: TcpSocketState,
send_state: TcpSocketState,
}
struct TcpSocketCreation {
control: SharedControl,
socket: TcpSocket<'static>,
}
type SharedNotify = Arc<Notify>;
type SharedControl = Arc<SpinMutex<TcpSocketControl>>;
struct TcpListenerRunner;
impl TcpListenerRunner {
fn create(
device: VirtualDevice,
iface: Interface,
iface_ingress_tx: UnboundedSender<Vec<u8>>,
iface_ingress_tx_avail: Arc<AtomicBool>,
tcp_rx: Receiver<AnyIpPktFrame>,
stream_tx: Sender<TcpStream>,
sockets: HashMap<SocketHandle, SharedControl>,
) -> Runner {
Runner::new(async move {
let notify = Arc::new(Notify::new());
let (socket_tx, socket_rx) = channel::<TcpSocketCreation>(1024);
let res = tokio::select! {
v = Self::handle_packet(notify.clone(), iface_ingress_tx, iface_ingress_tx_avail.clone(), tcp_rx, stream_tx, socket_tx) => v,
v = Self::handle_socket(notify, device, iface, iface_ingress_tx_avail, sockets, socket_rx) => v,
};
res?;
trace!("VirtDevice::poll thread exited");
Ok(())
})
}
async fn handle_packet(
notify: SharedNotify,
iface_ingress_tx: UnboundedSender<Vec<u8>>,
iface_ingress_tx_avail: Arc<AtomicBool>,
mut tcp_rx: Receiver<AnyIpPktFrame>,
stream_tx: Sender<TcpStream>,
socket_tx: Sender<TcpSocketCreation>,
) -> std::io::Result<()> {
while let Some(frame) = tcp_rx.recv().await {
let packet = match IpPacket::new_checked(frame.as_slice()) {
Ok(p) => p,
Err(err) => {
error!("invalid TCP IP packet: {:?}", err,);
continue;
}
};
// Specially handle icmp packet by TCP interface.
if matches!(packet.protocol(), IpProtocol::Icmp | IpProtocol::Icmpv6) {
iface_ingress_tx
.send(frame)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::BrokenPipe, e))?;
iface_ingress_tx_avail.store(true, Ordering::Release);
notify.notify_one();
continue;
}
let src_ip = packet.src_addr();
let dst_ip = packet.dst_addr();
let payload = packet.payload();
let packet = match TcpPacket::new_checked(payload) {
Ok(p) => p,
Err(err) => {
error!("invalid TCP err: {err}, src_ip: {src_ip}, dst_ip: {dst_ip}, payload: {payload:?}");
continue;
}
};
let src_port = packet.src_port();
let dst_port = packet.dst_port();
let src_addr = SocketAddr::new(src_ip, src_port);
let dst_addr = SocketAddr::new(dst_ip, dst_port);
// TCP first handshake packet, create a new Connection
if packet.syn() && !packet.ack() {
let mut socket = TcpSocket::new(
TcpSocketBuffer::new(vec![0u8; DEFAULT_TCP_RECV_BUFFER_SIZE as usize]),
TcpSocketBuffer::new(vec![0u8; DEFAULT_TCP_SEND_BUFFER_SIZE as usize]),
);
socket.set_keep_alive(Some(Duration::from_secs(28)));
// FIXME: It should follow system's setting. 7200 is Linux's default.
socket.set_timeout(Some(Duration::from_secs(7200)));
// NO ACK delay
// socket.set_ack_delay(None);
if let Err(err) = socket.listen(dst_addr) {
error!("listen error: {:?}", err);
continue;
}
trace!("created TCP connection for {} <-> {}", src_addr, dst_addr);
let control = Arc::new(SpinMutex::new(TcpSocketControl {
send_buffer: RingBuffer::new(vec![0u8; DEFAULT_TCP_SEND_BUFFER_SIZE as usize]),
send_waker: None,
recv_buffer: RingBuffer::new(vec![0u8; DEFAULT_TCP_RECV_BUFFER_SIZE as usize]),
recv_waker: None,
recv_state: TcpSocketState::Normal,
send_state: TcpSocketState::Normal,
}));
if let Err(_) = stream_tx.try_send(TcpStream {
src_addr,
dst_addr,
notify: notify.clone(),
control: control.clone(),
}) {
error!("stream_tx full or dropped, dropping SYN from {}", src_addr);
continue;
}
if let Err(_) = socket_tx.try_send(TcpSocketCreation { control, socket }) {
error!("socket_tx full or dropped, dropping SYN from {}", src_addr);
continue;
}
}
// Pipeline tcp stream packet
iface_ingress_tx
.send(frame)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::BrokenPipe, e))?;
iface_ingress_tx_avail.store(true, Ordering::Release);
notify.notify_one();
}
Ok(())
}
async fn handle_socket(
notify: SharedNotify,
mut device: VirtualDevice,
mut iface: Interface,
iface_ingress_tx_avail: Arc<AtomicBool>,
mut sockets: HashMap<SocketHandle, SharedControl>,
mut socket_rx: Receiver<TcpSocketCreation>,
) -> std::io::Result<()> {
let mut socket_set = SocketSet::new(vec![]);
loop {
while let Ok(TcpSocketCreation { control, socket }) = socket_rx.try_recv() {
let handle = socket_set.add(socket);
sockets.insert(handle, control);
}
let before_poll = Instant::now();
let updated_sockets = iface.poll(before_poll, &mut device, &mut socket_set);
if matches!(
updated_sockets,
smoltcp::iface::PollResult::SocketStateChanged
) {
trace!("VirtDevice::poll costed {}", Instant::now() - before_poll);
}
// Check all the sockets' status
let mut sockets_to_remove = Vec::new();
for (socket_handle, control) in sockets.iter() {
let socket_handle = *socket_handle;
let socket = socket_set.get_mut::<TcpSocket>(socket_handle);
let mut control = control.lock();
// Remove the socket only when it is in the closed state.
if socket.state() == TcpState::Closed {
sockets_to_remove.push(socket_handle);
control.send_state = TcpSocketState::Closed;
control.recv_state = TcpSocketState::Closed;
if let Some(waker) = control.send_waker.take() {
waker.wake();
}
if let Some(waker) = control.recv_waker.take() {
waker.wake();
}
trace!("closed TCP connection");
continue;
}
// SHUT_WR — only close once the send_buffer has been fully
// drained into the smoltcp socket. Closing earlier transitions
// the socket to FIN_WAIT_1, making can_send() return false, so
// the send loop below never runs and the remaining data is lost.
if matches!(control.send_state, TcpSocketState::Close)
&& control.send_buffer.is_empty()
{
trace!("closing TCP Write Half, {:?}", socket.state());
socket.close();
control.send_state = TcpSocketState::Closing;
}
// Check if readable
let mut wake_receiver = false;
while socket.can_recv() && !control.recv_buffer.is_full() {
let result = socket.recv(|buffer| {
let n = control.recv_buffer.enqueue_slice(buffer);
(n, ())
});
match result {
Ok(..) => wake_receiver = true,
Err(err) => {
error!("socket recv error: {:?}, {:?}", err, socket.state());
// Don't know why. Abort the connection.
socket.abort();
if matches!(control.recv_state, TcpSocketState::Normal) {
control.recv_state = TcpSocketState::Closed;
}
wake_receiver = true;
// The socket will be recycled in the next poll.
break;
}
}
}
// If socket is not in ESTABLISH, FIN-WAIT-1, FIN-WAIT-2,
// the local client have closed our receiver.
let states = [
TcpState::Listen,
TcpState::SynReceived,
TcpState::Established,
TcpState::FinWait1,
TcpState::FinWait2,
];
if matches!(control.recv_state, TcpSocketState::Normal)
&& !socket.may_recv()
&& !states.contains(&socket.state())
{
trace!("closed TCP Read Half, {:?}", socket.state());
// Let TcpStream::poll_read returns EOF.
control.recv_state = TcpSocketState::Closed;
wake_receiver = true;
}
if wake_receiver && control.recv_waker.is_some() {
if let Some(waker) = control.recv_waker.take() {
waker.wake();
}
}
// Check if writable
let mut wake_sender = false;
while socket.can_send() && !control.send_buffer.is_empty() {
let result = socket.send(|buffer| {
let n = control.send_buffer.dequeue_slice(buffer);
(n, ())
});
match result {
Ok(..) => wake_sender = true,
Err(err) => {
error!("socket send error: {:?}, {:?}", err, socket.state());
// Don't know why. Abort the connection.
socket.abort();
if matches!(control.send_state, TcpSocketState::Normal) {
control.send_state = TcpSocketState::Closed;
}
wake_sender = true;
// The socket will be recycled in the next poll.
break;
}
}
}
if wake_sender && control.send_waker.is_some() {
if let Some(waker) = control.send_waker.take() {
waker.wake();
}
}
}
for socket_handle in sockets_to_remove {
sockets.remove(&socket_handle);
socket_set.remove(socket_handle);
}
if !iface_ingress_tx_avail.load(Ordering::Acquire) {
let next_duration = iface
.poll_delay(before_poll, &socket_set)
.unwrap_or(Duration::from_millis(5));
if next_duration != Duration::ZERO {
let _ = tokio::time::timeout(
tokio::time::Duration::from(next_duration),
notify.notified(),
)
.await;
}
}
}
}
}
pub struct TcpListener {
stream_rx: Receiver<TcpStream>,
}
impl TcpListener {
pub(super) fn new(
tcp_rx: Receiver<AnyIpPktFrame>,
stack_tx: Sender<AnyIpPktFrame>,
mtu: usize,
) -> std::io::Result<(Runner, Self)> {
let (mut device, iface_ingress_tx, iface_ingress_tx_avail) =
VirtualDevice::new(stack_tx, mtu);
let iface = Self::create_interface(&mut device)?;
let (stream_tx, stream_rx) = channel(1024);
let runner = TcpListenerRunner::create(
device,
iface,
iface_ingress_tx,
iface_ingress_tx_avail,
tcp_rx,
stream_tx,
HashMap::new(),
);
Ok((runner, Self { stream_rx }))
}
fn create_interface<D>(device: &mut D) -> std::io::Result<Interface>
where
D: Device + ?Sized,
{
let mut iface_config = InterfaceConfig::new(HardwareAddress::Ip);
iface_config.random_seed = rand::random();
let mut iface = Interface::new(iface_config, device, Instant::now());
iface.update_ip_addrs(|ip_addrs| {
ip_addrs
.push(IpCidr::new(IpAddress::v4(0, 0, 0, 1), 0))
.expect("iface IPv4");
ip_addrs
.push(IpCidr::new(IpAddress::v6(0, 0, 0, 0, 0, 0, 0, 1), 0))
.expect("iface IPv6");
});
iface
.routes_mut()
.add_default_ipv4_route(Ipv4Address::new(0, 0, 0, 1))
.map_err(|e| std::io::Error::new(std::io::ErrorKind::AddrNotAvailable, e))?;
iface
.routes_mut()
.add_default_ipv6_route(Ipv6Address::new(0, 0, 0, 0, 0, 0, 0, 1))
.map_err(|e| std::io::Error::new(std::io::ErrorKind::AddrNotAvailable, e))?;
iface.set_any_ip(true);
Ok(iface)
}
}
impl Stream for TcpListener {
type Item = (TcpStream, SocketAddr, SocketAddr);
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
self.stream_rx.poll_recv(cx).map(|stream| {
stream.map(|stream| {
let local_addr = *stream.local_addr();
let remote_addr: SocketAddr = *stream.remote_addr();
(stream, local_addr, remote_addr)
})
})
}
}
pub struct TcpStream {
src_addr: SocketAddr,
dst_addr: SocketAddr,
notify: SharedNotify,
control: SharedControl,
}
impl Drop for TcpStream {
fn drop(&mut self) {
let mut control = self.control.lock();
if matches!(control.recv_state, TcpSocketState::Normal) {
control.recv_state = TcpSocketState::Close;
}
if matches!(control.send_state, TcpSocketState::Normal) {
control.send_state = TcpSocketState::Close;
}
self.notify.notify_one();
}
}
impl TcpStream {
pub fn local_addr(&self) -> &SocketAddr {
&self.src_addr
}
pub fn remote_addr(&self) -> &SocketAddr {
&self.dst_addr
}
}
impl AsyncRead for TcpStream {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<std::io::Result<()>> {
let mut control = self.control.lock();
// Read from buffer
if control.recv_buffer.is_empty() {
// If socket is already closed / half closed, just return EOF directly.
if matches!(control.recv_state, TcpSocketState::Closed) {
return Ok(()).into();
}
// Nothing could be read. Wait for notify.
if let Some(old_waker) = control.recv_waker.replace(cx.waker().clone()) {
if !old_waker.will_wake(cx.waker()) {
old_waker.wake();
}
}
return Poll::Pending;
}
let recv_buf = buf.initialize_unfilled();
let n = control.recv_buffer.dequeue_slice(recv_buf);
buf.advance(n);
if n > 0 {
self.notify.notify_one();
}
Ok(()).into()
}
}
impl AsyncWrite for TcpStream {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<std::io::Result<usize>> {
let mut control = self.control.lock();
// If state == Close | Closing | Closed, the TCP stream WR half is closed.
if !matches!(control.send_state, TcpSocketState::Normal) {
return Err(std::io::ErrorKind::BrokenPipe.into()).into();
}
// Write to buffer
if control.send_buffer.is_full() {
if let Some(old_waker) = control.send_waker.replace(cx.waker().clone()) {
if !old_waker.will_wake(cx.waker()) {
old_waker.wake();
}
}
return Poll::Pending;
}
let n = control.send_buffer.enqueue_slice(buf);
if n > 0 {
self.notify.notify_one();
}
Ok(n).into()
}
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Ok(()).into()
}
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
let mut control = self.control.lock();
if matches!(control.send_state, TcpSocketState::Closed | TcpSocketState::Closing) {
return Ok(()).into();
}
// SHUT_WR
if matches!(control.send_state, TcpSocketState::Normal) {
control.send_state = TcpSocketState::Close;
}
if let Some(old_waker) = control.send_waker.replace(cx.waker().clone()) {
if !old_waker.will_wake(cx.waker()) {
old_waker.wake();
}
}
self.notify.notify_one();
Poll::Pending
}
}

155
netstack-smoltcp/src/udp.rs Normal file
View File

@ -0,0 +1,155 @@
use std::{
net::SocketAddr,
pin::Pin,
task::{Context, Poll},
};
use etherparse::PacketBuilder;
use futures::{ready, Sink, SinkExt, Stream};
use smoltcp::wire::UdpPacket;
use tokio::sync::mpsc::{Receiver, Sender};
use tokio_util::sync::PollSender;
use tracing::{error, trace};
use crate::packet::{AnyIpPktFrame, IpPacket};
pub type UdpMsg = (
Vec<u8>, /* payload */
SocketAddr, /* local */
SocketAddr, /* remote */
);
pub struct UdpSocket {
udp_rx: Receiver<AnyIpPktFrame>,
stack_tx: PollSender<AnyIpPktFrame>,
}
impl UdpSocket {
pub(super) fn new(udp_rx: Receiver<AnyIpPktFrame>, stack_tx: Sender<AnyIpPktFrame>) -> Self {
Self {
udp_rx,
stack_tx: PollSender::new(stack_tx),
}
}
pub fn split(self) -> (ReadHalf, WriteHalf) {
(
ReadHalf {
udp_rx: self.udp_rx,
},
WriteHalf {
stack_tx: self.stack_tx,
},
)
}
}
pub struct ReadHalf {
udp_rx: Receiver<AnyIpPktFrame>,
}
pub struct WriteHalf {
stack_tx: PollSender<AnyIpPktFrame>,
}
impl Stream for ReadHalf {
type Item = UdpMsg;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
loop {
match ready!(self.udp_rx.poll_recv(cx)) {
Some(frame) => {
let packet = match IpPacket::new_checked(frame.as_slice()) {
Ok(p) => p,
Err(err) => {
error!("invalid IP packet: {}", err);
continue;
}
};
let src_ip = packet.src_addr();
let dst_ip = packet.dst_addr();
let payload = packet.payload();
let packet = match UdpPacket::new_checked(payload) {
Ok(p) => p,
Err(err) => {
error!("invalid err: {err}, src_ip: {src_ip}, dst_ip: {dst_ip}, payload: {payload:?}");
continue;
}
};
let src_port = packet.src_port();
let dst_port = packet.dst_port();
let src_addr = SocketAddr::new(src_ip, src_port);
let dst_addr = SocketAddr::new(dst_ip, dst_port);
trace!("created UDP socket for {} <-> {}", src_addr, dst_addr);
return Poll::Ready(Some((packet.payload().to_vec(), src_addr, dst_addr)));
}
None => return Poll::Ready(None),
}
}
}
}
impl Sink<UdpMsg> for WriteHalf {
type Error = std::io::Error;
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
match ready!(self.stack_tx.poll_ready_unpin(cx)) {
Ok(()) => Poll::Ready(Ok(())),
Err(err) => Poll::Ready(Err(std::io::Error::other(err))),
}
}
fn start_send(mut self: Pin<&mut Self>, item: UdpMsg) -> Result<(), Self::Error> {
use std::io::{Error, ErrorKind::InvalidData};
let (data, src_addr, dst_addr) = item;
if data.is_empty() {
return Ok(());
}
let builder = match (src_addr, dst_addr) {
(SocketAddr::V4(src), SocketAddr::V4(dst)) => {
PacketBuilder::ipv4(src.ip().octets(), dst.ip().octets(), 20)
.udp(src_addr.port(), dst_addr.port())
}
(SocketAddr::V6(src), SocketAddr::V6(dst)) => {
PacketBuilder::ipv6(src.ip().octets(), dst.ip().octets(), 20)
.udp(src_addr.port(), dst_addr.port())
}
_ => {
return Err(Error::new(InvalidData, "src or destination type unmatch"));
}
};
let mut ip_packet_writer = Vec::with_capacity(builder.size(data.len()));
builder
.write(&mut ip_packet_writer, &data)
.map_err(|err| Error::other(format!("PacketBuilder::write: {err}")))?;
match self.stack_tx.start_send_unpin(ip_packet_writer) {
Ok(()) => Ok(()),
Err(err) => Err(Error::other(format!("send error: {err}"))),
}
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
use std::io::Error;
match ready!(self.stack_tx.poll_flush_unpin(cx)) {
Ok(()) => Poll::Ready(Ok(())),
Err(err) => Poll::Ready(Err(Error::other(format!("flush error: {err}")))),
}
}
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
use std::io::Error;
match ready!(self.stack_tx.poll_close_unpin(cx)) {
Ok(()) => Poll::Ready(Ok(())),
Err(err) => Poll::Ready(Err(Error::other(format!("close error: {err}")))),
}
}
}

View File

@ -0,0 +1,75 @@
//! Regression tests that reproduce the bugs found in the static analysis.
use std::time::Duration;
use etherparse::{IpNumber, Ipv4Header, UdpHeader};
use futures::SinkExt;
use tokio::time::timeout;
use netstack_smoltcp::StackBuilder;
fn make_udp_ipv4(
src_ip: [u8; 4],
src_port: u16,
dst_ip: [u8; 4],
dst_port: u16,
payload: &[u8],
) -> Vec<u8> {
let udp_hdr = UdpHeader::with_ipv4_checksum(
src_port,
dst_port,
&Ipv4Header::new(
(UdpHeader::LEN + payload.len()) as u16,
64,
IpNumber::UDP,
src_ip,
dst_ip,
)
.unwrap(),
payload,
)
.unwrap();
let ip_hdr = Ipv4Header::new(
(UdpHeader::LEN + payload.len()) as u16,
64,
IpNumber::UDP,
src_ip,
dst_ip,
)
.unwrap();
let mut buf = Vec::with_capacity(Ipv4Header::MIN_LEN + UdpHeader::LEN + payload.len());
ip_hdr.write(&mut buf).unwrap();
udp_hdr.write(&mut buf).unwrap();
buf.extend_from_slice(payload);
buf
}
/// before(include) a15e0b72bfc72cb032e67138070da01e325d66f8
/// sink_buf is used in `Stack` to hold a slot for sending any pkt
///
/// the original assumption is that the `poll_ready` -> `start_send` -> `poll_flush`
/// are called sequentially so the slot could be reused and will never get blocked.
///
/// but once the user calls `send_all` on `Stack`, which will not immediate flush the pkt(call `poll_flush`),
/// then `sink_buf` is could be Some(pkt), then it will trigger `Poll::Pending` branch in `Stack::poll_ready`,
/// who did not register the waker correctly, so it will got hanged forever.
#[tokio::test(flavor = "current_thread")]
async fn bug1_poll_ready_waker_registered_via_send_all() {
let (mut stack, _runner, _udp_socket, _tcp) = StackBuilder::default()
.enable_udp(true)
.udp_buffer_size(64)
.stack_buffer_size(64)
.build()
.unwrap();
let pkt1 = make_udp_ipv4([1, 2, 3, 4], 1111, [5, 6, 7, 8], 9999, b"first");
let pkt2 = make_udp_ipv4([1, 2, 3, 4], 1111, [5, 6, 7, 8], 9999, b"second");
let mut stream = futures::stream::iter([Ok(pkt1), Ok(pkt2)]);
let result = timeout(Duration::from_secs(1), stack.send_all(&mut stream)).await;
// should be ok after the fix
assert!(result.is_ok());
}

View File

@ -9,7 +9,7 @@ anyhow.workspace = true
bytes.workspace = true
tokio.workspace = true
tracing.workspace = true
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tracing-subscriber = { version = "0.3", features = ["env-filter", "time"] }
tracing-appender = "0.2"
ostp-core = { path = "../ostp-core" }
ostp-tun = { path = "../ostp-tun" }
@ -29,4 +29,11 @@ tun = { version = "0.8.9", features = ["async"] }
netstack-smoltcp = "0.2.2"
futures = "0.3.32"
libc = "0.2.186"
winapi = { version = "0.3.9", features = ["iphlpapi", "tcpmib", "processthreadsapi", "psapi", "handleapi", "winerror", "minwindef", "winnt", "iptypes", "ws2def"] }
x25519-dalek = "2.0.1"
chacha20poly1305.workspace = true
hex = "0.4.3"
winapi = { version = "0.3.9", features = ["iphlpapi", "tcpmib", "processthreadsapi", "psapi", "handleapi", "winerror", "minwindef", "winnt", "iptypes", "ws2def", "ws2tcpip", "winsock2"] }
ipnet = "2.12.0"
[target."cfg(unix)".dependencies]
libc = "0.2.186"

File diff suppressed because it is too large Load Diff

View File

@ -1,163 +1,133 @@
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
/// Client runtime configuration.
/// Constructed by the main binary from the unified `config.json`,
/// then passed into `runner::run_client`. All I/O happens in the
/// binary layer — this crate only owns the plain data structures.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClientConfig {
pub mode: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
#[serde(default)]
pub debug: bool,
pub ostp: OstpConfig,
pub local_proxy: LocalProxyConfig,
pub log: LogConfig,
#[serde(default)]
pub transport: TransportConfig,
pub inbounds: Vec<InboundConfig>,
#[serde(default)]
pub exclusions: ExclusionConfig,
pub outbounds: Vec<OutboundConfig>,
#[serde(default)]
pub multiplex: MultiplexConfig,
pub dns_server: Option<String>,
#[serde(default = "default_tun_stack")]
pub tun_stack: String,
#[serde(default)]
pub kill_switch: bool,
pub routing: RoutingConfig,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub gui: Option<serde_json::Value>,
}
fn default_tun_stack() -> String { "system".to_string() }
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogConfig {
#[serde(default = "default_log_level")]
pub level: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ExclusionConfig {
#[serde(default)]
pub domains: Vec<String>,
#[serde(default)]
pub ips: Vec<String>,
#[serde(default)]
pub processes: Vec<String>,
impl Default for LogConfig {
fn default() -> Self {
Self { level: default_log_level() }
}
}
fn default_log_level() -> String { "info".to_string() }
fn default_true() -> bool { true }
pub fn default_mtu() -> usize { 1140 }
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum InboundConfig {
Tun {
tag: String,
#[serde(default = "default_true")]
auto_route: bool,
#[serde(default = "default_mtu")]
mtu: usize,
#[serde(default, skip_serializing_if = "Option::is_none")]
fd: Option<i32>,
},
LocalProxy {
tag: String,
protocol: String, // "socks" or "http"
listen: String,
port: u16,
#[serde(default)]
set_system_proxy: bool,
},
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MultiplexConfig {
pub enabled: bool,
pub sessions: usize,
#[serde(tag = "type", rename_all = "snake_case")]
pub enum OutboundConfig {
Selector {
tag: String,
outbounds: Vec<String>,
default: Option<String>,
},
Urltest {
tag: String,
outbounds: Vec<String>,
url: Option<String>,
interval: Option<String>,
},
Ostp {
tag: String,
server: String,
port: u16,
access_key: String,
#[serde(default)]
transport: TransportConfig,
#[serde(default)]
multiplex: MultiplexConfig,
},
Direct {
tag: String,
},
Socks {
tag: String,
server: String,
port: u16,
},
Block {
tag: String,
},
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OstpConfig {
pub server_addr: String,
pub local_bind_addr: String,
#[serde(alias = "auth_token")]
pub access_key: String,
pub handshake_timeout_ms: u64,
pub io_timeout_ms: u64,
#[serde(default = "default_mtu")]
pub mtu: usize,
#[serde(default = "default_keepalive")]
pub keepalive_interval_sec: u64,
}
fn default_keepalive() -> u64 { 5 }
fn default_mtu() -> usize { 1140 }
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LocalProxyConfig {
pub bind_addr: String,
pub connect_timeout_ms: u64,
}
/// Transport layer configuration.
/// `mode` = "udp" (default) or "uot" (UDP over TCP, no protocol mimicry —
/// zapret-like: no recognizable header at all, not a fake TLS/HTTP shell).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TransportConfig {
/// "udp" or "uot"
#[serde(default = "default_transport_mode")]
pub mode: String,
/// Split the first UoT/TCP packet (handshake) into tiny TCP segments to
/// break DPI that inspects the first packet. UoT/TCP only; ignored for UDP.
pub tcp_fragmentation: bool,
/// TCP chunk size (bytes)
#[serde(default = "default_frag_chunk")]
pub frag_chunk: usize,
/// TCP sleep duration between chunks (ms)
#[serde(default = "default_frag_sleep")]
pub frag_sleep: u64,
/// [min, max] junk packet count
#[serde(default = "default_junk_count")]
pub junk_pc: [usize; 2],
/// [min, max] junk packet size in bytes
#[serde(default = "default_junk_size")]
pub junk_ps: [usize; 2],
pub r#type: String, // "udp", "uot", or "dns"
// Settings for DNS transport
#[serde(default, skip_serializing_if = "Option::is_none")]
pub domain: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resolver: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pubkey: Option<String>,
}
fn default_transport_mode() -> String { "udp".to_string() }
fn default_frag_chunk() -> usize { 2 }
fn default_frag_sleep() -> u64 { 2 }
fn default_junk_count() -> [usize; 2] { [2, 5] }
fn default_junk_size() -> [usize; 2] { [100, 1000] }
impl Default for TransportConfig {
fn default() -> Self {
Self {
mode: default_transport_mode(),
tcp_fragmentation: false,
frag_chunk: default_frag_chunk(),
frag_sleep: default_frag_sleep(),
junk_pc: default_junk_count(),
junk_ps: default_junk_size(),
r#type: default_transport_mode(),
domain: None,
resolver: None,
pubkey: None,
}
}
}
impl Default for OstpConfig {
fn default() -> Self {
Self {
server_addr: "127.0.0.1:50000".to_string(),
local_bind_addr: "0.0.0.0:0".to_string(),
access_key: String::new(),
handshake_timeout_ms: 5000,
io_timeout_ms: 2500,
mtu: default_mtu(),
keepalive_interval_sec: default_keepalive(),
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MultiplexConfig {
#[serde(default)]
pub enabled: bool,
#[serde(default = "default_mux_sessions")]
pub sessions: usize,
}
impl Default for LocalProxyConfig {
fn default() -> Self {
Self {
bind_addr: "127.0.0.1:1088".to_string(),
connect_timeout_ms: 15000,
}
}
}
impl Default for ClientConfig {
fn default() -> Self {
Self {
mode: "proxy".to_string(),
debug: false,
ostp: OstpConfig::default(),
local_proxy: LocalProxyConfig::default(),
transport: TransportConfig::default(),
exclusions: ExclusionConfig::default(),
multiplex: MultiplexConfig::default(),
dns_server: None,
tun_stack: "system".to_string(),
kill_switch: false,
gui: None,
}
}
}
fn default_mux_sessions() -> usize { 1 }
impl Default for MultiplexConfig {
fn default() -> Self {
@ -168,60 +138,30 @@ impl Default for MultiplexConfig {
}
}
/// Unified shape of `config.json` as seen by the client.
/// Used only for hot-reloading (`BridgeCommand::ReloadConfig`).
#[derive(Debug, Deserialize)]
struct RawUnifiedConfig {
#[allow(dead_code)]
mode: String,
debug: Option<bool>,
server: Option<String>,
access_key: Option<String>,
mtu: Option<usize>,
socks5_bind: Option<String>,
tun: Option<RawTunSection>,
exclude: Option<RawExcludeSection>,
mux: Option<RawMuxSection>,
transport: Option<RawTransportSection>,
gui: Option<serde_json::Value>,
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct RoutingConfig {
#[serde(default)]
pub rules: Vec<RoutingRule>,
#[serde(default)]
pub default_outbound: String,
}
#[derive(Debug, Deserialize)]
struct RawTransportSection {
mode: Option<String>,
tcp_fragmentation: Option<bool>,
frag_chunk: Option<usize>,
frag_sleep: Option<u64>,
junk_pc: Option<[usize; 2]>,
junk_ps: Option<[usize; 2]>,
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RoutingRule {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub domain_suffix: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ip_cidr: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub process_name: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub inbound_tag: Option<Vec<String>>,
pub outbound: String,
}
#[derive(Debug, Deserialize)]
struct RawTunSection {
enable: Option<bool>,
dns: Option<String>,
stack: Option<String>,
kill_switch: Option<bool>,
}
#[derive(Debug, Deserialize)]
struct RawExcludeSection {
domains: Option<Vec<String>>,
ips: Option<Vec<String>>,
processes: Option<Vec<String>>,
}
#[derive(Debug, Deserialize)]
struct RawMuxSection {
enabled: Option<bool>,
sessions: Option<usize>,
}
impl ClientConfig {
/// Hot-reload from `config.json` placed next to the running binary.
/// Returns a new `ClientConfig` built from the unified JSON format.
/// Returns a new `ClientConfig` built from the JSON format.
pub fn reload_from_json_near_binary() -> Result<Self> {
let exe = std::env::current_exe().context("cannot resolve binary path")?;
let dir = exe.parent().context("cannot resolve binary directory")?;
@ -230,309 +170,161 @@ impl ClientConfig {
let raw = std::fs::read_to_string(&path)
.with_context(|| format!("failed to read {}", path.display()))?;
let mut stripped = json_comments::StripComments::new(raw.as_bytes());
let raw: RawUnifiedConfig = serde_json::from_reader(&mut stripped)
.with_context(|| format!("failed to parse {}", path.display()))?;
let raw_json: serde_json::Value = serde_json::from_reader(&mut stripped)
.with_context(|| format!("failed to parse JSON from {}", path.display()))?;
let is_tun = raw.tun.as_ref().and_then(|t| t.enable).unwrap_or(false);
let server = raw.server.unwrap_or_else(|| "127.0.0.1:50000".to_string());
let key = raw.access_key.unwrap_or_default();
let mtu = raw.mtu.unwrap_or(default_mtu());
let socks5 = raw.socks5_bind.unwrap_or_else(|| "127.0.0.1:1088".to_string());
let exclusions = raw.exclude.unwrap_or(RawExcludeSection {
domains: None,
ips: None,
processes: None,
});
let mux = raw.mux.unwrap_or(RawMuxSection {
enabled: None,
sessions: None,
let (migrated_json, was_migrated) = Self::migrate_json(raw_json);
if was_migrated {
tracing::warn!(
"Config at {} is in an outdated format. Run 'ostp --migrate' to upgrade it.",
path.display()
);
}
let config: ClientConfig = serde_json::from_value(migrated_json)
.with_context(|| format!("failed to deserialize config from {}", path.display()))?;
Ok(config)
}
/// Migrates old monolithic JSON to the new modular format.
/// Returns the migrated JSON value and a boolean indicating if a migration occurred.
pub fn migrate_json(json: serde_json::Value) -> (serde_json::Value, bool) {
// Consider the config already migrated if:
// 1. Version matches exactly, OR
// 2. The JSON already has the new modular format (inbounds + outbounds arrays)
let has_version = json.get("version").and_then(|v| v.as_str()) == Some(env!("CARGO_PKG_VERSION"));
let has_new_format = json.get("inbounds").and_then(|v| v.as_array()).is_some()
&& json.get("outbounds").and_then(|v| v.as_array()).is_some();
if has_version || has_new_format {
// If format is already new but version is old, just bump the version
if has_new_format && !has_version {
let mut updated = json.clone();
updated["version"] = serde_json::json!(env!("CARGO_PKG_VERSION"));
return (updated, false);
}
return (json, false);
}
// Needs migration
let mut new_json = serde_json::json!({
"version": env!("CARGO_PKG_VERSION"),
});
Ok(ClientConfig {
mode: if is_tun { "tun".to_string() } else { "proxy".to_string() },
debug: raw.debug.unwrap_or(false),
ostp: OstpConfig {
server_addr: server,
local_bind_addr: "0.0.0.0:0".to_string(),
access_key: key,
handshake_timeout_ms: 5000,
io_timeout_ms: 2500,
mtu,
keepalive_interval_sec: default_keepalive(),
},
local_proxy: LocalProxyConfig {
bind_addr: socks5,
connect_timeout_ms: 15000,
},
transport: TransportConfig {
mode: raw.transport.as_ref().and_then(|t| t.mode.clone()).unwrap_or_else(default_transport_mode),
tcp_fragmentation: raw.transport.as_ref().and_then(|t| t.tcp_fragmentation).unwrap_or(false),
frag_chunk: raw.transport.as_ref().and_then(|t| t.frag_chunk).unwrap_or_else(default_frag_chunk),
frag_sleep: raw.transport.as_ref().and_then(|t| t.frag_sleep).unwrap_or_else(default_frag_sleep),
junk_pc: raw.transport.as_ref().and_then(|t| t.junk_pc).unwrap_or_else(default_junk_count),
junk_ps: raw.transport.as_ref().and_then(|t| t.junk_ps).unwrap_or_else(default_junk_size),
},
exclusions: ExclusionConfig {
domains: exclusions.domains.unwrap_or_default(),
ips: exclusions.ips.unwrap_or_default(),
processes: exclusions.processes.unwrap_or_default(),
},
multiplex: MultiplexConfig {
enabled: mux.enabled.unwrap_or(false),
sessions: mux.sessions.unwrap_or(1),
},
dns_server: raw.tun.as_ref().and_then(|t| t.dns.clone()),
tun_stack: raw.tun.as_ref().and_then(|t| t.stack.clone()).unwrap_or_else(|| "system".to_string()),
kill_switch: raw.tun.as_ref().and_then(|t| t.kill_switch).unwrap_or(false),
gui: raw.gui,
})
}
}
// 1. Log level
let log_level = if let Some(ll) = json.get("log_level") {
ll.clone()
} else if let Some(d) = json.get("debug") {
if d.as_bool().unwrap_or(false) { serde_json::json!("debug") } else { serde_json::json!("info") }
} else {
serde_json::json!("info")
};
new_json["log"] = serde_json::json!({ "level": log_level });
// ═══════════════════════════════════════════════════════════════════════
// On-disk config.json shapes — client, server, and relay.
//
// This is the ONE place these are defined. They used to be declared locally
// inside ostp/src/main.rs (the CLI binary) with no other consumer able to
// see them, which is exactly how ostp-client::migrate ended up working
// against loosely-typed serde_json::Value instead of a real schema, and how
// the CLI, the migrator, and this crate's own hot-reload path could each
// silently drift out of sync with what a config.json actually looks like.
// main.rs now imports these instead of re-declaring them (see the `use
// ostp_client::config::{...}` at its top).
//
// These are DELIBERATELY separate from ClientConfig/OstpConfig/etc. above:
// this section is the friendly, minimal shape a user actually edits by
// hand; the types above are what the running engine needs internally
// (handshake/io timeouts, resolved addresses, ...) and are built FROM one
// of these via the mapping in ostp/src/main.rs::run_client_directly. Only
// `ClientConfig` collides by name with the runtime type above, so the
// on-disk one is `ClientFileConfig` — everything else keeps its natural name.
// ═══════════════════════════════════════════════════════════════════════
#[derive(Debug, Deserialize, Serialize)]
#[serde(tag = "mode", rename_all = "lowercase")]
pub enum AppMode {
Server(ServerConfig),
Client(ClientFileConfig),
Relay(RelayServerConfig),
}
#[derive(Debug, Deserialize, Serialize)]
pub struct UnifiedConfig {
#[serde(flatten)]
pub mode: AppMode,
pub log_level: Option<String>,
}
impl UnifiedConfig {
pub fn validate(&self) -> Result<()> {
match &self.mode {
AppMode::Server(cfg) => {
if cfg.access_keys.is_empty() {
anyhow::bail!("Server configuration must contain at least one access_key.");
}
if let Some(outbound) = &cfg.outbound {
if outbound.enabled {
let action = outbound.default_action.as_deref().unwrap_or("direct");
if action == "direct" && outbound.rules.is_empty() {
println!("\n[WARNING] Server outbound proxy is ENABLED, but default_action is 'direct' and there are no rules!");
println!(" This means ALL traffic will bypass the proxy and go out directly from the server IP.");
println!(" If you want all traffic to be proxied, change 'default_action' to 'proxy'.\n");
}
}
}
}
AppMode::Client(cfg) => {
if cfg.access_key.is_empty() {
anyhow::bail!("Client configuration must contain an access_key.");
}
}
AppMode::Relay(cfg) => {
if cfg.upstream_tcp.is_empty() {
anyhow::bail!("Relay configuration must specify upstream_tcp address.");
}
if cfg.upstream_api_url.is_empty() {
anyhow::bail!("Relay configuration must specify upstream_api_url.");
}
// 2. Inbounds
let mut inbounds = Vec::new();
if let Some(tun) = json.get("tun") {
if tun.get("enable").and_then(|v| v.as_bool()).unwrap_or(false) {
inbounds.push(serde_json::json!({
"type": "tun",
"tag": "tun-in",
"auto_route": true,
"mtu": 1140
}));
}
}
Ok(())
}
}
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(untagged)]
pub enum UserConfig {
Detailed {
access_key: String,
name: Option<String>,
limit_bytes: Option<u64>,
},
KeyOnly(String),
}
let socks_bind = json.get("socks5_bind").and_then(|v| v.as_str()).unwrap_or("127.0.0.1:1088");
let parts: Vec<&str> = socks_bind.split(':').collect();
let listen = parts.get(0).unwrap_or(&"127.0.0.1");
let port = parts.get(1).unwrap_or(&"1088").parse::<u16>().unwrap_or(1088);
inbounds.push(serde_json::json!({
"type": "local_proxy",
"tag": "socks-in",
"protocol": "socks",
"listen": listen,
"port": port
}));
impl UserConfig {
pub fn key(&self) -> String {
match self {
UserConfig::KeyOnly(k) => k.clone(),
UserConfig::Detailed { access_key, .. } => access_key.clone(),
new_json["inbounds"] = serde_json::Value::Array(inbounds);
// 3. Outbounds
let mut outbounds = Vec::new();
let server_full = json.get("server").and_then(|v| v.as_str()).unwrap_or("127.0.0.1:50000");
let server_parts: Vec<&str> = server_full.split(':').collect();
let server_host = server_parts.get(0).unwrap_or(&"127.0.0.1");
let server_port = server_parts.get(1).unwrap_or(&"50000").parse::<u16>().unwrap_or(50000);
let access_key = json.get("access_key").and_then(|v| v.as_str()).unwrap_or("");
let transport_type = json.get("transport").and_then(|t| t.get("mode").or(t.get("type"))).and_then(|v| v.as_str()).unwrap_or("udp");
let mux_enabled = json.get("mux").and_then(|m| m.get("enabled")).and_then(|v| v.as_bool()).unwrap_or(false);
let mux_sessions = json.get("mux").and_then(|m| m.get("sessions")).and_then(|v| v.as_u64()).unwrap_or(1);
outbounds.push(serde_json::json!({
"type": "ostp",
"tag": "proxy",
"server": server_host,
"port": server_port,
"access_key": access_key,
"transport": {
"type": transport_type
},
"multiplex": {
"enabled": mux_enabled,
"sessions": mux_sessions
}
}));
outbounds.push(serde_json::json!({
"type": "direct",
"tag": "direct"
}));
outbounds.push(serde_json::json!({
"type": "block",
"tag": "block"
}));
new_json["outbounds"] = serde_json::Value::Array(outbounds);
// 4. Routing
let mut rules = Vec::new();
// Migrate exclusions to route to direct
if let Some(exclude) = json.get("exclude") {
if let Some(domains) = exclude.get("domains") {
rules.push(serde_json::json!({
"domain_suffix": domains,
"outbound": "direct"
}));
}
if let Some(ips) = exclude.get("ips") {
rules.push(serde_json::json!({
"ip_cidr": ips,
"outbound": "direct"
}));
}
if let Some(processes) = exclude.get("processes") {
rules.push(serde_json::json!({
"process_name": processes,
"outbound": "direct"
}));
}
}
}
pub fn name(&self) -> Option<String> {
match self {
UserConfig::KeyOnly(_) => None,
UserConfig::Detailed { name, .. } => name.clone(),
}
}
pub fn limit(&self) -> Option<u64> {
match self {
UserConfig::KeyOnly(_) => None,
UserConfig::Detailed { limit_bytes, .. } => *limit_bytes,
new_json["routing"] = serde_json::json!({
"rules": rules,
"default_outbound": "proxy"
});
// 5. Preserve GUI state
if let Some(gui) = json.get("gui") {
new_json["gui"] = gui.clone();
}
(new_json, true)
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ServerConfig {
pub listen: ListenConfig,
pub access_keys: Vec<UserConfig>,
pub debug: Option<bool>,
pub outbound: Option<OutboundConfig>,
pub api: Option<ApiConfig>,
pub fallback: Option<FallbackCfg>,
pub transport: Option<TransportConfigRaw>,
// Left untyped: ostp-client does not (and should not) depend on
// ostp-server just to name its DnsConfig type. The CLI binary — which
// already depends on both crates — deserializes this into
// ostp_server::dns::DnsConfig right before handing it to run_server().
pub dns: Option<serde_json::Value>,
}
/// Relay-node config.json shape.
#[derive(Debug, Deserialize, Serialize)]
pub struct RelayServerConfig {
/// Listen address(es) (UDP + TCP UoT)
pub listen: ListenConfig,
/// Upstream address for TCP (UoT) traffic
pub upstream_tcp: String,
/// Upstream address for UDP traffic
pub upstream_udp: String,
// ── Deprecated ──────────────────────────────────────────────────────────
// The relay used to authenticate clients itself and pulled the access-key
// list from the target server's management API to do it. It no longer does:
// sessions are authenticated end-to-end by the target server, and a relay
// that re-checks credentials only adds a weaker second gate plus a copy of
// the key list on a machine that does not need one. These are kept solely
// so existing relay configs still parse; they are ignored.
#[serde(default)]
pub upstream_api_url: String,
#[serde(default)]
pub upstream_api_token: String,
#[serde(default)]
pub sync_interval_secs: u64,
pub debug: Option<bool>,
}
/// Supports both a single string "0.0.0.0:50000" and an array
/// ["0.0.0.0:50000", "[::]:50000"].
#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(untagged)]
pub enum ListenConfig {
Single(String),
Multiple(Vec<String>),
}
impl ListenConfig {
pub fn addresses(&self) -> Vec<String> {
match self {
ListenConfig::Single(s) => vec![s.clone()],
ListenConfig::Multiple(v) => v.clone(),
}
}
pub fn primary(&self) -> String {
match self {
ListenConfig::Single(s) => s.clone(),
ListenConfig::Multiple(v) => v.first().cloned().unwrap_or_default(),
}
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ApiConfig {
pub enabled: Option<bool>,
pub bind: Option<String>,
pub token: Option<String>,
pub webpath: Option<String>,
pub username: Option<String>,
pub password_hash: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct FallbackCfg {
pub enabled: Option<bool>,
pub listen: Option<String>,
pub target: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ClientFileConfig {
pub server: String,
pub access_key: String,
pub mtu: Option<usize>,
pub socks5_bind: Option<String>,
pub tun: Option<TunConfig>,
pub debug: Option<bool>,
pub exclude: Option<ExcludeConfig>,
pub mux: Option<MuxConfig>,
pub transport: Option<TransportConfigRaw>,
pub gui: Option<serde_json::Value>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct TransportConfigRaw {
pub mode: Option<String>,
pub tcp_fragmentation: Option<bool>,
}
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct TunConfig {
pub enable: bool,
pub wintun_path: Option<String>,
pub ipv4_address: Option<String>,
pub dns: Option<String>,
pub kill_switch: Option<bool>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct OutboundConfig {
pub enabled: bool,
pub protocol: String,
pub address: String,
pub port: u16,
#[serde(default)]
pub rules: Vec<OutboundRule>,
pub default_action: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct OutboundRule {
pub domain_suffix: Option<Vec<String>>,
pub ip_cidr: Option<Vec<String>>,
pub protocol: Option<String>,
pub action: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct ExcludeConfig {
pub domains: Option<Vec<String>>,
pub ips: Option<Vec<String>>,
pub processes: Option<Vec<String>>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct MuxConfig {
pub enabled: Option<bool>,
pub sessions: Option<usize>,
}

View File

@ -0,0 +1,41 @@
use anyhow::{anyhow, Result};
use chacha20poly1305::{ChaCha20Poly1305, Nonce};
use chacha20poly1305::aead::{Aead, KeyInit};
use sha2::{Sha256, Digest};
/// Symmetric IPC channel encryption for the tun-helper ↔ GUI pipe.
///
/// Both sides derive the same key from the per-launch random token, so no
/// secret is ever passed on the command line. The zero nonce is safe here
/// because each session uses a fresh random token, making key reuse impossible.
#[derive(Clone)]
pub struct IpcCrypto {
cipher: ChaCha20Poly1305,
}
impl IpcCrypto {
pub fn new(key: &[u8; 32]) -> Self {
let cipher = ChaCha20Poly1305::new_from_slice(key)
.expect("32-byte key is always valid for ChaCha20Poly1305");
Self { cipher }
}
pub fn encrypt(&self, plaintext: &[u8]) -> Result<Vec<u8>> {
let nonce = Nonce::from_slice(&[0u8; 12]);
self.cipher.encrypt(nonce, plaintext)
.map_err(|e| anyhow!("IPC encrypt: {}", e))
}
pub fn decrypt(&self, ciphertext: &[u8]) -> Result<Vec<u8>> {
let nonce = Nonce::from_slice(&[0u8; 12]);
self.cipher.decrypt(nonce, ciphertext)
.map_err(|e| anyhow!("IPC decrypt: {}", e))
}
}
/// Derive a 32-byte key from the per-session random token.
pub fn derive_key(token: &str) -> [u8; 32] {
let mut key = [0u8; 32];
key.copy_from_slice(&Sha256::digest(token.as_bytes()));
key
}

View File

@ -1,7 +1,6 @@
pub mod app;
pub mod bridge;
pub mod config;
pub mod migrate;
pub mod signal;
pub mod sysproxy;
pub mod transport;
@ -10,3 +9,4 @@ pub mod tunnel;
pub mod runner;
pub mod logging;
pub mod ipc_crypto;

View File

@ -3,53 +3,6 @@ use std::io::Write;
use std::path::PathBuf;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
/// The single canonical log file for the whole core. Every process (CLI daemon,
/// GUI, TUN helper) and every subsystem (tracing, the core event logger, the
/// helper IPC, panics) writes here — no more per-binary / per-subsystem sprawl
/// (`ostp-cli.log` + `ostp-core.log` + `ostp-helper.log` + `ostp-crash.log`).
pub const LOG_FILE_NAME: &str = "ostp.log";
/// Absolute path to the shared log file, next to the running executable.
pub fn log_file_path() -> PathBuf {
std::env::current_exe()
.ok()
.and_then(|p| p.parent().map(|d| d.join(LOG_FILE_NAME)))
.unwrap_or_else(|| PathBuf::from(LOG_FILE_NAME))
}
/// True if this invocation is the long-running daemon (a client/server run),
/// as opposed to a one-shot subcommand (`gk`, `check`, `init`, `-V`, ...).
///
/// Used to gate log truncation: only the daemon clears the log at startup, so a
/// one-shot command run while a daemon is live can never wipe the daemon's log.
/// A daemon invocation is simply one that carries none of the one-shot tokens
/// (`ostp`, `ostp run`, `ostp connect <url>` → daemon; everything else → one-shot).
pub fn invocation_is_daemon<I: IntoIterator<Item = String>>(args: I) -> bool {
const ONE_SHOT: &[&str] = &[
"gk", "generate-key", "check", "init", "setup", "links", "import",
"update", "migrate", "prober", "proxy-env", "proxy-env-clear",
"uninstall", "-V", "--version", "-h", "--help", "help",
];
!args
.into_iter()
.skip(1) // program name
.any(|a| ONE_SHOT.contains(&a.as_str()))
}
/// Append a single timestamped line to the shared log file. Used by the manual
/// writers (core event logger, TUN helper IPC) so their output lands in the same
/// `ostp.log` as the tracing subscriber instead of a separate file.
pub fn append_line(msg: &str) {
if let Ok(mut file) = OpenOptions::new().create(true).append(true).open(log_file_path()) {
let _ = writeln!(
file,
"[{}] {}",
chrono::Local::now().format("%Y-%m-%d %H:%M:%S"),
msg
);
}
}
pub fn setup_panic_hook() {
std::panic::set_hook(Box::new(|info| {
let payload = info.payload();
@ -63,7 +16,7 @@ pub fn setup_panic_hook() {
let location = info.location().unwrap_or_else(|| std::panic::Location::caller());
let backtrace = std::backtrace::Backtrace::force_capture();
let crash_msg = format!(
"[{}] PANIC at {}:{}\nMessage: {}\nBacktrace:\n{:?}",
chrono::Local::now().format("%Y-%m-%d %H:%M:%S"),
@ -76,16 +29,19 @@ pub fn setup_panic_hook() {
eprintln!("{}", crash_msg);
tracing::error!("{}", crash_msg);
// Crashes land in the same shared log file (append — a crash must never
// truncate, and the tracing worker may already be dead so we write direct).
if let Ok(mut file) = OpenOptions::new().create(true).append(true).open(log_file_path()) {
let path = std::env::current_exe()
.ok()
.and_then(|p| p.parent().map(|d| d.join("ostp-crash.log")))
.unwrap_or_else(|| PathBuf::from("ostp-crash.log"));
if let Ok(mut file) = OpenOptions::new().create(true).append(true).open(path) {
let _ = file.write_all(crash_msg.as_bytes());
let _ = file.write_all(b"\n===================================================\n");
}
}));
}
/// Initialises tracing and writes to the shared `ostp.log` next to the executable.
/// Initialises tracing and writes to `<app_name>.log` next to the executable.
///
/// The `level` parameter controls the minimum log level:
/// - `"error"` — only errors
@ -95,17 +51,7 @@ pub fn setup_panic_hook() {
/// - `"trace"` — all messages including very verbose internal state
///
/// The environment variable `RUST_LOG` overrides this value if set.
///
/// `truncate`: clear the log at startup. Honoured **only on Windows** — Linux
/// servers keep their history (OS-rotated). Pass `true` only from the daemon's
/// own entrypoint; one-shot commands and child processes (the TUN helper) pass
/// `false` so they append instead of wiping a running daemon's log.
pub fn init_tracing(
level: &str,
app_name: &str,
version: &str,
truncate: bool,
) -> Option<tracing_appender::non_blocking::WorkerGuard> {
pub fn init_tracing(level: &str, app_name: &str, version: &str) -> Option<tracing_appender::non_blocking::WorkerGuard> {
// RUST_LOG overrides the config-derived level
let env_filter = EnvFilter::try_from_default_env()
.unwrap_or_else(|_| {
@ -120,30 +66,37 @@ pub fn init_tracing(
}
});
let path = log_file_path();
let path = std::env::current_exe()
.ok()
.and_then(|p| p.parent().map(|d| d.join(format!("{}.log", app_name))))
.unwrap_or_else(|| PathBuf::from(format!("{}.log", app_name)));
let mut open_opts = OpenOptions::new();
open_opts.create(true);
// Truncate-on-startup is Windows-only and daemon-only. Everywhere else append:
// Linux keeps server history, and one-shot commands / the TUN helper must not
// wipe a running daemon's log.
if truncate && cfg!(windows) {
open_opts.write(true).truncate(true);
} else {
open_opts.append(true);
}
if let Ok(file) = OpenOptions::new().create(true).append(true).open(&path) {
let (file_writer, guard) = tracing_appender::non_blocking(file);
if let Ok(mut file) = open_opts.open(&path) {
// Write the startup banner directly to the log file, bypassing the
// tracing subscriber entirely. Emitting it via tracing::info!() hits
// BOTH layers below (file AND stderr), so every one-shot CLI command
// (`ostp -V`, `ostp gk`, `ostp check`, ...) printed this banner to the
// terminal on every single invocation — pure noise for anything that
// isn't the long-running daemon. It's still genuinely useful for
// whoever's reading the log file later, so keep it there, just not on
// screen for commands that aren't the daemon.
let _ = writeln!(
file,
let timer = tracing_subscriber::fmt::time::UtcTime::rfc_3339();
let fmt_layer = tracing_subscriber::fmt::layer()
.with_target(true)
.with_line_number(false)
.with_thread_ids(false)
.with_thread_names(false)
.with_ansi(false)
.with_timer(timer.clone())
.with_writer(file_writer);
let stderr_layer = tracing_subscriber::fmt::layer()
.with_target(true)
.with_timer(timer)
.with_writer(std::io::stderr);
let _ = tracing_subscriber::registry()
.with(env_filter)
.with(fmt_layer)
.with(stderr_layer)
.try_init();
tracing::debug!(
"{} v{} | OS: {} | Arch: {} | log_level: {} | log_file: {}",
app_name,
version,
@ -152,32 +105,13 @@ pub fn init_tracing(
level,
path.display(),
);
let (file_writer, guard) = tracing_appender::non_blocking(file);
let fmt_layer = tracing_subscriber::fmt::layer()
.with_target(true)
.with_line_number(true)
.with_thread_ids(false)
.with_thread_names(false)
.with_ansi(false)
.with_writer(file_writer);
let stderr_layer = tracing_subscriber::fmt::layer()
.with_target(true)
.with_writer(std::io::stderr);
let _ = tracing_subscriber::registry()
.with(env_filter)
.with(fmt_layer)
.with(stderr_layer)
.try_init();
Some(guard)
} else {
// Fallback: stderr only
let stderr_layer = tracing_subscriber::fmt::layer()
.with_target(true)
.with_timer(tracing_subscriber::fmt::time::UtcTime::rfc_3339())
.with_writer(std::io::stderr);
let _ = tracing_subscriber::registry()
.with(EnvFilter::new(level))

View File

@ -1,559 +0,0 @@
//! The ONE authoritative place that upgrades an old `config.json` to the
//! current schema. Reachable only via the explicit `ostp migrate` command —
//! nothing else in this codebase silently rewrites a user's config on their
//! behalf (the old 0.3.x line used to auto-migrate on every load with just a
//! log warning; that's exactly the kind of "invisible until something looks
//! wrong" behavior this module replaces).
//!
//! Every field this module cannot map forward is reported explicitly in
//! `MigrationReport.notes`, never silently dropped without a trace.
use serde_json::{json, Value};
#[derive(Debug, Default)]
pub struct MigrationReport {
/// Whether anything was actually different from the current schema.
pub changed: bool,
/// Human-readable line per field added, converted, or dropped.
pub notes: Vec<String>,
}
impl MigrationReport {
fn note(&mut self, msg: impl Into<String>) {
self.changed = true;
self.notes.push(msg.into());
}
}
/// Which config this file is (mirrors `AppMode`'s `"mode"` tag). Old configs
/// from before that tag existed are sniffed structurally as a fallback.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConfigKind {
Client,
Server,
Relay,
}
pub fn detect_kind(json: &Value) -> Option<ConfigKind> {
match json.get("mode").and_then(|v| v.as_str()) {
Some("client") => return Some(ConfigKind::Client),
Some("server") => return Some(ConfigKind::Server),
Some("relay") => return Some(ConfigKind::Relay),
_ => {}
}
// No (or unrecognized) "mode" tag — this is an older config from before
// it was mandatory. Sniff by the fields that have been present on each
// shape since the earliest surviving config format.
if json.get("upstream_tcp").is_some() || json.get("upstream_api_url").is_some() {
Some(ConfigKind::Relay)
} else if json.get("access_keys").is_some() || json.get("listen").is_some() {
Some(ConfigKind::Server)
} else if json.get("access_key").is_some() || json.get("server").is_some() {
Some(ConfigKind::Client)
} else {
None
}
}
/// Migrates a client config of any known past shape to the current flat
/// schema. Returns the migrated JSON and a report of every change made.
///
/// Known input shapes, oldest first:
/// - **v0.3.1v0.3.21 "modular multi-server"**: `inbounds`/`outbounds` arrays
/// + `routing.rules`. Only the first `ostp`-type outbound is kept (this
/// line no longer supports multiple simultaneous servers); every other
/// `ostp` outbound is reported by tag+address so nothing vanishes
/// invisibly. `urltest`/`selector`/`direct`/`block` outbounds have no
/// equivalent and are dropped (reported).
/// - **pre-0.3.1 flat (up to v0.2.98)**: same field names as today
/// (`server`, `access_key`, `tun`, `exclude`, `mux`, `transport`, ...)
/// except `tun.wintun_path`/`tun.ipv4_address` (internal driver detail,
/// never user-meaningful data) and `transport.wss` (the WSS framing
/// feature removed entirely in the 0.4.0 rebuild) — both dropped with an
/// explicit note; everything else maps 1:1, nothing to convert.
/// - **configs carrying a leftover `transport.stealth_sni`**: dropped with a
/// note, same reasoning as `wss` — it never fed into anything on the wire
/// (no TLS/HTTP mimicry exists in this project), so there is no successor
/// field. Not tied to a specific version: it lingered in the schema well
/// past when the mimicry work it was meant for got removed.
/// - **current flat schema**: no-op, `changed = false`.
pub fn migrate_client_json(json: Value) -> (Value, MigrationReport) {
let mut report = MigrationReport::default();
let has_inbounds = json.get("inbounds").and_then(|v| v.as_array()).is_some();
let has_outbounds = json.get("outbounds").and_then(|v| v.as_array()).is_some();
if has_inbounds && has_outbounds {
return migrate_client_from_modular(json, report);
}
// Flat shape already (current or pre-0.3.1) — normalize obsolete fields
// in place rather than rebuilding the whole document from scratch, so
// any field this module doesn't know about yet still survives untouched.
let mut out = json;
if let Some(tun) = out.get_mut("tun").and_then(|t| t.as_object_mut()) {
for dead_field in ["wintun_path", "ipv4_address"] {
if tun.remove(dead_field).is_some() {
report.note(format!(
"Dropped tun.{dead_field} — internal driver detail from an older WinTun \
integration, not applicable to the current TUN implementation."
));
}
}
}
if let Some(transport) = out.get_mut("transport").and_then(|t| t.as_object_mut()) {
if transport.remove("wss").is_some() {
report.note(
"Dropped transport.wss — WSS framing was removed in the 0.4.0 rebuild \
(the project follows a zapret-like approach: no protocol mimicry, \
just packet-level obfuscation/manipulation, so there is no successor field)."
.to_string(),
);
}
if transport.remove("stealth_sni").is_some() {
report.note(
"Dropped transport.stealth_sni — never actually used to construct any wire \
bytes (no TLS/HTTP mimicry exists in this project same zapret-like \
reasoning as transport.wss), so it was unused config plumbing with no effect."
.to_string(),
);
}
}
(out, report)
}
fn migrate_client_from_modular(json: Value, mut report: MigrationReport) -> (Value, MigrationReport) {
report.changed = true; // the shape itself is being replaced regardless of field-level detail
let inbounds = json.get("inbounds").and_then(|v| v.as_array()).cloned().unwrap_or_default();
let outbounds = json.get("outbounds").and_then(|v| v.as_array()).cloned().unwrap_or_default();
let routing = json.get("routing").cloned().unwrap_or(json!({}));
let default_outbound = routing.get("default_outbound").and_then(|v| v.as_str()).map(String::from);
// ── Pick the primary "ostp" outbound ────────────────────────────────
// Prefer the one routing.default_outbound points at (directly, or via a
// urltest/selector group that references it); otherwise take the first
// ostp outbound in file order. Every other ostp outbound is reported by
// tag+address, not silently discarded.
let ostp_outbounds: Vec<&Value> = outbounds
.iter()
.filter(|o| o.get("type").and_then(|t| t.as_str()) == Some("ostp"))
.collect();
// default_outbound might name an ostp outbound directly, OR name a
// urltest/selector GROUP whose first member is the one to actually use —
// check both, since a plain `.or_else` here would never even attempt the
// group lookup while default_outbound is Some(_) (which it almost always
// is), silently falling through to "just take the first ostp outbound in
// file order" instead — exactly the kind of silent wrong answer this
// migrator exists to avoid.
let primary_tag: Option<String> = default_outbound.as_deref().and_then(|def_tag| {
if ostp_outbounds.iter().any(|o| o.get("tag").and_then(|t| t.as_str()) == Some(def_tag)) {
return Some(def_tag.to_string());
}
outbounds.iter().find_map(|o| {
let is_group = matches!(o.get("type").and_then(|t| t.as_str()), Some("urltest") | Some("selector"));
let tag_matches = o.get("tag").and_then(|t| t.as_str()) == Some(def_tag);
if is_group && tag_matches {
o.get("outbounds")
.and_then(|v| v.as_array())
.and_then(|arr| arr.first())
.and_then(|v| v.as_str())
.map(String::from)
} else {
None
}
})
});
let primary = primary_tag
.as_deref()
.and_then(|tag| ostp_outbounds.iter().find(|o| o.get("tag").and_then(|t| t.as_str()) == Some(tag)))
.copied()
.or_else(|| ostp_outbounds.first().copied());
let Some(primary) = primary else {
report.note(
"No 'ostp'-type outbound found in the old modular config — nothing to migrate \
the server connection from. Wrote a placeholder; you MUST fill in server/access_key \
by hand or re-import a share link."
.to_string(),
);
return (
json!({
"server": "127.0.0.1:50000",
"access_key": "",
}),
report,
);
};
for other in &ostp_outbounds {
if !std::ptr::eq(*other, primary) {
let tag = other.get("tag").and_then(|t| t.as_str()).unwrap_or("?");
let addr = other.get("server").and_then(|t| t.as_str()).unwrap_or("?");
let port = other.get("port").and_then(|t| t.as_u64()).unwrap_or(0);
report.note(format!(
"Dropped additional server '{tag}' ({addr}:{port}) — multi-server / urltest \
failover is no longer supported; only one server per config now. Kept the \
one from routing.default_outbound (or the first one if that wasn't set)."
));
}
}
let server = primary.get("server").and_then(|v| v.as_str()).unwrap_or("127.0.0.1").to_string();
let port = primary.get("port").and_then(|v| v.as_u64()).unwrap_or(50000);
let access_key = primary.get("access_key").and_then(|v| v.as_str()).unwrap_or("").to_string();
let transport_type = primary
.get("transport")
.and_then(|t| t.get("type").or_else(|| t.get("mode")))
.and_then(|v| v.as_str())
.unwrap_or("udp")
.to_string();
if let Some(sni) = primary.get("transport").and_then(|t| t.get("stealth_sni")).and_then(|v| v.as_str()) {
if !sni.is_empty() {
report.note(format!(
"Dropped transport.stealth_sni ({sni:?}) — never actually used to construct \
any wire bytes; unused config plumbing with no successor field."
));
}
}
let tcp_fragmentation = primary
.get("transport")
.and_then(|t| t.get("tcp_fragmentation"))
.and_then(|v| v.as_bool())
.unwrap_or(false);
let mux_enabled = primary.get("multiplex").and_then(|m| m.get("enabled")).and_then(|v| v.as_bool()).unwrap_or(false);
let mux_sessions = primary.get("multiplex").and_then(|m| m.get("sessions")).and_then(|v| v.as_u64()).unwrap_or(1);
// ── TUN + local proxy inbounds ───────────────────────────────────────
let tun_inbound = inbounds.iter().find(|i| i.get("type").and_then(|t| t.as_str()) == Some("tun"));
let proxy_inbound = inbounds.iter().find(|i| i.get("type").and_then(|t| t.as_str()) == Some("local_proxy"));
let tun_enable = tun_inbound.is_some();
let mtu = tun_inbound.and_then(|t| t.get("mtu")).and_then(|v| v.as_u64());
let socks5_bind = proxy_inbound
.map(|p| {
let listen = p.get("listen").and_then(|v| v.as_str()).unwrap_or("127.0.0.1");
let port = p.get("port").and_then(|v| v.as_u64()).unwrap_or(1088);
format!("{listen}:{port}")
})
.unwrap_or_else(|| "127.0.0.1:1088".to_string());
// ── Exclusions from routing.rules → direct ──────────────────────────
let mut ex_domains: Vec<String> = Vec::new();
let mut ex_ips: Vec<String> = Vec::new();
let mut ex_processes: Vec<String> = Vec::new();
if let Some(rules) = routing.get("rules").and_then(|v| v.as_array()) {
for rule in rules {
if rule.get("outbound").and_then(|v| v.as_str()) != Some("direct") {
continue; // only "route to direct" rules were ever exclusions in the old format
}
if let Some(v) = rule.get("domain_suffix").and_then(|v| v.as_array()) {
ex_domains.extend(v.iter().filter_map(|s| s.as_str().map(String::from)));
}
if let Some(v) = rule.get("ip_cidr").and_then(|v| v.as_array()) {
ex_ips.extend(v.iter().filter_map(|s| s.as_str().map(String::from)));
}
if let Some(v) = rule.get("process_name").and_then(|v| v.as_array()) {
ex_processes.extend(v.iter().filter_map(|s| s.as_str().map(String::from)));
}
}
}
for other_rule_outbound in routing
.get("rules")
.and_then(|v| v.as_array())
.into_iter()
.flatten()
.filter_map(|r| r.get("outbound").and_then(|v| v.as_str()))
.filter(|o| *o != "direct")
{
report.note(format!(
"Dropped a routing rule targeting outbound '{other_rule_outbound}' — only \
\"route to direct\" rules map to today's exclusions; anything else \
(custom per-domain outbound selection) has no equivalent anymore."
));
}
let debug = json.get("log").and_then(|l| l.get("level")).and_then(|v| v.as_str()) == Some("debug");
let mut client = json!({
"server": server,
"port": port,
"access_key": access_key,
"socks5_bind": socks5_bind,
"debug": debug,
"tun": {
"enable": tun_enable,
"dns": null,
"kill_switch": false,
},
"exclude": {
"domains": ex_domains,
"ips": ex_ips,
"processes": ex_processes,
},
"mux": {
"enabled": mux_enabled,
"sessions": mux_sessions,
},
"transport": {
"mode": transport_type,
"tcp_fragmentation": tcp_fragmentation,
},
});
if let Some(mtu) = mtu {
client["mtu"] = json!(mtu);
}
if let Some(gui) = json.get("gui") {
client["gui"] = gui.clone();
}
(client, report)
}
/// Migrates a server config. The server shape has stayed structurally
/// identical since the earliest surviving version — this only backfills the
/// `api` section (added after some configs already existed) and drops the
/// legacy `api.token` field. Ported from the ad-hoc Python snippet that used
/// to live in `scripts/install.sh` and only ran at install/update time.
pub fn migrate_server_json(json: Value) -> (Value, MigrationReport) {
let mut report = MigrationReport::default();
let mut out = json;
let obj = match out.as_object_mut() {
Some(o) => o,
None => return (out, report),
};
let api = obj.entry("api").or_insert_with(|| json!({}));
if let Some(api_obj) = api.as_object_mut() {
let defaults: [(&str, Value); 5] = [
("enabled", json!(false)),
("bind", json!("0.0.0.0:9090")),
("webpath", json!("")),
("username", json!("")),
("password_hash", json!("")),
];
for (key, default) in defaults {
if !api_obj.contains_key(key) {
report.note(format!("Added api.{key} = {default} (missing default)"));
api_obj.insert(key.to_string(), default);
}
}
if api_obj.remove("token").is_some() {
report.note(
"Dropped legacy api.token — superseded by api.password_hash; \
set a new admin password with the management API or panel."
.to_string(),
);
}
}
(out, report)
}
#[cfg(test)]
mod tests {
use super::*;
/// A realistic v0.3.21-shaped modular config (TUN + local_proxy inbounds,
/// a single ostp outbound, exclusion rules, mux) — mirrors the actual
/// shape from that tag, field for field.
#[test]
fn modular_single_server_preserves_every_field() {
let old = json!({
"version": "0.3.21",
"log": { "level": "debug" },
"inbounds": [
{ "type": "tun", "tag": "tun-in", "auto_route": true, "mtu": 1350 },
{ "type": "local_proxy", "tag": "socks-in", "protocol": "socks", "listen": "127.0.0.1", "port": 1088 }
],
"outbounds": [
{
"type": "ostp", "tag": "proxy",
"server": "203.0.113.5", "port": 50000, "access_key": "sekrit123",
"transport": { "type": "uot", "stealth_sni": "vk.com", "tcp_fragmentation": true },
"multiplex": { "enabled": true, "sessions": 4 }
},
{ "type": "direct", "tag": "direct" },
{ "type": "block", "tag": "block" }
],
"routing": {
"rules": [
{ "domain_suffix": ["local.lan", "internal.corp"], "outbound": "direct" },
{ "ip_cidr": ["192.168.0.0/16"], "outbound": "direct" },
{ "process_name": ["steam.exe"], "outbound": "direct" }
],
"default_outbound": "proxy"
}
});
let (new, report) = migrate_client_json(old);
assert!(report.changed);
assert_eq!(new["server"], "203.0.113.5");
assert_eq!(new["port"], 50000);
assert_eq!(new["access_key"], "sekrit123");
assert_eq!(new["socks5_bind"], "127.0.0.1:1088");
assert_eq!(new["mtu"], 1350);
assert_eq!(new["debug"], true);
assert_eq!(new["tun"]["enable"], true);
assert_eq!(new["transport"]["mode"], "uot");
assert_eq!(new["transport"]["tcp_fragmentation"], true);
assert_eq!(new["mux"]["enabled"], true);
assert_eq!(new["mux"]["sessions"], 4);
assert_eq!(new["exclude"]["domains"], json!(["local.lan", "internal.corp"]));
assert_eq!(new["exclude"]["ips"], json!(["192.168.0.0/16"]));
assert_eq!(new["exclude"]["processes"], json!(["steam.exe"]));
// stealth_sni never fed into any wire bytes — dropped, not carried forward.
assert!(new["transport"].get("stealth_sni").is_none());
assert!(report.notes.iter().any(|n| n.contains("stealth_sni") && n.contains("vk.com")));
}
/// Old modular configs that had MULTIPLE ostp outbounds (multi-server) —
/// must keep the one routing.default_outbound points at and report every
/// other one by name/address rather than picking silently.
#[test]
fn modular_multi_server_keeps_default_and_reports_the_rest() {
let old = json!({
"inbounds": [],
"outbounds": [
{ "type": "ostp", "tag": "proxy-0", "server": "1.1.1.1", "port": 50000, "access_key": "k1" },
{ "type": "ostp", "tag": "proxy-1", "server": "2.2.2.2", "port": 50000, "access_key": "k2" },
{
"type": "urltest", "tag": "proxy",
"outbounds": ["proxy-1", "proxy-0"], "url": "http://cp.cloudflare.com"
}
],
"routing": { "rules": [], "default_outbound": "proxy" }
});
let (new, report) = migrate_client_json(old);
// urltest's first member (proxy-1 / 2.2.2.2) is the one actually picked.
assert_eq!(new["server"], "2.2.2.2");
assert_eq!(new["access_key"], "k2");
assert!(report.notes.iter().any(|n| n.contains("proxy-0") && n.contains("1.1.1.1")));
}
/// Pre-0.3.1 flat config carrying fields that no longer exist
/// (tun.wintun_path, tun.ipv4_address, transport.wss, transport.stealth_sni)
/// — those get dropped with a note; every field that's still meaningful
/// passes through untouched, byte for byte.
#[test]
fn flat_legacy_drops_only_dead_fields() {
let old = json!({
"server": "198.51.100.9:50000",
"access_key": "oldkey",
"mtu": 1200,
"socks5_bind": "127.0.0.1:1090",
"tun": {
"enable": true,
"wintun_path": "C:\\Program Files\\wintun\\wintun.dll",
"ipv4_address": "10.0.0.2",
"dns": "1.1.1.1",
"kill_switch": true
},
"exclude": { "domains": ["a.com"], "ips": null, "processes": null },
"mux": { "enabled": false, "sessions": 1 },
"transport": { "mode": "udp", "stealth_sni": "bing.com", "wss": true }
});
let (new, report) = migrate_client_json(old);
assert!(report.changed);
// Untouched fields survive exactly as they were.
assert_eq!(new["server"], "198.51.100.9:50000");
assert_eq!(new["access_key"], "oldkey");
assert_eq!(new["mtu"], 1200);
assert_eq!(new["tun"]["enable"], true);
assert_eq!(new["tun"]["dns"], "1.1.1.1");
assert_eq!(new["tun"]["kill_switch"], true);
assert_eq!(new["exclude"]["domains"], json!(["a.com"]));
// Dead fields are gone...
assert!(new["tun"].get("wintun_path").is_none());
assert!(new["tun"].get("ipv4_address").is_none());
assert!(new["transport"].get("wss").is_none());
assert!(new["transport"].get("stealth_sni").is_none());
// ...and their removal was reported, not silent.
assert!(report.notes.iter().any(|n| n.contains("wintun_path")));
assert!(report.notes.iter().any(|n| n.contains("ipv4_address")));
assert!(report.notes.iter().any(|n| n.contains("wss")));
assert!(report.notes.iter().any(|n| n.contains("stealth_sni")));
}
/// A config already in the current shape must be a true no-op: report
/// says nothing changed, and every field is untouched.
#[test]
fn current_flat_config_is_a_no_op() {
let current = json!({
"server": "example.com:50000",
"access_key": "k",
"tun": { "enable": false, "dns": null, "kill_switch": false },
"exclude": { "domains": [], "ips": [], "processes": [] },
"mux": { "enabled": false, "sessions": 1 },
"transport": { "mode": "udp", "tcp_fragmentation": false }
});
let (new, report) = migrate_client_json(current.clone());
assert!(!report.changed);
assert_eq!(new, current);
}
/// Every migrated output must actually deserialize into the ONE
/// canonical schema (`crate::config`) — this is the same check
/// `cmd_migrate` runs at runtime before ever touching a user's file,
/// exercised here directly so a schema/migrator drift fails a fast unit
/// test instead of surfacing as "your migrated config won't load".
#[test]
fn every_migrated_output_matches_the_canonical_schema() {
let modular = json!({
"inbounds": [{ "type": "tun", "tag": "tun-in", "mtu": 1350 }],
"outbounds": [
{ "type": "ostp", "tag": "proxy", "server": "1.2.3.4", "port": 50000, "access_key": "k" },
{ "type": "direct", "tag": "direct" }
],
"routing": { "rules": [], "default_outbound": "proxy" }
});
let (new, _) = migrate_client_json(modular);
serde_json::from_value::<crate::config::ClientFileConfig>(new)
.expect("modular->flat migration output must match ClientFileConfig");
let legacy_flat = json!({
"server": "1.2.3.4:50000",
"access_key": "k",
"tun": { "enable": true, "wintun_path": "x", "ipv4_address": "y" }
});
let (new, _) = migrate_client_json(legacy_flat);
serde_json::from_value::<crate::config::ClientFileConfig>(new)
.expect("legacy-flat migration output must match ClientFileConfig");
let server = json!({ "listen": "0.0.0.0:50000", "access_keys": ["k"] });
let (new, _) = migrate_server_json(server);
serde_json::from_value::<crate::config::ServerConfig>(new)
.expect("server migration output must match ServerConfig");
}
#[test]
fn server_config_backfills_api_defaults_and_drops_legacy_token() {
let old = json!({
"listen": "0.0.0.0:50000",
"access_keys": ["k1"],
"api": { "token": "old-plain-token" }
});
let (new, report) = migrate_server_json(old);
assert!(report.changed);
assert_eq!(new["api"]["enabled"], false);
assert_eq!(new["api"]["bind"], "0.0.0.0:9090");
assert!(new["api"].get("token").is_none());
assert!(report.notes.iter().any(|n| n.contains("api.token")));
}
#[test]
fn detect_kind_falls_back_to_structural_sniffing_without_mode_tag() {
assert_eq!(detect_kind(&json!({"access_key": "x", "server": "y"})), Some(ConfigKind::Client));
assert_eq!(detect_kind(&json!({"access_keys": ["x"], "listen": "y"})), Some(ConfigKind::Server));
assert_eq!(detect_kind(&json!({"upstream_tcp": "x", "upstream_api_url": "y"})), Some(ConfigKind::Relay));
assert_eq!(detect_kind(&json!({"mode": "client", "server": "x"})), Some(ConfigKind::Client));
}
}

View File

@ -1,488 +1,153 @@
use anyhow::Result;
use anyhow::{anyhow, Result};
use std::sync::Arc;
use tokio::sync::{mpsc, watch};
use crate::app::BridgeCommand;
use crate::bridge::{Bridge, BridgeMetrics};
use crate::signal::wait_for_shutdown_signal;
use crate::tunnel;
use std::sync::Arc;
use std::fs::OpenOptions;
use std::io::Write as _;
use crate::config::{ClientConfig, InboundConfig};
use crate::tunnel::balancer::Balancer;
use crate::tunnel::outbounds::OutboundManager;
use crate::tunnel::router::Router;
fn log_to_core_file(msg: &str) {
// Writes into the single shared ostp.log (same file as the tracing appender),
// not a separate ostp-core.log — see logging::LOG_FILE_NAME.
let path = crate::logging::log_file_path();
if let Ok(mut file) = OpenOptions::new().create(true).append(true).open(path) {
let _ = writeln!(file, "[{}] {}", chrono::Local::now().format("%Y-%m-%d %H:%M:%S"), msg);
}
}
#[cfg(target_os = "windows")]
#[link(name = "kernel32")]
extern "system" {
fn FreeConsole() -> i32;
fn GetConsoleWindow() -> *mut std::ffi::c_void;
}
#[cfg(target_os = "windows")]
#[link(name = "user32")]
extern "system" {
fn ShowWindow(hwnd: *mut std::ffi::c_void, cmd_show: i32) -> i32;
}
fn hide_console() {
#[cfg(target_os = "windows")]
unsafe {
let hwnd = GetConsoleWindow();
if !hwnd.is_null() {
ShowWindow(hwnd, 0); // SW_HIDE = 0
}
FreeConsole();
}
}
#[cfg(target_os = "windows")]
pub fn is_admin() -> bool {
std::process::Command::new("net")
.arg("session")
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.map(|s| s.success())
.unwrap_or(false)
}
#[cfg(target_os = "windows")]
fn relaunch_as_admin() -> Result<()> {
use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
use std::ptr::null_mut;
let exe = std::env::current_exe()?;
let exe_wstr: Vec<u16> = exe.as_os_str().encode_wide().chain(Some(0)).collect();
let mut args_joined = String::new();
for arg in std::env::args().skip(1) {
if !args_joined.is_empty() {
args_joined.push(' ');
}
args_joined.push('"');
args_joined.push_str(&arg.replace('"', "\\\""));
args_joined.push('"');
}
let args_wstr: Vec<u16> = OsStr::new(&args_joined).encode_wide().chain(Some(0)).collect();
let dir = std::env::current_dir()?;
let dir_wstr: Vec<u16> = dir.as_os_str().encode_wide().chain(Some(0)).collect();
let verb_wstr: Vec<u16> = OsStr::new("runas").encode_wide().chain(Some(0)).collect();
#[link(name = "shell32")]
extern "system" {
fn ShellExecuteW(
hwnd: *mut std::ffi::c_void,
lpOperation: *const u16,
lpFile: *const u16,
lpParameters: *const u16,
lpDirectory: *const u16,
nShowCmd: i32,
) -> isize;
}
unsafe {
let ret = ShellExecuteW(
null_mut(),
verb_wstr.as_ptr(),
exe_wstr.as_ptr(),
args_wstr.as_ptr(),
dir_wstr.as_ptr(),
1, // SW_SHOWNORMAL = 1
);
if ret <= 32 {
return Err(anyhow::anyhow!(
"Windows UAC Elevation failed or was denied by policy (ShellExecuteW code: {})",
ret
));
}
}
std::process::exit(0);
}
#[cfg(target_os = "linux")]
pub fn is_root() -> bool {
unsafe { libc::geteuid() == 0 }
}
#[cfg(target_os = "linux")]
fn relaunch_as_root() -> Result<()> {
use std::io::IsTerminal;
let exe = std::env::current_exe()?;
let args: Vec<String> = std::env::args().skip(1).collect();
let is_gui = std::env::var("DISPLAY").is_ok() || std::env::var("WAYLAND_DISPLAY").is_ok();
let is_term = std::io::stdout().is_terminal();
let mut cmd = if is_gui && !is_term {
let mut c = std::process::Command::new("pkexec");
c.arg(exe);
c
} else {
let mut c = std::process::Command::new("sudo");
c.arg(exe);
c
};
cmd.args(&args);
let status = cmd.status().map_err(|e| anyhow::anyhow!("Failed to execute privilege escalation command: {}", e))?;
if !status.success() {
return Err(anyhow::anyhow!("Privilege escalation failed or was denied."));
}
std::process::exit(0);
}
pub async fn run_client(config: crate::config::ClientConfig) -> Result<()> {
#[cfg(target_os = "windows")]
if config.mode == "tun" && !is_admin() {
println!("[ostp] TUN mode requires administrator privileges. Relaunching...");
relaunch_as_admin()?;
}
#[cfg(target_os = "linux")]
if config.mode == "tun" && !is_root() {
println!("[ostp] TUN mode requires root privileges. Requesting sudo/pkexec elevation...");
relaunch_as_root()?;
}
let bg = std::env::args().any(|a| a == "--bg");
if bg {
hide_console();
}
let metrics = Arc::new(BridgeMetrics {
bytes_sent: portable_atomic::AtomicU64::new(0),
bytes_recv: portable_atomic::AtomicU64::new(0),
connection_state: portable_atomic::AtomicU8::new(0),
rtt_ms: portable_atomic::AtomicU32::new(0),
});
let (shutdown_tx, shutdown_rx) = watch::channel(false);
tokio::spawn(async move {
if wait_for_shutdown_signal().await.is_ok() {
let _ = shutdown_tx.send(true);
}
});
run_client_core(config, metrics, shutdown_rx, None).await
}
/// Runs the client with auto-reconnect: any subsystem ending — a network
/// change stranding the TUN adapter/UDP socket on a dead interface, the OSTP
/// protocol connection dropping in a way the inner Bridge-level retry (see
/// `UiEvent::TunnelStopped` below) couldn't recover from, or a proxy/TUN task
/// crashing outright — triggers a full clean restart (fresh DNS resolution,
/// fresh Bridge, fresh TUN/proxy) with exponential backoff, instead of the
/// client just dying. Only an explicit shutdown request stops this loop.
pub async fn run_client_core(
config: crate::config::ClientConfig,
metrics: Arc<BridgeMetrics>,
config: ClientConfig,
metrics: Arc<crate::bridge::BridgeMetrics>,
mut shutdown_rx_ext: watch::Receiver<bool>,
config_rx: Option<watch::Receiver<crate::config::ClientConfig>>,
_config_rx: Option<watch::Receiver<ClientConfig>>,
) -> Result<()> {
use portable_atomic::Ordering;
tracing::info!("starting client core");
const BACKOFF_SCHEDULE_SECS: [u64; 6] = [1, 2, 5, 10, 20, 30];
// A run that stayed up at least this long counts as "was actually
// connected", so a later drop restarts the backoff from the top instead
// of inheriting a long delay from a previous flaky stretch.
const STABLE_UPTIME: std::time::Duration = std::time::Duration::from_secs(60);
let mut backoff_idx = 0usize;
// Report "connecting" until the primary inbound has fully come up. The TUN
// inbound flips this to 2 (connected) only after the device and the server
// bypass route are installed; the SOCKS inbound does so only when it is the
// primary (SOCKS-only mode). If any inbound's setup fails the whole connect
// aborts and we reset to 0 — the GUI never sees a fake "connected".
metrics.connection_state.store(1, Ordering::Relaxed);
loop {
if *shutdown_rx_ext.borrow() {
return Ok(());
let router = Arc::new(Router::new(config.routing.clone()));
let balancer = Arc::new(Balancer::new(&config));
// TODO: Detect physical interface index for bypassing
let phys_if_for_bypass = None;
let outbound_manager = Arc::new(OutboundManager::new(balancer.clone(), phys_if_for_bypass, None));
// When a TUN inbound is present it is the primary one and owns the connected
// state; the SOCKS proxy is then secondary and must not report "connected".
let has_tun = config
.inbounds
.iter()
.any(|i| matches!(i, InboundConfig::Tun { .. }));
// Any inbound that fails its setup reports the error here; the first report
// aborts the whole connect so we never come up half-broken.
let (failure_tx, mut failure_rx) = mpsc::channel::<String>(4);
let mut handles = Vec::new();
let metrics_ping = metrics.clone();
let server_ip = config.outbounds.iter().find_map(|o| {
match o {
crate::config::OutboundConfig::Ostp { server, .. } => Some(server.clone()),
crate::config::OutboundConfig::Socks { server, .. } => Some(server.clone()),
_ => None,
}
let attempt_start = std::time::Instant::now();
let result = run_client_once(config.clone(), metrics.clone(), shutdown_rx_ext.clone(), config_rx.clone()).await;
if *shutdown_rx_ext.borrow() {
// Shutdown was requested during (or right after) this attempt — honor it, don't retry.
return result;
}
if let Err(ref e) = result {
tracing::warn!("client run ended unexpectedly, will auto-reconnect: {e}");
}
if attempt_start.elapsed() >= STABLE_UPTIME {
backoff_idx = 0;
}
let delay = BACKOFF_SCHEDULE_SECS[backoff_idx.min(BACKOFF_SCHEDULE_SECS.len() - 1)];
backoff_idx += 1;
// Reflect the retry wait as "connecting" rather than "disconnected".
metrics.connection_state.store(1, Ordering::Relaxed);
tokio::select! {
_ = tokio::time::sleep(std::time::Duration::from_secs(delay)) => {}
_ = shutdown_rx_ext.changed() => {
if *shutdown_rx_ext.borrow() {
return Ok(());
}
}
}
}
}
async fn run_client_once(
mut config: crate::config::ClientConfig,
metrics: Arc<BridgeMetrics>,
mut shutdown_rx_ext: watch::Receiver<bool>,
mut config_rx: Option<watch::Receiver<crate::config::ClientConfig>>,
) -> Result<()> {
#[cfg(target_os = "windows")]
if config.mode == "tun" && !is_admin() {
return Err(anyhow::anyhow!("Administrator privileges are required to initialize TUN mode. Please run the application as Administrator."));
}
#[cfg(target_os = "linux")]
if config.mode == "tun" && !is_root() {
return Err(anyhow::anyhow!("Root privileges are required to initialize TUN mode on Linux. Please run with sudo."));
}
log_to_core_file(&format!("[core] Starting run_client_core in mode: {}", config.mode));
// Resolve the server IP before we override system routing and DNS.
// This prevents DNS deadlock if the VPN disconnects and tries to reconnect,
// and also ensures we add the direct route to the exact IP the bridge connects to.
#[allow(unused_mut)]
let mut resolved_addrs: Vec<std::net::SocketAddr> = tokio::net::lookup_host(&config.ostp.server_addr)
.await
.map_err(|e| anyhow::anyhow!("Failed to resolve server address {}: {}", config.ostp.server_addr, e))?
.collect();
let target_addr = resolved_addrs.first()
.ok_or_else(|| anyhow::anyhow!("No IP addresses resolved for {}", config.ostp.server_addr))?;
log_to_core_file(&format!("[core] Resolved server address to {}", target_addr));
config.ostp.server_addr = target_addr.to_string();
#[cfg(target_os = "linux")]
if config.mode == "tun" {
println!("\n[ostp] ===========================================================================");
println!("[ostp] WARNING: You are starting TUN mode on a Linux system.");
println!("[ostp] If this is a remote headless server, routing all traffic through the TUN");
println!("[ostp] interface WILL DROP your SSH connection and lock you out!");
println!("[ostp] ");
println!("[ostp] SOLUTION: Add a static route for your client IP to bypass the TUN.");
println!("[ostp] Find your default gateway (ip route | grep default) and run:");
println!("[ostp] sudo ip route add <your-client-ip> via <default-gateway-ip>");
println!("[ostp] ===========================================================================\n");
}
#[cfg(target_os = "linux")]
if config.mode == "proxy" {
println!("\n[ostp] ===========================================================================");
println!("[ostp] Proxy mode initialized on {}", config.local_proxy.bind_addr);
println!("[ostp] ===========================================================================\n");
}
let _sysproxy_guard = if config.mode == "proxy" {
// Enable system proxy and set initial ProxyOverride with user exclusions
let guard = Some(crate::sysproxy::SystemProxyGuard::enable(&config.local_proxy.bind_addr));
crate::sysproxy::update_proxy_bypass_list(
&config.exclusions.domains,
&config.exclusions.ips,
);
guard
} else {
None
};
let (proxy_events_tx, proxy_events_rx) = mpsc::channel(256);
let (client_msgs_tx, client_msgs_rx) = mpsc::unbounded_channel();
});
// Setup exclusions hot-reload channel
let (reload_tx, reload_rx) = watch::channel(config.exclusions.clone());
let mut bridge = Bridge::new(&config, metrics)?;
bridge.reload_tx = Some(reload_tx.clone());
let (ui_tx, mut ui_rx) = mpsc::channel(512);
let (cmd_tx, cmd_rx) = mpsc::channel(128);
let (shutdown_tx, shutdown_rx) = watch::channel(false);
let proxy_shutdown_rx = shutdown_tx.subscribe();
// Auto-connect on startup
let _ = cmd_tx.send(BridgeCommand::ToggleTunnel).await;
let debug_enabled = config.debug;
// Headless event logger
let cmd_tx_clone = cmd_tx.clone();
tokio::spawn(async move {
let mut last_status = None;
while let Some(msg) = ui_rx.recv().await {
match msg {
crate::app::UiEvent::Log(text) => {
if debug_enabled || is_essential_log(&text) {
log_to_core_file(&format!("[ostp] {text}"));
println!("[ostp] {text}");
if let Some(mut server) = server_ip {
if !server.contains(':') {
server.push_str(":443");
}
let mut shutdown_rx = shutdown_rx_ext.clone();
handles.push(tokio::spawn(async move {
loop {
tokio::select! {
_ = tokio::time::sleep(std::time::Duration::from_secs(3)) => {}
_ = shutdown_rx.changed() => {
if *shutdown_rx.borrow() { break; }
}
}
crate::app::UiEvent::Metrics { status, rtt_ms, .. } => {
let status_str = status.as_str().to_string();
if last_status != Some(status_str.clone()) {
last_status = Some(status_str.clone());
println!("[ostp] Status: {} (rtt={:.1}ms)", status_str, rtt_ms);
}
}
crate::app::UiEvent::Traffic { .. } => {}
crate::app::UiEvent::ProfileChanged(profile) => {
if debug_enabled {
println!("[ostp] Obfuscation profile: {profile:?}");
}
}
crate::app::UiEvent::TunnelStopped => {
println!("[ostp] Connection interrupted. Reconnecting in 5 seconds...");
let cmd_tx_inner = cmd_tx_clone.clone();
tokio::spawn(async move {
tokio::time::sleep(tokio::time::Duration::from_secs(5)).await;
let _ = cmd_tx_inner.send(BridgeCommand::ToggleTunnel).await;
});
let start = std::time::Instant::now();
if let Ok(Ok(_)) = tokio::time::timeout(
std::time::Duration::from_secs(2),
tokio::net::TcpStream::connect(&server)
).await {
let rtt = start.elapsed().as_millis() as u32;
metrics_ping.rtt_ms.store(rtt, Ordering::Relaxed);
}
}
}));
}
for inbound in config.inbounds.clone() {
let router_clone = router.clone();
let outbound_manager_clone = outbound_manager.clone();
let shutdown_rx = shutdown_rx_ext.clone();
let config_clone = config.clone();
let metrics_clone = metrics.clone();
let failure_tx = failure_tx.clone();
match inbound.clone() {
InboundConfig::Tun { .. } => {
handles.push(tokio::spawn(async move {
if let Err(e) = crate::tunnel::inbounds::tun::run_tun_inbound(
config_clone,
inbound,
router_clone,
outbound_manager_clone,
shutdown_rx,
metrics_clone,
).await {
tracing::error!("TUN inbound failed: {}", e);
let _ = failure_tx.send(format!("TUN inbound: {e}")).await;
}
}));
}
InboundConfig::LocalProxy { .. } => {
let is_primary = !has_tun;
handles.push(tokio::spawn(async move {
if let Err(e) = crate::tunnel::inbounds::local_proxy::run_socks_inbound(
config_clone,
inbound,
router_clone,
outbound_manager_clone,
shutdown_rx,
metrics_clone,
is_primary,
).await {
tracing::error!("SOCKS inbound failed: {}", e);
let _ = failure_tx.send(format!("SOCKS inbound: {e}")).await;
}
}));
}
}
});
}
// Drop our own sender so the channel closes once every inbound task has ended.
drop(failure_tx);
let mut bridge_task = tokio::spawn(async move {
bridge.run(ui_tx, cmd_rx, shutdown_rx, proxy_events_rx, client_msgs_tx).await
});
let config_clone = config.clone();
let proxy_exclusions_rx = reload_rx.clone();
let mut proxy_task = tokio::spawn(async move {
tunnel::run_local_proxy(
config.local_proxy,
config.ostp,
proxy_exclusions_rx,
config.debug,
proxy_shutdown_rx,
proxy_events_tx,
client_msgs_rx,
)
.await
});
let wintun_shutdown_rx = shutdown_tx.subscribe();
let wintun_exclusions_rx = reload_rx.clone();
let mut wintun_task = if config_clone.mode == "tun" {
Some(tokio::spawn(async move {
tunnel::run_tun_tunnel(config_clone, wintun_shutdown_rx, wintun_exclusions_rx).await
}))
} else {
None
// Run until: an external shutdown, a fatal inbound failure, or all inbounds
// ending on their own.
let result = tokio::select! {
_ = shutdown_rx_ext.changed() => {
if *shutdown_rx_ext.borrow() {
tracing::info!("Shutdown signal received in run_client_core");
}
Ok(())
}
maybe_err = failure_rx.recv() => {
match maybe_err {
Some(err) => {
tracing::error!("tunnel startup failed: {err}");
Err(anyhow!("tunnel startup failed: {err}"))
}
None => Ok(()),
}
}
};
// Wait for local_shutdown
let mut local_shutdown = shutdown_rx_ext.clone();
let cmd_tx_loop = cmd_tx.clone();
tokio::spawn(async move {
loop {
tokio::select! {
_ = local_shutdown.changed() => {
if *local_shutdown.borrow() {
let _ = cmd_tx_loop.send(BridgeCommand::Shutdown).await;
break;
}
}
Some(Ok(_)) = async {
if let Some(ref mut rx) = config_rx {
Some(rx.changed().await)
} else {
std::future::pending().await
}
} => {
if let Some(ref rx) = config_rx {
let new_cfg = rx.borrow().clone();
// Update Windows ProxyOverride so excluded domains/IPs
// bypass the system proxy immediately (proxy mode only).
crate::sysproxy::update_proxy_bypass_list(
&new_cfg.exclusions.domains,
&new_cfg.exclusions.ips,
);
let _ = reload_tx.send(new_cfg.exclusions);
}
}
}
}
});
// Wait for either external shutdown OR any task to fail
tokio::select! {
_ = shutdown_rx_ext.changed() => {
let _ = cmd_tx.send(BridgeCommand::Shutdown).await;
let _ = shutdown_tx.send(true);
}
res = &mut bridge_task => {
let _ = shutdown_tx.send(true);
res.map_err(|e| anyhow::anyhow!("Bridge task panicked: {}", e))??;
}
res = &mut proxy_task => {
let _ = shutdown_tx.send(true);
res.map_err(|e| anyhow::anyhow!("Proxy task panicked: {}", e))??;
}
res = async {
if let Some(t) = wintun_task.as_mut() { t.await } else { std::future::pending().await }
} => {
let _ = shutdown_tx.send(true);
res.map_err(|e| anyhow::anyhow!("TUN task panicked: {}", e))??;
}
// Tear down every inbound regardless of why we are exiting, then report
// disconnected so the GUI reflects the real state.
for h in &handles {
h.abort();
}
// Final cleanup: wait for tasks to finish
let _ = bridge_task.await;
let _ = proxy_task.await;
if let Some(task) = wintun_task {
let _ = task.await;
}
Ok(())
}
#[allow(dead_code)]
fn format_bytes(bps: u64) -> String {
if bps >= 1_000_000 {
format!("{:.1}MB", bps as f64 / 1_000_000.0)
} else if bps >= 1_000 {
format!("{:.1}KB", bps as f64 / 1_000.0)
} else {
format!("{bps}B")
}
}
fn is_essential_log(text: &str) -> bool {
matches!(
text,
"Connection established"
| "TUN tunnel established"
| "TUN tunnel stopped"
| "Bridge stopped"
| "Runtime config reloaded"
| "Connecting to remote server..."
) || text.starts_with("Connected to ")
|| text.starts_with("TURN relay allocated")
|| text.starts_with("TURN allocation failed")
|| text.starts_with("Allocating TURN relay")
|| text.starts_with("Connection failed:")
|| text.starts_with("Connection lost")
|| text.starts_with("Protocol tick fatal error")
metrics.connection_state.store(0, Ordering::Relaxed);
result
}

View File

@ -189,7 +189,7 @@ fn refresh_wininet() {
#[cfg(not(target_os = "windows"))]
pub fn enable_system_proxy(proxy_addr: &str) {
let parts: Vec<&str> = proxy_addr.split(':').collect();
let host = parts.first().unwrap_or(&"127.0.0.1");
let host = parts.get(0).unwrap_or(&"127.0.0.1");
let port = parts.get(1).unwrap_or(&"1088");
let is_gui = std::env::var("DISPLAY").is_ok() || std::env::var("WAYLAND_DISPLAY").is_ok();
@ -235,7 +235,7 @@ pub fn enable_system_proxy(proxy_addr: &str) {
println!("OSTP Local Proxy is running at socks5://{}", proxy_addr);
println!("Since you are in a headless/terminal environment, OSTP cannot automatically");
println!("configure your system proxy. To route traffic from this terminal, run:");
println!("\n eval $(ostp proxy-env)\n");
println!("\n eval $(ostp --proxy-env)\n");
println!("Or configure your application (e.g. curl -x socks5://{})", proxy_addr);
println!("===================================================================\n");
}

View File

@ -0,0 +1 @@
// Left empty by request

View File

@ -1,4 +1,3 @@
use std::sync::Arc;
use tokio::net::UdpSocket;
use bytes::Bytes;
@ -9,6 +8,11 @@ pub enum Transport {
Uot {
tx: tokio::sync::mpsc::Sender<Bytes>,
rx: Arc<tokio::sync::Mutex<tokio::sync::mpsc::Receiver<Bytes>>>,
},
Dnstt {
tx: tokio::sync::mpsc::Sender<Bytes>,
rx: Arc<tokio::sync::Mutex<tokio::sync::mpsc::Receiver<Bytes>>>,
_guard: Arc<tokio::sync::Mutex<ostp_core::dnstt::DnsttProcess>>,
}
}
@ -16,8 +20,8 @@ impl Transport {
pub async fn send(&self, frame: &Bytes) -> std::io::Result<usize> {
match self {
Self::Udp(sock) => sock.send(frame).await,
Self::Uot { tx, .. } => {
tx.send(frame.clone()).await.map_err(|_| std::io::Error::new(std::io::ErrorKind::BrokenPipe, "uot closed"))?;
Self::Uot { tx, .. } | Self::Dnstt { tx, .. } => {
tx.send(frame.clone()).await.map_err(|_| std::io::Error::new(std::io::ErrorKind::BrokenPipe, "channel closed"))?;
Ok(frame.len())
}
}
@ -26,31 +30,40 @@ impl Transport {
pub async fn send_to(&self, frame: &Bytes, target: std::net::SocketAddr) -> std::io::Result<usize> {
match self {
Self::Udp(sock) => sock.send_to(frame, target).await,
Self::Uot { .. } => self.send(frame).await,
Self::Uot { .. } | Self::Dnstt { .. } => self.send(frame).await,
}
}
pub async fn recv(&self, buf: &mut [u8]) -> std::io::Result<usize> {
match self {
Self::Udp(sock) => sock.recv(buf).await,
Self::Uot { rx, .. } => {
Self::Uot { rx, .. } | Self::Dnstt { rx, .. } => {
let mut rx = rx.lock().await;
match rx.recv().await {
Some(bytes) => {
let len = bytes.len().min(buf.len());
buf[..len].copy_from_slice(&bytes[..len]);
Ok(len)
}
None => Err(std::io::Error::new(std::io::ErrorKind::BrokenPipe, "uot closed")),
if let Some(frame) = rx.recv().await {
let len = frame.len().min(buf.len());
buf[..len].copy_from_slice(&frame[..len]);
Ok(len)
} else {
Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "channel closed"))
}
}
}
}
pub async fn recv_from(&self, buf: &mut [u8]) -> std::io::Result<(usize, std::net::SocketAddr)> {
match self {
Self::Udp(sock) => sock.recv_from(buf).await,
Self::Uot { .. } | Self::Dnstt { .. } => {
let n = self.recv(buf).await?;
Ok((n, "127.0.0.1:0".parse().unwrap()))
}
}
}
pub fn local_addr(&self) -> std::io::Result<std::net::SocketAddr> {
match self {
Self::Udp(sock) => sock.local_addr(),
Self::Uot { .. } => Ok("0.0.0.0:0".parse().unwrap()),
Self::Uot { .. } | Self::Dnstt { .. } => Ok("0.0.0.0:0".parse().unwrap()),
}
}
}

View File

@ -0,0 +1,394 @@
use std::net::IpAddr;
use std::sync::Arc;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use bytes::{Buf, BufMut, Bytes, BytesMut};
use anyhow::{Result, Context};
use tokio::sync::mpsc;
use hmac::Hmac;
use sha2::Sha256;
use base64::Engine;
use std::pin::Pin;
use std::task::{Context as TaskContext, Poll};
use x25519_dalek::PublicKey;
use chacha20poly1305::{aead::Aead, ChaCha20Poly1305, Nonce};
use ostp_core::crypto::reality::{build_client_hello, derive_keys, generate_session_id, generate_x25519_keypair, REALITY_SERVER_HANDSHAKE_RECORDS};
use ostp_core::framing::wss::{encode_wss_frame, decode_wss_frame, WssFrameResult};
type HmacSha256 = Hmac<Sha256>;
pub async fn connect_xhttp(
target_ip: IpAddr,
port: u16,
sni: &str,
access_key: &[u8],
reality_enabled: bool,
wss: bool,
reality_pbk: &str,
reality_sid: &str,
) -> Result<(mpsc::Sender<Bytes>, Arc<tokio::sync::Mutex<mpsc::Receiver<Bytes>>>)> {
let addr = std::net::SocketAddr::new(target_ip, port);
#[cfg(not(target_os = "android"))]
let mut tcp_stream = tokio::time::timeout(
std::time::Duration::from_secs(10),
tokio::net::TcpStream::connect(addr),
)
.await
.map_err(|_| anyhow::anyhow!("TCP connect timeout to {}", addr))?
.with_context(|| format!("failed to connect to {}", addr))?;
#[cfg(target_os = "android")]
let mut tcp_stream = {
let domain = if target_ip.is_ipv6() { socket2::Domain::IPV6 } else { socket2::Domain::IPV4 };
let sock = socket2::Socket::new(domain, socket2::Type::STREAM, Some(socket2::Protocol::TCP))?;
use std::os::unix::io::AsRawFd;
crate::bridge::protect_socket(sock.as_raw_fd());
sock.set_nonblocking(true)?;
let tcp_socket = tokio::net::TcpSocket::from_std_stream(sock.into());
tokio::time::timeout(
std::time::Duration::from_secs(10),
tcp_socket.connect(addr),
)
.await
.map_err(|_| anyhow::anyhow!("TCP connect timeout to {}", addr))?
.with_context(|| format!("failed to connect to {}", addr))?
};
tcp_stream.set_nodelay(true)?;
if reality_enabled {
let pbk_bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(reality_pbk)
.context("invalid reality_pbk base64")?;
if pbk_bytes.len() != 32 {
anyhow::bail!("reality_pbk must be 32 bytes");
}
let pbk = PublicKey::from(<[u8; 32]>::try_from(pbk_bytes.as_slice()).unwrap());
let sid_bytes_vec = hex::decode(reality_sid).context("invalid reality_sid hex")?;
if sid_bytes_vec.len() != 8 {
anyhow::bail!("reality_sid must be 8 bytes");
}
let sid: [u8; 8] = sid_bytes_vec.try_into().unwrap();
let (c_priv, c_pub) = generate_x25519_keypair();
let shared_secret = c_priv.diffie_hellman(&pbk);
let (auth_key, data_key) = derive_keys(shared_secret.as_bytes());
let session_id = generate_session_id(&auth_key, &sid);
let client_hello = build_client_hello(if sni.is_empty() { "www.microsoft.com" } else { sni }, &session_id, &c_pub);
tcp_stream.write_all(&client_hello).await?;
// Drain all server handshake records (ServerHello, CCS, fake encrypted records).
// The server sends exactly REALITY_SERVER_HANDSHAKE_RECORDS records before data starts.
// Reading them explicitly prevents RealityStream from seeing non-AppData bytes.
for i in 0..REALITY_SERVER_HANDSHAKE_RECORDS {
let mut head = [0u8; 5];
tcp_stream.read_exact(&mut head).await
.with_context(|| format!("reality handshake: failed reading record {} header", i))?;
if i == 0 && head[0] != 0x16 {
anyhow::bail!("expected ServerHello (0x16), got 0x{:02x}", head[0]);
}
let record_len = u16::from_be_bytes([head[3], head[4]]) as usize;
if record_len > 16384 {
anyhow::bail!("reality handshake: record {} too large: {} bytes", i, record_len);
}
let mut _payload = vec![0u8; record_len];
tcp_stream.read_exact(&mut _payload).await
.with_context(|| format!("reality handshake: failed reading record {} payload", i))?;
}
let reality_stream = RealityStream::new(tcp_stream, data_key);
xhttp_handshake_and_loop(reality_stream, target_ip, sni, access_key, wss).await
} else {
xhttp_handshake_and_loop(tcp_stream, target_ip, sni, access_key, wss).await
}
}
// -----------------------------------------------------------------------
// RealityStream: Wraps a TCP stream in fake TLS Application Data Records
// -----------------------------------------------------------------------
struct RealityStream {
inner: TcpStream,
data_key: ChaCha20Poly1305,
rx_nonce: u64,
tx_nonce: u64,
rx_buf: BytesMut,
plaintext_buf: BytesMut,
tx_buf: BytesMut,
}
impl RealityStream {
fn new(inner: TcpStream, data_key: ChaCha20Poly1305) -> Self {
Self {
inner,
data_key,
rx_nonce: 0,
tx_nonce: 0,
rx_buf: BytesMut::with_capacity(16384),
plaintext_buf: BytesMut::new(),
tx_buf: BytesMut::new(),
}
}
fn make_nonce(seq: u64) -> [u8; 12] {
let mut nonce = [0u8; 12];
nonce[4..12].copy_from_slice(&seq.to_le_bytes());
nonce
}
}
impl tokio::io::AsyncRead for RealityStream {
fn poll_read(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &mut tokio::io::ReadBuf<'_>) -> Poll<std::io::Result<()>> {
loop {
if !self.plaintext_buf.is_empty() {
let out_len = std::cmp::min(buf.remaining(), self.plaintext_buf.len());
buf.put_slice(&self.plaintext_buf[..out_len]);
self.plaintext_buf.advance(out_len);
return Poll::Ready(Ok(()));
}
if self.rx_buf.len() >= 5 {
let len = u16::from_be_bytes([self.rx_buf[3], self.rx_buf[4]]) as usize;
if self.rx_buf.len() >= 5 + len {
if self.rx_buf[0] != 0x17 {
return Poll::Ready(Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "expected application data record")));
}
let ciphertext = &self.rx_buf[5..5+len];
let nonce_bytes = Self::make_nonce(self.rx_nonce);
let nonce = Nonce::from_slice(&nonce_bytes);
match self.data_key.decrypt(nonce, ciphertext) {
Ok(plaintext) => {
self.rx_nonce += 1;
self.plaintext_buf.put_slice(&plaintext);
self.rx_buf.advance(5 + len);
continue;
}
Err(_) => {
return Poll::Ready(Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "reality decrypt failed")));
}
}
}
}
let mut read_buf = [0u8; 8192];
let mut tokio_buf = tokio::io::ReadBuf::new(&mut read_buf);
match Pin::new(&mut self.inner).poll_read(cx, &mut tokio_buf) {
Poll::Ready(Ok(())) => {
if tokio_buf.filled().is_empty() {
return Poll::Ready(Ok(()));
}
self.rx_buf.put_slice(tokio_buf.filled());
}
Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
Poll::Pending => return Poll::Pending,
}
}
}
}
impl tokio::io::AsyncWrite for RealityStream {
fn poll_write(self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &[u8]) -> Poll<std::io::Result<usize>> {
let this = self.get_mut();
while !this.tx_buf.is_empty() {
match Pin::new(&mut this.inner).poll_write(cx, &this.tx_buf) {
Poll::Ready(Ok(n)) => this.tx_buf.advance(n),
Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
Poll::Pending => return Poll::Pending,
}
}
let nonce_bytes = Self::make_nonce(this.tx_nonce);
let nonce = Nonce::from_slice(&nonce_bytes);
match this.data_key.encrypt(nonce, buf) {
Ok(ciphertext) => {
this.tx_nonce += 1;
this.tx_buf.reserve(5 + ciphertext.len());
this.tx_buf.put_u8(0x17);
this.tx_buf.put_u16(0x0303);
this.tx_buf.put_u16(ciphertext.len() as u16);
this.tx_buf.put_slice(&ciphertext);
match Pin::new(&mut this.inner).poll_write(cx, &this.tx_buf) {
Poll::Ready(Ok(n)) => this.tx_buf.advance(n),
Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
Poll::Pending => {}
}
Poll::Ready(Ok(buf.len()))
}
Err(_) => Poll::Ready(Err(std::io::Error::new(std::io::ErrorKind::Other, "reality encrypt failed"))),
}
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<std::io::Result<()>> {
let this = self.get_mut();
while !this.tx_buf.is_empty() {
match Pin::new(&mut this.inner).poll_write(cx, &this.tx_buf) {
Poll::Ready(Ok(n)) => this.tx_buf.advance(n),
Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
Poll::Pending => return Poll::Pending,
}
}
Pin::new(&mut this.inner).poll_flush(cx)
}
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<std::io::Result<()>> {
let this = self.get_mut();
while !this.tx_buf.is_empty() {
match Pin::new(&mut this.inner).poll_write(cx, &this.tx_buf) {
Poll::Ready(Ok(n)) => this.tx_buf.advance(n),
Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
Poll::Pending => return Poll::Pending,
}
}
Pin::new(&mut this.inner).poll_shutdown(cx)
}
}
async fn xhttp_handshake_and_loop<S>(
mut stream: S,
target_ip: IpAddr,
sni: &str,
access_key: &[u8],
wss: bool,
) -> Result<(mpsc::Sender<Bytes>, Arc<tokio::sync::Mutex<mpsc::Receiver<Bytes>>>)>
where
S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static,
{
// 1. Generate auth token: [8-byte timestamp BE] ++ [HMAC-SHA256]
let timestamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_secs();
let ts_bytes = timestamp.to_be_bytes();
use hmac::Mac;
let mut mac = <HmacSha256 as Mac>::new_from_slice(access_key).unwrap_or_else(|_| <HmacSha256 as Mac>::new_from_slice(b"").unwrap());
mac.update(&ts_bytes);
let mac_bytes = mac.finalize().into_bytes();
let mut sig_bytes = Vec::with_capacity(8 + mac_bytes.len());
sig_bytes.extend_from_slice(&ts_bytes);
sig_bytes.extend_from_slice(&mac_bytes);
let auth_token = base64::engine::general_purpose::STANDARD_NO_PAD.encode(&sig_bytes);
let http_host = if sni.is_empty() { target_ip.to_string() } else { sni.to_string() };
let req = if wss {
format!(
"GET /wss HTTP/1.1\r\n\
Host: {}\r\n\
Upgrade: websocket\r\n\
Connection: upgrade\r\n\
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\
Sec-WebSocket-Version: 13\r\n\
Authorization: Bearer {}\r\n\
\r\n",
http_host, auth_token
)
} else {
format!(
"GET /stream HTTP/1.1\r\n\
Host: {}\r\n\
Authorization: Bearer {}\r\n\
\r\n",
http_host, auth_token
)
};
stream.write_all(req.as_bytes()).await?;
// Wait for HTTP 200 OK or 101 Switching Protocols
let mut header_buf = Vec::new();
let mut temp = [0u8; 1];
loop {
let n = stream.read(&mut temp).await?;
if n == 0 {
anyhow::bail!("connection closed by server during handshake");
}
header_buf.push(temp[0]);
if header_buf.ends_with(b"\r\n\r\n") {
break;
}
if header_buf.len() > 8192 {
anyhow::bail!("server response too long");
}
}
let resp_str = String::from_utf8_lossy(&header_buf);
if wss {
if !resp_str.starts_with("HTTP/1.1 101 ") {
anyhow::bail!("failed to switch protocols: {}", resp_str.lines().next().unwrap_or(""));
}
} else {
if !resp_str.starts_with("HTTP/1.1 200 OK") {
anyhow::bail!("server rejected stream: {}", resp_str.lines().next().unwrap_or(""));
}
}
let (tx, mut rx) = mpsc::channel::<Bytes>(16384);
let (mut read_half, mut write_half) = tokio::io::split(stream);
let writer_task = tokio::spawn(async move {
while let Some(packet) = rx.recv().await {
if wss {
let header = encode_wss_frame(&packet, true);
if write_half.write_all(&header).await.is_err() { break; }
} else {
let mut out = BytesMut::with_capacity(2 + packet.len());
out.put_u16(packet.len() as u16);
out.put_slice(&packet);
if write_half.write_all(&out).await.is_err() { break; }
}
}
});
let (in_tx, in_rx) = mpsc::channel::<Bytes>(16384);
let in_rx_arc = Arc::new(tokio::sync::Mutex::new(in_rx));
let in_tx_clone = in_tx.clone();
let reader_task = tokio::spawn(async move {
if wss {
let mut read_buf = BytesMut::with_capacity(65536);
let mut tmp = [0u8; 8192];
loop {
match read_half.read(&mut tmp).await {
Ok(0) => break,
Ok(n) => {
read_buf.put_slice(&tmp[..n]);
loop {
match decode_wss_frame(&mut read_buf) {
WssFrameResult::Frame { payload, total_len } => {
if in_tx_clone.send(Bytes::from(payload)).await.is_err() { return; }
read_buf.advance(total_len);
}
WssFrameResult::Incomplete => break,
}
}
}
Err(_) => break,
}
}
} else {
let mut len_buf = [0u8; 2];
loop {
if read_half.read_exact(&mut len_buf).await.is_err() { break; }
let len = u16::from_be_bytes(len_buf) as usize;
if len > 65535 { break; }
let mut data = vec![0u8; len];
if read_half.read_exact(&mut data).await.is_err() { break; }
if in_tx_clone.send(Bytes::from(data)).await.is_err() { break; }
}
}
});
tokio::spawn(async move {
let _ = tokio::join!(writer_task, reader_task);
});
Ok((tx, in_rx_arc))
}

View File

@ -0,0 +1,65 @@
use crate::config::{ClientConfig, OutboundConfig};
use std::collections::HashMap;
pub struct Balancer {
outbounds: HashMap<String, OutboundConfig>,
}
impl Balancer {
pub fn new(config: &ClientConfig) -> Self {
let mut outbounds = HashMap::new();
for outbound in &config.outbounds {
let tag = match outbound {
OutboundConfig::Selector { tag, .. } => tag,
OutboundConfig::Urltest { tag, .. } => tag,
OutboundConfig::Ostp { tag, .. } => tag,
OutboundConfig::Direct { tag } => tag,
OutboundConfig::Socks { tag, .. } => tag,
OutboundConfig::Block { tag } => tag,
};
outbounds.insert(tag.clone(), outbound.clone());
}
Self { outbounds }
}
/// Resolves an outbound tag into a concrete, non-group outbound tag.
/// E.g. "proxy-group" -> "server-helsinki"
pub fn resolve_outbound(&self, tag: &str) -> String {
// Prevent infinite loops if groups point to groups
let mut current_tag = tag.to_string();
for _ in 0..10 {
if let Some(outbound) = self.outbounds.get(&current_tag) {
match outbound {
OutboundConfig::Selector { outbounds, default, .. } => {
current_tag = if let Some(def) = default {
def.clone()
} else {
outbounds.first().cloned().unwrap_or_else(|| "direct".to_string())
};
}
OutboundConfig::Urltest { outbounds, .. } => {
// TODO: Implement background ping worker to find the fastest node.
// For now, act as a fallback by taking the first available node.
current_tag = outbounds.first().cloned().unwrap_or_else(|| "direct".to_string());
}
_ => {
// It's a concrete physical outbound (ostp, direct, block)
return current_tag;
}
}
} else {
// Outbound not found, fallback to direct
return "direct".to_string();
}
}
"direct".to_string() // Max depth reached
}
/// Fetches the config for a concrete outbound
pub fn get_concrete_outbound(&self, tag: &str) -> Option<&OutboundConfig> {
let resolved_tag = self.resolve_outbound(tag);
tracing::debug!("Balancer: tag '{}' resolved to '{}'", tag, resolved_tag);
self.outbounds.get(&resolved_tag)
}
}

View File

@ -0,0 +1,246 @@
use anyhow::{anyhow, Result};
use std::sync::Arc;
use crate::config::{ClientConfig, InboundConfig};
use crate::tunnel::router::{Router, Session};
use crate::tunnel::outbounds::OutboundManager;
use tokio::net::TcpListener;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::sync::watch;
pub async fn run_socks_inbound(
_config: ClientConfig,
inbound_config: InboundConfig,
router: Arc<Router>,
outbound_manager: Arc<OutboundManager>,
mut shutdown: watch::Receiver<bool>,
metrics: Arc<crate::bridge::BridgeMetrics>,
is_primary: bool,
) -> Result<()> {
use portable_atomic::Ordering;
let InboundConfig::LocalProxy { tag, protocol, listen, port, set_system_proxy } = inbound_config else {
return Err(anyhow!("Invalid config for LocalProxy inbound"));
};
let bind_addr = format!("{}:{}", listen, port);
tracing::info!("Starting {} proxy inbound on {} (tag: {})", protocol, bind_addr, tag);
let _proxy_guard = if set_system_proxy {
let proxy_host = if listen == "0.0.0.0" { "127.0.0.1" } else { &listen };
Some(crate::sysproxy::SystemProxyGuard::enable(&format!("{}:{}", proxy_host, port)))
} else {
None
};
let listener = TcpListener::bind(&bind_addr).await?;
// Binding a local socket only proves the proxy can accept connections, not
// that the tunnel actually reaches the server. Only report "connected" from
// here when this proxy is the primary inbound (SOCKS-only mode). In TUN mode
// the TUN inbound owns the connected state — it is set after the device and
// server bypass route are in place — so we must not flip it prematurely.
if is_primary {
metrics.connection_state.store(2, Ordering::Relaxed);
tracing::info!("{} proxy inbound ready on {}, connection state = connected", protocol, bind_addr);
} else {
tracing::info!("{} proxy inbound ready on {}", protocol, bind_addr);
}
loop {
tokio::select! {
_ = shutdown.changed() => {
tracing::info!("Local proxy inbound {} shutting down", tag);
break;
}
accept_res = listener.accept() => {
if let Ok((mut stream, client_addr)) = accept_res {
let rt = router.clone();
let om = outbound_manager.clone();
let proto = protocol.clone();
let inbound_tag = tag.clone();
tokio::spawn(async move {
if proto == "socks" {
if let Err(e) = handle_socks5_connection(&mut stream, &rt, &om, &inbound_tag, client_addr).await {
tracing::debug!("SOCKS5 handling error: {}", e);
}
} else if proto == "http" {
if let Err(e) = handle_http_connection(&mut stream, &rt, &om, &inbound_tag, client_addr).await {
tracing::debug!("HTTP proxy handling error: {}", e);
}
} else {
tracing::error!("Unknown local proxy protocol: {}", proto);
}
});
}
}
}
}
Ok(())
}
async fn handle_socks5_connection(
stream: &mut tokio::net::TcpStream,
router: &Arc<Router>,
outbound_manager: &Arc<OutboundManager>,
inbound_tag: &str,
client_addr: std::net::SocketAddr,
) -> Result<()> {
let mut buf = [0u8; 256];
// Read version and method selection
stream.read_exact(&mut buf[0..2]).await?;
if buf[0] != 0x05 {
return Err(anyhow!("Unsupported SOCKS version: {}", buf[0]));
}
let num_methods = buf[1] as usize;
stream.read_exact(&mut buf[0..num_methods]).await?;
// Reply with NO AUTHENTICATION REQUIRED (0x00)
stream.write_all(&[0x05, 0x00]).await?;
// Read the actual request
stream.read_exact(&mut buf[0..4]).await?;
if buf[0] != 0x05 || buf[1] != 0x01 { // Only CONNECT is supported
return Err(anyhow!("Unsupported SOCKS command"));
}
let atyp = buf[3];
let (target_host, ip_addr) = match atyp {
0x01 => { // IPv4
stream.read_exact(&mut buf[0..4]).await?;
let ip = std::net::Ipv4Addr::new(buf[0], buf[1], buf[2], buf[3]);
(ip.to_string(), Some(std::net::IpAddr::V4(ip)))
}
0x03 => { // Domain
stream.read_exact(&mut buf[0..1]).await?;
let domain_len = buf[0] as usize;
stream.read_exact(&mut buf[0..domain_len]).await?;
let domain = String::from_utf8_lossy(&buf[0..domain_len]).to_string();
(domain, None)
}
0x04 => { // IPv6
stream.read_exact(&mut buf[0..16]).await?;
let mut ip_bytes = [0u8; 16];
ip_bytes.copy_from_slice(&buf[0..16]);
let ip = std::net::Ipv6Addr::from(ip_bytes);
(ip.to_string(), Some(std::net::IpAddr::V6(ip)))
}
_ => return Err(anyhow!("Unsupported SOCKS address type: {}", atyp)),
};
stream.read_exact(&mut buf[0..2]).await?;
let target_port = u16::from_be_bytes([buf[0], buf[1]]);
let process_name = crate::tunnel::process_lookup::get_process_name_from_port(client_addr.port());
let session = Session {
protocol: "tcp".to_string(),
inbound_tag: inbound_tag.to_string(),
source_ip: Some(client_addr.ip()),
destination_ip: ip_addr,
destination_port: target_port,
sni: if atyp == 0x03 { Some(target_host.clone()) } else { None },
process_name,
};
let outbound_tag = router.route(&session);
tracing::info!("SOCKS5 TCP {} -> {}:{} routed to {}", client_addr, target_host, target_port, outbound_tag);
match outbound_manager.dial_tcp(&outbound_tag, &target_host, target_port).await {
Ok(mut remote_stream) => {
// Reply success
stream.write_all(&[0x05, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]).await?;
// Forward data
tokio::io::copy_bidirectional(stream, &mut remote_stream).await?;
}
Err(e) => {
tracing::warn!("SOCKS5 TCP dial failed to {}: {}", outbound_tag, e);
// Reply host unreachable
let _ = stream.write_all(&[0x05, 0x04, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]).await;
}
}
Ok(())
}
async fn handle_http_connection(
stream: &mut tokio::net::TcpStream,
router: &Arc<Router>,
outbound_manager: &Arc<OutboundManager>,
inbound_tag: &str,
client_addr: std::net::SocketAddr,
) -> Result<()> {
// Basic HTTP CONNECT implementation
let mut buf = [0u8; 4096];
let n = stream.read(&mut buf).await?;
if n == 0 { return Ok(()); }
let request = String::from_utf8_lossy(&buf[0..n]);
let mut lines = request.lines();
let first_line = lines.next().ok_or_else(|| anyhow!("Empty HTTP request"))?;
let parts: Vec<&str> = first_line.split_whitespace().collect();
if parts.len() < 3 {
return Err(anyhow!("Invalid HTTP request line"));
}
let method = parts[0];
let target = parts[1]; // host:port for CONNECT, http://host:port/... for GET
let (target_host, target_port) = if method == "CONNECT" {
let parts: Vec<&str> = target.split(':').collect();
let host = parts[0].to_string();
let port = parts.get(1).unwrap_or(&"443").parse::<u16>().unwrap_or(443);
(host, port)
} else {
// Rudimentary GET parsing, ideally use httparse
if target.starts_with("http://") {
let without_scheme = &target[7..];
let host_part = without_scheme.split('/').next().unwrap_or(without_scheme);
let parts: Vec<&str> = host_part.split(':').collect();
let host = parts[0].to_string();
let port = parts.get(1).unwrap_or(&"80").parse::<u16>().unwrap_or(80);
(host, port)
} else {
return Err(anyhow!("Unsupported HTTP method/target: {} {}", method, target));
}
};
let process_name = crate::tunnel::process_lookup::get_process_name_from_port(client_addr.port());
let session = Session {
protocol: "tcp".to_string(),
inbound_tag: inbound_tag.to_string(),
source_ip: Some(client_addr.ip()),
destination_ip: None, // Could parse if IP
destination_port: target_port,
sni: Some(target_host.clone()),
process_name,
};
let outbound_tag = router.route(&session);
tracing::info!("HTTP TCP {} -> {}:{} routed to {}", client_addr, target_host, target_port, outbound_tag);
match outbound_manager.dial_tcp(&outbound_tag, &target_host, target_port).await {
Ok(mut remote_stream) => {
if method == "CONNECT" {
stream.write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n").await?;
} else {
remote_stream.write_all(&buf[0..n]).await?;
}
tokio::io::copy_bidirectional(stream, &mut remote_stream).await?;
}
Err(e) => {
tracing::warn!("HTTP TCP dial failed to {}: {}", outbound_tag, e);
if method == "CONNECT" {
let _ = stream.write_all(b"HTTP/1.1 502 Bad Gateway\r\n\r\n").await;
}
}
}
Ok(())
}

Binary file not shown.

View File

@ -0,0 +1,2 @@
pub mod tun;
pub mod local_proxy;

View File

@ -0,0 +1,313 @@
use anyhow::{anyhow, Result};
use std::sync::Arc;
use crate::config::{ClientConfig, InboundConfig};
#[allow(unused_imports)]
use crate::tunnel::router::{Router, Session};
use crate::tunnel::outbounds::OutboundManager;
use tokio::sync::watch;
#[cfg(any(target_os = "windows", target_os = "linux"))]
pub async fn run_tun_inbound(
config: ClientConfig,
inbound_config: InboundConfig,
router: Arc<Router>,
outbound_manager: Arc<OutboundManager>,
mut shutdown: watch::Receiver<bool>,
metrics: Arc<crate::bridge::BridgeMetrics>,
) -> Result<()> {
use netstack_smoltcp::StackBuilder;
use portable_atomic::Ordering;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use futures::{StreamExt, SinkExt};
let InboundConfig::Tun { tag, auto_route, mtu, .. } = inbound_config else {
return Err(anyhow!("Invalid config for TUN inbound"));
};
tracing::info!("Starting TUN inbound (tag: {}, auto_route: {}, mtu: {})", tag, auto_route, mtu);
#[cfg(target_os = "windows")]
let _phys_if_for_bypass: Option<u32> = ostp_tun::windows::windows_route::sys::get_default_ipv4_route().map(|(_, idx)| idx);
#[cfg(not(target_os = "windows"))]
let _phys_if_for_bypass: Option<u32> = None;
let mut bypass_ips: Vec<std::net::IpAddr> = Vec::new();
// Bypass all outbound server IPs
for outbound in &config.outbounds {
let server = match outbound {
crate::config::OutboundConfig::Ostp { server, .. } => Some(server),
crate::config::OutboundConfig::Socks { server, .. } => Some(server),
_ => None,
};
if let Some(host) = server {
if let Ok(ip) = host.parse::<std::net::IpAddr>() {
bypass_ips.push(ip);
} else {
if let Ok(addrs) = tokio::net::lookup_host((host.as_str(), 443)).await {
for addr in addrs {
bypass_ips.push(addr.ip());
}
}
}
}
}
// Build smoltcp network stack with proper buffer sizes for throughput
let (stack, tcp_runner, udp_socket, tcp_listener) = StackBuilder::default()
.stack_buffer_size(65536) // 64KB for packet accumulation
.tcp_buffer_size(131072) // 128KB for TCP streams
.udp_buffer_size(65536) // 64KB for UDP datagrams
.enable_tcp(true)
.enable_udp(true)
.mtu(mtu)
.build()?;
let mut runner_task = tokio::spawn(async move {
if let Some(runner) = tcp_runner {
let _ = runner.await;
}
});
let (mut stack_sink, mut stack_stream) = stack.split();
#[allow(unused_variables)]
let mut _route_guard = None;
let (tun_to_stack, stack_to_tun) = {
#[cfg(target_os = "android")]
{
if let Some(fd) = fd {
use std::os::fd::{FromRawFd, AsRawFd};
use tokio::io::unix::AsyncFd;
use std::os::unix::io::OwnedFd;
let async_fd = AsyncFd::new(unsafe { OwnedFd::from_raw_fd(fd) })?;
let async_fd_shared = std::sync::Arc::new(async_fd);
let afd1 = async_fd_shared.clone();
let tun_to_stack = tokio::spawn(async move {
let mut frame = vec![0u8; 65535];
loop {
let mut guard = match afd1.readable().await {
Ok(g) => g,
Err(_) => break,
};
match guard.try_io(|inner| {
let res = unsafe { libc::read(inner.as_raw_fd(), frame.as_mut_ptr() as *mut libc::c_void, frame.len()) };
if res < 0 {
let err = std::io::Error::last_os_error();
if err.kind() == std::io::ErrorKind::WouldBlock { Err(err) } else { Ok(res as isize) }
} else { Ok(res as isize) }
}) {
Ok(Ok(n)) if n > 0 => {
if let Err(_) = stack_sink.send(frame[..n as usize].to_vec()).await { break; }
}
Ok(Ok(_)) => break,
Ok(Err(_)) => break,
Err(_) => continue,
}
}
});
let afd2 = async_fd_shared.clone();
let stack_to_tun = tokio::spawn(async move {
while let Some(Ok(frame)) = stack_stream.next().await {
let mut written = 0;
while written < frame.len() {
let mut guard = match afd2.writable().await {
Ok(g) => g,
Err(_) => break,
};
match guard.try_io(|inner| {
let res = unsafe { libc::write(inner.as_raw_fd(), frame[written..].as_ptr() as *const libc::c_void, frame.len() - written) };
if res < 0 {
let err = std::io::Error::last_os_error();
if err.kind() == std::io::ErrorKind::WouldBlock { Err(err) } else { Ok(res as isize) }
} else { Ok(res as isize) }
}) {
Ok(Ok(n)) if n > 0 => written += n as usize,
Ok(Ok(_)) => break,
Ok(Err(_)) => break,
Err(_) => continue,
}
}
}
});
(tun_to_stack, stack_to_tun)
} else {
return Err(anyhow!("FD is required on Android but not provided"));
}
}
#[cfg(not(target_os = "android"))]
{
let opts = ostp_tun::OstpTunOptions {
server_ip: bypass_ips.first().copied().unwrap_or_else(|| "127.0.0.1".parse().unwrap()),
bypass_ips: bypass_ips,
dns_server: None,
kill_switch: false,
mtu: mtu as u16,
wintun_path: None,
};
let tun_interface = ostp_tun::OstpTunInterface::create(opts)
.await
.map_err(|e| anyhow!("Failed to create OstpTunInterface: {}", e))?;
let dev = tun_interface.device;
_route_guard = Some(tun_interface.guard);
let (mut tun_read, mut tun_write) = tokio::io::split(dev);
let m_sent = metrics.clone();
let tun_to_stack = tokio::spawn(async move {
let mut buf = vec![0u8; 65536];
loop {
match tun_read.read(&mut buf).await {
Ok(0) => break,
Ok(n) => {
m_sent.bytes_sent.fetch_add(n as u64, Ordering::Relaxed);
if let Err(_) = stack_sink.send(buf[..n].to_vec()).await { break; }
}
Err(e) => tracing::debug!("tun_read error: {e}"),
}
}
});
let m_recv = metrics.clone();
let stack_to_tun = tokio::spawn(async move {
while let Some(Ok(frame)) = stack_stream.next().await {
m_recv.bytes_recv.fetch_add(frame.len() as u64, Ordering::Relaxed);
if let Err(e) = tun_write.write(&frame).await { tracing::debug!("tun_write error: {e}"); }
}
});
(tun_to_stack, stack_to_tun)
}
};
// TUN device is up and the default route has been installed inside
// OstpTunInterface::create — the tunnel is now carrying traffic.
metrics.connection_state.store(2, Ordering::Relaxed);
tracing::info!("TUN inbound ready, connection state = connected");
// ── TCP Handler ──
let outbound_manager_tcp = outbound_manager.clone();
let router_tcp = router.clone();
let tag_tcp = tag.clone();
let tcp_accept_task = tokio::spawn(async move {
let Some(mut listener) = tcp_listener else { return; };
while let Some((mut stream, local, remote)) = listener.next().await {
let om = outbound_manager_tcp.clone();
let rt = router_tcp.clone();
let ib_tag = tag_tcp.clone();
tokio::spawn(async move {
let process_name = crate::tunnel::process_lookup::get_process_name_from_port(local.port());
let mut sniff_buf = [0u8; 2048];
let sniff_len = match tokio::time::timeout(
std::time::Duration::from_millis(100),
stream.read(&mut sniff_buf)
).await {
Ok(Ok(n)) => n,
_ => 0,
};
let mut domain_suffix = None;
if sniff_len > 0 {
domain_suffix = crate::tunnel::sni_sniff::extract_sni(&sniff_buf[..sniff_len]);
}
let session = Session {
protocol: "tcp".to_string(),
inbound_tag: ib_tag.clone(),
source_ip: Some(local.ip()),
destination_ip: Some(remote.ip()),
destination_port: remote.port(),
sni: domain_suffix.map(|s| s.to_string()),
process_name,
};
let outbound_tag = rt.route(&session);
tracing::info!("TUN TCP {} -> {} routed to {}", local, remote, outbound_tag);
let target_host = if let Some(domain) = session.sni {
domain
} else {
remote.ip().to_string()
};
match om.dial_tcp(&outbound_tag, &target_host, session.destination_port).await {
Ok(mut remote_stream) => {
if sniff_len > 0 {
if let Err(e) = remote_stream.write_all(&sniff_buf[..sniff_len]).await {
tracing::warn!("Failed to forward sniffed bytes to {}: {}", outbound_tag, e);
return;
}
}
let _ = tokio::io::copy_bidirectional(&mut stream, &mut remote_stream).await;
}
Err(e) => {
tracing::warn!("TUN TCP dial failed to {}: {}", outbound_tag, e);
}
}
});
}
});
// ── UDP Handler ──
let outbound_manager_udp = outbound_manager.clone();
let router_udp = router.clone();
let tag_udp = tag.clone();
let udp_proxy_task = tokio::spawn(async move {
if let Some(udp_sock) = udp_socket {
let (mut udp_rx, _udp_tx) = udp_sock.split();
while let Some((payload, local, remote)) = udp_rx.next().await {
let process_name = crate::tunnel::process_lookup::get_process_name_from_port_udp(local.port());
let session = Session {
protocol: "udp".to_string(),
inbound_tag: tag_udp.clone(),
source_ip: Some(local.ip()),
destination_ip: Some(remote.ip()),
destination_port: remote.port(),
sni: None,
process_name,
};
let outbound_tag = router_udp.route(&session);
let payload_bytes = bytes::Bytes::copy_from_slice(&payload);
if let Err(e) = outbound_manager_udp.handle_udp(&outbound_tag, local, remote, payload_bytes).await {
tracing::debug!("TUN UDP drop to {}: {}", outbound_tag, e);
}
}
}
});
tokio::select! {
_ = shutdown.changed() => {
tracing::info!("TUN inbound {} shutting down", tag);
}
_ = &mut runner_task => {}
}
tun_to_stack.abort();
stack_to_tun.abort();
tcp_accept_task.abort();
udp_proxy_task.abort();
Ok(())
}
#[cfg(not(any(target_os = "windows", target_os = "linux")))]
pub async fn run_tun_inbound(
_config: ClientConfig,
_inbound_config: InboundConfig,
_router: Arc<Router>,
_outbound_manager: Arc<OutboundManager>,
_shutdown: watch::Receiver<bool>,
_metrics: Arc<crate::bridge::BridgeMetrics>,
) -> Result<()> {
Err(anyhow!("TUN is only supported on Windows and Linux"))
}

Binary file not shown.

View File

@ -1,67 +1,7 @@
mod proxy;
pub mod native_handler;
pub mod router;
pub mod balancer;
pub mod outbounds;
pub mod inbounds;
mod udp_nat;
pub async fn run_tun_tunnel(
config: crate::config::ClientConfig,
shutdown: tokio::sync::watch::Receiver<bool>,
exclusions_rx: tokio::sync::watch::Receiver<crate::config::ExclusionConfig>,
) -> anyhow::Result<()> {
native_handler::run_native_tunnel(config, shutdown, exclusions_rx).await
}
use tokio::sync::{mpsc, watch};
use crate::config::{ExclusionConfig, LocalProxyConfig, OstpConfig};
pub use proxy::run_local_socks5_proxy;
#[derive(Debug)]
pub enum ProxyEvent {
NewStream {
stream_id: u16,
target: String,
},
UdpAssociate {
stream_id: u16,
},
UdpData {
stream_id: u16,
target: String,
payload: bytes::Bytes,
},
Data {
stream_id: u16,
payload: bytes::Bytes,
},
Close {
stream_id: u16,
},
}
#[derive(Debug)]
pub enum ProxyToClientMsg {
ConnectOk,
Data(bytes::Bytes),
UdpData(String, bytes::Bytes),
Close,
Error(String),
}
pub async fn run_local_proxy(
cfg: LocalProxyConfig,
ostp: OstpConfig,
exclusions_rx: watch::Receiver<ExclusionConfig>,
debug: bool,
shutdown: watch::Receiver<bool>,
proxy_events_tx: mpsc::Sender<ProxyEvent>,
client_msgs_rx: mpsc::UnboundedReceiver<(u16, ProxyToClientMsg)>,
) -> anyhow::Result<()> {
run_local_socks5_proxy(cfg, ostp, exclusions_rx, debug, shutdown, proxy_events_tx, client_msgs_rx).await
}
pub mod exclusion;
pub mod process_lookup;
pub mod sni_sniff;

View File

@ -1,744 +0,0 @@
use anyhow::{anyhow, Result};
use tokio::sync::watch;
// ──────────────────────────────────────────────────────────────────────────────
// Windows / Linux desktop TUN
// ──────────────────────────────────────────────────────────────────────────────
#[cfg(any(target_os = "windows", target_os = "linux"))]
pub async fn run_native_tunnel(
config: crate::config::ClientConfig,
mut shutdown: watch::Receiver<bool>,
mut exclusions_rx: watch::Receiver<crate::config::ExclusionConfig>,
) -> Result<()> {
use std::net::ToSocketAddrs;
use netstack_smoltcp::StackBuilder;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use futures::{StreamExt, SinkExt};
#[cfg(target_os = "linux")]
{
use std::io::{self, IsTerminal, Write};
if io::stdout().is_terminal() {
println!("\n===================================================================");
println!("WARNING: TUN mode will modify the system routing table.");
println!("If you are connected to a headless server via SSH, you may lose");
println!("your connection when default routes are redirected into the tunnel.");
println!("===================================================================\n");
print!("Are you sure you want to initialize the TUN interface? [yes/no]: ");
io::stdout().flush().unwrap();
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
let ans = input.trim().to_lowercase();
if ans != "y" && ans != "yes" {
return Err(anyhow!("TUN initialization aborted by user."));
}
}
}
let debug = config.debug;
tracing::info!("Initializing NATIVE TUN tunnel (smoltcp)...");
// Capture physical interface index for bypass BEFORE we create the TUN device and alter routes.
#[cfg(target_os = "windows")]
let phys_if_for_bypass: Option<u32> = ostp_tun::windows::windows_route::sys::get_default_ipv4_route().map(|(_, idx)| idx);
#[cfg(not(target_os = "windows"))]
let phys_if_for_bypass: Option<u32> = None;
// ── 1. Resolve server IP ──────────────────────────────────────────────────
let server_ip = config
.ostp
.server_addr
.to_socket_addrs()
.map_err(|e| anyhow!("Failed to resolve server IP: {}", e))?
.next()
.map(|a| a.ip())
.ok_or_else(|| anyhow!("Could not resolve server host"))?;
#[allow(unused_variables)]
let server_ip_str = server_ip.to_string();
// ── 2. Resolve excluded domains → IP addresses for bypass routing ─────────
let mut bypass_ips: Vec<std::net::IpAddr> = Vec::new();
// Server IP always bypasses TUN
bypass_ips.push(server_ip);
for ip_str in &config.exclusions.ips {
let host = ip_str.split('/').next().unwrap_or(ip_str);
if let Ok(ip) = host.parse() {
bypass_ips.push(ip);
}
}
for domain in &config.exclusions.domains {
match tokio::net::lookup_host((domain.as_str(), 443u16)).await {
Ok(addrs) => {
for addr in addrs {
bypass_ips.push(addr.ip());
}
}
Err(e) => {
tracing::warn!("Failed to pre-resolve excluded domain {domain}: {e}");
}
}
}
// ── 3. Create TUN device via ostp-tun crate ───────────────────────────────
let opts = ostp_tun::OstpTunOptions {
server_ip,
bypass_ips,
dns_server: config.dns_server.clone(),
kill_switch: config.kill_switch,
mtu: config.ostp.mtu as u16,
wintun_path: None,
};
let tun_interface = ostp_tun::OstpTunInterface::create(opts)
.await
.map_err(|e| anyhow!("Failed to create OstpTunInterface: {}", e))?;
let dev = tun_interface.device;
let _route_guard = tun_interface.guard;
// ── 7. Build smoltcp network stack ────────────────────────────────────────
let (stack, tcp_runner, udp_socket, tcp_listener) = StackBuilder::default()
.stack_buffer_size(1024)
.tcp_buffer_size(1024)
.udp_buffer_size(1024)
.enable_tcp(true)
.enable_udp(true)
.mtu(config.ostp.mtu)
.build()?;
let mut runner_task = tokio::spawn(async move {
if let Some(runner) = tcp_runner {
let _ = runner.await;
}
});
// ── 8. Wire TUN ↔ smoltcp stack ───────────────────────────────────────────
let (mut stack_sink, mut stack_stream) = stack.split();
let (mut tun_read, mut tun_write) = tokio::io::split(dev);
let mut tun_to_stack = tokio::spawn(async move {
let mut buf = vec![0u8; 65536];
loop {
match tun_read.read(&mut buf).await {
Ok(0) => break,
Ok(n) => {
let frame = buf[..n].to_vec();
if let Err(e) = stack_sink.send(frame).await {
if e.kind() == std::io::ErrorKind::BrokenPipe {
break;
}
}
}
Err(e) => {
tracing::debug!("tun_read error: {e}");
}
}
}
});
let mut stack_to_tun = tokio::spawn(async move {
while let Some(Ok(frame)) = stack_stream.next().await {
if let Err(e) = tun_write.write(&frame).await {
tracing::debug!("tun_write error: {e}");
}
}
});
// ── 9. UDP: forward everything through OSTP proxy ─────────────────────────
// UDP exclusions are handled at the routing table level (step 5), so
// UDP packets for excluded IPs never reach smoltcp at all.
let udp_proxy_addr = {
let mut a = config.local_proxy.bind_addr.clone();
if a.starts_with("0.0.0.0:") {
a = a.replace("0.0.0.0:", "127.0.0.1:");
}
a
};
// Build exclusion matcher for dynamic bypass
let current_exclusions = exclusions_rx.borrow().clone();
let matcher = crate::tunnel::exclusion::ExclusionMatcher::new(&current_exclusions, None, None);
let matcher_arc = std::sync::Arc::new(tokio::sync::RwLock::new(matcher));
let matcher_clone = matcher_arc.clone();
tokio::spawn(async move {
while let Ok(_) = exclusions_rx.changed().await {
let current = exclusions_rx.borrow().clone();
let new_matcher = crate::tunnel::exclusion::ExclusionMatcher::new(&current, None, None);
*matcher_clone.write().await = new_matcher;
if true {
tracing::debug!("Desktop TUN exclusions hot-reloaded");
}
}
});
// Linux: physical interface name for SO_BINDTODEVICE
#[cfg(target_os = "linux")]
let linux_phys_name = crate::tunnel::proxy::get_linux_physical_if_name();
#[cfg(not(target_os = "linux"))]
let linux_phys_name: Option<String> = None;
let _ = &linux_phys_name; // suppress unused warning on Windows
let debug_udp = debug;
let udp_matcher = matcher_arc.clone();
#[cfg(target_os = "linux")]
let udp_lin_name = linux_phys_name.clone();
let mut udp_proxy_task = tokio::spawn(async move {
if let Some(udp_sock) = udp_socket {
#[cfg(target_os = "linux")]
super::udp_nat::run_udp_nat(udp_sock, udp_proxy_addr, debug_udp, udp_matcher, phys_if_for_bypass, udp_lin_name).await;
#[cfg(not(target_os = "linux"))]
super::udp_nat::run_udp_nat(udp_sock, udp_proxy_addr, debug_udp, udp_matcher, phys_if_for_bypass, None).await;
}
});
// ── 10. TCP: forward to OSTP proxy (with domain-level bypass via SNI) ─────
//
// For IP-based exclusions: handled by routing table → packets never arrive here.
// For domain-based exclusions: The IP is already in routing table (pre-resolved in
// step 3), so most traffic won't arrive. As a belt-and-suspenders fallback,
// we also sniff TLS SNI and bypass if it matches — this covers CDN cases where
// the IP wasn't known at startup.
//
// For bypassed connections we bind the outgoing socket to the physical interface
// (IP_UNICAST_IF) so it goes out via the real NIC, not TUN.
let proxy_addr_tcp = {
let mut a = config.local_proxy.bind_addr.clone();
if a.starts_with("0.0.0.0:") {
a = a.replace("0.0.0.0:", "127.0.0.1:");
}
a
};
// Physical interface index was captured at the start of the function.
let mut tcp_accept_task = tokio::spawn(async move {
let Some(mut listener) = tcp_listener else { return; };
while let Some((mut stream, local, remote)) = listener.next().await {
let proxy_addr = proxy_addr_tcp.clone();
let matcher_arc = matcher_arc.clone();
#[cfg(target_os = "linux")]
let lin_name = linux_phys_name.clone();
tokio::spawn(async move {
let matcher = matcher_arc.read().await.clone();
if debug {
tracing::debug!("TUN TCP {local} → {remote}");
}
// ── Sniff TLS ClientHello for SNI ─────────────────────────────
let mut sniff_buf = [0u8; 2048];
let sniff_len =
match tokio::time::timeout(
std::time::Duration::from_millis(100),
stream.read(&mut sniff_buf),
)
.await
{
Ok(Ok(n)) => n,
_ => 0,
};
// ── Decide: bypass or tunnel? ─────────────────────────────────
let mut should_bypass = false;
// 1. Process match via OS Extended TCP Table (Windows)
#[cfg(target_os = "windows")]
if !should_bypass {
if let Some(proc_name) = crate::tunnel::process_lookup::get_process_name_from_port(local.port()) {
if debug {
tracing::debug!("TUN TCP lookup: port {} -> process {}", local.port(), proc_name);
}
if matcher.match_process(&proc_name) {
if debug {
tracing::debug!("TUN TCP BYPASS (Process match): {} → {remote}", proc_name);
}
should_bypass = true;
}
} else {
if debug {
tracing::debug!("TUN TCP lookup: port {} -> no process found", local.port());
}
}
}
// 2. SNI domain check (belt-and-suspenders for CDNs / late-resolved IPs)
if !should_bypass && sniff_len > 0 {
if let Some(sni) =
crate::tunnel::sni_sniff::extract_sni(&sniff_buf[..sniff_len])
{
if debug {
tracing::debug!("TUN SNI: {sni}");
}
if matcher.match_domain(&sni) {
if debug {
tracing::info!("TUN TCP BYPASS (SNI domain): {sni} → {remote}");
}
should_bypass = true;
}
}
}
// 3. Destination IP CIDR check (for IPs not in routing table / IPv6)
if !should_bypass && matcher.match_ip(&remote.ip()) {
if debug {
tracing::info!("TUN TCP BYPASS (IP match): {remote}");
}
should_bypass = true;
}
// ── Bypass path: direct TCP bypassing TUN ─────────────────────
if should_bypass {
let socket = match remote {
std::net::SocketAddr::V4(_) => tokio::net::TcpSocket::new_v4(),
std::net::SocketAddr::V6(_) => tokio::net::TcpSocket::new_v6(),
};
let Ok(socket) = socket else { return; };
// Bind to physical interface so packets don't loop back into TUN
#[cfg(target_os = "windows")]
if let Some(idx) = phys_if_for_bypass {
if let Err(e) = crate::tunnel::proxy::bind_socket_to_interface(
&socket,
remote.is_ipv6(),
idx,
) {
tracing::error!("TUN TCP BYPASS failed to bind to physical interface {}: {}", idx, e);
} else {
if debug {
tracing::info!("TUN TCP BYPASS bound to physical interface {}", idx);
}
}
} else {
tracing::warn!("TUN TCP BYPASS has no physical interface index!");
}
#[cfg(target_os = "linux")]
if let Some(ref name) = lin_name {
let _ = crate::tunnel::proxy::bind_socket_to_interface(&socket, name);
}
match tokio::time::timeout(
std::time::Duration::from_secs(10),
socket.connect(remote),
)
.await
{
Ok(Ok(mut direct)) => {
if sniff_len > 0 {
if direct.write_all(&sniff_buf[..sniff_len]).await.is_err() {
return;
}
}
let _ = tokio::io::copy_bidirectional(&mut stream, &mut direct).await;
}
_ => {
tracing::debug!("Direct bypass connect to {remote} failed");
}
}
return;
}
// ── Tunnel path: forward via local OSTP SOCKS5 proxy ──────────
let Ok(mut socks) = tokio::net::TcpStream::connect(&proxy_addr).await else {
return;
};
// SOCKS5 handshake (no auth)
if socks.write_all(&[5, 1, 0]).await.is_err() { return; }
let mut buf2 = [0u8; 2];
if socks.read_exact(&mut buf2).await.is_err() || buf2[0] != 5 || buf2[1] != 0 {
return;
}
// CONNECT request
let mut req = vec![5u8, 1, 0];
match remote.ip() {
std::net::IpAddr::V4(v4) => {
req.push(1);
req.extend_from_slice(&v4.octets());
}
std::net::IpAddr::V6(v6) => {
req.push(4);
req.extend_from_slice(&v6.octets());
}
}
req.extend_from_slice(&remote.port().to_be_bytes());
if socks.write_all(&req).await.is_err() { return; }
let mut rep = [0u8; 10];
if socks.read_exact(&mut rep).await.is_err() || rep[1] != 0 { return; }
// Replay sniffed bytes
if sniff_len > 0 && socks.write_all(&sniff_buf[..sniff_len]).await.is_err() {
return;
}
let _ = tokio::io::copy_bidirectional(&mut stream, &mut socks).await;
});
}
});
tracing::info!("NATIVE TUN tunnel active.");
tokio::select! {
_ = shutdown.changed() => {}
_ = &mut runner_task => {}
_ = &mut tun_to_stack => {}
_ = &mut stack_to_tun => {}
_ = &mut udp_proxy_task => {}
_ = &mut tcp_accept_task => {}
}
tracing::info!("Deactivating NATIVE TUN tunnel...");
// ── Cleanup ───────────────────────────────────────────────────────────────
// Cleanup is handled automatically by the _route_guard Drop trait in ostp-tun
Ok(())
}
// ──────────────────────────────────────────────────────────────────────────────
// Stub for unsupported platforms
// ──────────────────────────────────────────────────────────────────────────────
#[cfg(not(any(target_os = "windows", target_os = "linux")))]
pub async fn run_native_tunnel(
_config: crate::config::ClientConfig,
_shutdown: watch::Receiver<bool>,
_exclusions_rx: watch::Receiver<crate::config::ExclusionConfig>,
) -> Result<()> {
Err(anyhow!("Native TUN tunnel is only supported on Windows/Linux"))
}
// ──────────────────────────────────────────────────────────────────────────────
// Android: TUN from file-descriptor (opened by VpnService)
// ──────────────────────────────────────────────────────────────────────────────
#[cfg(target_os = "android")]
pub async fn run_native_tunnel_from_fd(
config: crate::config::ClientConfig,
mut shutdown: watch::Receiver<bool>,
mut exclusions_rx: watch::Receiver<crate::config::ExclusionConfig>,
fd: i32,
) -> Result<()> {
use netstack_smoltcp::StackBuilder;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use futures::{StreamExt, SinkExt};
use std::os::unix::io::{FromRawFd, AsRawFd};
let debug = config.debug;
tracing::info!("Initializing NATIVE TUN tunnel on Android (FD {})", fd);
unsafe {
let flags = libc::fcntl(fd, libc::F_GETFL);
if flags >= 0 {
libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK);
}
}
let read_fd = unsafe { libc::dup(fd) };
if read_fd < 0 {
return Err(anyhow!("Failed to dup tun fd for reading"));
}
let file = unsafe { std::fs::File::from_raw_fd(read_fd) };
let tun_stream = tokio::io::unix::AsyncFd::new(file)?;
let (stack, tcp_runner, udp_socket, tcp_listener) = StackBuilder::default()
.stack_buffer_size(1024)
.tcp_buffer_size(1024)
.udp_buffer_size(1024)
.enable_tcp(true)
.enable_udp(true)
.mtu(config.ostp.mtu)
.build()?;
let mut runner_task = tokio::spawn(async move {
if let Some(runner) = tcp_runner {
let _ = runner.await;
}
});
let (mut stack_sink, mut stack_stream) = stack.split();
let _tun_to_stack = tokio::spawn(async move {
let mut buf = vec![0u8; 65536];
loop {
let mut guard = match tun_stream.readable().await {
Ok(g) => g,
Err(_) => break,
};
let n = match guard.try_io(|inner| {
let res = unsafe {
libc::read(
inner.as_raw_fd(),
buf.as_mut_ptr() as *mut libc::c_void,
buf.len(),
)
};
if res < 0 {
let err = std::io::Error::last_os_error();
if err.kind() == std::io::ErrorKind::WouldBlock {
Err(err)
} else {
Ok(0_isize)
}
} else {
Ok(res)
}
}) {
Ok(Ok(n)) if n > 0 => n as usize,
Ok(Ok(_)) => continue,
Ok(Err(_)) => continue,
Err(_) => continue,
};
let frame = buf[..n].to_vec();
if let Err(e) = stack_sink.send(frame).await {
if e.kind() == std::io::ErrorKind::BrokenPipe {
break;
}
}
}
});
let write_fd = unsafe { libc::dup(fd) };
if write_fd < 0 {
return Err(anyhow!("Failed to dup tun fd for writing"));
}
unsafe {
let flags = libc::fcntl(write_fd, libc::F_GETFL);
if flags >= 0 {
libc::fcntl(write_fd, libc::F_SETFL, flags | libc::O_NONBLOCK);
}
}
let write_file = unsafe { std::fs::File::from_raw_fd(write_fd) };
let tun_write_stream = tokio::io::unix::AsyncFd::new(write_file)?;
let _stack_to_tun = tokio::spawn(async move {
while let Some(Ok(frame)) = stack_stream.next().await {
let mut written = 0;
while written < frame.len() {
let mut guard = match tun_write_stream.writable().await {
Ok(g) => g,
Err(_) => break,
};
let res = guard.try_io(|inner| {
let res = unsafe {
libc::write(
inner.as_raw_fd(),
frame[written..].as_ptr() as *const libc::c_void,
frame.len() - written,
)
};
if res < 0 {
let err = std::io::Error::last_os_error();
if err.kind() == std::io::ErrorKind::WouldBlock {
Err(err)
} else {
Ok(res)
}
} else {
Ok(res)
}
});
match res {
Ok(Ok(n)) if n > 0 => written += n as usize,
Ok(Ok(_)) => break,
Ok(Err(_)) => break,
Err(_) => continue,
}
}
}
});
let mut proxy_addr = config.local_proxy.bind_addr.clone();
if proxy_addr.starts_with("0.0.0.0:") {
proxy_addr = proxy_addr.replace("0.0.0.0:", "127.0.0.1:");
}
let current_exclusions = exclusions_rx.borrow().clone();
let matcher = crate::tunnel::exclusion::ExclusionMatcher::new(&current_exclusions, None, None);
let matcher_arc = std::sync::Arc::new(tokio::sync::RwLock::new(matcher));
let matcher_clone = matcher_arc.clone();
tokio::spawn(async move {
while let Ok(_) = exclusions_rx.changed().await {
let current = exclusions_rx.borrow().clone();
let new_matcher = crate::tunnel::exclusion::ExclusionMatcher::new(&current, None, None);
*matcher_clone.write().await = new_matcher;
if true {
tracing::debug!("Android TUN exclusions hot-reloaded");
}
}
});
let udp_proxy_addr = proxy_addr.clone();
let debug_udp = debug;
let udp_matcher = matcher_arc.clone();
let mut udp_proxy_task = tokio::spawn(async move {
if let Some(udp_sock) = udp_socket {
super::udp_nat::run_udp_nat(udp_sock, udp_proxy_addr, debug_udp, udp_matcher, None, None).await;
}
});
let mut tcp_accept_task = tokio::spawn(async move {
let Some(mut listener) = tcp_listener else { return; };
while let Some((mut stream, local, remote)) = listener.next().await {
let proxy_addr = proxy_addr.clone();
let matcher_arc = matcher_arc.clone();
tokio::spawn(async move {
let matcher = matcher_arc.read().await.clone();
if true {
tracing::debug!("Android TUN TCP {local} → {remote}");
}
// Sniff SNI
let mut sniff_buf = [0u8; 2048];
let sniff_len =
match tokio::time::timeout(
std::time::Duration::from_millis(100),
stream.read(&mut sniff_buf),
)
.await
{
Ok(Ok(n)) => n,
_ => 0,
};
let mut should_bypass = false;
// 1. SNI domain
if sniff_len > 0 {
if let Some(sni) =
crate::tunnel::sni_sniff::extract_sni(&sniff_buf[..sniff_len])
{
if true { tracing::debug!("Android TUN SNI: {sni}"); }
if matcher.match_domain(&sni) {
should_bypass = true;
}
}
}
// 2. Process (Android: /proc/net lookup)
if !should_bypass {
if let Some(exe) =
crate::tunnel::process_lookup::get_process_name_from_port(local.port())
{
if true {
tracing::debug!("Android TUN port {} → EXE: {}", local.port(), exe);
}
if matcher.match_process(&exe) {
should_bypass = true;
}
}
}
// 3. IP CIDR
if !should_bypass && matcher.match_ip(&remote.ip()) {
should_bypass = true;
}
// Bypass: connect directly (Android VPN service already protects the socket
// from re-entering the TUN through VpnService.protect())
if should_bypass {
if true {
tracing::debug!("Android TUN BYPASS: {remote}");
}
let socket = match remote {
std::net::SocketAddr::V4(_) => tokio::net::TcpSocket::new_v4(),
std::net::SocketAddr::V6(_) => tokio::net::TcpSocket::new_v6(),
};
let Ok(socket) = socket else { return; };
match tokio::time::timeout(
std::time::Duration::from_secs(10),
socket.connect(remote),
)
.await
{
Ok(Ok(mut direct)) => {
if sniff_len > 0 {
if direct.write_all(&sniff_buf[..sniff_len]).await.is_err() {
return;
}
}
let _ = tokio::io::copy_bidirectional(&mut stream, &mut direct).await;
}
_ => {
tracing::debug!("Android bypass connect to {remote} failed");
}
}
return;
}
// Tunnel via SOCKS5 proxy
let Ok(mut socks) = tokio::net::TcpStream::connect(&proxy_addr).await else {
return;
};
if socks.write_all(&[5, 1, 0]).await.is_err() { return; }
let mut buf2 = [0u8; 2];
if socks.read_exact(&mut buf2).await.is_err() || buf2[0] != 5 || buf2[1] != 0 {
return;
}
let mut req = vec![5u8, 1, 0];
match remote.ip() {
std::net::IpAddr::V4(v4) => {
req.push(1);
req.extend_from_slice(&v4.octets());
}
std::net::IpAddr::V6(v6) => {
req.push(4);
req.extend_from_slice(&v6.octets());
}
}
req.extend_from_slice(&remote.port().to_be_bytes());
if socks.write_all(&req).await.is_err() { return; }
let mut rep = [0u8; 10];
if socks.read_exact(&mut rep).await.is_err() || rep[1] != 0 { return; }
if sniff_len > 0 && socks.write_all(&sniff_buf[..sniff_len]).await.is_err() {
return;
}
let _ = tokio::io::copy_bidirectional(&mut stream, &mut socks).await;
});
}
});
tracing::info!("NATIVE TUN (Android) tunnel active.");
tokio::select! {
_ = shutdown.changed() => {}
_ = &mut runner_task => {}
_ = _tun_to_stack => {}
_ = _stack_to_tun => {}
_ = &mut udp_proxy_task => {}
_ = &mut tcp_accept_task => {}
}
tracing::info!("NATIVE TUN (Android) deactivated.");
Ok(())
}
#[cfg(not(target_os = "android"))]
pub async fn run_native_tunnel_from_fd(
_config: crate::config::ClientConfig,
_shutdown: watch::Receiver<bool>,
_exclusions_rx: watch::Receiver<crate::config::ExclusionConfig>,
_fd: i32,
) -> Result<()> {
Err(anyhow!("Native TUN from FD is only supported on Android"))
}

View File

@ -0,0 +1,14 @@
use anyhow::{anyhow, Result};
use tokio::net::TcpStream;
pub async fn dial_tcp(_target_host: &str, _target_port: u16) -> Result<TcpStream> {
Err(anyhow!("Connection blocked by routing rule"))
}
pub async fn handle_udp(
_client_src: std::net::SocketAddr,
_target_dst: std::net::SocketAddr,
_payload: bytes::Bytes,
) -> Result<()> {
Err(anyhow!("Connection blocked by routing rule"))
}

View File

@ -0,0 +1,99 @@
use anyhow::{anyhow, Result};
use tokio::net::TcpStream;
#[cfg(target_os = "windows")]
pub fn bind_socket_to_interface(socket: &tokio::net::TcpSocket, is_ipv6: bool, if_index: u32) -> std::io::Result<()> {
use std::os::windows::io::AsRawSocket;
use winapi::shared::ws2def::{IPPROTO_IP, IPPROTO_IPV6};
// These constants are defined as 31 in the Windows SDK.
const IP_UNICAST_IF: i32 = 31;
const IPV6_UNICAST_IF: i32 = 31;
let fd = socket.as_raw_socket() as usize;
let idx_net = if_index.to_be();
let (level, optname) = if is_ipv6 {
(IPPROTO_IPV6 as i32, IPV6_UNICAST_IF)
} else {
(IPPROTO_IP as i32, IP_UNICAST_IF)
};
let ret = unsafe {
winapi::um::winsock2::setsockopt(
fd,
level as i32,
optname as i32,
&idx_net as *const _ as *const i8,
std::mem::size_of_val(&idx_net) as i32,
)
};
if ret != 0 {
return Err(std::io::Error::last_os_error());
}
Ok(())
}
#[cfg(target_os = "linux")]
pub fn bind_socket_to_interface(socket: &tokio::net::TcpSocket, _is_ipv6: bool, if_name: &str) -> std::io::Result<()> {
use std::os::unix::io::AsRawFd;
let fd = socket.as_raw_fd();
let name_bytes = if_name.as_bytes();
let ret = unsafe {
libc::setsockopt(
fd,
libc::SOL_SOCKET,
libc::SO_BINDTODEVICE,
name_bytes.as_ptr() as *const libc::c_void,
name_bytes.len() as libc::socklen_t,
)
};
if ret != 0 {
return Err(std::io::Error::last_os_error());
}
Ok(())
}
#[cfg(target_os = "macos")]
pub fn bind_socket_to_interface(socket: &tokio::net::TcpSocket, _is_ipv6: bool, if_index: u32) -> std::io::Result<()> {
// macOS uses IP_BOUND_IF for IPv4 and IPV6_BOUND_IF for IPv6, similar to Windows
use std::os::unix::io::AsRawFd;
let fd = socket.as_raw_fd();
// We can implement this later, for now just a stub so compilation works
tracing::debug!("macOS socket binding not yet fully implemented for interface {}", if_index);
Ok(())
}
pub async fn dial_tcp(target_host: &str, target_port: u16, _phys_if_idx: Option<u32>) -> Result<TcpStream> {
let addrs = tokio::net::lookup_host((target_host, target_port)).await?.collect::<Vec<_>>();
if addrs.is_empty() {
return Err(anyhow!("Could not resolve target host: {}", target_host));
}
let target_addr = addrs[0];
let socket = match target_addr {
std::net::SocketAddr::V4(_) => tokio::net::TcpSocket::new_v4()?,
std::net::SocketAddr::V6(_) => tokio::net::TcpSocket::new_v6()?,
};
#[cfg(target_os = "windows")]
if let Some(idx) = _phys_if_idx {
if let Err(e) = bind_socket_to_interface(&socket, target_addr.is_ipv6(), idx) {
tracing::warn!("DIRECT: Failed to bind to physical interface {}: {}", idx, e);
}
}
let stream = tokio::time::timeout(std::time::Duration::from_secs(10), socket.connect(target_addr)).await??;
Ok(stream)
}
pub async fn handle_udp(
_client_src: std::net::SocketAddr,
_target_dst: std::net::SocketAddr,
_payload: bytes::Bytes,
_phys_if_idx: Option<u32>,
) -> Result<()> {
Err(anyhow!("Direct UDP is not yet fully implemented"))
}

View File

@ -0,0 +1,77 @@
use anyhow::{anyhow, Result};
use std::sync::Arc;
use crate::tunnel::balancer::Balancer;
use crate::config::OutboundConfig;
pub mod direct;
pub mod block;
pub mod ostp;
pub mod socks;
pub struct OutboundManager {
balancer: Arc<Balancer>,
phys_if_index: Option<u32>,
_phys_if_name: Option<String>,
}
impl OutboundManager {
pub fn new(
balancer: Arc<Balancer>,
phys_if_index: Option<u32>,
phys_if_name: Option<String>,
) -> Self {
Self {
balancer,
phys_if_index,
_phys_if_name: phys_if_name,
}
}
pub async fn dial_tcp(&self, tag: &str, target_host: &str, target_port: u16) -> Result<tokio::net::TcpStream> {
let concrete_config = self.balancer.get_concrete_outbound(tag)
.ok_or_else(|| anyhow!("Outbound tag '{}' not found or resolved to invalid node", tag))?;
match concrete_config {
OutboundConfig::Direct { .. } => {
direct::dial_tcp(target_host, target_port, self.phys_if_index).await
}
OutboundConfig::Block { .. } => {
block::dial_tcp(target_host, target_port).await
}
OutboundConfig::Ostp { server, port, access_key, transport, multiplex, .. } => {
ostp::dial_tcp(target_host, target_port, server, *port, access_key, transport, multiplex).await
}
OutboundConfig::Socks { server, port, .. } => {
socks::dial_tcp(target_host, target_port, server, *port).await
}
_ => Err(anyhow!("Invalid concrete outbound type for {}", tag)),
}
}
pub async fn handle_udp(
&self,
tag: &str,
client_src: std::net::SocketAddr,
target_dst: std::net::SocketAddr,
payload: bytes::Bytes,
) -> Result<()> {
let concrete_config = self.balancer.get_concrete_outbound(tag)
.ok_or_else(|| anyhow!("Outbound tag '{}' not found or resolved to invalid node", tag))?;
match concrete_config {
OutboundConfig::Direct { .. } => {
direct::handle_udp(client_src, target_dst, payload, self.phys_if_index).await
}
OutboundConfig::Block { .. } => {
block::handle_udp(client_src, target_dst, payload).await
}
OutboundConfig::Ostp { server, port, access_key, transport, multiplex, .. } => {
ostp::handle_udp(client_src, target_dst, payload, server, *port, access_key, transport, multiplex).await
}
OutboundConfig::Socks { server, port, .. } => {
socks::handle_udp(client_src, target_dst, payload, server, *port).await
}
_ => Err(anyhow!("Invalid concrete outbound type for {}", tag)),
}
}
}

View File

@ -0,0 +1,458 @@
use anyhow::Result;
use tokio::net::TcpStream;
use crate::config::{TransportConfig, MultiplexConfig};
use ostp_core::{OstpEvent, ProtocolAction, ProtocolConfig, ProtocolMachine};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
/// Build the handshake payload the server expects:
/// [timestamp_u64_be (8 bytes)] [session_id_u32_be (4 bytes)] [access_key bytes]
fn build_handshake_payload(session_id: u32, access_key: &str) -> Vec<u8> {
let ts = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let mut payload = Vec::with_capacity(12 + access_key.len());
payload.extend_from_slice(&ts.to_be_bytes());
payload.extend_from_slice(&session_id.to_be_bytes());
payload.extend_from_slice(access_key.as_bytes());
payload
}
/// Build a correctly configured ProtocolConfig for an outgoing OSTP connection.
fn make_initiator_config(
session_id: u32,
access_key: &str,
transport_cfg: &TransportConfig,
) -> ProtocolConfig {
let secrets = ostp_core::crypto::derive_all_secrets(access_key.as_bytes());
let payload = build_handshake_payload(session_id, access_key);
let mtu = match transport_cfg.r#type.as_str() {
"dns" => 1100,
_ => 1350,
};
// For DNS transport: use larger ack_delay and rto to match DNS round-trip latency
// (each DNS query + reply takes 300-800ms end-to-end through Cloudflare).
// For UDP: minimize ack_delay to 1ms (ACK asap) and let CC drive the RTO.
let (ack_delay_ms, rto_ms) = match transport_cfg.r#type.as_str() {
"dns" => (50, 1500),
_ => (1, 200),
};
ProtocolConfig {
role: ostp_core::NoiseRole::Initiator,
psk: secrets.psk,
session_id,
handshake_payload: payload,
max_padding: 256,
padding_strategy: ostp_core::framing::PaddingStrategy::Adaptive,
obfuscation_key: secrets.obfuscation_key,
max_reorder: 16384,
max_reorder_buffer: 8192,
ack_delay_ms,
rto_ms,
max_retries: 8,
max_sent_history: 32768,
handshake_pad_min: secrets.handshake_pad_min,
handshake_pad_max: secrets.handshake_pad_max,
mtu,
}
}
fn random_session_id() -> u32 {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let mut h = DefaultHasher::new();
std::time::Instant::now().hash(&mut h);
std::thread::current().id().hash(&mut h);
h.finish() as u32
}
pub async fn dial_tcp(
target_host: &str,
target_port: u16,
server: &str,
port: u16,
access_key: &str,
transport_cfg: &TransportConfig,
_multiplex: &MultiplexConfig,
) -> Result<TcpStream> {
tracing::info!("Dialing OSTP server {}:{} for target {}:{}", server, port, target_host, target_port);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
let local_addr = listener.local_addr()?;
let client_stream = tokio::net::TcpStream::connect(local_addr).await?;
let (mut server_stream, _) = listener.accept().await?;
let transport = make_transport(transport_cfg, server, port).await?;
let session_id = random_session_id();
let config = make_initiator_config(session_id, access_key, transport_cfg);
let mut machine = ProtocolMachine::new(config).unwrap();
let target_host_str = target_host.to_string();
let server_str = server.to_string();
// Spawn bridge task
tokio::spawn(async move {
// Send initial handshake
if let Ok(action) = machine.on_event(OstpEvent::Start) {
handle_action(action, &transport, &mut server_stream).await;
}
// Wait for handshake response (server sends HandshakePayload back)
let mut buf = [0u8; 8192];
let mut handshake_success = false;
match tokio::time::timeout(
std::time::Duration::from_millis(15000),
transport.recv(&mut buf),
).await {
Ok(Ok(n)) => {
if let Ok(action) = machine.on_event(OstpEvent::Inbound(bytes::Bytes::copy_from_slice(&buf[..n]))) {
handle_action(action, &transport, &mut server_stream).await;
handshake_success = true;
}
}
_ => {
tracing::warn!("OSTP handshake timeout for {}:{}", server_str, port);
return;
}
}
if !handshake_success {
tracing::warn!("TCP handshake failed or protocol machine error");
return;
}
// Send connection request
let connect_msg = ostp_core::relay::RelayMessage::Connect(format!("{}:{}", target_host_str, target_port));
let connect_encoded = connect_msg.encode();
if let Ok(action) = machine.on_event(OstpEvent::Outbound(1, bytes::Bytes::from(connect_encoded))) {
handle_action(action, &transport, &mut server_stream).await;
}
// ── Wait for ConnectOk before forwarding any data ─────────────────
// This is critical: if we enter the data loop immediately, the TLS
// ClientHello arrives at the server before it has established the
// outbound TCP connection, causing it to drop the packet as
// "Relay DATA for unknown stream".
// The kernel will buffer incoming data from server_stream while we wait.
let mut connect_ok = false;
match tokio::time::timeout(
std::time::Duration::from_secs(30),
async {
let mut wait_buf = [0u8; 8192];
loop {
tokio::select! {
Ok(n) = transport.recv(&mut wait_buf) => {
if let Ok(action) = machine.on_event(OstpEvent::Inbound(
bytes::Bytes::copy_from_slice(&wait_buf[..n]),
)) {
// Check for ConnectOk or Error before dispatching
let result = check_connect_result(&action);
handle_action(action, &transport, &mut server_stream).await;
match result {
Some(true) => return true,
Some(false) => return false,
None => {}
}
}
}
_ = tokio::time::sleep(std::time::Duration::from_millis(10)) => {
if let Ok(action) = machine.on_event(OstpEvent::Tick) {
handle_action(action, &transport, &mut server_stream).await;
}
}
}
}
},
)
.await
{
Ok(true) => {
tracing::debug!("ConnectOk received for {}:{}, starting data forwarding", target_host_str, target_port);
connect_ok = true;
}
Ok(false) => {
tracing::warn!("Server refused connection to {}:{}", target_host_str, target_port);
}
Err(_) => {
tracing::warn!("ConnectOk timeout for {}:{}", target_host_str, target_port);
}
}
if !connect_ok {
return;
}
// ── Main bidirectional data forwarding loop ───────────────────────
// Backpressure: we track how many frames are in-flight vs the congestion
// window. When the window is full we stop reading from the TCP stream
// (the kernel buffers it) until the remote ACKs enough frames.
// This prevents overrunning the sender's sent_history and collapsing cwnd.
let mut buf = [0u8; 65535];
let mut udp_buf = [0u8; 65535];
loop {
// Compute adaptive tick interval:
// - If there is a pending ACK: tick = ack_delay (flush it quickly)
// - Otherwise: tick = rto/4 (check retransmits without busy-spinning)
// Floor at 1ms, ceiling at 50ms.
let tick_ms = (machine.rto().as_millis() / 4).clamp(1, 50) as u64;
let can_send = machine.in_flight_count() < machine.cwnd_packets().max(4);
tokio::select! {
// Only read from the application TCP stream when cwnd allows
Ok(n) = server_stream.read(&mut buf), if can_send => {
if n == 0 { break; }
let data_msg = ostp_core::relay::RelayMessage::Data(buf[..n].to_vec());
let encoded = data_msg.encode();
if let Ok(action) = machine.on_event(OstpEvent::Outbound(1, bytes::Bytes::from(encoded))) {
handle_action(action, &transport, &mut server_stream).await;
}
}
Ok(n) = transport.recv(&mut udp_buf) => {
if let Ok(action) = machine.on_event(OstpEvent::Inbound(bytes::Bytes::copy_from_slice(&udp_buf[..n]))) {
handle_action(action, &transport, &mut server_stream).await;
}
}
_ = tokio::time::sleep(std::time::Duration::from_millis(tick_ms)) => {
if let Ok(action) = machine.on_event(OstpEvent::Tick) {
handle_action(action, &transport, &mut server_stream).await;
}
}
}
}
});
Ok(client_stream)
}
pub async fn handle_udp(
client_src: std::net::SocketAddr,
target_dst: std::net::SocketAddr,
payload: bytes::Bytes,
server: &str,
port: u16,
access_key: &str,
transport_cfg: &TransportConfig,
_multiplex: &MultiplexConfig,
) -> Result<()> {
let transport = make_transport(transport_cfg, server, port).await?;
// Derive session_id from client source addr for stable per-flow sessions
let ip_bytes = match client_src.ip() {
std::net::IpAddr::V4(v4) => {
let o = v4.octets();
u32::from_be_bytes(o)
}
std::net::IpAddr::V6(v6) => {
let o = v6.octets();
u32::from_be_bytes([o[12], o[13], o[14], o[15]])
}
};
let session_id = ip_bytes ^ (client_src.port() as u32);
let config = make_initiator_config(session_id, access_key, transport_cfg);
let mut machine = ProtocolMachine::new(config)?;
// Send handshake first
if let Ok(action) = machine.on_event(OstpEvent::Start) {
handle_udp_action(action, &transport).await;
}
// Wait for handshake response (server sends HandshakePayload back)
let mut buf = [0u8; 8192];
match tokio::time::timeout(
std::time::Duration::from_millis(15000),
transport.recv(&mut buf),
).await {
Ok(Ok(n)) => {
let _ = machine.on_event(OstpEvent::Inbound(bytes::Bytes::copy_from_slice(&buf[..n])));
}
_ => {
tracing::warn!("OSTP handshake timeout for {}:{}", server, port);
return Ok(());
}
}
// Send relay UdpAssociate + data
let assoc_msg = ostp_core::relay::RelayMessage::UdpAssociate;
let encoded = assoc_msg.encode();
if let Ok(action) = machine.on_event(OstpEvent::Outbound(1, bytes::Bytes::from(encoded))) {
handle_udp_action(action, &transport).await;
}
let data_msg = ostp_core::relay::RelayMessage::UdpData(
format!("{}:{}", target_dst.ip(), target_dst.port()),
payload.to_vec()
);
let encoded = data_msg.encode();
if let Ok(action) = machine.on_event(OstpEvent::Outbound(1, bytes::Bytes::from(encoded))) {
handle_udp_action(action, &transport).await;
}
// Keep-alive for a short time to receive response
for _ in 0..5 {
match tokio::time::timeout(
std::time::Duration::from_millis(100),
transport.recv(&mut buf),
).await {
Ok(Ok(n)) => {
if let Ok(action) = machine.on_event(OstpEvent::Inbound(bytes::Bytes::copy_from_slice(&buf[..n]))) {
// Just process incoming UDP response internally
let _ = action;
}
}
_ => break,
}
}
Ok(())
}
async fn make_transport(
transport_cfg: &TransportConfig,
server: &str,
port: u16,
) -> Result<crate::transport::Transport> {
let debug = tracing::enabled!(tracing::Level::DEBUG);
match transport_cfg.r#type.as_str() {
"dns" => {
let domain = transport_cfg.domain.clone()
.unwrap_or_else(|| "tunnel.example.com".to_string());
let pubkey = transport_cfg.pubkey.clone()
.unwrap_or_else(|| "".to_string());
let resolver = transport_cfg.resolver.clone()
.unwrap_or_else(|| server.to_string());
let resolver_with_port = if resolver.contains(':') {
resolver.clone()
} else {
format!("{}:53", resolver)
};
let (local_port, process) = ostp_core::dnstt::spawn_client(&pubkey, &domain, &resolver_with_port, debug)?;
// Wait for dnstt-client to start its local TCP listener
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
// Connect TCP to the local dnstt-client port
let stream = tokio::net::TcpStream::connect(("127.0.0.1", local_port)).await?;
let (mut rh, mut wh) = stream.into_split();
let (tx_send, mut tx_recv) = tokio::sync::mpsc::channel::<bytes::Bytes>(1024);
let (rx_send, rx_recv) = tokio::sync::mpsc::channel::<bytes::Bytes>(1024);
// Writer task
tokio::spawn(async move {
use tokio::io::AsyncWriteExt;
while let Some(data) = tx_recv.recv().await {
let len = data.len() as u16;
if wh.write_u16(len).await.is_err() { break; }
if wh.write_all(&data).await.is_err() { break; }
}
});
// Reader task
tokio::spawn(async move {
use tokio::io::AsyncReadExt;
loop {
let len = match rh.read_u16().await {
Ok(l) => l,
Err(_) => break,
};
let mut buf = vec![0u8; len as usize];
if rh.read_exact(&mut buf).await.is_err() { break; }
if rx_send.send(bytes::Bytes::from(buf)).await.is_err() { break; }
}
});
Ok(crate::transport::Transport::Dnstt {
tx: tx_send,
rx: std::sync::Arc::new(tokio::sync::Mutex::new(rx_recv)),
_guard: std::sync::Arc::new(tokio::sync::Mutex::new(process)),
})
}
_ => {
let udp = tokio::net::UdpSocket::bind("0.0.0.0:0").await?;
udp.connect((server, port)).await?;
Ok(crate::transport::Transport::Udp(std::sync::Arc::new(udp)))
}
}
}
async fn handle_udp_action(action: ProtocolAction, transport: &crate::transport::Transport) {
match action {
ProtocolAction::SendDatagram(data) => {
let _ = transport.send(&data).await;
}
ProtocolAction::Multiple(actions) => {
for a in actions {
if let ProtocolAction::SendDatagram(data) = a {
let _ = transport.send(&data).await;
}
}
}
_ => {}
}
}
async fn handle_action(action: ProtocolAction, transport: &crate::transport::Transport, server_stream: &mut tokio::net::TcpStream) {
match action {
ProtocolAction::SendDatagram(data) => {
let _ = transport.send(&data).await;
}
ProtocolAction::DeliverApp(_stream_id, payload) => {
if let Ok(msg) = ostp_core::relay::RelayMessage::decode(&payload) {
match msg {
ostp_core::relay::RelayMessage::Data(data) => {
let _ = server_stream.write_all(&data).await;
}
ostp_core::relay::RelayMessage::ConnectOk => {
tracing::debug!("TCP Connection established successfully");
}
ostp_core::relay::RelayMessage::Error(err) => {
tracing::warn!("Server returned TCP connection error: {}", err);
}
_ => {}
}
}
}
ProtocolAction::Multiple(actions) => {
for a in actions {
Box::pin(handle_action(a, transport, server_stream)).await;
}
}
_ => {}
}
}
/// Inspect a ProtocolAction for ConnectOk / Error relay messages.
/// Returns Some(true) on ConnectOk, Some(false) on Error, None if neither.
/// Works recursively through Multiple actions.
fn check_connect_result(action: &ProtocolAction) -> Option<bool> {
match action {
ProtocolAction::DeliverApp(_stream_id, payload) => {
if let Ok(msg) = ostp_core::relay::RelayMessage::decode(payload) {
match msg {
ostp_core::relay::RelayMessage::ConnectOk => return Some(true),
ostp_core::relay::RelayMessage::Error(_) => return Some(false),
_ => {}
}
}
None
}
ProtocolAction::Multiple(actions) => {
for a in actions {
if let Some(result) = check_connect_result(a) {
return Some(result);
}
}
None
}
_ => None,
}
}

View File

@ -0,0 +1,17 @@
use anyhow::{anyhow, Result};
use tokio::net::TcpStream;
pub async fn dial_tcp(_target_host: &str, _target_port: u16, _server: &str, _port: u16) -> Result<TcpStream> {
// SOCKS5 dialer implementation stub
Err(anyhow!("SOCKS outbound TCP dialer not yet implemented"))
}
pub async fn handle_udp(
_client_src: std::net::SocketAddr,
_target_dst: std::net::SocketAddr,
_payload: bytes::Bytes,
_server: &str,
_port: u16,
) -> Result<()> {
Err(anyhow!("SOCKS outbound UDP handler not yet implemented"))
}

View File

@ -148,9 +148,8 @@ pub fn get_process_name_from_port(port: u16) -> Option<String> {
let target_inode = check_net_file("/proc/net/tcp")
.or_else(|| check_net_file("/proc/net/tcp6"))
.or_else(|| check_net_file("/proc/net/udp"))
.or_else(|| check_net_file("/proc/net/udp6"));
.or_else(|| check_net_file("/proc/net/udp6"))?;
let target_inode = target_inode?;
let socket_str = format!("socket:[{}]", target_inode);
for entry in fs::read_dir("/proc").ok()?.filter_map(Result::ok) {

View File

@ -1,939 +0,0 @@
use std::collections::HashMap;
use crate::tunnel::exclusion::ExclusionMatcher;
use anyhow::{anyhow, Context, Result};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream, UdpSocket};
use std::sync::Arc;
use tokio::sync::{mpsc, watch};
use tokio::time::{timeout, Duration};
use crate::config::{ExclusionConfig, LocalProxyConfig, OstpConfig};
use crate::tunnel::{ProxyEvent, ProxyToClientMsg};
#[cfg(target_os = "windows")]
use std::os::windows::io::AsRawSocket;
#[cfg(target_os = "linux")]
use std::os::fd::AsRawFd;
#[cfg(target_os = "windows")]
#[link(name = "ws2_32")]
extern "system" {
fn setsockopt(
s: usize,
level: i32,
optname: i32,
optval: *const u8,
optlen: i32,
) -> i32;
}
#[cfg(target_os = "windows")]
pub fn bind_socket_to_interface(socket: &impl AsRawSocket, is_ipv6: bool, if_index: u32) -> std::io::Result<()> {
let s = socket.as_raw_socket() as usize;
if is_ipv6 {
// IPV6_UNICAST_IF expects interface index in host byte order
let optval = if_index;
let ret = unsafe {
setsockopt(
s,
41, // IPPROTO_IPV6
31, // IPV6_UNICAST_IF
&optval as *const u32 as *const u8,
4,
)
};
if ret != 0 {
return Err(std::io::Error::last_os_error());
}
} else {
// IP_UNICAST_IF expects interface index in NETWORK byte order (big-endian)
let optval = if_index.to_be();
let ret = unsafe {
setsockopt(
s,
0, // IPPROTO_IP
31, // IP_UNICAST_IF
&optval as *const u32 as *const u8,
4,
)
};
if ret != 0 {
return Err(std::io::Error::last_os_error());
}
}
Ok(())
}
#[cfg(target_os = "linux")]
pub fn bind_socket_to_interface(socket: &impl AsRawFd, if_name: &str) -> std::io::Result<()> {
let fd = socket.as_raw_fd();
let mut if_name_bytes = if_name.as_bytes().to_vec();
if_name_bytes.push(0);
let ret = unsafe {
libc::setsockopt(
fd,
libc::SOL_SOCKET,
libc::SO_BINDTODEVICE,
if_name_bytes.as_ptr() as *const std::ffi::c_void,
if_name_bytes.len() as libc::socklen_t,
)
};
if ret != 0 {
return Err(std::io::Error::last_os_error());
}
Ok(())
}
pub fn get_windows_physical_if_index() -> Option<u32> {
#[cfg(target_os = "windows")]
{
return ostp_tun::windows::windows_route::sys::get_default_ipv4_route().map(|(_, idx)| idx);
}
#[cfg(not(target_os = "windows"))]
{
None
}
}
pub fn get_linux_physical_if_name() -> Option<String> {
#[cfg(target_os = "linux")]
{
let output = std::process::Command::new("ip")
.args(["route", "show", "default"])
.output()
.ok()?;
if output.status.success() {
let s = String::from_utf8_lossy(&output.stdout);
if let Some(dev_part) = s.split_whitespace().skip_while(|w| *w != "dev").nth(1) {
return Some(dev_part.to_string());
}
}
}
None
}
#[allow(unused_variables)]
async fn connect_bypassing_tun(
target: &str,
physical_if_index: Option<u32>,
_physical_if_name: &Option<String>,
) -> Result<TcpStream> {
let resolved = tokio::net::lookup_host(target).await
.with_context(|| format!("failed to resolve host for bypass connect: {target}"))?;
let mut last_err = None;
for addr in resolved {
let socket = if addr.is_ipv6() {
let s = tokio::net::TcpSocket::new_v6()?;
let _ = s.bind("[::]:0".parse().unwrap());
s
} else {
let s = tokio::net::TcpSocket::new_v4()?;
let _ = s.bind("0.0.0.0:0".parse().unwrap());
s
};
#[cfg(target_os = "windows")]
if let Some(if_index) = physical_if_index {
if let Err(e) = bind_socket_to_interface(&socket, addr.is_ipv6(), if_index) {
tracing::warn!("Failed to bind TCP socket to interface {}: {}", if_index, e);
}
}
#[cfg(target_os = "linux")]
if let Some(ref if_name) = _physical_if_name {
if let Err(e) = bind_socket_to_interface(&socket, if_name) {
tracing::warn!("Failed to bind TCP socket to interface {}: {}", if_name, e);
}
}
match socket.connect(addr).await {
Ok(stream) => return Ok(stream),
Err(e) => {
last_err = Some(e);
}
}
}
Err(anyhow!(
"direct connect failed: {:?}",
last_err.map(|e| e.to_string()).unwrap_or_else(|| "no addresses resolved".to_string())
))
}
#[allow(unused_variables)]
async fn create_udp_socket_bypassing_tun(
is_ipv6: bool,
physical_if_index: Option<u32>,
_physical_if_name: &Option<String>,
) -> Result<UdpSocket> {
let addr: std::net::SocketAddr = if is_ipv6 {
"[::]:0".parse().unwrap()
} else {
"0.0.0.0:0".parse().unwrap()
};
let socket = UdpSocket::bind(addr).await
.with_context(|| format!("failed to bind direct UdpSocket to wildcard {}", addr))?;
#[cfg(target_os = "windows")]
if let Some(if_index) = physical_if_index {
if let Err(e) = bind_socket_to_interface(&socket, is_ipv6, if_index) {
tracing::warn!("Failed to bind UDP socket to interface index {}: {}", if_index, e);
}
}
#[cfg(target_os = "linux")]
if let Some(ref if_name) = _physical_if_name {
if let Err(e) = bind_socket_to_interface(&socket, if_name) {
tracing::warn!("Failed to bind UDP socket to interface {}: {}", if_name, e);
}
}
Ok(socket)
}
pub async fn run_local_socks5_proxy(
cfg: LocalProxyConfig,
ostp: OstpConfig,
mut exclusions_rx: watch::Receiver<ExclusionConfig>,
debug: bool,
mut shutdown: watch::Receiver<bool>,
proxy_events_tx: mpsc::Sender<ProxyEvent>,
mut client_msgs_rx: mpsc::UnboundedReceiver<(u16, ProxyToClientMsg)>,
) -> Result<()> {
let connect_timeout = Duration::from_millis(cfg.connect_timeout_ms.max(1));
let listener = TcpListener::bind(&cfg.bind_addr)
.await
.with_context(|| format!("failed to bind local HTTP/SOCKS5 proxy at {}", cfg.bind_addr))?;
tracing::info!("local HTTP/SOCKS5 proxy listening at {}", cfg.bind_addr);
let physical_if_index = tokio::task::spawn_blocking(get_windows_physical_if_index).await.unwrap_or(None);
let physical_if_name = tokio::task::spawn_blocking(get_linux_physical_if_name).await.unwrap_or(None);
if physical_if_index.is_some() {
tracing::info!("Local proxy physical interface index: {:?}", physical_if_index);
}
if physical_if_name.is_some() {
tracing::info!("Local proxy physical interface name: {:?}", physical_if_name);
}
let mut current_exclusions = exclusions_rx.borrow().clone();
let mut matcher = ExclusionMatcher::new(&current_exclusions, physical_if_index, physical_if_name.clone());
let (connect_tx, mut connect_rx) = mpsc::channel(128);
let max_chunk = ostp.mtu.saturating_sub(150).max(512);
let mut next_stream_id: u16 = 1;
let mut active_streams: HashMap<u16, mpsc::UnboundedSender<ProxyToClientMsg>> = HashMap::new();
loop {
tokio::select! {
_ = shutdown.changed() => {
if *shutdown.borrow() {
break;
}
}
Ok(_) = exclusions_rx.changed() => {
current_exclusions = exclusions_rx.borrow().clone();
matcher = ExclusionMatcher::new(&current_exclusions, physical_if_index, physical_if_name.clone());
if true {
tracing::info!("Local proxy exclusions hot-reloaded");
}
}
accepted = listener.accept() => {
let (socket, _) = accepted?;
let stream_id = next_stream_id;
// Advance, skipping zero and any stream_id still in active_streams
loop {
next_stream_id = next_stream_id.wrapping_add(1);
if next_stream_id == 0 { next_stream_id = 1; }
if !active_streams.contains_key(&next_stream_id) { break; }
}
let (tx, rx) = mpsc::unbounded_channel();
active_streams.insert(stream_id, tx);
let event_tx = proxy_events_tx.clone();
let c_tx = connect_tx.clone();
let matcher_clone = matcher.clone();
tokio::spawn(async move {
if let Err(err) = handle_proxy_client(
socket,
stream_id,
event_tx,
rx,
c_tx,
connect_timeout,
debug,
matcher_clone,
max_chunk,
).await {
let msg = err.to_string();
// Suppress routine disconnects and unsupported SOCKS5 command attempts (like UDP) from spam logs
if !msg.contains("UnexpectedEof")
&& !msg.contains("Connection reset")
&& !msg.contains("Broken pipe")
&& !msg.contains("unsupported SOCKS5 command")
&& debug {
tracing::warn!("proxy client error: {err}");
}
}
});
}
Some((stream_id, msg)) = client_msgs_rx.recv() => {
if stream_id == 0 {
if let ProxyToClientMsg::Close = msg {
if true {
tracing::info!("Resetting all active proxy streams on reconnect");
}
for (_, tx) in active_streams.drain() {
let _ = tx.send(ProxyToClientMsg::Close);
}
}
} else if let Some(tx) = active_streams.get(&stream_id) {
if tx.send(msg).is_err() {
active_streams.remove(&stream_id);
}
}
}
Some(stream_id) = connect_rx.recv() => {
active_streams.remove(&stream_id);
}
}
}
Ok(())
}
/// Extracts `host:port` from an HTTP absolute-URI like `http://example.com/path` or `https://example.com`.
/// Falls back to the raw target if already in `host:port` form.
fn extract_host_port(uri: &str, default_port: u16) -> String {
let without_scheme = if let Some(rest) = uri.strip_prefix("https://") {
rest
} else if let Some(rest) = uri.strip_prefix("http://") {
rest
} else {
uri
};
// Trim path/query fragment
let host_part = without_scheme.split('/').next().unwrap_or(without_scheme);
if host_part.contains(':') {
host_part.to_string()
} else {
format!("{}:{}", host_part, default_port)
}
}
struct StreamGuard {
stream_id: u16,
close_tx: mpsc::Sender<u16>,
}
impl Drop for StreamGuard {
fn drop(&mut self) {
let tx = self.close_tx.clone();
let id = self.stream_id;
tokio::spawn(async move {
let _ = tx.send(id).await;
});
}
}
async fn handle_udp_associate(
mut client_tcp: TcpStream,
udp_socket: tokio::net::UdpSocket,
stream_id: u16,
event_tx: mpsc::Sender<ProxyEvent>,
mut rx: mpsc::UnboundedReceiver<ProxyToClientMsg>,
close_tx: mpsc::Sender<u16>,
debug: bool,
matcher: ExclusionMatcher,
connect_timeout: Duration,
) -> Result<()> {
let client_udp_addr = Arc::new(std::sync::Mutex::new(None));
let mut buf = vec![0u8; 65536];
let udp_socket = Arc::new(udp_socket);
let sock_rx = udp_socket.clone();
let sock_tx = udp_socket;
let mut direct_udp_v4: Option<Arc<UdpSocket>> = None;
let mut direct_udp_v6: Option<Arc<UdpSocket>> = None;
// Held only to keep the direct-UDP readers' cancellation senders alive;
// dropping this (on every return path from this function) is what tells
// spawn_direct_udp_reader's tasks to stop. See its doc comment.
let mut direct_udp_cancel_txs: Vec<tokio::sync::oneshot::Sender<()>> = Vec::new();
let mut tcp_buf = [0u8; 1];
loop {
tokio::select! {
res = client_tcp.read(&mut tcp_buf) => {
match res {
Ok(0) | Err(_) => break,
Ok(_) => {}
}
}
res = sock_rx.recv_from(&mut buf) => {
let (len, addr) = match res {
Ok(v) => v,
Err(e) => {
tracing::debug!("udp_associate recv_from error: {}", e);
continue; // transient error, don't kill the session
}
};
{
let mut guard = client_udp_addr.lock().unwrap();
if guard.is_none() {
*guard = Some(addr);
}
}
if len < 4 { continue; }
let frag = buf[2];
if frag != 0 { continue; } // Fragmented UDP not supported
let atyp = buf[3];
let (header_len, target) = match atyp {
0x01 => {
if len < 10 { continue; }
let ip = std::net::Ipv4Addr::new(buf[4], buf[5], buf[6], buf[7]);
let port = u16::from_be_bytes([buf[8], buf[9]]);
(10, format!("{}:{}", ip, port))
}
0x03 => {
if len < 5 { continue; }
let domain_len = buf[4] as usize;
if len < 5 + domain_len + 2 { continue; }
let domain = String::from_utf8_lossy(&buf[5..5+domain_len]);
let port = u16::from_be_bytes([buf[5+domain_len], buf[5+domain_len+1]]);
(5 + domain_len + 2, format!("{}:{}", domain, port))
}
0x04 => {
if len < 22 { continue; }
let mut octets = [0u8; 16];
octets.copy_from_slice(&buf[4..20]);
let ip = std::net::Ipv6Addr::from(octets);
let port = u16::from_be_bytes([buf[20], buf[21]]);
(22, format!("[{}]:{}", ip, port))
}
_ => continue,
};
let payload = bytes::Bytes::copy_from_slice(&buf[header_len..len]);
let target_host = if let Some((host, _)) = split_host_port(&target) { host } else { target.clone() };
let target_port = match split_host_port(&target) { Some((_, p)) => p, None => 0 };
// Check if target should bypass the tunnel
if matcher.should_bypass_target(&target_host, target_port, connect_timeout).await {
if true {
tracing::debug!("proxy UDP BYPASS target={}", target);
}
// Resolve target to find if it is IPv4 or IPv6
if let Ok(resolved_addrs) = tokio::net::lookup_host(&target).await {
if let Some(target_addr) = resolved_addrs.into_iter().next() {
let is_ipv6 = target_addr.is_ipv6();
let direct_socket = if is_ipv6 {
if direct_udp_v6.is_none() {
match create_udp_socket_bypassing_tun(true, matcher.physical_if_index, &matcher.physical_if_name).await {
Ok(s) => {
let s_arc = Arc::new(s);
let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel();
spawn_direct_udp_reader(s_arc.clone(), sock_tx.clone(), client_udp_addr.clone(), debug, cancel_rx);
direct_udp_cancel_txs.push(cancel_tx);
direct_udp_v6 = Some(s_arc);
}
Err(e) => {
tracing::error!("Failed to create bypass UDP v6 socket: {}", e);
}
}
}
&direct_udp_v6
} else {
if direct_udp_v4.is_none() {
match create_udp_socket_bypassing_tun(false, matcher.physical_if_index, &matcher.physical_if_name).await {
Ok(s) => {
let s_arc = Arc::new(s);
let (cancel_tx, cancel_rx) = tokio::sync::oneshot::channel();
spawn_direct_udp_reader(s_arc.clone(), sock_tx.clone(), client_udp_addr.clone(), debug, cancel_rx);
direct_udp_cancel_txs.push(cancel_tx);
direct_udp_v4 = Some(s_arc);
}
Err(e) => {
tracing::error!("Failed to create bypass UDP v4 socket: {}", e);
}
}
}
&direct_udp_v4
};
if let Some(s) = direct_socket {
if let Err(e) = s.send_to(&payload, target_addr).await {
if true {
tracing::warn!("failed to send bypass UDP packet to {}: {}", target_addr, e);
}
}
}
}
}
} else {
tracing::debug!("proxy.rs forwarding UDP DATA to server for target={} payload len={}", target, payload.len());
let _ = event_tx.send(ProxyEvent::UdpData { stream_id, target, payload }).await;
}
}
msg = rx.recv() => {
match msg {
Some(ProxyToClientMsg::UdpData(target, data)) => {
if let Some(client_addr) = {
let guard = client_udp_addr.lock().unwrap();
*guard
} {
let mut packet = vec![0x00, 0x00, 0x00];
let mut parts = target.rsplitn(2, ':');
let port_str = parts.next().unwrap_or("0");
let host_str = parts.next().unwrap_or(&target);
let host_str = host_str.trim_start_matches('[').trim_end_matches(']');
let port = port_str.parse::<u16>().unwrap_or(0);
if let Ok(ipv4) = host_str.parse::<std::net::Ipv4Addr>() {
packet.push(0x01);
packet.extend_from_slice(&ipv4.octets());
} else if let Ok(ipv6) = host_str.parse::<std::net::Ipv6Addr>() {
packet.push(0x04);
packet.extend_from_slice(&ipv6.octets());
} else {
packet.push(0x03);
let bytes = host_str.as_bytes();
packet.push(bytes.len() as u8);
packet.extend_from_slice(bytes);
}
packet.extend_from_slice(&port.to_be_bytes());
packet.extend_from_slice(&data);
tracing::debug!("proxy.rs forwarding UDP REPLY to client_addr={} from server for target={} payload len={}", client_addr, target, data.len());
let _ = sock_tx.send_to(&packet, client_addr).await;
} else {
tracing::error!("proxy.rs failed to parse target string as SocketAddr: {}", target);
}
}
Some(ProxyToClientMsg::Close) | Some(ProxyToClientMsg::Error(_)) | None => break,
_ => {}
}
}
}
}
let _ = close_tx.send(stream_id).await;
Ok(())
}
fn spawn_direct_udp_reader(
direct_socket: Arc<UdpSocket>,
sock_tx: Arc<UdpSocket>,
client_udp_addr: Arc<std::sync::Mutex<Option<std::net::SocketAddr>>>,
_debug: bool,
mut cancel_rx: tokio::sync::oneshot::Receiver<()>,
) {
tokio::spawn(async move {
let mut buf = vec![0u8; 65536];
loop {
let recv_result = tokio::select! {
// Fires as soon as the sender half (held by handle_udp_associate
// for exactly this reason) is dropped - which happens the
// instant that function returns, on every exit path, with no
// explicit signaling needed. Without this, a UDP-associate
// session that ever bypassed traffic direct (excluded IP/
// domain) leaked this socket + task for the rest of the
// process's life once the session ended: nothing else ever
// stopped this loop.
_ = &mut cancel_rx => break,
res = direct_socket.recv_from(&mut buf) => res,
};
match recv_result {
Ok((len, target_addr)) => {
let client_addr = {
let guard = client_udp_addr.lock().unwrap();
*guard
};
if let Some(client_addr) = client_addr {
let mut packet = vec![0x00, 0x00, 0x00];
if let Ok(ipv4) = target_addr.ip().to_string().parse::<std::net::Ipv4Addr>() {
packet.push(0x01);
packet.extend_from_slice(&ipv4.octets());
} else if let Ok(ipv6) = target_addr.ip().to_string().parse::<std::net::Ipv6Addr>() {
packet.push(0x04);
packet.extend_from_slice(&ipv6.octets());
} else {
continue;
}
packet.extend_from_slice(&target_addr.port().to_be_bytes());
packet.extend_from_slice(&buf[..len]);
if let Err(e) = sock_tx.send_to(&packet, client_addr).await {
if true {
tracing::warn!("failed to send direct UDP response to client: {e}");
}
}
}
}
Err(e) => {
if true {
tracing::debug!("direct UDP socket read loop exiting: {e}");
}
break;
}
}
}
});
}
async fn handle_proxy_client(
mut client: TcpStream,
stream_id: u16,
event_tx: mpsc::Sender<ProxyEvent>,
mut rx: mpsc::UnboundedReceiver<ProxyToClientMsg>,
close_tx: mpsc::Sender<u16>,
connect_timeout: Duration,
debug: bool,
matcher: ExclusionMatcher,
max_chunk: usize,
) -> Result<()> {
let _guard = StreamGuard { stream_id, close_tx: close_tx.clone() };
// Peek the first byte to distinguish SOCKS5 (0x05) from HTTP (any printable ASCII)
let mut first_byte = [0_u8; 1];
client.read_exact(&mut first_byte).await?;
let target: String;
let is_socks5 = first_byte[0] == 0x05;
if is_socks5 {
// ── SOCKS5 Handshake ──────────────────────────────────────────
let mut second_byte = [0_u8; 1];
client.read_exact(&mut second_byte).await?;
let nmethods = second_byte[0] as usize;
if nmethods > 0 {
let mut methods_buf = vec![0_u8; nmethods];
client.read_exact(&mut methods_buf).await?;
}
// Reply: version=5, NO AUTHENTICATION
client.write_all(&[0x05, 0x00]).await?;
// ── SOCKS5 Request ────────────────────────────────────────────
let mut req = [0_u8; 4];
client.read_exact(&mut req).await?;
if req[0] != 0x05 {
return Err(anyhow!("SOCKS5 request version mismatch"));
}
let is_udp = req[1] == 0x03;
if req[1] != 0x01 && !is_udp {
// Not CONNECT and Not UDP ASSOCIATE — send COMMAND NOT SUPPORTED
client.write_all(&[0x05, 0x07, 0x00, 0x01, 0, 0, 0, 0, 0, 0]).await?;
return Err(anyhow!("unsupported SOCKS5 command {}", req[1]));
}
let mut addr_buf = [0_u8; 256];
target = match req[3] {
0x01 => {
// IPv4: 4 bytes address + 2 bytes port
client.read_exact(&mut addr_buf[0..6]).await?;
let ip = std::net::Ipv4Addr::new(addr_buf[0], addr_buf[1], addr_buf[2], addr_buf[3]);
let port = u16::from_be_bytes([addr_buf[4], addr_buf[5]]);
format!("{}:{}", ip, port)
}
0x03 => {
// Domain: 1 byte length, then domain, then 2 bytes port
client.read_exact(&mut addr_buf[0..1]).await?;
let domain_len = addr_buf[0] as usize;
client.read_exact(&mut addr_buf[0..domain_len + 2]).await?;
let domain = String::from_utf8_lossy(&addr_buf[0..domain_len]);
let port = u16::from_be_bytes([addr_buf[domain_len], addr_buf[domain_len + 1]]);
format!("{}:{}", domain, port)
}
0x04 => {
// IPv6: 16 bytes + 2 bytes port
client.read_exact(&mut addr_buf[0..18]).await?;
let mut octets = [0u8; 16];
octets.copy_from_slice(&addr_buf[0..16]);
let ip = std::net::Ipv6Addr::from(octets);
let port = u16::from_be_bytes([addr_buf[16], addr_buf[17]]);
format!("[{}]:{}", ip, port)
}
atyp => {
client.write_all(&[0x05, 0x08, 0x00, 0x01, 0, 0, 0, 0, 0, 0]).await?;
return Err(anyhow!("unsupported SOCKS5 address type: {}", atyp));
}
};
if is_udp {
if true { tracing::debug!("proxy UDP ASSOCIATE stream_id={stream_id}"); }
let udp_socket = UdpSocket::bind("127.0.0.1:0").await?;
let port = udp_socket.local_addr()?.port();
let mut reply = vec![0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1];
reply.extend_from_slice(&port.to_be_bytes());
client.write_all(&reply).await?;
event_tx.send(ProxyEvent::UdpAssociate { stream_id }).await?;
return handle_udp_associate(
client,
udp_socket,
stream_id,
event_tx,
rx,
close_tx,
debug,
matcher,
connect_timeout,
).await;
}
tracing::debug!("proxy CONNECT stream_id={stream_id} target={target}");
let target_host = if let Some((host, _)) = split_host_port(&target) { host } else { target.clone() };
let target_port = match split_host_port(&target) { Some((_, p)) => p, None => 0 };
if matcher.should_bypass_target(&target_host, target_port, connect_timeout).await {
return direct_connect_socks5(
client,
stream_id,
&target,
matcher.physical_if_index,
&matcher.physical_if_name,
close_tx,
debug,
).await;
}
event_tx.send(ProxyEvent::NewStream { stream_id, target: target.clone() }).await?;
match timeout(connect_timeout, rx.recv()).await {
Ok(Some(ProxyToClientMsg::ConnectOk)) => {
// SUCCESS: version, 0=success, reserved, IPv4 type, 4 bytes addr, 2 bytes port
client.write_all(&[0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0]).await?;
}
Ok(Some(ProxyToClientMsg::Error(msg))) => {
client.write_all(&[0x05, 0x04, 0x00, 0x01, 0, 0, 0, 0, 0, 0]).await?;
let _ = close_tx.send(stream_id).await;
return Err(anyhow!("SOCKS5 connect error: {msg}"));
}
Ok(_) => {
client.write_all(&[0x05, 0x05, 0x00, 0x01, 0, 0, 0, 0, 0, 0]).await?;
let _ = close_tx.send(stream_id).await;
return Err(anyhow!("connect dropped"));
}
Err(_) => {
client.write_all(&[0x05, 0x04, 0x00, 0x01, 0, 0, 0, 0, 0, 0]).await?;
let _ = close_tx.send(stream_id).await;
return Err(anyhow!("connect timeout"));
}
}
} else {
// ── HTTP Proxy (CONNECT and plain GET/POST) ───────────────────
// Read the rest of the HTTP request headers byte-by-byte
let mut header_bytes = Vec::with_capacity(512);
header_bytes.push(first_byte[0]);
let mut chunk = [0_u8; 512];
loop {
let n = client.read(&mut chunk).await?;
if n == 0 {
return Err(anyhow!("connection closed during HTTP header read"));
}
header_bytes.extend_from_slice(&chunk[..n]);
if header_bytes.len() >= 4 {
let tail = &header_bytes[header_bytes.len().saturating_sub(4)..];
if tail.ends_with(b"\r\n\r\n") {
break;
}
}
if header_bytes.len() > 8192 {
client.write_all(b"HTTP/1.1 431 Request Header Fields Too Large\r\n\r\n").await?;
return Err(anyhow!("HTTP header too large"));
}
}
let req_str = String::from_utf8_lossy(&header_bytes);
let first_line = req_str.lines().next().unwrap_or("");
let parts: Vec<&str> = first_line.split_whitespace().collect();
if parts.len() < 2 {
client.write_all(b"HTTP/1.1 400 Bad Request\r\n\r\n").await?;
return Err(anyhow!("malformed HTTP request line: {:?}", first_line));
}
let method = parts[0].to_uppercase();
let raw_uri = parts[1];
target = if method == "CONNECT" {
// CONNECT uses host:port directly — e.g. "CONNECT example.com:443 HTTP/1.1"
if raw_uri.contains(':') {
raw_uri.to_string()
} else {
format!("{}:443", raw_uri)
}
} else {
// Plain HTTP: absolute URI like "GET http://example.com/path HTTP/1.1"
let default_port = if raw_uri.starts_with("https://") { 443u16 } else { 80u16 };
extract_host_port(raw_uri, default_port)
};
if true {
tracing::info!("proxy CONNECT stream_id={stream_id} target={target}");
}
let target_host = if let Some((host, _)) = split_host_port(&target) { host } else { target.clone() };
let target_port = match split_host_port(&target) { Some((_, p)) => p, None => 443 };
if matcher.should_bypass_target(&target_host, target_port, connect_timeout).await {
return direct_connect_http(
client,
stream_id,
&target,
method.as_str(),
header_bytes,
matcher.physical_if_index,
&matcher.physical_if_name,
close_tx,
debug,
).await;
}
event_tx.send(ProxyEvent::NewStream { stream_id, target: target.clone() }).await?;
match timeout(connect_timeout, rx.recv()).await {
Ok(Some(ProxyToClientMsg::ConnectOk)) => {
if method == "CONNECT" {
// For CONNECT, tell client the tunnel is ready
client.write_all(b"HTTP/1.1 200 Connection Established\r\nProxy-Agent: ostp/1.0\r\n\r\n").await?;
} else {
// For plain HTTP (GET/POST), we MUST forward the request headers we consumed
// to the server over the newly established tunnel.
event_tx.send(ProxyEvent::Data {
stream_id,
payload: bytes::Bytes::copy_from_slice(&header_bytes),
}).await?;
}
}
Ok(Some(ProxyToClientMsg::Error(msg))) => {
client.write_all(b"HTTP/1.1 502 Bad Gateway\r\n\r\n").await?;
let _ = close_tx.send(stream_id).await;
return Err(anyhow!("HTTP connect error: {msg}"));
}
Ok(_) => {
client.write_all(b"HTTP/1.1 502 Bad Gateway\r\n\r\n").await?;
let _ = close_tx.send(stream_id).await;
return Err(anyhow!("connect dropped"));
}
Err(_) => {
client.write_all(b"HTTP/1.1 504 Gateway Timeout\r\n\r\n").await?;
let _ = close_tx.send(stream_id).await;
return Err(anyhow!("connect timeout"));
}
}
}
// ── Bidirectional raw data forwarding ─────────────────────────────
let mut tcp_buf = vec![0_u8; 65536];
loop {
tokio::select! {
read_res = client.read(&mut tcp_buf) => {
match read_res {
Ok(0) => {
let _ = event_tx.send(ProxyEvent::Close { stream_id }).await;
if true {
tracing::info!("proxy CLOSE stream_id={stream_id}");
}
break;
}
Ok(n) => {
let mut offset = 0;
while offset < n {
let end = (offset + max_chunk).min(n);
let _ = event_tx.send(ProxyEvent::Data {
stream_id,
payload: bytes::Bytes::copy_from_slice(&tcp_buf[offset..end]),
}).await;
offset = end;
}
}
Err(_) => {
let _ = event_tx.send(ProxyEvent::Close { stream_id }).await;
if true {
tracing::info!("proxy CLOSE stream_id={stream_id}");
}
break;
}
}
}
msg = rx.recv() => {
match msg {
Some(ProxyToClientMsg::Data(data)) => {
if client.write_all(&data).await.is_err() {
let _ = event_tx.send(ProxyEvent::Close { stream_id }).await;
break;
}
}
Some(ProxyToClientMsg::Close) | Some(ProxyToClientMsg::Error(_)) | None => {
break;
}
Some(ProxyToClientMsg::ConnectOk) | Some(ProxyToClientMsg::UdpData(_, _)) => {} // ignored after connect phase
}
}
}
}
let _ = close_tx.send(stream_id).await;
Ok(())
}
fn split_host_port(target: &str) -> Option<(String, u16)> {
if let Some((host, port)) = target.rsplit_once(':') {
if host.starts_with('[') && host.ends_with(']') {
let host = host.trim_start_matches('[').trim_end_matches(']').to_string();
let port = port.parse().ok()?;
return Some((host, port));
}
if host.contains(':') {
return None;
}
let port = port.parse().ok()?;
return Some((host.to_string(), port));
}
None
}
async fn direct_connect_socks5(
mut client: TcpStream,
stream_id: u16,
target: &str,
physical_if_index: Option<u32>,
physical_if_name: &Option<String>,
close_tx: mpsc::Sender<u16>,
_debug: bool,
) -> Result<()> {
if true {
tracing::info!("proxy BYPASS stream_id={stream_id} target={target}");
}
let mut remote = connect_bypassing_tun(target, physical_if_index, physical_if_name).await?;
client.write_all(&[0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0]).await?;
let _ = tokio::io::copy_bidirectional(&mut client, &mut remote).await;
let _ = close_tx.send(stream_id).await;
Ok(())
}
async fn direct_connect_http(
mut client: TcpStream,
stream_id: u16,
target: &str,
method: &str,
header_bytes: Vec<u8>,
physical_if_index: Option<u32>,
physical_if_name: &Option<String>,
close_tx: mpsc::Sender<u16>,
_debug: bool,
) -> Result<()> {
if true {
tracing::info!("proxy BYPASS stream_id={stream_id} target={target}");
}
let mut remote = connect_bypassing_tun(target, physical_if_index, physical_if_name).await?;
if method == "CONNECT" {
client.write_all(b"HTTP/1.1 200 Connection Established\r\nProxy-Agent: ostp/1.0\r\n\r\n").await?;
} else {
remote.write_all(&header_bytes).await?;
}
let _ = tokio::io::copy_bidirectional(&mut client, &mut remote).await;
let _ = close_tx.send(stream_id).await;
Ok(())
}

View File

@ -0,0 +1,158 @@
use std::net::IpAddr;
use crate::config::{RoutingConfig, RoutingRule};
#[derive(Debug, Clone)]
pub struct Session {
pub inbound_tag: String,
pub source_ip: Option<IpAddr>,
pub destination_ip: Option<IpAddr>,
pub destination_port: u16,
pub protocol: String, // "tcp" or "udp"
pub sni: Option<String>,
pub process_name: Option<String>,
}
pub struct Router {
config: RoutingConfig,
}
impl Router {
pub fn new(config: RoutingConfig) -> Self {
Self { config }
}
/// Evaluates the session against routing rules and returns the outbound tag
pub fn route(&self, session: &Session) -> String {
for rule in &self.config.rules {
if self.match_rule(rule, session) {
return rule.outbound.clone();
}
}
self.config.default_outbound.clone()
}
fn match_rule(&self, rule: &RoutingRule, session: &Session) -> bool {
// All specified conditions in a rule must match (AND logic)
let mut matched_any_condition = false;
// 1. Inbound Tag match
if let Some(inbounds) = &rule.inbound_tag {
if !inbounds.iter().any(|tag| tag == &session.inbound_tag) {
return false;
}
matched_any_condition = true;
}
// 2. Domain / SNI match
if let Some(domains) = &rule.domain_suffix {
let mut domain_match = false;
if let Some(sni) = &session.sni {
let sni_lower = sni.to_lowercase();
domain_match = domains.iter().any(|d| {
let d_lower = d.to_lowercase();
sni_lower == d_lower || sni_lower.ends_with(&format!(".{}", d_lower))
});
}
if !domain_match {
return false;
}
matched_any_condition = true;
}
// 3. Process match
if let Some(processes) = &rule.process_name {
let mut proc_match = false;
if let Some(proc) = &session.process_name {
let proc_lower = proc.to_lowercase();
proc_match = processes.iter().any(|p| {
let p_lower = p.to_lowercase();
proc_lower.contains(&p_lower)
});
}
if !proc_match {
return false;
}
matched_any_condition = true;
}
// 4. IP CIDR match
if let Some(cidrs) = &rule.ip_cidr {
let mut ip_match = false;
if let Some(dst_ip) = session.destination_ip {
ip_match = cidrs.iter().any(|cidr| {
match ipnet::IpNet::from_str(cidr) {
Ok(net) => net.contains(&dst_ip),
Err(_) => {
// fallback to exact ip match if not a valid CIDR
if let Ok(ip) = cidr.parse::<IpAddr>() {
ip == dst_ip
} else {
false
}
}
}
});
}
if !ip_match {
return false;
}
matched_any_condition = true;
}
// A rule must have at least one condition to match
matched_any_condition
}
}
use std::str::FromStr;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_router() {
let rules = vec![
RoutingRule {
domain_suffix: Some(vec!["vk.com".to_string()]),
ip_cidr: None,
process_name: None,
inbound_tag: None,
outbound: "direct".to_string(),
},
RoutingRule {
domain_suffix: None,
ip_cidr: None,
process_name: Some(vec!["telegram.exe".to_string()]),
inbound_tag: None,
outbound: "proxy-group".to_string(),
},
];
let config = RoutingConfig {
rules,
default_outbound: "proxy-group".to_string(),
};
let router = Router::new(config);
let mut session = Session {
inbound_tag: "tun-in".to_string(),
source_ip: None,
destination_ip: None,
destination_port: 443,
protocol: "tcp".to_string(),
sni: Some("api.vk.com".to_string()),
process_name: None,
};
assert_eq!(router.route(&session), "direct");
session.sni = None;
session.process_name = Some("C:\\App\\Telegram.exe".to_string());
assert_eq!(router.route(&session), "proxy-group");
session.process_name = Some("chrome.exe".to_string());
assert_eq!(router.route(&session), "proxy-group"); // fallback
}
}

View File

@ -1,313 +1 @@
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::sync::{mpsc, Mutex};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpStream, UdpSocket};
use futures::StreamExt;
pub async fn run_udp_nat(
udp_socket: netstack_smoltcp::UdpSocket,
proxy_addr: String,
debug: bool,
matcher: std::sync::Arc<tokio::sync::RwLock<crate::tunnel::exclusion::ExclusionMatcher>>,
phys_if_index: Option<u32>,
phys_if_name: Option<String>,
) {
let (mut rx, tx) = udp_socket.split();
let tx = Arc::new(Mutex::new(tx));
// map from internal client src to a channel that sends (payload, external_dst)
let mut sessions: HashMap<SocketAddr, mpsc::Sender<(Vec<u8>, SocketAddr)>> = HashMap::new();
let mut cleanup_tick = tokio::time::interval(std::time::Duration::from_secs(60));
loop {
tokio::select! {
packet = rx.next() => {
match packet {
Some((payload, src, dst)) => {
if payload.is_empty() { continue; }
if !sessions.contains_key(&src) {
let (session_tx, mut session_rx) = mpsc::channel::<(Vec<u8>, SocketAddr)>(1024);
sessions.insert(src, session_tx);
let proxy_addr_clone = proxy_addr.clone();
let tx_clone = tx.clone();
let mut should_bypass = false;
{
let matcher_guard = matcher.read().await;
if matcher_guard.match_ip(&dst.ip()) {
should_bypass = true;
if debug {
tracing::info!("TUN UDP BYPASS (IP match): {} → {}", src, dst);
}
}
#[cfg(target_os = "windows")]
if !should_bypass {
if let Some(proc_name) = crate::tunnel::process_lookup::get_process_name_from_port_udp(src.port()) {
if debug {
tracing::debug!("TUN UDP lookup: port {} -> process {}", src.port(), proc_name);
}
if matcher_guard.match_process(&proc_name) {
should_bypass = true;
if debug {
tracing::debug!("TUN UDP BYPASS (Process match): {} ({} → {})", proc_name, src, dst);
}
}
} else {
if debug {
tracing::debug!("TUN UDP lookup: port {} -> no process found", src.port());
}
}
}
}
let p_if_idx = phys_if_index;
let p_if_name = phys_if_name.clone();
tokio::spawn(async move {
if should_bypass {
if debug {
tracing::info!("Starting UDP BYPASS session for {}", src);
}
let res = start_udp_bypass_session(src, p_if_idx, p_if_name, &mut session_rx, tx_clone).await;
if res.is_err() {
tracing::debug!("UDP BYPASS session for {} ended: {:?}", src, res.err());
}
} else {
tracing::debug!("Starting UDP NAT session for {}", src);
let res = start_udp_session(src, proxy_addr_clone, &mut session_rx, tx_clone).await;
if res.is_err() {
tracing::debug!("UDP NAT session for {} ended: {:?}", src, res.err());
}
}
});
}
if let Some(sender) = sessions.get(&src) {
match sender.try_send((payload, dst)) {
Err(mpsc::error::TrySendError::Closed(_)) => {
sessions.remove(&src);
}
Err(mpsc::error::TrySendError::Full(_)) => {
// Drop packet to avoid blocking the TUN interface loop
}
Ok(_) => {}
}
}
}
None => break,
}
}
_ = cleanup_tick.tick() => {
sessions.retain(|_, sender| !sender.is_closed());
}
}
}
}
async fn start_udp_bypass_session(
client_src: SocketAddr,
phys_if_index: Option<u32>,
_phys_if_name: Option<String>,
session_rx: &mut mpsc::Receiver<(Vec<u8>, SocketAddr)>,
smoltcp_tx: Arc<Mutex<netstack_smoltcp::udp::WriteHalf>>,
) -> anyhow::Result<()> {
let socket = match client_src {
SocketAddr::V4(_) => UdpSocket::bind("0.0.0.0:0").await?,
SocketAddr::V6(_) => UdpSocket::bind("[::]:0").await?,
};
#[cfg(target_os = "windows")]
if let Some(idx) = phys_if_index {
if let Err(e) = crate::tunnel::proxy::bind_socket_to_interface(&socket, client_src.is_ipv6(), idx) {
tracing::error!("TUN UDP BYPASS failed to bind to physical interface {}: {}", idx, e);
} else {
// Keep debug log
}
} else {
tracing::warn!("TUN UDP BYPASS has no physical interface index!");
}
#[cfg(target_os = "linux")]
if let Some(ref name) = _phys_if_name {
let _ = crate::tunnel::proxy::bind_socket_to_interface(&socket, name);
}
// A single select! loop over both directions, rather than spawning a
// separate task for the read side, so the whole session - physical
// socket included - is torn down the moment this function returns
// (e.g. when session_rx closes). The previous spawned-task version left
// that task (and its Arc<UdpSocket> clone, keeping the OS socket fd
// alive) running forever after this function returned: nothing ever
// cancelled it, so every bypassed UDP flow (any excluded app/IP in TUN
// mode) leaked one socket + one task for the lifetime of the process.
use futures::SinkExt;
let mut buf = [0u8; 65536];
loop {
tokio::select! {
outbound = session_rx.recv() => {
match outbound {
Some((payload, dst)) => { socket.send_to(&payload, dst).await?; }
None => break,
}
}
inbound = socket.recv_from(&mut buf) => {
match inbound {
Ok((n, peer)) => {
let mut lock = smoltcp_tx.lock().await;
let _ = lock.send((buf[..n].to_vec(), peer, client_src)).await;
}
Err(_) => break,
}
}
}
}
Ok(())
}
async fn start_udp_session(
client_src: SocketAddr,
proxy_addr: String,
session_rx: &mut mpsc::Receiver<(Vec<u8>, SocketAddr)>,
smoltcp_tx: Arc<Mutex<netstack_smoltcp::udp::WriteHalf>>,
) -> anyhow::Result<()> {
// 1. TCP Connect to SOCKS5 proxy
let mut tcp = TcpStream::connect(&proxy_addr).await?;
// Auth
tcp.write_all(&[5, 1, 0]).await?;
let mut buf = [0u8; 2];
tcp.read_exact(&mut buf).await?;
if buf[0] != 5 || buf[1] != 0 {
return Err(anyhow::anyhow!("socks5 auth rejected"));
}
// UDP ASSOCIATE to 0.0.0.0:0
tcp.write_all(&[5, 3, 0, 1, 0, 0, 0, 0, 0, 0]).await?;
let mut rep_hdr = [0u8; 4];
tcp.read_exact(&mut rep_hdr).await?;
if rep_hdr[1] != 0 {
return Err(anyhow::anyhow!("socks5 udp associate rejected"));
}
let mut relay_addr = match rep_hdr[3] {
1 => {
let mut addr_buf = [0u8; 6];
tcp.read_exact(&mut addr_buf).await?;
let ip = std::net::Ipv4Addr::new(addr_buf[0], addr_buf[1], addr_buf[2], addr_buf[3]);
let port = u16::from_be_bytes([addr_buf[4], addr_buf[5]]);
SocketAddr::new(std::net::IpAddr::V4(ip), port)
}
4 => {
let mut addr_buf = [0u8; 18];
tcp.read_exact(&mut addr_buf).await?;
let mut octets = [0u8; 16];
octets.copy_from_slice(&addr_buf[0..16]);
let ip = std::net::Ipv6Addr::from(octets);
let port = u16::from_be_bytes([addr_buf[16], addr_buf[17]]);
SocketAddr::new(std::net::IpAddr::V6(ip), port)
}
_ => return Err(anyhow::anyhow!("unsupported ATYP in UDP ASSOCIATE response")),
};
// If proxy returned 0.0.0.0 or ::, use the proxy's IP
if relay_addr.ip().is_unspecified() {
if let Ok(proxy_sock) = proxy_addr.parse::<SocketAddr>() {
relay_addr.set_ip(proxy_sock.ip());
}
}
// Local SOCKS5 proxy always returns 127.0.0.1 (IPv4), so always bind IPv4
let udp = UdpSocket::bind("127.0.0.1:0").await?;
// CRITICAL for Android: protect this UDP socket so it goes out via the
// real physical interface, not back into the TUN (which would cause an
// infinite routing loop for DNS and all other UDP traffic).
#[cfg(target_os = "android")]
{
use std::os::unix::io::AsRawFd;
crate::bridge::protect_socket(udp.as_raw_fd());
}
let mut buf = vec![0u8; 65536];
let timeout = std::time::Duration::from_secs(300); // 5 min idle timeout
let mut tcp_buf = [0u8; 1];
loop {
tokio::select! {
res = tokio::time::timeout(timeout, session_rx.recv()) => {
match res {
Ok(Some((payload, dst))) => {
let mut packet = vec![0u8; 3]; // RSV, FRAG
match dst.ip() {
std::net::IpAddr::V4(v4) => { packet.push(1); packet.extend_from_slice(&v4.octets()); }
std::net::IpAddr::V6(v6) => { packet.push(4); packet.extend_from_slice(&v6.octets()); }
}
packet.extend_from_slice(&dst.port().to_be_bytes());
packet.extend_from_slice(&payload);
tracing::debug!("udp_nat SENDING UDP ASSOCIATE payload len={} to relay_addr={} (original dst: {})", payload.len(), relay_addr, dst);
let _ = udp.send_to(&packet, relay_addr).await;
}
Ok(None) => break,
Err(_) => break, // timeout
}
}
res = udp.recv_from(&mut buf) => {
match res {
Err(e) => {
tracing::debug!("udp_nat recv_from error: {}", e);
continue; // transient error, don't kill the session
}
Ok((len, _peer)) => {
if len < 4 { continue; }
let frag = buf[2];
if frag != 0 { continue; } // fragment not supported
let atyp = buf[3];
let (header_len, remote_dst) = match atyp {
1 => {
if len < 10 { continue; }
let ip = std::net::Ipv4Addr::new(buf[4], buf[5], buf[6], buf[7]);
let port = u16::from_be_bytes([buf[8], buf[9]]);
(10, SocketAddr::new(std::net::IpAddr::V4(ip), port))
}
4 => {
if len < 22 { continue; }
let mut octets = [0u8; 16];
octets.copy_from_slice(&buf[4..20]);
let ip = std::net::Ipv6Addr::from(octets);
let port = u16::from_be_bytes([buf[20], buf[21]]);
(22, SocketAddr::new(std::net::IpAddr::V6(ip), port))
}
_ => continue,
};
let payload = buf[header_len..len].to_vec();
tracing::debug!("udp_nat RECEIVED UDP ASSOCIATE REPLY from {} for {} len={}", remote_dst, client_src, payload.len());
use futures::SinkExt;
if let Err(e) = smoltcp_tx.lock().await.send((payload, remote_dst, client_src)).await {
tracing::error!("udp_nat failed to inject packet into smoltcp: {}", e);
} else {
tracing::debug!("udp_nat successfully injected packet into smoltcp from {} to {}", remote_dst, client_src);
}
}
}
}
// If TCP drops, UDP association is over
res = tcp.read(&mut tcp_buf) => {
match res {
Ok(0) | Err(_) => break,
Ok(_) => {}
}
}
}
}
Ok(())
}
// Cleared for refactoring

Binary file not shown.

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

1
ostp-control/dist/favicon.svg vendored Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 9.3 KiB

24
ostp-control/dist/icons.svg vendored Normal file
View File

@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="bluesky-icon" viewBox="0 0 16 17">
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
</symbol>
<symbol id="discord-icon" viewBox="0 0 20 19">
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
</symbol>
<symbol id="documentation-icon" viewBox="0 0 21 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
</symbol>
<symbol id="github-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
</symbol>
<symbol id="social-icon" viewBox="0 0 20 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
</symbol>
<symbol id="x-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
</symbol>
</svg>

After

Width:  |  Height:  |  Size: 4.9 KiB

14
ostp-control/dist/index.html vendored Normal file
View File

@ -0,0 +1,14 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="./favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ostp-control</title>
<script type="module" crossorigin src="./assets/index-eeBKspfZ.js"></script>
<link rel="stylesheet" crossorigin href="./assets/index-DADo1Z55.css">
</head>
<body>
<div id="root"></div>
</body>
</html>

View File

@ -12,7 +12,10 @@ rand.workspace = true
snow.workspace = true
thiserror.workspace = true
tracing.workspace = true
byteorder = "1.5"
sha2.workspace = true
hmac.workspace = true
x25519-dalek = { version = "2.0.1", features = ["static_secrets"] }
hkdf = "0.12.0"
tokio.workspace = true
serde = { version = "1.0", features = ["derive"] }

3
ostp-core/build.rs Normal file
View File

@ -0,0 +1,3 @@
fn main() {
// Left empty by request
}

View File

@ -0,0 +1,58 @@
use ostp_core::{ProtocolMachine, ProtocolConfig, OstpEvent, ProtocolAction, NoiseRole};
fn main() {
let key = "3f5dfaf68e377a3724bdde3ac7b4f4de";
let secrets = ostp_core::crypto::derive_all_secrets(key.as_bytes());
let mut init_cfg = ProtocolConfig {
role: NoiseRole::Initiator,
session_id: 12345,
psk: secrets.psk,
obfuscation_key: secrets.obfuscation_key,
handshake_pad_min: secrets.handshake_pad_min,
handshake_pad_max: secrets.handshake_pad_max,
max_reorder: 10,
max_reorder_buffer: 10,
ack_delay_ms: 10,
rto_ms: 100,
max_retries: 5,
max_sent_history: 100,
handshake_payload: vec![],
mtu: 1400,
max_padding: 0,
padding_strategy: ostp_core::PaddingStrategy::Adaptive,
};
let mut payload = Vec::new();
payload.extend_from_slice(&0u64.to_be_bytes()); // time
payload.extend_from_slice(&12345u32.to_be_bytes());
payload.extend_from_slice(key.as_bytes());
init_cfg.handshake_payload = payload;
let mut init_machine = ProtocolMachine::new(init_cfg.clone()).unwrap();
let action = init_machine.on_event(OstpEvent::Start).unwrap();
let pkt = match action {
ProtocolAction::SendDatagram(p) => p,
_ => panic!("Expected SendDatagram"),
};
println!("Initiator sent {} bytes", pkt.len());
let mut resp_cfg = init_cfg.clone();
resp_cfg.role = NoiseRole::Responder;
let mut resp_machine = ProtocolMachine::new(resp_cfg).unwrap();
// Simulate what server dispatcher does
let mut raw_vec = pkt.to_vec();
ostp_core::crypto::deobfuscate_packet_inplace(&mut raw_vec, &secrets.obfuscation_key, true);
println!("Deobfuscated length: {}", raw_vec.len());
let action = resp_machine.on_event(OstpEvent::Inbound(pkt));
match action {
Ok(ProtocolAction::HandshakePayload(_, _)) => println!("Responder: Handshake OK!"),
Ok(_) => println!("Responder: Not HandshakePayload"),
Err(e) => println!("Responder error: {:?}", e),
}
}

View File

@ -39,18 +39,10 @@ pub struct CongestionController {
loss_count: u32,
/// Pacing rate: bytes per second
pacing_rate: u64,
/// Token-bucket allowance for pacing, in bytes.
pacing_tokens: f64,
pacing_last_refill: Instant,
/// MTU estimate (used for cwnd → packet count conversion)
mtu: u64,
/// Min RTT expiry: re-probe after 10 seconds
min_rtt_stamp: Instant,
/// Loss events counted toward SLOW_START_LOSS_TOLERANCE within the
/// current SLOW_START_LOSS_WINDOW (see on_loss's SlowStart arm).
slow_start_losses: u32,
/// Start of the current loss-tolerance window.
slow_start_loss_window_start: Instant,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@ -68,20 +60,6 @@ const MIN_CWND_PACKETS: u64 = 2;
/// Min RTT expiry window (after which we re-probe)
const MIN_RTT_EXPIRY: Duration = Duration::from_secs(10);
/// Minimum RTO (RFC 6298: 1s in TCP; we use 50ms since we own the protocol)
/// Absolute ceiling on the congestion window, in packets. At a ~1200-byte MTU
/// this is roughly 1.2 MB in flight — already far above the bandwidth-delay
/// product of any link this protocol realistically runs over, so anything
/// beyond it is standing queue, not throughput. The client previously allowed
/// up to 16384 packets (~20 MB), which on a mobile uplink is minutes of buffer.
const MAX_CWND_PACKETS: u64 = 1024;
/// SRTT/min_rtt ratio at which slow start stops. Doubling is what fills a deep
/// buffer fastest, so growth must end when the queue starts building rather
/// than waiting for a loss that a deep buffer may never produce.
const RTT_INFLATION_EXIT_SLOW_START: f64 = 2.0;
/// SRTT/min_rtt ratio treated as a standing queue that must be actively drained.
const RTT_INFLATION_BACKOFF: f64 = 4.0;
/// How much pacing allowance may accumulate, expressed as time-at-rate.
const PACING_BURST: Duration = Duration::from_millis(10);
const RTO_MIN: Duration = Duration::from_millis(50);
/// Maximum RTO
const RTO_MAX: Duration = Duration::from_secs(16);
@ -89,24 +67,6 @@ const RTO_MAX: Duration = Duration::from_secs(16);
/// Will be replaced by first real measurement within milliseconds.
const INITIAL_RTT: Duration = Duration::from_millis(30);
/// Isolated packet loss during slow start (a single dropped frame from
/// wireless noise, a brief LTE handover blip, etc.) is normal on real
/// mobile/Wi-Fi links and does NOT mean the link is congested. The previous
/// behavior exited slow start and halved cwnd on the very FIRST loss, which
/// on any link with a non-zero background loss rate permanently downgrades
/// the session from exponential growth to linear (+1 MTU/RTT) ProbeBandwidth
/// growth within the first few RTTs - turning what should be a sub-second
/// ramp-up into tens of seconds to minutes before throughput opens up
/// (observed as: a trickle of KB/s, then a sudden jump once cwnd finally
/// claws back up). Only treat loss as a real congestion signal - and pay
/// the full slow-start-exit + halving cost - once this many losses land
/// within SLOW_START_LOSS_WINDOW.
const SLOW_START_LOSS_TOLERANCE: u32 = 3;
/// Window within which SLOW_START_LOSS_TOLERANCE losses must land to count
/// as sustained (rather than isolated) loss. Roughly a few RTTs on a
/// well-connected link, generous on a slow one.
const SLOW_START_LOSS_WINDOW: Duration = Duration::from_millis(500);
impl CongestionController {
pub fn new(mtu: u64) -> Self {
let now = Instant::now();
@ -128,52 +88,9 @@ impl CongestionController {
pacing_rate: initial_pacing,
mtu,
min_rtt_stamp: now,
slow_start_losses: 0,
slow_start_loss_window_start: now,
pacing_tokens: (INITIAL_CWND_PACKETS * mtu) as f64,
pacing_last_refill: now,
}
}
/// Bytes of pacing allowance available right now, without consuming any.
///
/// Read-only so the send path can use it as an admission check before it
/// commits to building a datagram.
pub fn pacing_available(&self) -> f64 {
let elapsed = self.pacing_last_refill.elapsed().as_secs_f64();
(self.pacing_tokens + elapsed * self.pacing_rate as f64).min(self.pacing_burst())
}
/// Whether at least one full-size packet may be released right now.
pub fn can_pace_packet(&self) -> bool {
self.pacing_available() >= self.mtu as f64
}
/// Ceiling on accumulated allowance.
///
/// Pacing intervals here are fractions of a millisecond, so releasing
/// strictly one packet at a time would need a sub-millisecond timer per
/// packet. Instead we allow a short burst — the same trade every real
/// pacing implementation makes — sized so the loop's existing ~10ms wakeups
/// can still saturate the configured rate, with a small floor so a
/// cold/low estimate can never wedge sending entirely.
fn pacing_burst(&self) -> f64 {
let by_rate = self.pacing_rate as f64 * PACING_BURST.as_secs_f64();
by_rate.max((self.mtu * 4) as f64)
}
/// Refill from elapsed time and deduct `bytes`. Called on the real send
/// path; allowance is permitted to go negative so an oversized packet still
/// pays for itself rather than being released for free.
fn consume_pacing(&mut self, bytes: u64) {
let now = Instant::now();
let elapsed = now.duration_since(self.pacing_last_refill).as_secs_f64();
self.pacing_last_refill = now;
self.pacing_tokens =
(self.pacing_tokens + elapsed * self.pacing_rate as f64).min(self.pacing_burst())
- bytes as f64;
}
/// Returns the current congestion window in bytes.
pub fn cwnd(&self) -> u64 {
self.cwnd
@ -225,24 +142,6 @@ impl CongestionController {
/// Record that we sent `bytes` of data.
pub fn on_send(&mut self, bytes: u64) {
self.bytes_in_flight = self.bytes_in_flight.saturating_add(bytes);
// Charge the pacing bucket here rather than at the admission check, so
// every byte that actually reaches the wire is paid for exactly once —
// including retransmits, which are precisely what must not be allowed
// to bypass the rate limit and pile into an already-full queue.
self.consume_pacing(bytes);
}
/// Record that `bytes` were acknowledged but WITHOUT a usable RTT sample
/// (e.g. every acked frame was retransmitted, so Karn's algorithm forbids
/// measuring RTT from it). The window still advances; only the RTT estimator
/// is left untouched.
pub fn on_ack_no_rtt(&mut self, bytes: u64) {
let now = Instant::now();
self.bytes_in_flight = self.bytes_in_flight.saturating_sub(bytes);
self.total_acked = self.total_acked.saturating_add(bytes);
self.grow_window(bytes);
self.update_pacing_rate();
self.last_ack_time = now;
}
/// Record that `bytes` were acknowledged with the given RTT sample.
@ -254,53 +153,9 @@ impl CongestionController {
// Update RTT measurements
self.update_rtt(rtt, now);
self.grow_window(bytes);
self.update_pacing_rate();
self.last_ack_time = now;
}
/// Congestion-window growth shared by both ACK paths (slow start / probe).
fn grow_window(&mut self, bytes: u64) {
// ── Delay-based congestion signal ────────────────────────────────────
// A loss-only controller is blind on a deeply-buffered path, and mobile
// carrier buffers are very deep: they absorb a burst instead of dropping
// it, so no loss is ever signalled and cwnd keeps growing. The queue —
// not the link — is what grows, and the standing delay it adds shows up
// as RTT inflating far above the path's floor. Left unchecked this is a
// positive feedback loop: bigger queue -> larger RTT samples -> larger
// SRTT -> larger RTO -> retransmits pile on -> bigger queue, which is
// how a session ends up reporting multi-second (even multi-minute) RTT
// and stalls video until the buffer finally drains or the user
// reconnects. Treat sustained RTT inflation as congestion in its own
// right, exactly as it is.
let inflation = if self.rtt_initialized && !self.min_rtt.is_zero() {
self.srtt.as_secs_f64() / self.min_rtt.as_secs_f64()
} else {
1.0
};
if inflation >= RTT_INFLATION_BACKOFF {
// Standing queue is severe — actively drain it.
self.cwnd = (self.cwnd / 2).max(MIN_CWND_PACKETS * self.mtu);
self.ssthresh = self.cwnd;
self.phase = Phase::ProbeBandwidth;
tracing::debug!(cwnd = self.cwnd, inflation, "congestion: draining standing queue");
self.clamp_cwnd();
return;
}
// State machine
match self.phase {
Phase::SlowStart => {
// Exponential doubling is what fills a deep buffer fastest, so
// leave slow start as soon as the queue starts to build rather
// than waiting for the loss that may never come.
if inflation >= RTT_INFLATION_EXIT_SLOW_START {
self.ssthresh = self.cwnd;
self.phase = Phase::ProbeBandwidth;
tracing::debug!(cwnd = self.cwnd, inflation, "congestion: RTT inflation ended slow start");
self.clamp_cwnd();
return;
}
// Exponential growth: increase cwnd by acked bytes (doubles per RTT)
self.cwnd = self.cwnd.saturating_add(bytes);
if self.cwnd >= self.ssthresh {
@ -314,20 +169,8 @@ impl CongestionController {
}
}
self.clamp_cwnd();
}
/// Hard ceiling on the congestion window.
///
/// Independent of any estimate: no real path this protocol runs over has a
/// bandwidth-delay product anywhere near this, so a window above it is
/// buffered queue rather than data in transit. Without it, slow start on a
/// buffer that never drops could grow the window into the tens of megabytes.
fn clamp_cwnd(&mut self) {
let ceiling = MAX_CWND_PACKETS.saturating_mul(self.mtu);
if self.cwnd > ceiling {
self.cwnd = ceiling;
}
self.update_pacing_rate();
self.last_ack_time = now;
}
/// Record a loss event.
@ -337,28 +180,11 @@ impl CongestionController {
match self.phase {
Phase::SlowStart => {
let now = Instant::now();
if now.duration_since(self.slow_start_loss_window_start) > SLOW_START_LOSS_WINDOW {
// Previous window's losses have aged out - this loss starts a fresh count.
self.slow_start_losses = 0;
self.slow_start_loss_window_start = now;
}
self.slow_start_losses += 1;
if self.slow_start_losses >= SLOW_START_LOSS_TOLERANCE {
// Sustained loss within the window: treat as real congestion.
// Exit slow start, set ssthresh to half of cwnd.
self.ssthresh = self.cwnd / 2;
self.cwnd = self.ssthresh.max(MIN_CWND_PACKETS * self.mtu);
self.phase = Phase::ProbeBandwidth;
tracing::debug!(cwnd = self.cwnd, ssthresh = self.ssthresh, "congestion: sustained loss during slow start, exiting");
} else {
// Isolated loss: likely non-congestive noise. Take a mild,
// temporary haircut but keep exponential growth going -
// don't throw away slow start over a single dropped frame.
self.cwnd = (self.cwnd * 8 / 10).max(MIN_CWND_PACKETS * self.mtu);
tracing::debug!(cwnd = self.cwnd, count = self.slow_start_losses, "congestion: isolated loss during slow start, staying in slow start");
}
// Exit slow start, set ssthresh to half of cwnd
self.ssthresh = self.cwnd / 2;
self.cwnd = self.ssthresh.max(MIN_CWND_PACKETS * self.mtu);
self.phase = Phase::ProbeBandwidth;
tracing::debug!(cwnd = self.cwnd, ssthresh = self.ssthresh, "congestion: loss during slow start");
}
Phase::ProbeBandwidth => {
// Multiplicative decrease: cwnd *= 0.7 (BBR-style, less aggressive than Cubic's 0.5)
@ -447,138 +273,6 @@ mod tests {
assert!(cc.cwnd() < initial);
}
/// The bufferbloat case: a deep buffer absorbs everything, so NOTHING is
/// ever lost, but the standing queue inflates RTT. A loss-only controller
/// grows cwnd forever here — which is how a session ends up reporting
/// multi-second RTT and stalling video.
#[test]
fn test_rtt_inflation_halts_growth_without_any_loss() {
let mut cc = CongestionController::new(1200);
// Establish a low path floor; this becomes min_rtt.
for _ in 0..4 {
cc.on_send(1200);
cc.on_ack(1200, Duration::from_millis(20));
}
let cwnd_before = cc.cwnd();
// Queue builds: RTT climbs far above the floor, still zero loss.
for _ in 0..20 {
cc.on_send(1200);
cc.on_ack(1200, Duration::from_millis(400));
}
assert!(
cc.cwnd() <= cwnd_before,
"cwnd kept growing while the queue was inflating RTT ({} -> {})",
cwnd_before,
cc.cwnd()
);
}
/// Pacing must actually bound the release rate: draining the bucket has to
/// deny the next packet. Without this the congestion window alone decides,
/// and a whole window leaves back-to-back.
#[test]
fn test_pacing_bucket_denies_once_drained() {
let mut cc = CongestionController::new(1200);
assert!(cc.can_pace_packet(), "a fresh controller must allow sending");
// Spend well beyond one burst allowance.
let burst_bytes = cc.pacing_available();
let mut spent = 0.0;
while spent <= burst_bytes + 1200.0 {
cc.on_send(1200);
spent += 1200.0;
}
assert!(
!cc.can_pace_packet(),
"pacing allowed unbounded sending: {} bytes still available after spending {}",
cc.pacing_available(),
spent
);
}
/// The allowance must refill over time, or sending would stall permanently
/// once the first burst is spent.
#[test]
fn test_pacing_bucket_refills_over_time() {
let mut cc = CongestionController::new(1200);
while cc.can_pace_packet() {
cc.on_send(1200);
}
assert!(!cc.can_pace_packet());
std::thread::sleep(Duration::from_millis(25));
assert!(
cc.can_pace_packet(),
"pacing bucket never refilled; sending would be stuck forever"
);
}
/// cwnd must never exceed the absolute ceiling, however long slow start
/// runs unopposed — above it the window is buffered queue, not throughput.
#[test]
fn test_cwnd_never_exceeds_absolute_ceiling() {
let mut cc = CongestionController::new(1200);
// Constant RTT: no inflation signal, so only the hard cap can stop this.
for _ in 0..5000 {
cc.on_send(1200);
cc.on_ack(1200, Duration::from_millis(30));
}
assert!(
cc.cwnd() <= MAX_CWND_PACKETS * 1200,
"cwnd {} exceeded the {}-packet ceiling",
cc.cwnd(),
MAX_CWND_PACKETS
);
}
#[test]
fn test_isolated_slow_start_loss_does_not_exit_slow_start() {
// A single dropped packet (wireless noise, a brief handover blip) is
// normal on real links and must not permanently downgrade the
// session from exponential to linear growth.
let mut cc = CongestionController::new(1200);
cc.on_loss(1200);
assert_eq!(cc.phase, Phase::SlowStart, "one isolated loss must not exit slow start");
// It should still shrink the window somewhat (not ignored entirely),
// just far less punishing than the sustained-congestion case.
let after_one = cc.cwnd();
assert!(after_one < INITIAL_CWND_PACKETS * 1200);
}
#[test]
fn test_sustained_slow_start_loss_exits_slow_start() {
// Losses landing close together (within SLOW_START_LOSS_WINDOW) are
// a real congestion signal and must still trigger the harsher
// exit-slow-start + halve response.
let mut cc = CongestionController::new(1200);
for _ in 0..SLOW_START_LOSS_TOLERANCE {
cc.on_loss(1200);
}
assert_eq!(cc.phase, Phase::ProbeBandwidth, "sustained loss must exit slow start");
}
#[test]
fn test_slow_start_loss_window_resets_after_expiry() {
// Two losses far enough apart (window expired between them) must
// each be treated as isolated, not accumulated toward the sustained-
// loss threshold.
let mut cc = CongestionController::new(1200);
cc.on_loss(1200);
assert_eq!(cc.phase, Phase::SlowStart);
// Simulate the window having expired by resetting its start
// directly (std::thread::sleep in a unit test would be flaky/slow).
cc.slow_start_loss_window_start = Instant::now() - SLOW_START_LOSS_WINDOW - Duration::from_millis(1);
cc.on_loss(1200);
assert_eq!(cc.phase, Phase::SlowStart, "a loss after the window expired must restart the count, not accumulate");
assert_eq!(cc.slow_start_losses, 1);
}
#[test]
fn test_can_send_limits() {
let mut cc = CongestionController::new(1200);
@ -619,23 +313,6 @@ mod tests {
assert_eq!(rto, Duration::from_millis(150));
}
#[test]
fn test_on_ack_no_rtt_grows_window_without_touching_srtt() {
let mut cc = CongestionController::new(1200);
// Establish a known SRTT with a real sample.
cc.on_send(1200);
cc.on_ack(1200, Duration::from_millis(40));
let srtt_before = cc.smoothed_rtt();
let cwnd_before = cc.cwnd();
// A Karn's-algorithm ACK (all acked frames were retransmitted): window
// must advance, RTT estimate must be untouched.
cc.on_send(1200);
cc.on_ack_no_rtt(1200);
assert!(cc.cwnd() > cwnd_before, "cwnd should still grow on a no-RTT ack");
assert_eq!(cc.smoothed_rtt(), srtt_before, "SRTT must not move on a no-RTT ack");
}
#[test]
fn test_rto_clamp_min() {
let cc = CongestionController::new(1200);

View File

@ -8,5 +8,4 @@ pub use noise::{NoiseRole, NoiseSession};
pub use obfuscation::{
deobfuscate_header_inplace, deobfuscate_packet_inplace, obfuscate_packet_inplace,
derive_obfuscation_key, derive_psk, derive_all_secrets, DerivedSecrets,
derive_junk_marker, current_junk_window, JUNK_MARKER_WINDOW_SECS,
};

View File

@ -1,4 +1,4 @@
use snow::{Builder, HandshakeState};
use snow::{Builder, HandshakeState, TransportState};
use crate::protocol::ProtocolError;
@ -10,15 +10,9 @@ pub enum NoiseRole {
Responder,
}
/// A Noise handshake in progress. OSTP does not use snow's transport mode: once
/// the handshake finishes we extract the raw Split() keys (see [`raw_split`])
/// and drive our own out-of-order AEAD (see `crypto::aead`), because the wire
/// protocol needs explicit per-frame nonces for reordering that snow's internal
/// nonce counter can't express.
///
/// [`raw_split`]: NoiseSession::raw_split
pub struct NoiseSession {
handshake: Box<HandshakeState>,
pub enum NoiseSession {
Handshake(Box<HandshakeState>),
Transport(TransportState),
}
impl NoiseSession {
@ -42,92 +36,50 @@ impl NoiseSession {
.map_err(|_| ProtocolError::Crypto("noise-responder".to_string()))?,
};
Ok(Self { handshake: Box::new(handshake) })
Ok(Self::Handshake(Box::new(handshake)))
}
pub fn write_handshake(&mut self, payload: &[u8], out: &mut [u8]) -> Result<usize, ProtocolError> {
self.handshake
.write_message(payload, out)
.map_err(|_| ProtocolError::Crypto("noise-write".to_string()))
match self {
NoiseSession::Handshake(hs) => hs
.write_message(payload, out)
.map_err(|_| ProtocolError::Crypto("noise-write".to_string())),
NoiseSession::Transport(_) => Err(ProtocolError::State("noise already in transport".to_string())),
}
}
pub fn read_handshake(&mut self, input: &[u8], out: &mut [u8]) -> Result<usize, ProtocolError> {
self.handshake
.read_message(input, out)
.map_err(|e| ProtocolError::Crypto(format!("noise-read: {:?}", e)))
}
/// Derive the two directional transport keys via Noise's Split().
///
/// SECURITY: keys are taken from the final chaining key `ck` (which absorbs
/// the ephemeral `ee` DH result via MixKey), NOT from the handshake hash `h`
/// (which only absorbs public transcript data — ephemeral pubkeys and
/// ciphertexts — and never the DH secret). Deriving from `ck` is what gives
/// the session forward secrecy: an adversary who later learns the PSK still
/// cannot recompute these keys without the ephemeral private keys, which are
/// discarded after the handshake.
///
/// Must only be called once the handshake is finished (both messages of the
/// NNpsk0 exchange processed); at that point `ck` is final. Returns
/// `(send_key, recv_key)` for the given role, matching snow's TransportState
/// direction mapping: split output `.0` is initiator→responder, `.1` is
/// responder→initiator.
pub fn raw_split(&mut self, role: NoiseRole) -> Result<([u8; 32], [u8; 32]), ProtocolError> {
if !self.handshake.is_handshake_finished() {
return Err(ProtocolError::State("handshake not finished at key split".to_string()));
match self {
NoiseSession::Handshake(hs) => hs
.read_message(input, out)
.map_err(|e| ProtocolError::Crypto(format!("noise-read: {:?}", e))),
NoiseSession::Transport(_) => Err(ProtocolError::State("noise already in transport".to_string())),
}
}
pub fn handshake_hash(&self, out: &mut [u8]) -> Result<(), ProtocolError> {
match self {
NoiseSession::Handshake(hs) => {
let hash = hs.get_handshake_hash();
if out.len() != hash.len() {
return Err(ProtocolError::Crypto("handshake hash length mismatch".to_string()));
}
out.copy_from_slice(hash);
Ok(())
}
NoiseSession::Transport(_) => Err(ProtocolError::State("noise already in transport".to_string())),
}
}
pub fn into_transport(self) -> Result<Self, ProtocolError> {
match self {
NoiseSession::Handshake(hs) => {
let transport = hs
.into_transport_mode()
.map_err(|_| ProtocolError::Crypto("noise-transport".to_string()))?;
Ok(NoiseSession::Transport(transport))
}
NoiseSession::Transport(_) => Ok(self),
}
let (k0, k1) = self.handshake.dangerously_get_raw_split();
Ok(match role {
// Initiator sends on .0 (i→r), receives on .1 (r→i).
NoiseRole::Initiator => (k0, k1),
// Responder is the mirror image.
NoiseRole::Responder => (k1, k0),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Drive a full NNpsk0 handshake and confirm both sides derive matching
/// directional keys. This guards the .0/.1 → send/recv role mapping in
/// `raw_split`: if it were wrong, the two sides' send/recv keys wouldn't
/// cross-match and the transport channel would silently fail to decrypt.
#[test]
fn raw_split_keys_agree_across_roles() {
let psk = [7u8; 32];
let mut initiator = NoiseSession::new(NoiseRole::Initiator, &psk).unwrap();
let mut responder = NoiseSession::new(NoiseRole::Responder, &psk).unwrap();
// msg1: initiator -> responder
let mut buf1 = [0u8; 1024];
let n1 = initiator.write_handshake(&[], &mut buf1).unwrap();
let mut tmp = [0u8; 1024];
responder.read_handshake(&buf1[..n1], &mut tmp).unwrap();
// msg2: responder -> initiator
let mut buf2 = [0u8; 1024];
let n2 = responder.write_handshake(&[], &mut buf2).unwrap();
initiator.read_handshake(&buf2[..n2], &mut tmp).unwrap();
let (i_send, i_recv) = initiator.raw_split(NoiseRole::Initiator).unwrap();
let (r_send, r_recv) = responder.raw_split(NoiseRole::Responder).unwrap();
// What the initiator sends with, the responder must receive with.
assert_eq!(i_send, r_recv, "initiator send key must equal responder recv key");
assert_eq!(r_send, i_recv, "responder send key must equal initiator recv key");
// The two directions use distinct keys.
assert_ne!(i_send, i_recv, "the two directions must not share a key");
}
/// raw_split must refuse to hand out keys before the handshake is complete —
/// keys taken from a half-mixed chaining key would be wrong and insecure.
#[test]
fn raw_split_rejected_before_handshake_finishes() {
let psk = [9u8; 32];
let mut initiator = NoiseSession::new(NoiseRole::Initiator, &psk).unwrap();
// No messages exchanged yet: handshake not finished.
assert!(initiator.raw_split(NoiseRole::Initiator).is_err());
}
}

View File

@ -54,41 +54,14 @@ fn hkdf_expand(prk: &[u8; 32], info: &[u8], len: usize) -> Vec<u8> {
/// The derivation uses the access key as both IKM and salt material,
/// split into two halves. No fixed strings are used — the access key
/// alone determines all derived values.
#[derive(Clone)]
pub struct DerivedSecrets {
pub obfuscation_key: [u8; 8],
pub psk: [u8; 32],
pub handshake_pad_min: usize,
pub handshake_pad_max: usize,
}
// NOTE: the junk marker is NOT part of DerivedSecrets — it is time-rotating and
// derived separately per window via `derive_junk_marker` (see below), so it
// carries no static per-user signature.
/// OSTP wire protocol version. Mixed into key derivation (NOT sent on the
/// wire) so peers running incompatible versions derive entirely different
/// secrets and therefore cannot deobfuscate / decrypt each other's traffic.
///
/// This is a hard, deterministic version gate that needs NO plaintext version
/// byte on the wire — a constant marker would defeat the project's stealth
/// north-star ("no recognizable header"). A pre-0.4.0 client (which derived
/// without a version) produces a different obfuscation key, so a 0.4.0 server
/// cannot recover its handshake header and rejects it as an unauthorized probe.
///
/// Bump this on any wire-breaking protocol change. 0.4.0 = version 4;
/// version 5 (0.4.x hardening) moved transport keys from the handshake hash to
/// Noise's Split() output — a wire-breaking crypto change, so old peers must not
/// interop (they would derive different session keys and fail decryption).
pub const PROTOCOL_VERSION: u8 = 5;
pub fn derive_all_secrets(access_key: &[u8]) -> DerivedSecrets {
derive_all_secrets_versioned(access_key, PROTOCOL_VERSION)
}
/// Version-parameterised derivation. `derive_all_secrets` always pins the
/// current `PROTOCOL_VERSION`; this form exists so tests can prove that a
/// different version yields incompatible secrets (the version gate).
pub(crate) fn derive_all_secrets_versioned(access_key: &[u8], version: u8) -> DerivedSecrets {
// Split the key hash into two halves for salt/info separation.
// This avoids using any hardcoded strings while still providing
// domain separation between the derived values.
@ -97,16 +70,8 @@ pub(crate) fn derive_all_secrets_versioned(access_key: &[u8], version: u8) -> De
let salt = &key_hash[..16];
let info_base = &key_hash[16..];
// Mix the protocol version into the IKM so a different version produces a
// completely different PRK → different obf_key / psk / padding. This is the
// wire-version gate: it is invisible on the wire (only the derived output,
// which is already indistinguishable from random, ever leaves the host).
let mut ikm = Vec::with_capacity(access_key.len() + 1);
ikm.extend_from_slice(access_key);
ikm.push(version);
// Extract PRK from version-tagged access key using its hash as salt
let prk = hkdf_extract(salt, &ikm);
// Extract PRK from access key using its own hash as salt
let prk = hkdf_extract(salt, access_key);
// Derive obfuscation key (8 bytes) — info = key_hash[16..] || 0x01
let mut obf_info = info_base.to_vec();
@ -140,53 +105,6 @@ pub(crate) fn derive_all_secrets_versioned(access_key: &[u8], version: u8) -> De
}
}
/// Window length (seconds) for the rotating junk marker. The marker changes
/// every window, so junk carries no static per-user fingerprint on the wire;
/// the server checks the current and previous window to absorb clock skew.
pub const JUNK_MARKER_WINDOW_SECS: u64 = 60;
/// The current junk-marker time window (unix seconds / window length).
pub fn current_junk_window() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs() / JUNK_MARKER_WINDOW_SECS)
.unwrap_or(0)
}
/// Derive the 4-byte junk marker for a given time `window`.
///
/// Uses the same version-gated HKDF scheme as [`derive_all_secrets`], with the
/// window folded into the `info` (label byte `0x04`). Folding in the window
/// makes the marker rotate: to an on-path observer the junk prefix changes every
/// window (no fixed signature), and a captured marker is only valid for ~1
/// window. Only a holder of the access key can compute it, so an outsider cannot
/// forge a silently-dropped junk packet.
pub fn derive_junk_marker(access_key: &[u8], window: u64) -> [u8; 4] {
derive_junk_marker_versioned(access_key, window, PROTOCOL_VERSION)
}
pub(crate) fn derive_junk_marker_versioned(access_key: &[u8], window: u64, version: u8) -> [u8; 4] {
use sha2::Digest;
let key_hash = sha2::Sha256::digest(access_key);
let salt = &key_hash[..16];
let info_base = &key_hash[16..];
let mut ikm = Vec::with_capacity(access_key.len() + 1);
ikm.extend_from_slice(access_key);
ikm.push(version);
let prk = hkdf_extract(salt, &ikm);
// info = key_hash[16..] || 0x04 || window(LE) — same label byte as before,
// now parameterised by the time window.
let mut info = info_base.to_vec();
info.push(0x04);
info.extend_from_slice(&window.to_le_bytes());
let bytes = hkdf_expand(&prk, &info, 4);
let mut marker = [0u8; 4];
marker.copy_from_slice(&bytes);
marker
}
// ── Legacy API (delegates to derive_all_secrets) ─────────────────────────────
pub fn derive_obfuscation_key(access_key: &[u8]) -> [u8; 8] {

View File

@ -127,37 +127,6 @@ mod tests {
assert_eq!(correct_sid, session_id, "correct key must recover session_id");
}
/// §C version gate: a peer on a different PROTOCOL_VERSION derives
/// different secrets, so a handshake obfuscated with the OLD version's key
/// does NOT deobfuscate to a valid session_id under the current version.
/// This is exactly what makes an old (pre-0.4.0) client fail to connect to
/// a new server — with no plaintext version marker on the wire.
#[test]
fn test_protocol_version_gates_old_clients() {
let key = b"shared_access_key_across_versions";
let new = derive_all_secrets(key); // == derive_all_secrets_versioned(key, PROTOCOL_VERSION)
let old = derive_all_secrets_versioned(key, PROTOCOL_VERSION.wrapping_sub(1));
// Different protocol version → different derived secrets.
assert_ne!(new.obfuscation_key, old.obfuscation_key, "version must change obf_key");
assert_ne!(new.psk, old.psk, "version must change psk");
// Concretely: a handshake the old client obfuscated with its key does
// not recover a valid session_id when the new server deobfuscates it.
let session_id: u32 = 0x11223344;
let noise = [0x33u8; 48];
let mut pkt = Vec::new();
pkt.extend_from_slice(&session_id.to_be_bytes());
pkt.extend_from_slice(&(noise.len() as u16).to_be_bytes());
pkt.extend_from_slice(&noise);
pkt.extend_from_slice(&[0u8; 32]);
obfuscate_packet_inplace(&mut pkt, &old.obfuscation_key, true); // old client
deobfuscate_packet_inplace(&mut pkt, &new.obfuscation_key, true); // new server
let recovered = u32::from_be_bytes([pkt[0], pkt[1], pkt[2], pkt[3]]);
assert_ne!(recovered, session_id, "old-version client must NOT be accepted by new server");
}
/// Verifies data packet obfuscation round-trip (non-handshake path).
#[test]
fn test_data_packet_obfuscation_roundtrip() {
@ -191,29 +160,4 @@ mod tests {
assert_eq!(recovered_nonce, nonce);
assert_eq!(&packet[12..], &ciphertext);
}
/// The junk marker must: be stable within a window (client and server agree),
/// rotate across windows (no static on-wire fingerprint), and differ per key
/// (one user's marker never silently-drops on another user's flow).
#[test]
fn test_junk_marker_rotation() {
let key_a = b"access-key-alpha";
let key_b = b"access-key-bravo";
// Stable within a window.
assert_eq!(derive_junk_marker(key_a, 1000), derive_junk_marker(key_a, 1000));
// Rotates across adjacent windows.
assert_ne!(derive_junk_marker(key_a, 1000), derive_junk_marker(key_a, 1001));
assert_ne!(derive_junk_marker(key_a, 1000), derive_junk_marker(key_a, 999));
// Distinct per key within the same window.
assert_ne!(derive_junk_marker(key_a, 1000), derive_junk_marker(key_b, 1000));
// A different protocol version yields a different marker (version gate).
assert_ne!(
derive_junk_marker_versioned(key_a, 1000, PROTOCOL_VERSION),
derive_junk_marker_versioned(key_a, 1000, PROTOCOL_VERSION.wrapping_add(1)),
);
}
}

View File

@ -0,0 +1,279 @@
use bytes::{Buf, BufMut, Bytes, BytesMut};
use chacha20poly1305::{aead::{Aead, KeyInit}, ChaCha20Poly1305, Nonce};
use hkdf::Hkdf;
use sha2::Sha256;
use x25519_dalek::{PublicKey, StaticSecret};
use rand::{rngs::OsRng, RngCore};
use std::time::{SystemTime, UNIX_EPOCH};
const REALITY_INFO: &[u8] = b"ostp-reality-v1";
const RECORD_HEADER_LEN: usize = 5;
const HANDSHAKE_HEADER_LEN: usize = 4;
/// Number of TLS records sent by the server during the fake handshake phase.
/// Client must read and discard this many records before starting RealityStream.
/// Layout: 1× ServerHello (0x16) + 1× CCS (0x14) + 3× fake encrypted records (0x17)
pub const REALITY_SERVER_HANDSHAKE_RECORDS: usize = 5;
/// Generates an X25519 keypair
pub fn generate_x25519_keypair() -> (StaticSecret, PublicKey) {
let secret = StaticSecret::random_from_rng(OsRng);
let public = PublicKey::from(&secret);
(secret, public)
}
/// Derives the Auth Key and Data Key from the X25519 shared secret
pub fn derive_keys(shared_secret: &[u8; 32]) -> (ChaCha20Poly1305, ChaCha20Poly1305) {
let hk = Hkdf::<Sha256>::new(None, shared_secret);
let mut okm = [0u8; 64];
hk.expand(REALITY_INFO, &mut okm).expect("HKDF expand failed");
let auth_key = ChaCha20Poly1305::new_from_slice(&okm[0..32]).unwrap();
let data_key = ChaCha20Poly1305::new_from_slice(&okm[32..64]).unwrap();
(auth_key, data_key)
}
/// Creates an authenticated Session ID payload (32 bytes)
/// sid: 8 bytes, timestamp: 8 bytes. Encrypted with ChaCha20Poly1305 (16 byte tag). Total = 32 bytes.
pub fn generate_session_id(auth_aead: &ChaCha20Poly1305, sid: &[u8; 8]) -> [u8; 32] {
let ts = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
let mut plaintext = [0u8; 16];
plaintext[0..8].copy_from_slice(sid);
plaintext[8..16].copy_from_slice(&ts.to_be_bytes());
let nonce = Nonce::from_slice(&[0u8; 12]); // Fixed nonce since auth key is ephemeral per connection
let ciphertext = auth_aead.encrypt(nonce, plaintext.as_ref()).expect("encryption failed");
let mut session_id = [0u8; 32];
session_id.copy_from_slice(&ciphertext);
session_id
}
/// Verifies and decrypts the Session ID payload. Returns (sid, timestamp)
pub fn verify_session_id(auth_aead: &ChaCha20Poly1305, session_id: &[u8; 32]) -> Option<([u8; 8], u64)> {
let nonce = Nonce::from_slice(&[0u8; 12]);
let plaintext = auth_aead.decrypt(nonce, session_id.as_ref()).ok()?;
if plaintext.len() != 16 {
return None;
}
let mut sid = [0u8; 8];
sid.copy_from_slice(&plaintext[0..8]);
let mut ts_bytes = [0u8; 8];
ts_bytes.copy_from_slice(&plaintext[8..16]);
let ts = u64::from_be_bytes(ts_bytes);
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
// Allow up to 60 seconds of clock drift
if ts > now + 60 || ts < now.saturating_sub(60) {
return None; // Replay protection / stale connection
}
Some((sid, ts))
}
/// Builds a fake TLS 1.3 ClientHello matching Chrome's fingerprint
pub fn build_client_hello(sni: &str, session_id: &[u8; 32], c_pub: &PublicKey) -> Bytes {
let mut ext = BytesMut::new();
// SNI Extension
let sni_bytes = sni.as_bytes();
ext.put_u16(0x0000); // Type: server_name
ext.put_u16((sni_bytes.len() + 5) as u16);
ext.put_u16((sni_bytes.len() + 3) as u16); // Server Name list length
ext.put_u8(0x00); // Name Type: host_name
ext.put_u16(sni_bytes.len() as u16);
ext.put_slice(sni_bytes);
// Supported Groups
ext.put_u16(0x000a); // Type
ext.put_u16(8); // Length
ext.put_u16(6); // List length
ext.put_u16(0x001d); // x25519
ext.put_u16(0x0017); // secp256r1
ext.put_u16(0x0018); // secp384r1
// Key Share
let pub_bytes = c_pub.as_bytes();
ext.put_u16(0x0033); // Type
ext.put_u16((pub_bytes.len() + 6) as u16); // Length
ext.put_u16((pub_bytes.len() + 4) as u16); // ClientShares length
ext.put_u16(0x001d); // Group: x25519
ext.put_u16(pub_bytes.len() as u16);
ext.put_slice(pub_bytes);
// Supported Versions
ext.put_u16(0x002b); // Type
ext.put_u16(5); // Length
ext.put_u8(4); // List length
ext.put_u16(0x0304); // TLS 1.3
ext.put_u16(0x0303); // TLS 1.2
// ALPN
let alpn = b"\x02h2\x08http/1.1";
ext.put_u16(0x0010); // Type
ext.put_u16((alpn.len() + 2) as u16);
ext.put_u16(alpn.len() as u16);
ext.put_slice(alpn);
// Signature Algorithms
ext.put_u16(0x000d); // Type
ext.put_u16(10); // Length
ext.put_u16(8); // List length
ext.put_u16(0x0403); // ecdsa_secp256r1_sha256
ext.put_u16(0x0804); // rsa_pss_rsae_sha256
ext.put_u16(0x0401); // rsa_pkcs1_sha256
ext.put_u16(0x0503); // ecdsa_secp384r1_sha384
let mut handshake = BytesMut::new();
handshake.put_u16(0x0303); // Client Version
let mut random = [0u8; 32];
OsRng.fill_bytes(&mut random);
handshake.put_slice(&random); // Random
handshake.put_u8(32); // Session ID length
handshake.put_slice(session_id); // Session ID
// Cipher Suites
handshake.put_u16(6); // Length
handshake.put_u16(0x1301); // TLS_AES_128_GCM_SHA256
handshake.put_u16(0x1303); // TLS_CHACHA20_POLY1305_SHA256
handshake.put_u16(0x1302); // TLS_AES_256_GCM_SHA384
// Compression
handshake.put_u8(1); // Length
handshake.put_u8(0); // null
// Extensions
handshake.put_u16(ext.len() as u16);
handshake.put_slice(&ext);
let handshake_len = handshake.len();
let mut record = BytesMut::new();
record.put_u8(0x16); // Handshake
record.put_u16(0x0301); // TLS 1.0 (Compatibility)
record.put_u16((handshake_len + HANDSHAKE_HEADER_LEN) as u16); // Length
record.put_u8(0x01); // ClientHello
record.put_u8((handshake_len >> 16) as u8);
record.put_u8((handshake_len >> 8) as u8);
record.put_u8(handshake_len as u8);
record.put_slice(&handshake);
// Append ChangeCipherSpec for TLS 1.3 middlebox compatibility (RFC 8446 §D.4)
// This makes the flow look like: ClientHello → ServerHello → CCS → AppData
// instead of the DPI-suspicious: ClientHello → AppData directly.
let mut out = BytesMut::new();
out.put_slice(&record);
out.put_slice(&[0x14, 0x03, 0x03, 0x00, 0x01, 0x01]);
out.freeze()
}
pub struct ParsedClientHello {
pub sni: String,
pub session_id: [u8; 32],
pub c_pub: PublicKey,
}
/// Parses a TLS ClientHello. Returns None if invalid or missing required fields.
pub fn parse_client_hello(mut buf: &[u8]) -> Option<ParsedClientHello> {
if buf.len() < RECORD_HEADER_LEN + HANDSHAKE_HEADER_LEN {
return None;
}
// Record Header
let typ = buf.get_u8();
if typ != 0x16 { return None; } // Not a handshake
let _version = buf.get_u16();
let record_len = buf.get_u16() as usize;
if buf.len() < record_len {
return None; // Incomplete record
}
let mut payload = &buf[..record_len];
// Handshake Header
let hs_type = payload.get_u8();
if hs_type != 0x01 { return None; } // Not ClientHello
let hs_len_hi = payload.get_u8() as usize;
let hs_len_mid = payload.get_u8() as usize;
let hs_len_lo = payload.get_u8() as usize;
let hs_len = (hs_len_hi << 16) | (hs_len_mid << 8) | hs_len_lo;
if payload.len() < hs_len { return None; }
let mut ch = &payload[..hs_len];
let _client_version = ch.get_u16();
if ch.len() < 32 { return None; }
ch.advance(32); // Skip Random
let sid_len = ch.get_u8() as usize;
if sid_len != 32 || ch.len() < 32 { return None; }
let mut session_id = [0u8; 32];
session_id.copy_from_slice(&ch[..32]);
ch.advance(32);
let ciphers_len = ch.get_u16() as usize;
if ch.len() < ciphers_len { return None; }
ch.advance(ciphers_len);
let comp_len = ch.get_u8() as usize;
if ch.len() < comp_len { return None; }
ch.advance(comp_len);
let ext_len = ch.get_u16() as usize;
if ch.len() < ext_len { return None; }
let mut exts = &ch[..ext_len];
let mut parsed_sni = None;
let mut parsed_c_pub = None;
while exts.len() >= 4 {
let ext_type = exts.get_u16();
let ext_len = exts.get_u16() as usize;
if exts.len() < ext_len { break; }
let mut ext_data = &exts[..ext_len];
if ext_type == 0x0000 { // SNI
let _list_len = ext_data.get_u16() as usize;
if ext_data.len() >= 3 {
let name_type = ext_data.get_u8();
if name_type == 0x00 { // Hostname
let name_len = ext_data.get_u16() as usize;
if ext_data.len() >= name_len {
if let Ok(name) = std::str::from_utf8(&ext_data[..name_len]) {
parsed_sni = Some(name.to_string());
}
}
}
}
} else if ext_type == 0x0033 { // Key Share
let _client_shares_len = ext_data.get_u16() as usize;
while ext_data.len() >= 4 {
let group = ext_data.get_u16();
let key_ex_len = ext_data.get_u16() as usize;
if ext_data.len() < key_ex_len { break; }
if group == 0x001d && key_ex_len == 32 { // X25519
let mut pub_bytes = [0u8; 32];
pub_bytes.copy_from_slice(&ext_data[..32]);
parsed_c_pub = Some(PublicKey::from(pub_bytes));
}
ext_data.advance(key_ex_len);
}
}
exts.advance(ext_len);
}
match (parsed_sni, parsed_c_pub) {
(Some(sni), Some(c_pub)) => Some(ParsedClientHello { sni, session_id, c_pub }),
_ => None,
}
}

Some files were not shown because too many files have changed in this diff Show More