Compare commits

...

92 Commits

Author SHA1 Message Date
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
ospab 31d0020483 CI/CD: release version v0.2.98 2026-06-16 14:21:02 +03:00
ospab 04761fb6a3 Fix memory leaks, hang issues, gui helper token vulns, and log spam 2026-06-16 14:11:37 +03:00
ospab feaac0c713 CI/CD: release version v0.2.97 2026-06-14 01:49:53 +03:00
ospab b841053628 fix(jni): add exclusions_rx param to run_native_tunnel_from_fd stub to fix non-Android builds 2026-06-14 01:49:06 +03:00
ospab cf92089005 CI/CD: release version v0.2.96 2026-06-14 01:46:14 +03:00
ospab e0a13702ea fix(tun): resolve OS error 10049 for TCP bypass on Windows and fix 16GB memory leak by bounding smoltcp channels 2026-06-14 01:44:56 +03:00
ospab c36e7373e8 fix(tun): hide verbose split tunneling logs behind debug flag 2026-06-14 01:34:34 +03:00
ospab 3671a83971 chore(tun): add verbose logging for TCP and UDP split tunneling bypass 2026-06-14 01:26:34 +03:00
ospab c7bca41616 chore: fix JNI UoT handler args, center Flutter home screen metrics, update READMEs 2026-06-14 01:04:50 +03:00
ospab 486d745d47 feat(tun): implement process bypass for TCP/UDP and IP bypass for UDP using existing Extended tables 2026-06-14 00:02:08 +03:00
ospab 74b6648db1 fix(tun): fix bypass loop by capturing physical iface before tun route overrides 2026-06-13 23:09:33 +03:00
ospab 4543fa82f8 fix(split-tunnel): hot-reload exclusions into running proxy tunnel without reconnect 2026-06-13 22:30:01 +03:00
ospab 83ba39e59a feat(gui): split tunneling — tag-chip UI, process picker with live process list 2026-06-13 02:55:28 +03:00
ospab 533466b63a CI/CD: release version v0.2.95 2026-06-13 02:45:40 +03:00
ospab 6dee7613a5 CI: Add step to create dummy dist directory for rust-embed during check-and-test 2026-06-13 02:44:01 +03:00
ospab 4c0263f7f7 CI/CD: release version v0.2.94 2026-06-13 02:34:06 +03:00
ospab 4d228cf1e1 CI/CD: release version v0.2.93 2026-06-13 02:32:23 +03:00
ospab 55215567dd Fix all compilation errors and suppress all warnings across workspace 2026-06-13 02:30:57 +03:00
ospab ab8d2c2185 CI/CD: release version v0.2.92 2026-06-13 02:28:22 +03:00
ospab 875177f779 CI/CD: release version v0.2.91 2026-06-13 02:23:24 +03:00
ospab 2a24ac34d0 Remove Reality/XTLS from all UI components and TSX pages (Dashboard, Settings, Tools) 2026-06-13 02:19:53 +03:00
ospab 8fc61f986f CI/CD: release version v0.2.90 2026-06-13 02:12:51 +03:00
ospab ee6768dee1 CI: restore run-name format, add check-and-test gate before all builds 2026-06-13 02:04:03 +03:00
ospab 091bb2c707 CI/CD: release version v0.2.89 2026-06-13 02:00:26 +03:00
ospab 2d05fb282d CI/CD: release version v0.2.88 2026-06-13 01:58:32 +03:00
ospab 3c54aba63f Remove Reality/XTLS UI from ostp-gui, ostp-flutter, ostp-control 2026-06-13 01:57:20 +03:00
ospab a9e4511190 Fix CLI setup permissions, enforce global debug tracing, and fix GUI silent startup crash 2026-06-13 01:25:54 +03:00
ospab fbf13b86f3 Fix syntax and type errors after DNS removal 2026-06-10 22:59:10 +03:00
ospab 9f35caf4ca Remove built-in DNS server and owndns features 2026-06-10 22:52:35 +03:00
ospab 7bb7d211fa Remove stealth_port entirely and integrate fallback into UoT HTTP handler 2026-06-10 02:26:13 +03:00
ospab 430ab8a743 CI/CD: release version v0.2.87 2026-06-09 01:02:11 +03:00
ospab 04c31c7f53 feat: implement wintun dynamic downloading, add missing driver frontend modal, fix background logging and UAC helper issues 2026-06-09 01:01:36 +03:00
ospab 60282d730f CI/CD: release version v0.2.86 2026-06-07 21:05:23 +03:00
ospab da238fad5c fix(client): fix compilation error on linux due to server_ip_str 2026-06-07 21:03:52 +03:00
ospab 85f0cb19cf CI/CD: release version v0.2.85 2026-06-07 20:44:28 +03:00
ospab c95720f3da CI/CD: release version v0.2.84 2026-06-07 20:10:39 +03:00
ospab 730eab8553 feat: implement built-in DNS server, adblock and dns leak prevention 2026-06-07 19:55:42 +03:00
ospab 4d0249e8ef CI/CD: release version v0.2.83 2026-06-06 20:57:46 +03:00
212 changed files with 13417 additions and 9370 deletions

View File

@ -1,4 +1,6 @@
name: Universal CI/CD Release Matrix
name: CI/CD
run-name: "CI/CD: release version ${{ github.ref_name }}"
on:
push:
@ -16,8 +18,45 @@ env:
RUST_BACKTRACE: short
jobs:
check-and-test:
name: Check & Test
runs-on: ubuntu-latest
steps:
- 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:
toolchain: stable
- name: Restore Cargo cache
uses: actions/cache@v4
with:
path: |
~/.cargo/registry/index/
~/.cargo/registry/cache/
~/.cargo/git/db/
target/
key: cargo-check-${{ hashFiles('**/Cargo.lock') }}
restore-keys: cargo-check-
- name: Install musl-tools
run: sudo apt-get update && sudo apt-get install -y musl-tools
- name: cargo check
run: cargo check --workspace
- name: cargo test
run: cargo test --workspace --lib
publish-release-matrix:
name: Release for ${{ matrix.target }}
needs: check-and-test
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
@ -103,16 +142,9 @@ 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
working-directory: ostp-control
run: |
npm install
npm run build
- name: Bump version based on tag
if: startsWith(github.ref, 'refs/tags/v')
run: python scripts/bump_version.py ${{ github.ref_name }}
# ── Rust toolchain ─────────────────────────────────────────────────────
- name: Setup Rust toolchain
@ -204,6 +236,7 @@ jobs:
build-windows-gui:
name: Build Windows GUI (Tauri) - ${{ matrix.arch }}
needs: check-and-test
runs-on: windows-latest
strategy:
matrix:
@ -215,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:
@ -277,6 +314,7 @@ jobs:
build-linux-gui:
name: Build Linux GUI (Tauri) - ${{ matrix.arch }}
needs: check-and-test
runs-on: ubuntu-latest
strategy:
matrix:
@ -286,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:
@ -336,6 +378,7 @@ jobs:
build-macos-gui:
name: Build macOS GUI (Tauri) - ${{ matrix.arch }}
needs: check-and-test
runs-on: macos-latest
strategy:
matrix:
@ -347,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:
@ -392,6 +439,7 @@ jobs:
build-android:
name: Build Android Client (Flutter) - ${{ matrix.arch }}
needs: check-and-test
runs-on: ubuntu-latest
strategy:
matrix:
@ -406,6 +454,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 Java
uses: actions/setup-java@v3
with:

BIN
.gitignore vendored

Binary file not shown.

View File

@ -1 +0,0 @@
127.0.0.1

View File

@ -21,8 +21,8 @@ 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).
* **Node.js (18+) & npm**: Required to compile Tauri GUI resources.
* **Git**: For version control.
### Building the Project
@ -33,15 +33,7 @@ To build and test OSTP locally, you will need:
cd ostp
```
2. **Build the control panel frontend**:
```bash
cd ostp-control
npm install
npm run build
cd ..
```
3. **Build the entire Cargo workspace**:
2. **Build the entire Cargo workspace**:
```bash
cargo build
```
@ -59,8 +51,7 @@ 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, `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 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-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.

View File

@ -21,8 +21,8 @@
Для локальной сборки и тестирования OSTP вам понадобятся:
* **Rust Toolchain (1.75+)**: Рекомендуется установить через [rustup](https://rustup.rs/).
* **Node.js (18+) и npm**: Необходимы для сборки веб-панели управления (`ostp-control`) и сборки интерфейса Tauri.
* **Rust Toolchain**: Установите через [rustup](https://rustup.rs/) (stable канал).
* **Node.js (18+) и npm**: Необходимы для сборки интерфейса Tauri.
* **Git**: Для контроля версий.
### Сборка проекта
@ -33,15 +33,7 @@
cd ostp
```
2. **Соберите веб-интерфейс панели управления**:
```bash
cd ostp-control
npm install
npm run build
cd ..
```
3. **Соберите весь Cargo-workspace**:
2. **Соберите весь Cargo-workspace**:
```bash
cargo build
```
@ -59,8 +51,7 @@
* [`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 прокси-серверы, интеграция с драйвером `wintun` / `tun2socks` и реализация раздельного туннелирования для прямого обхода трафика.
* [`ostp-server/`](file:///d:/ospab-projects/ostp/ostp-server): Серверная часть: диспетчеризация сессий, маскировка под классические веб-серверы при активном сканировании, база данных ключей доступа и REST API панели управления.
* [`ostp-control/`](file:///d:/ospab-projects/ostp/ostp-control): Панель администратора (пользователи, статистика трафика в реальном времени, лимиты скорости и объема данных).
* [`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.

213
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"
@ -432,6 +454,15 @@ dependencies = [
"libc",
]
[[package]]
name = "crossbeam-channel"
version = "0.5.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "82b8f8f868b36967f9606790d1903570de9ceaf870a7bf9fbbd3016d636a2cb2"
dependencies = [
"crossbeam-utils",
]
[[package]]
name = "crossbeam-utils"
version = "0.8.21"
@ -467,6 +498,7 @@ dependencies = [
"cfg-if",
"cpufeatures",
"curve25519-dalek-derive",
"digest",
"fiat-crypto",
"rustc_version",
"subtle",
@ -525,6 +557,25 @@ 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"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
dependencies = [
"powerfmt",
]
[[package]]
name = "digest"
version = "0.10.7"
@ -547,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"
@ -1187,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"
@ -1331,6 +1412,12 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "num-conv"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
[[package]]
name = "num-traits"
version = "0.2.19"
@ -1360,17 +1447,20 @@ checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
[[package]]
name = "ostp"
version = "0.2.82"
version = "0.3.12"
dependencies = [
"anyhow",
"base64",
"clap",
"clipboard-win",
"colored",
"json_comments",
"ostp-client",
"ostp-core",
"ostp-server",
"pico-args",
"rand 0.8.5",
"reqwest",
"serde",
"serde_json",
"tokio",
@ -1381,7 +1471,7 @@ dependencies = [
[[package]]
name = "ostp-client"
version = "0.2.82"
version = "0.3.12"
dependencies = [
"anyhow",
"base64",
@ -1392,10 +1482,12 @@ dependencies = [
"futures-util",
"hex",
"hmac",
"ipnet",
"json_comments",
"libc",
"netstack-smoltcp",
"ostp-core",
"ostp-tun",
"portable-atomic",
"rand 0.8.5",
"serde",
@ -1404,6 +1496,8 @@ dependencies = [
"socket2",
"tokio",
"tracing",
"tracing-appender",
"tracing-subscriber",
"tun",
"webpki-roots 0.26.11",
"winapi",
@ -1412,17 +1506,20 @@ dependencies = [
[[package]]
name = "ostp-core"
version = "0.2.82"
version = "0.3.12"
dependencies = [
"anyhow",
"byteorder",
"bytes",
"chacha20poly1305",
"hkdf",
"hmac",
"rand 0.8.5",
"serde",
"sha2",
"snow",
"thiserror 1.0.69",
"tokio",
"tracing",
"x25519-dalek",
]
@ -1446,7 +1543,7 @@ dependencies = [
[[package]]
name = "ostp-server"
version = "0.2.82"
version = "0.3.12"
dependencies = [
"anyhow",
"axum",
@ -1454,6 +1551,7 @@ dependencies = [
"bytes",
"chacha20poly1305",
"chrono",
"ed25519-dalek",
"futures-util",
"hex",
"hmac",
@ -1476,9 +1574,21 @@ dependencies = [
"x25519-dalek",
]
[[package]]
name = "ostp-tun"
version = "0.3.12"
dependencies = [
"anyhow",
"libc",
"tokio",
"tracing",
"tun",
"winapi",
]
[[package]]
name = "ostp-tun-helper"
version = "0.2.82"
version = "0.3.12"
dependencies = [
"anyhow",
"chrono",
@ -1502,6 +1612,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"
@ -1519,6 +1635,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"
@ -1557,6 +1683,12 @@ dependencies = [
"zerovec",
]
[[package]]
name = "powerfmt"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
[[package]]
name = "ppv-lite86"
version = "0.2.21"
@ -1767,7 +1899,9 @@ checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
dependencies = [
"base64",
"bytes",
"futures-channel",
"futures-core",
"futures-util",
"http",
"http-body",
"http-body-util",
@ -2030,6 +2164,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"
@ -2101,6 +2244,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"
@ -2119,6 +2272,12 @@ version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "symlink"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7973cce6668464ea31f176d85b13c7ab3bba2cb3b77a2ed26abd7801688010a"
[[package]]
name = "syn"
version = "2.0.117"
@ -2199,6 +2358,37 @@ dependencies = [
"cfg-if",
]
[[package]]
name = "time"
version = "0.3.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c"
dependencies = [
"deranged",
"itoa",
"num-conv",
"powerfmt",
"serde_core",
"time-core",
"time-macros",
]
[[package]]
name = "time-core"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca"
[[package]]
name = "time-macros"
version = "0.2.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215"
dependencies = [
"num-conv",
"time-core",
]
[[package]]
name = "tinystr"
version = "0.8.3"
@ -2341,6 +2531,19 @@ dependencies = [
"tracing-core",
]
[[package]]
name = "tracing-appender"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "050686193eb999b4bb3bc2acfa891a13da00f79734704c4b8b4ef1a10b368a3c"
dependencies = [
"crossbeam-channel",
"symlink",
"thiserror 2.0.18",
"time",
"tracing-subscriber",
]
[[package]]
name = "tracing-attributes"
version = "0.1.31"

View File

@ -6,13 +6,13 @@ members = [
"ostp-jni", "ostp",
"ostp-tun-helper"
]
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 = "BSL 1.1"
version = "0.2.82"
version = "0.3.12"
[workspace.dependencies]
anyhow = "1.0"
@ -26,6 +26,8 @@ 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" }

701
LICENSE
View File

@ -1,74 +1,661 @@
Business Source License 1.1
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Parameters
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Licensor: Ospab Foundation (represented by Syralev Georgiy)
Licensed Work: The Ospab Stealth Transport Protocol (OSTP) and all
associated workspace crates, utilities, and documents.
Additional Use Grant: The Licensor hereby grants you the right to copy,
modify, create derivative works, redistribute, and
make non-production and non-commercial use of the
Licensed Work. You are also permitted to use the
Licensed Work in production for personal, private
utility and non-profit organizations.
Change Date: May 14, 2030
Change License: MIT License (as defined below)
Preamble
-----------------------------------------------------------------------------------
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
Terms
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
1. The Licensor hereby grants you the right to copy, modify, create derivative works,
redistribute, and make use of the Licensed Work only as permitted by the
Additional Use Grant.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
2. The Licensor hereby grants you the right to copy, modify, create derivative works,
redistribute, and make use of the Licensed Work under the terms of the Change
License on and after the Change Date.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
3. To the extent that any term of this License (including the Additional Use Grant
and the Change License) is in conflict with the Terms of this License, these
Terms shall take precedence.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
4. Every copy of the Licensed Work and any derivative work must include this
License and all other copyright, trademark, and proprietary notices included
with the Licensed Work.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
5. Any use of the Licensed Work that is not permitted by this License is a breach
of this License and may terminate your rights under this License.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
6. DISCLAIMER OF WARRANTY. TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED
WORK IS PROVIDED ON AN "AS IS" BASIS. THE LICENSOR MAKES NO REPRESENTATIONS OR
WARRANTIES OF ANY KIND CONCERNING THE LICENSED WORK, EXPRESS OR IMPLIED, STATUTORY
OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE,
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NONINFRINGEMENT.
The precise terms and conditions for copying, distribution and
modification follow.
7. LIMITATION OF LIABILITY. TO THE EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT
WILL THE LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL,
CONSEQUENTIAL, PUNITIVE, OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE
USE OF THE LICENSED WORK, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
TERMS AND CONDITIONS
-----------------------------------------------------------------------------------
0. Definitions.
Change License Text (MIT License)
"This License" refers to version 3 of the GNU Affero General Public License.
Copyright (c) 2026 Syralev Georgiy (Ospab Foundation)
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
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 Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
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.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

243
README.md
View File

@ -1,201 +1,139 @@
# 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=flat-square&color=blue)
![License: BSL 1.1](https://img.shields.io/badge/License-BSL%201.1-orange.svg?style=flat-square)
![Platform: Windows | Linux | macOS | Android](https://img.shields.io/badge/Platform-Windows%20%7C%20Linux%20%7C%20macOS%20%7C%20Android-green.svg?style=flat-square)
![Crypto](https://img.shields.io/badge/Crypto-Noise__NNpsk0-blueviolet?style=flat-square)
![Transport](https://img.shields.io/badge/Transport-UDP%20ARQ-informational?style=flat-square)
![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)
![Platform: Windows | Linux | macOS | Android](https://img.shields.io/badge/Platform-Windows%20%7C%20Linux%20%7C%20macOS%20%7C%20Android-green.svg?style=for-the-badge)
![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)
**OSTP** is a high-performance, censorship-resistant transport protocol designed to tunnel TCP traffic over UDP with full traffic obfuscation. Every byte on the wire — including packet headers — is cryptographically indistinguishable from random noise. Resistant to Deep Packet Inspection (DPI), active probing, and statistical traffic analysis.
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.
> [!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 `tun2socks` integration. All traffic transparently routed through the tunnel. |
| **xHTTP Stealth (UoT)** | UDP-over-TCP tunnel disguised as standard HTTP/1.1 or TLS traffic to bypass Level 1 Deep Packet Inspection (DPI) whitelists. |
| **XTLS-Reality** | Custom, dependency-free implementation of the Reality protocol using ChaCha20Poly1305 and X25519 for perfect TLS 1.3 impersonation. |
| **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. |
---
## Architecture
```
┌─────────────────────────────────────────────────────────────┐
│ Client │
│ ┌──────────┐ ┌──────────┐ ┌────────────────────────┐ │
│ │ Browser │──▸│ SOCKS5/ │──▸│ Bridge (Mux) │ │
│ │ / Apps │ │ HTTP │ │ ┌─────────────────┐ │ │
│ │ │ │ Proxy │ │ │ ProtocolMachine │ │ │
│ └──────────┘ └──────────┘ │ │ (Noise + AEAD) │ │ │
│ │ └────────┬────────┘ │ │
│ ┌──────────┐ │ │ │ │
│ │ TUN Mode │──────────────────┤ UDP Socket │ │
│ │tun2socks │ │ (32MB buffers, │ │
│ └──────────┘ │ obfuscated wire) │ │
│ └───────────┬────────────┘ │
└────────────────────────────────────────────┼────────────────┘
│ UDP
┌────────────────────────────────────────────┼────────────────┐
│ Server │ │
│ ┌─────────────────────────────────────────┴───────────┐ │
│ │ Dispatcher │ │
│ │ (Session lookup, roaming, replay guard, per-user │ │
│ │ traffic accounting, limit enforcement) │ │
│ └──┬──────────────────────┬───────────────────────────┘ │
│ │ │ │
│ ┌──▾──────────────────┐ ┌─▾──────────────────────────┐ │
│ │ Relay Loop │ │ Management API (REST) │ │
│ │ (per-stream TCP) │ │ /api/users, /api/stats │ │
│ │ ──▸ Internet │ │ Bearer token auth │ │
│ └─────────────────────┘ └────────────────────────────┘ │
│ │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ Fallback TCP Proxy ──▸ nginx/caddy (anti-DPI) │ │
│ └──────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
```mermaid
flowchart LR
Apps[Local Apps] -->|SOCKS5 / TUN| CoreC
subgraph Client [Client Node]
CoreC[OSTP Client] -.->|Encrypt & Mask| NetC[Transport Layer]
end
NetC <==>|Encrypted UDP / UoT| NetS
subgraph Server [Server Node]
NetS[Transport Layer] -.->|Decrypt & Auth| CoreS[OSTP Server]
NetS -->|Unauthenticated| Fallback[Fallback Server]
end
CoreS -->|Relay| WWW((Internet))
Fallback -->|Forward| Web((Web / NGINX))
```
---
## Quick Start
### 1. Generate config
### 1. Installation
**Linux:**
```bash
# On your VPS (server):
bash <(curl -Ls https://raw.githubusercontent.com/ospab/ostp/master/scripts/install.sh)
```
**Windows (PowerShell as Administrator):**
```powershell
irm https://raw.githubusercontent.com/ospab/ostp/master/scripts/install.ps1 | iex
```
### 2. Configuration
Initialize the configuration files for the server and client:
```bash
# On the server:
./ostp --init server
# On your machine (client):
# On the client:
./ostp --init client
```
### 2. Edit config
**Server** — set your access keys:
**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", "stealth_sni": "vk.com", "stealth_port": 443 },
"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 --generate-key # 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 "ostp://ACCESS_KEY@server.com:50000?..."
```
> **Note**: 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 [OPTIONS] [URL]
Options:
--config <PATH> Config file path (default: config.json)
--init <MODE> Generate template config (server/client)
--check Validate configuration and exit
-g, --generate-key Generate a secure access key
-c, --count <N> Number of keys to generate (default: 1)
--format <FMT> Key format: hex, base64 (default: hex)
--links Print client share links from server config
Arguments:
[URL] Connect via share link: ostp://KEY@HOST:PORT
./ostp "ostp://YOUR_SECRET_KEY@YOUR_SERVER_IP:50000?transport=udp"
```
---
## Protocol Summary
## Protocol Specification
| Layer | Mechanism |
|-------|-----------|
| XTLS-Reality | Spoofed TLS 1.3 ClientHello, X25519 Key Exchange, ChaCha20-Poly1305 AEAD |
| Key Exchange | Noise NNpsk0 (X25519 + ChaChaPoly + BLAKE2s) |
| 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 |
@ -205,38 +143,31 @@ Arguments:
## 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
Business Source License 1.1. Free for personal and non-commercial use.
Converts to MIT License on May 14, 2030.
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,162 +1,129 @@
# 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=flat-square&color=blue)
![License: BSL 1.1](https://img.shields.io/badge/License-BSL%201.1-orange.svg?style=flat-square)
![Platform: Windows | Linux | macOS | Android](https://img.shields.io/badge/Platform-Windows%20%7C%20Linux%20%7C%20macOS%20%7C%20Android-green.svg?style=flat-square)
![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)
![Platform: Windows | Linux | macOS | Android](https://img.shields.io/badge/Platform-Windows%20%7C%20Linux%20%7C%20macOS%20%7C%20Android-green.svg?style=for-the-badge)
![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)
OSTP — высокопроизводительный транспортный протокол, устойчивый к цензуре. Туннелирует TCP-трафик поверх UDP с полной обфускацией. Устойчив к Deep Packet Inspection (DPI), активному зондированию и статистическому анализу трафика.
OSTP (Ospab Stealth Transport Protocol) — зашифрованный транспортный протокол, написанный на Rust. Реализует механизм 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 через интеграцию с `tun2socks` на Windows и Linux. |
| **xHTTP Стелс (UoT)** | Туннель UDP-over-TCP, замаскированный под обычный HTTP/1.1 или TLS трафик для обхода белых списков ТСПУ (DPI). |
| **XTLS-Reality** | Собственная реализация протокола Reality (без зависимостей) с использованием ChaCha20Poly1305 и X25519 для идеальной маскировки под TLS 1.3. |
| **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. |
---
## Архитектура
```
┌────────────────────────────────────────────────────────────┐
│ Клиент │
│ ┌──────────┐ ┌──────────┐ ┌───────────────────────┐ │
│ │ Браузер │──▸│ SOCKS5/ │──▸│ Bridge (Mux) │ │
│ │ / Прил. │ │ HTTP │ │ ┌─────────────────┐ │ │
│ │ │ │ Прокси │ │ │ ProtocolMachine │ │ │
│ └──────────┘ └──────────┘ │ │ (Noise + AEAD) │ │ │
│ │ └────────┬────────┘ │ │
│ ┌──────────┐ │ │ │ │
│ │ TUN Mode │──────────────────┤ UDP-сокет │ │
│ │tun2socks │ │ (32МБ буферы, │ │
│ └──────────┘ │ обфускация) │ │
│ └───────────┬────────────┘ │
└────────────────────────────────────────────┼────────────────┘
│ UDP
┌────────────────────────────────────────────┼────────────────┐
│ Сервер │ │
│ ┌─────────────────────────────────────────┴──────────┐ │
│ │ Dispatcher │ │
│ │ (Поиск сессий, роуминг, защита от replay) │ │
│ └──────────────┬──────────────────────────────────────┘ │
│ │ │
│ ┌──────────────▾──────────────────┐ │
│ │ Relay Loop (TCP per-stream) │──▸ Интернет / Backend │
│ └─────────────────────────────────┘ │
└──────────────────────────────────────────────────────────────┘
```mermaid
flowchart LR
Apps[Приложения] -->|SOCKS5 / TUN| CoreC
subgraph Client [Клиент]
CoreC[OSTP Клиент] -.->|Шифрование| NetC[Транспортный уровень]
end
NetC <==>|Зашифрованный UDP / UoT| NetS
subgraph Server [Сервер]
NetS[Транспортный уровень] -.->|Дешифрование| CoreS[OSTP Сервер]
NetS -->|Неавторизованные| Fallback[Fallback Сервер]
end
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",
"stealth_sni": "vk.com",
"stealth_port": 443
},
// 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
```
### TUN-режим (Windows)
Требуется `tun2socks.exe` в той же директории. Автоматически запрашивает права Администратора.
### TUN-режим (Linux)
Требуется root. Нужен бинарник `tun2socks` (рядом или в `$PATH`).
Либо подключение через однострочную ссылку на стороне клиента:
```bash
./ostp "ostp://ВАШ_КЛЮЧ@IP_СЕРВЕРА:50000?transport=udp"
```
---
@ -164,22 +131,19 @@ irm https://raw.githubusercontent.com/ospab/ostp/master/scripts/install.ps1 | ie
| Уровень | Механизм |
|---------|----------|
| XTLS-Reality | Поддельный TLS 1.3 ClientHello, X25519 обмен ключами, ChaCha20-Poly1305 AEAD |
| Обмен ключами | Noise NNpsk0 (X25519 + ChaChaPoly + BLAKE2s) |
| Обмен ключами | 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с на сервере |
---
## Сборка из исходников
```bash
# Требования: Rust toolchain (1.75+)
# Требования: Rust 1.75+
cargo build --release
# Кросс-компиляция для Linux
@ -190,16 +154,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)
---
## Лицензия
Business Source License 1.1. Бесплатно для личного и некоммерческого использования.
Переходит в MIT License 14 мая 2030 года.
GNU Affero General Public License v3.0 (AGPL-3.0). Подробнее см. в файле [LICENSE](LICENSE).
---
## Контакты
- **Telegram**: [@ospab0](https://t.me/ospab0)
- **Email**: gvoprgrg@gmail.com

1
dnstt Submodule

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

7
docs/banner.txt Normal file
View File

@ -0,0 +1,7 @@
____ _____ _______ _____
/ __ \ / ____|__ __| __ \
| | | | (___ | | | |__) |
| | | |\___ \ | | | ___/
| |__| |____) | | | | |
\____/|_____/ |_| |_|

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.

Binary file not shown.

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

@ -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"`.

Binary file not shown.

BIN
icons/circle.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 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

BIN
icons/sqare.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 183 KiB

15
icons/sqare.svg Normal file
View File

@ -0,0 +1,15 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<defs>
<linearGradient id="g2" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#111827" />
<stop offset="100%" stop-color="#374151" />
</linearGradient>
<linearGradient id="g2_path" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" stop-color="#3B82F6" />
<stop offset="100%" stop-color="#14B8A6" />
</linearGradient>
</defs>
<rect width="512" height="512" rx="120" fill="url(#g2)" />
<path d="M144 256c0-61.9 50.1-112 112-112s112 50.1 112 112-50.1 112-112 112S144 317.9 144 256zm-48 0c0 88.4 71.6 160 160 160s160-71.6 160-160S344.4 96 256 96 96 167.6 96 256z" fill="url(#g2_path)"/>
<circle cx="256" cy="256" r="40" fill="#F59E0B" />
</svg>

After

Width:  |  Height:  |  Size: 779 B

View File

@ -22,7 +22,7 @@ use spin::Mutex as SpinMutex;
use tokio::{
io::{AsyncRead, AsyncWrite, ReadBuf},
sync::{
mpsc::{unbounded_channel, Receiver, Sender, UnboundedReceiver, UnboundedSender},
mpsc::{channel, Receiver, Sender, UnboundedSender},
Notify,
},
};
@ -34,9 +34,9 @@ use crate::{
Runner,
};
// NOTE: Default buffer could contain 20 AEAD packets
const DEFAULT_TCP_SEND_BUFFER_SIZE: u32 = 0x3FFF * 20;
const DEFAULT_TCP_RECV_BUFFER_SIZE: u32 = 0x3FFF * 20;
// 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 {
@ -72,12 +72,12 @@ impl TcpListenerRunner {
iface_ingress_tx: UnboundedSender<Vec<u8>>,
iface_ingress_tx_avail: Arc<AtomicBool>,
tcp_rx: Receiver<AnyIpPktFrame>,
stream_tx: UnboundedSender<TcpStream>,
stream_tx: Sender<TcpStream>,
sockets: HashMap<SocketHandle, SharedControl>,
) -> Runner {
Runner::new(async move {
let notify = Arc::new(Notify::new());
let (socket_tx, socket_rx) = unbounded_channel::<TcpSocketCreation>();
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,
@ -93,8 +93,8 @@ impl TcpListenerRunner {
iface_ingress_tx: UnboundedSender<Vec<u8>>,
iface_ingress_tx_avail: Arc<AtomicBool>,
mut tcp_rx: Receiver<AnyIpPktFrame>,
stream_tx: UnboundedSender<TcpStream>,
socket_tx: UnboundedSender<TcpSocketCreation>,
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()) {
@ -160,17 +160,20 @@ impl TcpListenerRunner {
send_state: TcpSocketState::Normal,
}));
stream_tx
.send(TcpStream {
src_addr,
dst_addr,
notify: notify.clone(),
control: control.clone(),
})
.map_err(|e| std::io::Error::new(std::io::ErrorKind::BrokenPipe, e))?;
socket_tx
.send(TcpSocketCreation { control, socket })
.map_err(|e| std::io::Error::new(std::io::ErrorKind::BrokenPipe, e))?;
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
@ -189,7 +192,7 @@ impl TcpListenerRunner {
mut iface: Interface,
iface_ingress_tx_avail: Arc<AtomicBool>,
mut sockets: HashMap<SocketHandle, SharedControl>,
mut socket_rx: UnboundedReceiver<TcpSocketCreation>,
mut socket_rx: Receiver<TcpSocketCreation>,
) -> std::io::Result<()> {
let mut socket_set = SocketSet::new(vec![]);
loop {
@ -355,7 +358,7 @@ impl TcpListenerRunner {
}
pub struct TcpListener {
stream_rx: UnboundedReceiver<TcpStream>,
stream_rx: Receiver<TcpStream>,
}
impl TcpListener {
@ -368,7 +371,7 @@ impl TcpListener {
VirtualDevice::new(stack_tx, mtu);
let iface = Self::create_interface(&mut device)?;
let (stream_tx, stream_rx) = unbounded_channel();
let (stream_tx, stream_rx) = channel(1024);
let runner = TcpListenerRunner::create(
device,
@ -539,7 +542,7 @@ impl AsyncWrite for TcpStream {
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) {
if matches!(control.send_state, TcpSocketState::Closed | TcpSocketState::Closing) {
return Ok(()).into();
}

View File

@ -9,7 +9,10 @@ anyhow.workspace = true
bytes.workspace = true
tokio.workspace = true
tracing.workspace = true
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tracing-appender = "0.2"
ostp-core = { path = "../ostp-core" }
ostp-tun = { path = "../ostp-tun" }
rand.workspace = true
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
@ -29,4 +32,8 @@ libc = "0.2.186"
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"] }
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"

View File

@ -0,0 +1,21 @@
fn main() {
let socket = std::net::UdpSocket::bind("0.0.0.0:0").unwrap();
let port = socket.local_addr().unwrap().port();
println!("Bound UDP to port {}", port);
if let Some(name) = ostp_client::tunnel::process_lookup::get_process_name_from_port_udp(port) {
println!("Found process for UDP port {}: {}", port, name);
} else {
println!("Process not found for UDP port {}", port);
}
let tcp_socket = std::net::TcpListener::bind("0.0.0.0:0").unwrap();
let tcp_port = tcp_socket.local_addr().unwrap().port();
println!("Bound TCP to port {}", tcp_port);
if let Some(name) = ostp_client::tunnel::process_lookup::get_process_name_from_port(tcp_port) {
println!("Found process for TCP port {}: {}", tcp_port, name);
} else {
println!("Process not found for TCP port {}", tcp_port);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,161 +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 reality: RealityConfig,
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,
}
fn default_tun_stack() -> String { "system".to_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>,
pub routing: RoutingConfig,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub gui: Option<serde_json::Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MultiplexConfig {
pub enabled: bool,
pub sessions: usize,
pub struct LogConfig {
#[serde(default = "default_log_level")]
pub level: 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 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,
#[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,
},
}
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 with xHTTP stealth).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TransportConfig {
/// "udp" or "uot"
#[serde(default = "default_transport_mode")]
pub mode: String,
/// TLS SNI and HTTP Host for stealth routing
#[serde(default)]
pub stealth_sni: String,
/// TCP Port for the stealth connection
#[serde(default = "default_stealth_port")]
pub stealth_port: u16,
/// Enable strict RFC 6455 WebSocket framing
#[serde(default)]
pub wss: bool,
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_stealth_port() -> u16 { 443 }
impl Default for TransportConfig {
fn default() -> Self {
Self {
mode: default_transport_mode(),
stealth_sni: String::new(),
stealth_port: default_stealth_port(),
wss: false,
r#type: default_transport_mode(),
domain: None,
resolver: None,
pubkey: None,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct RealityConfig {
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MultiplexConfig {
#[serde(default)]
pub enabled: bool,
#[serde(default)]
pub sni: String,
#[serde(default)]
pub fp: String,
#[serde(default)]
pub pbk: String,
#[serde(default)]
pub sid: String,
#[serde(default)]
pub spx: String,
#[serde(default = "default_mux_sessions")]
pub sessions: usize,
}
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(),
}
}
}
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(),
reality: RealityConfig::default(),
transport: TransportConfig::default(),
exclusions: ExclusionConfig::default(),
multiplex: MultiplexConfig::default(),
dns_server: None,
tun_stack: "system".to_string(),
}
}
}
fn default_mux_sessions() -> usize { 1 }
impl Default for MultiplexConfig {
fn default() -> Self {
@ -166,65 +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>,
reality: Option<RawRealitySection>,
transport: Option<RawTransportSection>,
#[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>,
stealth_sni: Option<String>,
stealth_port: Option<u16>,
wss: Option<bool>,
}
#[derive(Debug, Deserialize)]
struct RawTunSection {
enable: Option<bool>,
dns: Option<String>,
stack: Option<String>,
}
#[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>,
}
#[derive(Debug, Deserialize)]
struct RawRealitySection {
enabled: Option<bool>,
sni: Option<String>,
fp: Option<String>,
pbk: Option<String>,
sid: Option<String>,
spx: Option<String>,
#[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,
}
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")?;
@ -233,66 +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,
},
reality: RealityConfig {
enabled: raw.reality.as_ref().and_then(|t| t.enabled).unwrap_or(false),
sni: raw.reality.as_ref().and_then(|t| t.sni.clone()).unwrap_or_default(),
fp: raw.reality.as_ref().and_then(|t| t.fp.clone()).unwrap_or_default(),
pbk: raw.reality.as_ref().and_then(|t| t.pbk.clone()).unwrap_or_default(),
sid: raw.reality.as_ref().and_then(|t| t.sid.clone()).unwrap_or_default(),
spx: raw.reality.as_ref().and_then(|t| t.spx.clone()).unwrap_or_default(),
},
transport: TransportConfig {
mode: raw.transport.as_ref().and_then(|t| t.mode.clone()).unwrap_or_else(|| "udp".to_string()),
stealth_sni: raw.transport.as_ref().and_then(|t| t.stealth_sni.clone()).unwrap_or_else(|| "microsoft.com".to_string()),
stealth_port: raw.transport.as_ref().and_then(|t| t.stealth_port).unwrap_or(443),
wss: raw.transport.as_ref().and_then(|t| t.wss).unwrap_or(false),
},
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()),
})
// 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 });
// 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
}));
}
}
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
}));
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"
}));
}
}
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)
}
}

View File

@ -8,3 +8,4 @@ pub mod tunnel;
pub mod runner;
pub mod logging;

118
ostp-client/src/logging.rs Normal file
View File

@ -0,0 +1,118 @@
use std::fs::OpenOptions;
use std::io::Write;
use std::path::PathBuf;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
pub fn setup_panic_hook() {
std::panic::set_hook(Box::new(|info| {
let payload = info.payload();
let msg = if let Some(s) = payload.downcast_ref::<&str>() {
*s
} else if let Some(s) = payload.downcast_ref::<String>() {
s.as_str()
} else {
"Box<dyn Any>"
};
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"),
location.file(),
location.line(),
msg,
backtrace
);
eprintln!("{}", crash_msg);
tracing::error!("{}", crash_msg);
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 `<app_name>.log` next to the executable.
///
/// The `level` parameter controls the minimum log level:
/// - `"error"` — only errors
/// - `"warn"` — warnings and errors
/// - `"info"` — informational messages (default)
/// - `"debug"` — detailed debug messages (use when `debug: true` in config)
/// - `"trace"` — all messages including very verbose internal state
///
/// The environment variable `RUST_LOG` overrides this value if set.
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(|_| {
// When debug or trace is requested, enable for all ostp crates
if level == "debug" || level == "trace" {
// Enable the requested level for ostp crates, but keep noisy deps at warn
EnvFilter::new(format!(
"warn,ostp_client={level},ostp_core={level},ostp_jni={level},ostp_gui_lib={level}"
))
} else {
EnvFilter::new(level)
}
});
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)));
if let Ok(file) = OpenOptions::new().create(true).append(true).open(&path) {
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();
tracing::debug!(
"{} v{} | OS: {} | Arch: {} | log_level: {} | log_file: {}",
app_name,
version,
std::env::consts::OS,
std::env::consts::ARCH,
level,
path.display(),
);
Some(guard)
} else {
// Fallback: stderr only
let stderr_layer = tracing_subscriber::fmt::layer()
.with_target(true)
.with_writer(std::io::stderr);
let _ = tracing_subscriber::registry()
.with(EnvFilter::new(level))
.with(stderr_layer)
.try_init();
eprintln!("[WARN] Could not open log file at {}. Logging to stderr only.", path.display());
None
}
}

View File

@ -1,389 +1,73 @@
use anyhow::Result;
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 tokio::sync::watch;
fn log_to_core_file(msg: &str) {
let path = std::env::current_exe()
.ok()
.and_then(|p| p.parent().map(|d| d.join("ostp-core.log")))
.unwrap_or_else(|| std::path::PathBuf::from("ostp-core.log"));
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).await
}
use crate::config::{ClientConfig, InboundConfig};
use crate::tunnel::balancer::Balancer;
use crate::tunnel::outbounds::OutboundManager;
use crate::tunnel::router::Router;
pub async fn run_client_core(
mut 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<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."));
}
println!("[ostp] Starting run_client_core with multi-server architecture");
#[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."));
}
let router = Arc::new(Router::new(config.routing.clone()));
let balancer = Arc::new(Balancer::new(&config));
log_to_core_file(&format!("[core] Starting run_client_core in mode: {}", config.mode));
// 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));
// 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 mut handles = Vec::new();
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 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" {
Some(crate::sysproxy::SystemProxyGuard::enable(&config.local_proxy.bind_addr))
} else {
None
};
if config.mode == "tun" && !config.exclusions.processes.is_empty() {
println!("[ostp] Process exclusions are not supported in TUN mode");
}
let (proxy_events_tx, proxy_events_rx) = mpsc::channel(256);
let (client_msgs_tx, client_msgs_rx) = mpsc::unbounded_channel();
let bridge = Bridge::new(&config, metrics)?;
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}");
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,
).await {
tracing::error!("TUN inbound failed: {}", e);
}
}
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);
}));
}
InboundConfig::LocalProxy { .. } => {
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,
).await {
tracing::error!("SOCKS inbound failed: {}", e);
}
}
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 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 mut proxy_task = tokio::spawn(async move {
tunnel::run_local_proxy(
config.local_proxy,
config.ostp,
config.exclusions,
config.debug,
proxy_shutdown_rx,
proxy_events_tx,
client_msgs_rx,
)
.await
});
let wintun_shutdown_rx = shutdown_tx.subscribe();
let mut wintun_task = if config_clone.mode == "tun" {
Some(tokio::spawn(async move {
tunnel::run_tun_tunnel(config_clone, wintun_shutdown_rx).await
}))
} else {
None
};
// 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))??;
}
}
// Final cleanup: wait for tasks to finish
let _ = bridge_task.await;
let _ = proxy_task.await;
if let Some(task) = wintun_task {
let _ = task.await;
// Wait for shutdown or for tasks to fail
tokio::select! {
_ = shutdown_rx_ext.changed() => {
if *shutdown_rx_ext.borrow() {
tracing::info!("Shutdown signal received in run_client_core");
}
}
}
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")
}

View File

@ -64,7 +64,79 @@ pub fn enable_windows_proxy(proxy_addr: &str) {
_ => {}
}
// Set bypass list to prevent proxy loop for localhost traffic
// Set initial bypass list (will be expanded by update_proxy_bypass_list)
update_proxy_bypass_list_windows(&[], &[]);
refresh_wininet();
tracing::info!("System proxy enabled successfully");
}
/// Update the Windows ProxyOverride registry value to include user-configured
/// excluded domains and IPs. This makes excluded hosts bypass the OSTP proxy
/// entirely at the OS level — the most reliable split-tunneling mechanism.
///
/// For each domain `d`, adds both `d` and `*.d` so both the root and all
/// subdomains bypass the proxy.
/// For IPs, adds them verbatim (Windows supports exact IPs and wildcards like
/// `192.168.*`).
#[cfg(target_os = "windows")]
pub fn update_proxy_bypass_list(domains: &[String], ips: &[String]) {
update_proxy_bypass_list_windows(domains, ips);
refresh_wininet();
}
#[cfg(not(target_os = "windows"))]
pub fn update_proxy_bypass_list(_domains: &[String], _ips: &[String]) {
// Linux/macOS: no-op (gnome/kde proxy bypass list update not implemented)
}
#[cfg(target_os = "windows")]
fn update_proxy_bypass_list_windows(domains: &[String], ips: &[String]) {
// Base list: always bypass local addresses
let mut parts: Vec<String> = vec![
"localhost".into(),
"127.*".into(),
"10.*".into(),
"172.16.*".into(),
"172.17.*".into(),
"172.18.*".into(),
"172.19.*".into(),
"172.20.*".into(),
"172.21.*".into(),
"172.22.*".into(),
"172.23.*".into(),
"172.24.*".into(),
"172.25.*".into(),
"172.26.*".into(),
"172.27.*".into(),
"172.28.*".into(),
"172.29.*".into(),
"172.30.*".into(),
"172.31.*".into(),
"192.168.*".into(),
"<local>".into(),
];
// Add excluded domains: both exact and wildcard subdomain form
for d in domains {
let d = d.trim().trim_start_matches('.').to_lowercase();
if d.is_empty() { continue; }
parts.push(d.clone());
parts.push(format!("*.{}", d));
}
// Add excluded IPs verbatim
for ip in ips {
let ip = ip.trim();
if ip.is_empty() { continue; }
// Strip CIDR suffix if present — Windows ProxyOverride doesn't support CIDR
let host = ip.split('/').next().unwrap_or(ip);
parts.push(host.to_string());
}
let override_value = parts.join(";");
tracing::info!("Updating ProxyOverride: {}", override_value);
let _ = Command::new("reg")
.creation_flags(CREATE_NO_WINDOW)
.args([
@ -72,13 +144,10 @@ pub fn enable_windows_proxy(proxy_addr: &str) {
"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings",
"/v", "ProxyOverride",
"/t", "REG_SZ",
"/d", "localhost;127.*;10.*;192.168.*;<local>",
"/d", &override_value,
"/f",
])
.output();
refresh_wininet();
tracing::info!("System proxy enabled successfully");
}
#[cfg(target_os = "windows")]

View File

@ -0,0 +1,104 @@
use std::sync::Arc;
use std::time::Duration;
use bytes::Bytes;
use tokio::net::UdpSocket;
use tokio::sync::{mpsc, Mutex};
use rand::Rng;
pub use ostp_core::dns::{
DnsPacket, DnsRecordType, encode_payload_to_domain,
decode_domain_to_payload,
};
use crate::transport::Transport;
pub async fn start_dns_transport(domain: String, resolver: String, _pubkey: Option<String>) -> std::io::Result<Transport> {
let (app_tx, transport_rx) = mpsc::channel::<Bytes>(100);
let (transport_tx, app_rx) = mpsc::channel::<Bytes>(100);
let resolver_addr = if resolver.contains(':') {
resolver.clone()
} else {
format!("{}:53", resolver)
};
let socket = UdpSocket::bind("0.0.0.0:0").await?;
socket.connect(&resolver_addr).await?;
let socket = Arc::new(socket);
let sock_rx = socket.clone();
let sock_tx = socket;
let base_domain = domain.clone();
// Send task (reads from app, encodes into DNS TXT, sends to UDP socket)
tokio::spawn(async move {
let mut rx = transport_rx;
loop {
let data_opt = tokio::select! {
res = rx.recv() => res,
_ = tokio::time::sleep(Duration::from_secs(2)) => Some(Bytes::new()),
};
let data = match data_opt {
Some(d) => d,
None => break, // App closed
};
// Encode data to base32 domain
let fqdn = encode_payload_to_domain(&data, &base_domain);
let id: u16 = rand::thread_rng().gen();
// Randomly choose TXT or NULL for diversity (as requested)
let qtype = if rand::thread_rng().gen_bool(0.5) {
DnsRecordType::TXT
} else {
DnsRecordType::NULL
};
let packet = DnsPacket::new_query(id, &fqdn, qtype);
let encoded = packet.encode();
if let Err(e) = sock_tx.send(&encoded).await {
tracing::warn!("DNS transport send error: {}", e);
break;
}
}
});
// Receive task (reads from UDP socket, decodes DNS answer, sends to app)
let _base_domain_rx = domain.clone();
tokio::spawn(async move {
let mut buf = vec![0u8; 65535];
loop {
match sock_rx.recv(&mut buf).await {
Ok(n) => {
if let Some(packet) = DnsPacket::decode(&buf[..n]) {
for answer in packet.answers {
if answer.rtype == DnsRecordType::TXT || answer.rtype == DnsRecordType::NULL {
// If it's a TXT record, the response might be base32 encoded payload?
// Actually, dnstt puts the payload in the TXT/NULL record data.
// We'll just assume the rdata is the raw payload, or base32 encoded if it was sent as such.
// Let's just pass the raw data (TXT strings are decoded in DnsPacket::decode)
// Wait, dnstt server responds with raw bytes in NULL, and base32/chunked strings in TXT.
// Our `DnsPacket::decode` already handles extracting TXT string bytes or NULL raw bytes into `rdata`.
// Let's just send `rdata` to the app.
if transport_tx.send(Bytes::from(answer.rdata)).await.is_err() {
return; // App closed
}
}
}
}
}
Err(e) => {
tracing::warn!("DNS transport recv error: {}", e);
break;
}
}
}
});
Ok(Transport::Dns {
tx: app_tx,
rx: Arc::new(Mutex::new(app_rx)),
})
}

View File

@ -1,5 +1,4 @@
pub mod xhttp;
pub mod dns;
use std::sync::Arc;
use tokio::net::UdpSocket;
use bytes::Bytes;
@ -10,6 +9,10 @@ pub enum Transport {
Uot {
tx: tokio::sync::mpsc::Sender<Bytes>,
rx: Arc<tokio::sync::Mutex<tokio::sync::mpsc::Receiver<Bytes>>>,
},
Dns {
tx: tokio::sync::mpsc::Sender<Bytes>,
rx: Arc<tokio::sync::Mutex<tokio::sync::mpsc::Receiver<Bytes>>>,
}
}
@ -17,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::Dns { tx, .. } => {
tx.send(frame.clone()).await.map_err(|_| std::io::Error::new(std::io::ErrorKind::BrokenPipe, "channel closed"))?;
Ok(frame.len())
}
}
@ -27,14 +30,14 @@ 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::Dns { .. } => 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::Dns { rx, .. } => {
let mut rx = rx.lock().await;
match rx.recv().await {
Some(bytes) => {
@ -42,7 +45,7 @@ impl Transport {
buf[..len].copy_from_slice(&bytes[..len]);
Ok(len)
}
None => Err(std::io::Error::new(std::io::ErrorKind::BrokenPipe, "uot closed")),
None => Err(std::io::Error::new(std::io::ErrorKind::BrokenPipe, "channel closed")),
}
}
}
@ -51,7 +54,7 @@ impl Transport {
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::Dns { .. } => Ok("0.0.0.0:0".parse().unwrap()),
}
}
}

View File

@ -31,8 +31,13 @@ pub async fn connect_xhttp(
let addr = std::net::SocketAddr::new(target_ip, port);
#[cfg(not(target_os = "android"))]
let mut tcp_stream = tokio::net::TcpStream::connect(addr).await
.with_context(|| format!("failed to connect to {}", addr))?;
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 = {
@ -44,8 +49,13 @@ pub async fn connect_xhttp(
sock.set_nonblocking(true)?;
let tcp_socket = tokio::net::TcpSocket::from_std_stream(sock.into());
tcp_socket.connect(addr).await
.with_context(|| format!("failed to connect to {}", addr))?
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)?;

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,231 @@
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>,
) -> Result<()> {
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?;
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,301 @@
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>,
) -> Result<()> {
use netstack_smoltcp::StackBuilder;
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 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) => {
if let Err(_) = stack_sink.send(buf[..n].to_vec()).await { break; }
}
Err(e) => tracing::debug!("tun_read error: {e}"),
}
}
});
let 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}"); }
}
});
(tun_to_stack, stack_to_tun)
}
};
// ── 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>,
) -> 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;
mod udp_nat;
pub mod router;
pub mod balancer;
pub mod outbounds;
pub mod inbounds;
pub async fn run_tun_tunnel(
config: crate::config::ClientConfig,
shutdown: watch::Receiver<bool>,
) -> anyhow::Result<()> {
native_handler::run_native_tunnel(config, shutdown).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: 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, debug, shutdown, proxy_events_tx, client_msgs_rx).await
}
pub mod exclusion;
pub mod process_lookup;
pub mod sni_sniff;

View File

@ -1,545 +0,0 @@
use anyhow::{anyhow, Result};
use tokio::sync::watch;
#[cfg(any(target_os = "windows", target_os = "linux"))]
pub async fn run_native_tunnel(
config: crate::config::ClientConfig,
mut shutdown: watch::Receiver<bool>,
) -> Result<()> {
use std::net::ToSocketAddrs;
use std::process::Command;
use netstack_smoltcp::StackBuilder;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use futures::{StreamExt, SinkExt};
#[cfg(target_os = "windows")]
use std::os::windows::process::CommandExt;
#[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. Run without TUN to use as a local proxy."));
}
}
}
let debug = config.debug;
tracing::info!("Initializing NATIVE TUN tunnel (smoltcp)...");
let server_ip = config.ostp.server_addr.to_socket_addrs()
.map_err(|e| anyhow!("Failed to resolve remote server IP: {}", e))?
.next()
.map(|addr| addr.ip())
.ok_or_else(|| anyhow!("Could not resolve host IP for routing exclusion"))?;
let server_ip_str = server_ip.to_string();
let mut tun_cfg = tun::Configuration::default();
tun_cfg.tun_name("ostp_tun")
.address((10, 1, 0, 2))
.netmask((255, 255, 255, 0))
.destination((10, 1, 0, 1))
.mtu(config.ostp.mtu as u16)
.up();
#[cfg(target_os = "linux")]
tun_cfg.platform_config(|config| {
config.packet_information(false);
});
let dev = tun::create(&tun_cfg)
.map_err(|e| anyhow!("Failed to create TUN device: {}", e))?;
let dev = tun::AsyncDevice::new(dev)
.map_err(|e| anyhow!("Failed to make TUN device async: {}", e))?;
tracing::info!("TUN device created natively.");
#[cfg(target_os = "windows")]
{
const CREATE_NO_WINDOW: u32 = 0x08000000;
let current_exe = std::env::current_exe()?.to_string_lossy().into_owned();
let setup_script = format!(
"$remote_ip = '{}'\n\
$exe_path = '{}'\n\
$route = Get-NetRoute -DestinationPrefix '0.0.0.0/0' | Where-Object {{ $_.InterfaceAlias -notmatch 'ostp' -and $_.InterfaceAlias -notmatch 'tun' -and $_.InterfaceAlias -notmatch 'wintun' }} | Sort-Object RouteMetric | Select-Object -First 1\n\
if ($route) {{\n\
$gw = $route.NextHop\n\
$ifIndex = $route.InterfaceIndex\n\
if ($gw -eq '0.0.0.0' -or $gw -eq '::') {{\n\
New-NetRoute -DestinationPrefix \"$remote_ip/32\" -InterfaceIndex $ifIndex -RouteMetric 1 -ErrorAction SilentlyContinue\n\
}} else {{\n\
New-NetRoute -DestinationPrefix \"$remote_ip/32\" -NextHop $gw -InterfaceIndex $ifIndex -RouteMetric 1 -ErrorAction SilentlyContinue\n\
}}\n\
if ($gw -ne '0.0.0.0') {{\n\
New-NetRoute -DestinationPrefix \"$gw/32\" -NextHop '0.0.0.0' -InterfaceIndex $ifIndex -RouteMetric 1 -ErrorAction SilentlyContinue\n\
}}\n\
}}\n\
New-NetFirewallRule -DisplayName 'OSTP Tunnel In' -Direction Inbound -Program $exe_path -Action Allow -Enabled True -ErrorAction SilentlyContinue\n\
New-NetFirewallRule -DisplayName 'OSTP Tunnel Out' -Direction Outbound -Program $exe_path -Action Allow -Enabled True -ErrorAction SilentlyContinue\n\
netsh interface ipv4 set interface name=\"ostp_tun\" metric=1\n\
New-NetRoute -DestinationPrefix '0.0.0.0/0' -InterfaceAlias 'ostp_tun' -NextHop '10.1.0.1' -RouteMetric 1 -ErrorAction SilentlyContinue\n",
server_ip_str, current_exe
);
let _ = tokio::task::spawn_blocking(move || {
Command::new("powershell")
.creation_flags(CREATE_NO_WINDOW)
.args(["-NoProfile", "-Command", &setup_script])
.output()
}).await.unwrap()?;
if let Some(ref dns) = config.dns_server {
if !dns.is_empty() {
let net_setup = format!("netsh interface ipv4 set dnsservers name=\"ostp_tun\" static {} primary\n", dns);
let _ = tokio::task::spawn_blocking(move || {
Command::new("powershell")
.creation_flags(CREATE_NO_WINDOW)
.args(["-NoProfile", "-Command", &net_setup])
.output()
}).await.unwrap()?;
}
}
}
#[cfg(target_os = "linux")]
{
// Get real gateway before routing through TUN
let gw_out = Command::new("ip")
.args(["route", "show", "default"])
.output()
.ok()
.and_then(|o| String::from_utf8(o.stdout).ok());
let real_gw = gw_out.as_deref().and_then(|s| {
// "default via 192.168.1.1 dev eth0" -> "192.168.1.1"
s.split_whitespace().skip_while(|w| *w != "via").nth(1).map(|s| s.to_string())
});
let real_dev = gw_out.as_deref().and_then(|s| {
s.split_whitespace().skip_while(|w| *w != "dev").nth(1).map(|s| s.to_string())
});
// Add exclusion route for server IP via real gateway (bypass TUN)
if let (Some(ref gw), Some(ref dev)) = (&real_gw, &real_dev) {
let _ = Command::new("ip").args(["route", "add", &format!("{}/32", server_ip_str), "via", gw, "dev", dev]).output();
}
// Add default route through TUN (lower metric to take priority)
let _ = Command::new("ip").args(["route", "add", "default", "via", "10.1.0.1", "dev", "ostp_tun", "metric", "10"]).output();
}
let (stack, tcp_runner, udp_socket, tcp_listener) = StackBuilder::default()
.stack_buffer_size(100000)
.tcp_buffer_size(100000)
.udp_buffer_size(100000)
.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 (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);
// continue reading
}
}
}
});
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);
}
}
});
let udp_proxy_addr = config.local_proxy.bind_addr.clone();
let debug_udp = config.debug;
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).await;
}
});
let proxy_addr = config.local_proxy.bind_addr.clone();
let mut tcp_accept_task = tokio::spawn(async move {
if let Some(mut listener) = tcp_listener {
while let Some((mut stream, _local, remote)) = listener.next().await {
let proxy_addr = proxy_addr.clone();
tokio::spawn(async move {
if debug { tracing::info!("Native TUN intercepted TCP to {}", remote); }
if let Ok(mut socks) = tokio::net::TcpStream::connect(&proxy_addr).await {
// SOCKS5 bypass handshake locally (loopback)
if socks.write_all(&[5, 1, 0]).await.is_err() { return; }
let mut buf = [0u8; 2];
if socks.read_exact(&mut buf).await.is_err() || buf[0] != 5 || buf[1] != 0 { return; }
let ip = remote.ip();
let port = remote.port();
let mut req = vec![5, 1, 0];
match 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(&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; }
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 routes
#[cfg(target_os = "windows")]
{
const CREATE_NO_WINDOW: u32 = 0x08000000;
let cleanup_script = format!(
"$remote_ip = '{}'\n\
Remove-NetRoute -DestinationPrefix \"$remote_ip/32\" -Confirm:$false -ErrorAction SilentlyContinue\n\
Remove-NetFirewallRule -DisplayName 'OSTP Tunnel*' -ErrorAction SilentlyContinue\n\
netsh interface ipv4 set dnsservers name=\"ostp_tun\" source=dhcp 2>$null\n",
server_ip_str
);
let _ = Command::new("powershell")
.creation_flags(CREATE_NO_WINDOW)
.args(["-NoProfile", "-Command", &cleanup_script])
.output();
}
#[cfg(target_os = "linux")]
{
// Remove default route via TUN and server exclusion route
let _ = Command::new("ip").args(["route", "del", "default", "dev", "ostp_tun"]).output();
let _ = Command::new("ip").args(["route", "del", &format!("{}/32", server_ip_str)]).output();
}
Ok(())
}
#[cfg(not(any(target_os = "windows", target_os = "linux")))]
pub async fn run_native_tunnel(
_config: crate::config::ClientConfig,
_shutdown: watch::Receiver<bool>,
) -> Result<()> {
Err(anyhow!("Native TUN tunnel is only supported on Windows/Linux currently"))
}
#[cfg(target_os = "android")]
pub async fn run_native_tunnel_from_fd(
config: crate::config::ClientConfig,
mut shutdown: watch::Receiver<bool>,
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::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(100000)
.tcp_buffer_size(100000)
.udp_buffer_size(100000)
.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 {
// EINTR or other transient error — treat as zero (will continue)
Ok(0_isize)
}
} else {
Ok(res as isize)
}
}) {
Ok(Ok(n)) if n > 0 => n as usize,
Ok(Ok(_)) => continue, // 0 = EINTR or transient error, try again
Ok(Err(_)) => continue, // WouldBlock retry
Err(_would_block) => 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"));
}
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(n)) if n == 0 => break,
Ok(Ok(_)) => break, // n < 0, error writing, drop this frame
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 udp_proxy_addr = proxy_addr.clone();
let debug_udp = config.debug;
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).await;
}
});
let matcher = crate::tunnel::exclusion::ExclusionMatcher::new(&config.exclusions, None, None);
let mut tcp_accept_task = tokio::spawn(async move {
if let Some(mut listener) = tcp_listener {
while let Some((mut stream, local, remote)) = listener.next().await {
let proxy_addr = proxy_addr.clone();
let matcher = matcher.clone();
tokio::spawn(async move {
if debug { tracing::info!("Native TUN intercepted TCP {local} -> {remote}"); }
// Peak first chunk to see SNI
let mut sniff_buf = [0u8; 1500];
let sniff_len = match tokio::time::timeout(std::time::Duration::from_millis(50), stream.read(&mut sniff_buf)).await {
Ok(Ok(n)) => n,
_ => 0, // Timeout or error
};
let mut should_bypass = false;
// 1. Check SNI
if sniff_len > 0 {
if let Some(sni) = crate::tunnel::sni_sniff::extract_sni(&sniff_buf[..sniff_len]) {
if debug { tracing::info!("Native TUN sniffed SNI: {}", sni); }
if matcher.match_domain(&sni) {
should_bypass = true;
}
}
}
// 2. Check Process
if !should_bypass {
if let Some(exe) = crate::tunnel::process_lookup::get_process_name_from_port(local.port()) {
if debug { tracing::info!("Native TUN source port {} maps to EXE: {}", local.port(), exe); }
if matcher.match_process(&exe) {
should_bypass = true;
}
}
}
// 3. Check Target IP
if !should_bypass {
if matcher.match_ip(&remote.ip()) {
should_bypass = true;
}
}
if should_bypass {
if debug { tracing::info!("Native TUN BYPASS matched for {}", remote); }
if let Ok(mut direct) = tokio::time::timeout(std::time::Duration::from_secs(5), tokio::net::TcpStream::connect(remote)).await.unwrap_or(Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "Direct connect timeout"))) {
if sniff_len > 0 {
let _ = direct.write_all(&sniff_buf[..sniff_len]).await;
}
let _ = tokio::io::copy_bidirectional(&mut stream, &mut direct).await;
}
return;
}
if let Ok(mut socks) = tokio::net::TcpStream::connect(&proxy_addr).await {
if socks.write_all(&[5, 1, 0]).await.is_err() { return; }
let mut buf = [0u8; 2];
if socks.read_exact(&mut buf).await.is_err() || buf[0] != 5 || buf[1] != 0 { return; }
let ip = remote.ip();
let port = remote.port();
let mut req = vec![5, 1, 0];
match 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(&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; }
// Write sniffed buffer to socks
if sniff_len > 0 {
if 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!("Deactivating NATIVE TUN tunnel...");
Ok(())
}
#[cfg(not(target_os = "android"))]
pub async fn run_native_tunnel_from_fd(
_config: crate::config::ClientConfig,
_shutdown: watch::Receiver<bool>,
_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,391 @@
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,
};
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: 5,
rto_ms: 100,
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 ───────────────────────
let mut buf = [0u8; 65535];
let mut udp_buf = [0u8; 65535];
loop {
tokio::select! {
Ok(n) = server_stream.read(&mut buf) => {
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(10)) => {
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> {
match transport_cfg.r#type.as_str() {
"dns" => {
let domain = transport_cfg.domain.clone()
.unwrap_or_else(|| "tunnel.example.com".to_string());
let resolver = transport_cfg.resolver.clone()
.unwrap_or_else(|| server.to_string());
let transport = crate::transport::dns::start_dns_transport(domain, resolver, transport_cfg.pubkey.clone()).await
.map_err(|e| anyhow::anyhow!(e))?;
Ok(transport)
}
_ => {
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

@ -1,6 +1,6 @@
#[cfg(target_os = "windows")]
pub fn get_process_name_from_port(port: u16) -> Option<String> {
use winapi::shared::minwindef::{DWORD, ULONG};
use winapi::shared::minwindef::ULONG;
use winapi::shared::winerror::ERROR_INSUFFICIENT_BUFFER;
use winapi::um::iphlpapi::GetExtendedTcpTable;
use winapi::shared::tcpmib::{MIB_TCPTABLE_OWNER_PID, MIB_TCPROW_OWNER_PID};
@ -47,6 +47,54 @@ pub fn get_process_name_from_port(port: u16) -> Option<String> {
None
}
#[cfg(target_os = "windows")]
pub fn get_process_name_from_port_udp(port: u16) -> Option<String> {
use winapi::shared::minwindef::ULONG;
use winapi::shared::winerror::ERROR_INSUFFICIENT_BUFFER;
use winapi::um::iphlpapi::GetExtendedUdpTable;
use winapi::shared::udpmib::{MIB_UDPTABLE_OWNER_PID, MIB_UDPROW_OWNER_PID};
let mut size: ULONG = 0;
let table_class = 1; // UDP_TABLE_OWNER_PID
let mut table = vec![0u8; 1024];
unsafe {
let mut ret = GetExtendedUdpTable(
table.as_mut_ptr() as *mut _,
&mut size,
0,
2, // AF_INET
table_class,
0,
);
if ret == ERROR_INSUFFICIENT_BUFFER {
table.resize(size as usize, 0);
ret = GetExtendedUdpTable(
table.as_mut_ptr() as *mut _,
&mut size,
0,
2, // AF_INET
table_class,
0,
);
}
if ret == 0 {
let udp_table = &*(table.as_ptr() as *const MIB_UDPTABLE_OWNER_PID);
let row_ptr = &udp_table.table[0] as *const MIB_UDPROW_OWNER_PID;
for i in 0..udp_table.dwNumEntries {
let row = &*row_ptr.add(i as usize);
let local_port = u16::from_be(row.dwLocalPort as u16);
if local_port == port {
return get_process_name_from_pid(row.dwOwningPid);
}
}
}
}
None
}
#[cfg(target_os = "windows")]
fn get_process_name_from_pid(pid: u32) -> Option<String> {
use winapi::um::processthreadsapi::OpenProcess;
@ -78,7 +126,6 @@ pub fn get_process_name_from_port(port: u16) -> Option<String> {
use std::fs;
use std::io::{BufRead, BufReader};
let mut target_inode = None;
let hex_port = format!("{:04X}", port);
let check_net_file = |path: &str| -> Option<u64> {
@ -98,12 +145,11 @@ pub fn get_process_name_from_port(port: u16) -> Option<String> {
None
};
target_inode = check_net_file("/proc/net/tcp")
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) {
@ -140,3 +186,8 @@ pub fn get_process_name_from_port(port: u16) -> Option<String> {
pub fn get_process_name_from_port(_port: u16) -> Option<String> {
None
}
#[cfg(not(target_os = "windows"))]
pub fn get_process_name_from_port_udp(port: u16) -> Option<String> {
get_process_name_from_port(port)
}

View File

@ -1,926 +0,0 @@
use std::collections::HashMap;
use crate::tunnel::exclusion::{ExclusionMatcher, Cidr};
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")]
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 {
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 {
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")]
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(())
}
fn get_windows_physical_if_index() -> Option<u32> {
#[cfg(target_os = "windows")]
{
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x08000000;
let output = std::process::Command::new("powershell")
.creation_flags(CREATE_NO_WINDOW)
.args([
"-NoProfile",
"-Command",
"Get-NetRoute -DestinationPrefix '0.0.0.0/0' | Where-Object { $_.InterfaceAlias -notmatch 'ostp' -and $_.InterfaceAlias -notmatch 'tun' -and $_.InterfaceAlias -notmatch 'wintun' } | Sort-Object RouteMetric | Select-Object -ExpandProperty InterfaceIndex -First 1"
])
.output()
.ok()?;
if output.status.success() {
let s = String::from_utf8_lossy(&output.stdout);
if let Ok(index) = s.trim().parse::<u32>() {
return Some(index);
}
}
}
None
}
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,
exclusions: 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))?;
if debug {
tracing::info!("local HTTP/SOCKS5 proxy listening at {}", cfg.bind_addr);
tracing::info!("Windows system proxy: set HTTP proxy to {}. tun2socks: SOCKS5 on same address.", 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 matcher = ExclusionMatcher::new(&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;
}
}
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 debug {
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;
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 debug {
tracing::info!("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);
spawn_direct_udp_reader(s_arc.clone(), sock_tx.clone(), client_udp_addr.clone(), debug);
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);
spawn_direct_udp_reader(s_arc.clone(), sock_tx.clone(), client_udp_addr.clone(), debug);
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 debug {
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,
) {
tokio::spawn(async move {
let mut buf = vec![0u8; 65536];
loop {
match direct_socket.recv_from(&mut buf).await {
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 debug {
tracing::warn!("failed to send direct UDP response to client: {e}");
}
}
}
}
Err(e) => {
if debug {
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 debug { tracing::info!("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;
}
if debug {
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 => 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 debug {
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 debug {
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 debug {
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 debug {
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 debug {
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

@ -52,7 +52,7 @@ pub fn extract_sni(data: &[u8]) -> Option<String> {
if ext_type == 0x0000 { // Server Name Indication (SNI)
if pos + 5 <= extensions_end {
let list_len = ((data[pos] as usize) << 8) | (data[pos + 1] as usize);
let _list_len = ((data[pos] as usize) << 8) | (data[pos + 1] as usize);
let name_type = data[pos + 2];
if name_type == 0 { // Hostname
let name_len = ((data[pos + 3] as usize) << 8) | (data[pos + 4] as usize);

View File

@ -1,176 +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,
) {
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();
while let Some((payload, src, dst)) = rx.next().await {
if payload.is_empty() { continue; }
if !sessions.contains_key(&src) {
let (session_tx, mut session_rx) = mpsc::channel::<(Vec<u8>, SocketAddr)>(100000);
sessions.insert(src, session_tx);
let proxy_addr_clone = proxy_addr.clone();
let tx_clone = tx.clone();
tokio::spawn(async move {
if debug { tracing::info!("Starting UDP NAT session for {}", src); }
let res = start_udp_session(src, proxy_addr_clone, &mut session_rx, tx_clone).await;
if debug && res.is_err() {
tracing::info!("UDP NAT session for {} ended: {:?}", src, res.err());
}
});
}
if let Some(sender) = sessions.get(&src) {
if sender.send((payload, dst)).await.is_err() {
sessions.remove(&src);
}
}
}
}
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?;
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"] }

View File

@ -1,7 +1,7 @@
pub mod aead;
pub mod noise;
pub mod obfuscation;
pub mod reality;
pub use aead::SessionCipher;
pub use noise::{NoiseRole, NoiseSession};

413
ostp-core/src/dns.rs Normal file
View File

@ -0,0 +1,413 @@
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use std::io::{Cursor, Read};
const BASE32_ALPHABET: &[u8] = b"abcdefghijklmnopqrstuvwxyz234567";
/// Encodes a byte slice into Base32 (RFC 4648) without padding, lowercase.
pub fn base32_encode(data: &[u8]) -> String {
let mut result = String::with_capacity((data.len() * 8 + 4) / 5);
let mut buffer = 0u32;
let mut bits_left = 0;
for &b in data {
buffer = (buffer << 8) | (b as u32);
bits_left += 8;
while bits_left >= 5 {
bits_left -= 5;
let index = ((buffer >> bits_left) & 0x1F) as usize;
result.push(BASE32_ALPHABET[index] as char);
}
}
if bits_left > 0 {
let index = ((buffer << (5 - bits_left)) & 0x1F) as usize;
result.push(BASE32_ALPHABET[index] as char);
}
result
}
/// Decodes a Base32 string (case-insensitive, no padding) into a byte vector.
pub fn base32_decode(encoded: &str) -> Option<Vec<u8>> {
let mut result = Vec::with_capacity(encoded.len() * 5 / 8);
let mut buffer = 0u32;
let mut bits_left = 0;
for c in encoded.bytes() {
let val = match c {
b'a'..=b'z' => c - b'a',
b'A'..=b'Z' => c - b'A',
b'2'..=b'7' => c - b'2' + 26,
_ => return None, // Invalid character
};
buffer = (buffer << 5) | (val as u32);
bits_left += 5;
if bits_left >= 8 {
bits_left -= 8;
result.push((buffer >> bits_left) as u8);
}
}
Some(result)
}
#[derive(Debug, Clone, PartialEq)]
pub enum DnsRecordType {
A,
CNAME,
NULL,
TXT,
AAAA,
Unknown(u16),
}
impl From<u16> for DnsRecordType {
fn from(val: u16) -> Self {
match val {
1 => DnsRecordType::A,
5 => DnsRecordType::CNAME,
10 => DnsRecordType::NULL,
16 => DnsRecordType::TXT,
28 => DnsRecordType::AAAA,
_ => DnsRecordType::Unknown(val),
}
}
}
impl DnsRecordType {
pub fn as_u16(&self) -> u16 {
match self {
DnsRecordType::A => 1,
DnsRecordType::CNAME => 5,
DnsRecordType::NULL => 10,
DnsRecordType::TXT => 16,
DnsRecordType::AAAA => 28,
DnsRecordType::Unknown(v) => *v,
}
}
}
#[derive(Debug, Clone)]
pub struct DnsQuestion {
pub name: String,
pub qtype: DnsRecordType,
pub qclass: u16, // Usually 1 (IN)
}
#[derive(Debug, Clone)]
pub struct DnsAnswer {
pub name: String,
pub rtype: DnsRecordType,
pub rclass: u16,
pub ttl: u32,
pub rdata: Vec<u8>,
}
#[derive(Debug, Clone)]
pub struct DnsPacket {
pub id: u16,
pub flags: u16,
pub questions: Vec<DnsQuestion>,
pub answers: Vec<DnsAnswer>,
}
impl DnsPacket {
pub fn new_query(id: u16, name: &str, qtype: DnsRecordType) -> Self {
DnsPacket {
id,
flags: 0x0100, // Standard query, recursion desired
questions: vec![DnsQuestion {
name: name.to_string(),
qtype,
qclass: 1, // IN
}],
answers: vec![],
}
}
pub fn new_response(id: u16, name: &str, rtype: DnsRecordType, rdata: Vec<u8>) -> Self {
DnsPacket {
id,
flags: 0x8180, // Response, standard query, recursion desired, recursion available
questions: vec![DnsQuestion {
name: name.to_string(),
qtype: rtype.clone(),
qclass: 1, // IN
}],
answers: vec![DnsAnswer {
name: name.to_string(),
rtype,
rclass: 1,
ttl: 0, // No caching
rdata,
}],
}
}
pub fn encode(&self) -> Vec<u8> {
let mut buf = Vec::new();
let _ = buf.write_u16::<BigEndian>(self.id);
let _ = buf.write_u16::<BigEndian>(self.flags);
let _ = buf.write_u16::<BigEndian>(self.questions.len() as u16);
let _ = buf.write_u16::<BigEndian>(self.answers.len() as u16);
let _ = buf.write_u16::<BigEndian>(0); // Authority PR
let _ = buf.write_u16::<BigEndian>(0); // Additional PR
for q in &self.questions {
encode_domain_name(&mut buf, &q.name);
let _ = buf.write_u16::<BigEndian>(q.qtype.as_u16());
let _ = buf.write_u16::<BigEndian>(q.qclass);
}
for a in &self.answers {
encode_domain_name(&mut buf, &a.name);
let _ = buf.write_u16::<BigEndian>(a.rtype.as_u16());
let _ = buf.write_u16::<BigEndian>(a.rclass);
let _ = buf.write_u32::<BigEndian>(a.ttl);
if a.rtype == DnsRecordType::TXT {
// TXT records have character-strings length-prefixed
// We split into chunks of up to 255 bytes
let mut txt_data = Vec::new();
for chunk in a.rdata.chunks(255) {
txt_data.push(chunk.len() as u8);
txt_data.extend_from_slice(chunk);
}
let _ = buf.write_u16::<BigEndian>(txt_data.len() as u16);
buf.extend_from_slice(&txt_data);
} else {
let _ = buf.write_u16::<BigEndian>(a.rdata.len() as u16);
buf.extend_from_slice(&a.rdata);
}
}
buf
}
pub fn decode(data: &[u8]) -> Option<Self> {
if data.len() < 12 {
return None;
}
let mut cursor = Cursor::new(data);
let id = cursor.read_u16::<BigEndian>().ok()?;
let flags = cursor.read_u16::<BigEndian>().ok()?;
let qdcount = cursor.read_u16::<BigEndian>().ok()?;
let ancount = cursor.read_u16::<BigEndian>().ok()?;
let _nscount = cursor.read_u16::<BigEndian>().ok()?;
let _arcount = cursor.read_u16::<BigEndian>().ok()?;
let mut questions = Vec::new();
for _ in 0..qdcount {
let name = decode_domain_name(&mut cursor, data)?;
let qtype = cursor.read_u16::<BigEndian>().ok()?.into();
let qclass = cursor.read_u16::<BigEndian>().ok()?;
questions.push(DnsQuestion { name, qtype, qclass });
}
let mut answers = Vec::new();
for _ in 0..ancount {
let name = decode_domain_name(&mut cursor, data)?;
let rtype: DnsRecordType = cursor.read_u16::<BigEndian>().ok()?.into();
let rclass = cursor.read_u16::<BigEndian>().ok()?;
let ttl = cursor.read_u32::<BigEndian>().ok()?;
let rdlength = cursor.read_u16::<BigEndian>().ok()?;
let mut rdata = vec![0u8; rdlength as usize];
cursor.read_exact(&mut rdata).ok()?;
if rtype == DnsRecordType::TXT {
// Decode TXT string chunks
let mut decoded_txt = Vec::new();
let mut txt_cursor = Cursor::new(&rdata);
while txt_cursor.position() < rdata.len() as u64 {
if let Ok(len) = txt_cursor.read_u8() {
let mut chunk = vec![0u8; len as usize];
if txt_cursor.read_exact(&mut chunk).is_ok() {
decoded_txt.extend_from_slice(&chunk);
} else {
break;
}
} else {
break;
}
}
rdata = decoded_txt;
}
answers.push(DnsAnswer {
name,
rtype,
rclass,
ttl,
rdata,
});
}
// Skip authority and additional sections (not needed for basic payload extraction)
Some(DnsPacket {
id,
flags,
questions,
answers,
})
}
}
fn encode_domain_name(buf: &mut Vec<u8>, name: &str) {
for part in name.split('.') {
if part.is_empty() {
continue;
}
let len = part.len().min(63) as u8;
buf.push(len);
buf.extend_from_slice(&part.as_bytes()[..len as usize]);
}
buf.push(0); // Root label
}
fn decode_domain_name(cursor: &mut Cursor<&[u8]>, full_data: &[u8]) -> Option<String> {
let mut parts = Vec::new();
let mut jumps = 0;
let mut current_pos = cursor.position();
loop {
if jumps > 100 {
return None; // Prevent infinite loops
}
if current_pos >= full_data.len() as u64 {
return None;
}
let len = full_data[current_pos as usize];
if len == 0 {
if jumps == 0 {
cursor.set_position(current_pos + 1);
}
break;
}
if len & 0xC0 == 0xC0 {
// Pointer
if current_pos + 1 >= full_data.len() as u64 {
return None;
}
let pointer = (((len & 0x3F) as u16) << 8) | (full_data[current_pos as usize + 1] as u16);
if jumps == 0 {
cursor.set_position(current_pos + 2);
}
jumps += 1;
current_pos = pointer as u64;
continue;
}
current_pos += 1;
if current_pos + len as u64 > full_data.len() as u64 {
return None;
}
let part = &full_data[current_pos as usize..(current_pos + len as u64) as usize];
parts.push(String::from_utf8_lossy(part).into_owned());
current_pos += len as u64;
if jumps == 0 {
cursor.set_position(current_pos);
}
}
if parts.is_empty() {
Some(".".to_string())
} else {
Some(parts.join("."))
}
}
/// Encodes a payload into a list of subdomain labels and appends the base domain.
/// Each label is max 63 chars. The base32 string is chunked.
pub fn encode_payload_to_domain(payload: &[u8], base_domain: &str) -> String {
let encoded = base32_encode(payload);
let mut domain = String::new();
let mut start = 0;
while start < encoded.len() {
let end = (start + 63).min(encoded.len());
domain.push_str(&encoded[start..end]);
domain.push('.');
start = end;
}
domain.push_str(base_domain);
domain
}
/// Decodes a payload from a subdomain string, ignoring the base domain.
pub fn decode_domain_to_payload(full_domain: &str, base_domain: &str) -> Option<Vec<u8>> {
// Strip base domain and trailing dots
let stripped = full_domain
.trim_end_matches('.')
.strip_suffix(base_domain)?;
let stripped = stripped.trim_end_matches('.');
let mut base32_str = String::with_capacity(stripped.len());
for part in stripped.split('.') {
base32_str.push_str(part);
}
base32_decode(&base32_str)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_base32() {
let data = b"Hello, OSTP DNS Tunnel!";
let encoded = base32_encode(data);
let decoded = base32_decode(&encoded).unwrap();
assert_eq!(data.as_ref(), decoded.as_slice());
}
#[test]
fn test_domain_encoding() {
let payload = vec![0x12; 20];
let base_domain = "tunnel.example.com";
let domain = encode_payload_to_domain(&payload, base_domain);
// Ensure no label is > 63 chars
for part in domain.split('.') {
assert!(part.len() <= 63);
}
assert!(domain.ends_with(base_domain));
let decoded = decode_domain_to_payload(&domain, base_domain).unwrap();
assert_eq!(payload, decoded);
}
#[test]
fn test_dns_packet() {
let payload = vec![1, 2, 3, 4, 5];
let domain = encode_payload_to_domain(&payload, "t.com");
let query = DnsPacket::new_query(1234, &domain, DnsRecordType::TXT);
let encoded_query = query.encode();
let decoded_query = DnsPacket::decode(&encoded_query).unwrap();
assert_eq!(decoded_query.id, 1234);
assert_eq!(decoded_query.questions[0].name, domain);
assert_eq!(decoded_query.questions[0].qtype, DnsRecordType::TXT);
let response_data = vec![5, 4, 3, 2, 1];
let response = DnsPacket::new_response(1234, &domain, DnsRecordType::TXT, response_data.clone());
let encoded_resp = response.encode();
let decoded_resp = DnsPacket::decode(&encoded_resp).unwrap();
assert_eq!(decoded_resp.answers[0].rdata, response_data);
}
}

View File

@ -0,0 +1,94 @@
use std::time::Duration;
use tokio::time::Instant;
use crate::dns::{DnsPacket, DnsRecordType, encode_payload_to_domain};
use rand::Rng;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone)]
pub struct DnsProbeResult {
pub name: String,
pub ip: String,
pub latency_ms: Option<u64>,
}
const PUBLIC_DNS_SERVERS: &[(&str, &str)] = &[
("Cloudflare", "1.1.1.1"),
("Cloudflare2", "1.0.0.1"),
("Google", "8.8.8.8"),
("Google2", "8.8.4.4"),
("Quad9", "9.9.9.9"),
("AdGuard", "94.140.14.14"),
("Yandex", "77.88.8.8"),
("Yandex2", "77.88.8.1"),
("SkyDNS", "193.58.251.251"),
("AliDNS", "223.5.5.5"),
("Tencent", "119.29.29.29"),
("114DNS", "114.114.114.114"),
("Shecan", "178.22.122.100"),
("Electro", "78.157.42.100"),
("Begzar", "185.55.226.26"),
];
async fn probe_resolver(domain: &str, resolver_ip: &str) -> Option<u64> {
let (probe_bytes, id) = {
let mut rng = rand::thread_rng();
let probe_bytes: [u8; 4] = rng.gen();
let id: u16 = rng.gen();
(probe_bytes, id)
};
let fqdn = encode_payload_to_domain(&probe_bytes, domain);
let qtype = if rand::thread_rng().gen_bool(0.5) { DnsRecordType::TXT } else { DnsRecordType::NULL };
let packet = DnsPacket::new_query(id, &fqdn, qtype);
let encoded = packet.encode();
let sock = tokio::net::UdpSocket::bind("0.0.0.0:0").await.ok()?;
sock.connect(format!("{}:53", resolver_ip)).await.ok()?;
let start = Instant::now();
sock.send(&encoded).await.ok()?;
let mut buf = [0u8; 4096];
match tokio::time::timeout(Duration::from_secs(2), sock.recv(&mut buf)).await {
Ok(Ok(n)) => {
if let Some(resp) = DnsPacket::decode(&buf[..n]) {
// Check if RCODE == 0 (NOERROR) and it has answers
let rcode = resp.flags & 0x000F;
if rcode == 0 && !resp.answers.is_empty() {
return Some(start.elapsed().as_millis() as u64);
}
}
None
},
_ => None,
}
}
pub async fn run_dns_prober(domain: &str) -> Result<Vec<DnsProbeResult>, String> {
if domain.is_empty() {
return Err("Please enter the tunnel domain first (e.g. tunnel.myvpn.com)".into());
}
let tasks: Vec<_> = PUBLIC_DNS_SERVERS
.iter()
.map(|(name, ip)| {
let domain = domain.to_string();
let name = name.to_string();
let ip = ip.to_string();
tokio::spawn(async move {
let latency_ms = probe_resolver(&domain, &ip).await;
DnsProbeResult { name, ip, latency_ms }
})
})
.collect();
let mut results = Vec::with_capacity(tasks.len());
for task in tasks {
if let Ok(r) = task.await {
results.push(r);
}
}
results.sort_by_key(|r| r.latency_ms.unwrap_or(u64::MAX));
Ok(results)
}

View File

@ -4,6 +4,8 @@ pub mod framing;
pub mod protocol;
pub mod relay;
pub mod resumption;
pub mod dns;
pub mod dns_prober;
pub use crypto::NoiseRole;
pub use framing::{TrafficProfile, PaddingStrategy};

View File

@ -160,6 +160,10 @@ impl ProtocolMachine {
self.cc.cwnd_packets() as usize
}
pub fn on_send(&mut self, bytes: u64) {
self.cc.on_send(bytes);
}
pub fn state(&self) -> OstpState {
self.state
}
@ -388,14 +392,22 @@ impl ProtocolMachine {
self.last_recv_advance = Instant::now();
} else {
// Gap detected
if self.reorder_buffer.len() < self.max_reorder_buffer {
self.reorder_buffer.insert(nonce, action);
} else {
tracing::warn!("Reorder buffer full ({}/{}), dropping frame nonce={}",
self.reorder_buffer.len(), self.max_reorder_buffer, nonce
if self.reorder_buffer.len() >= self.max_reorder_buffer {
tracing::warn!("Reorder buffer full ({}/{}), dropping new frame nonce={} to wait for recovery of nonce={}",
self.reorder_buffer.len(), self.max_reorder_buffer, nonce, self.expected_recv_nonce
);
}
if nonce >= self.expected_recv_nonce {
if self.reorder_buffer.len() < self.max_reorder_buffer {
self.reorder_buffer.insert(nonce, action);
} else {
tracing::warn!("Reorder buffer still full after gap recovery, dropping frame nonce={}", nonce);
}
} else {
tracing::debug!("Frame nonce={} arrived too late after gap recovery, dropping", nonce);
}
// Rate-limited NACK: send at most once per 30ms to prevent retransmit storms.
// Under high load with natural UDP reordering, sending a NACK per packet
// causes exponential retransmit explosion that saturates the channel.
@ -507,32 +519,6 @@ impl ProtocolMachine {
fn handle_tick(&mut self) -> Result<ProtocolAction, ProtocolError> {
let mut actions = Vec::new();
// ── Gap Recovery ──────────────────────────────────────────────
// If expected_recv_nonce hasn't advanced for 500ms+ and there
// are buffered frames waiting, the sender likely evicted the lost
// frame from sent_history. Skip the gap to restore data flow.
// This trades a small amount of data loss for connection liveness.
if !self.reorder_buffer.is_empty()
&& self.last_recv_advance.elapsed() > Duration::from_millis(500)
{
if let Some(&first_buffered) = self.reorder_buffer.keys().next() {
let skipped = first_buffered.saturating_sub(self.expected_recv_nonce);
self.expected_recv_nonce = first_buffered;
self.last_recv_advance = Instant::now();
let mut delivered = 0u64;
while let Some(buffered_action) = self.reorder_buffer.remove(&self.expected_recv_nonce) {
actions.push(buffered_action);
self.expected_recv_nonce = self.expected_recv_nonce.saturating_add(1);
delivered += 1;
}
self.ack_pending = true;
tracing::debug!("Gap recovery: skipped {} lost frames, delivered {} buffered frames (reorder_buf={})",
skipped, delivered, self.reorder_buffer.len()
);
}
}
// ── Pending ACK flush ─────────────────────────────────────────
if let Some(ack_frame) = self.build_ack_if_due()? {
actions.push(ProtocolAction::SendDatagram(ack_frame));
@ -677,6 +663,9 @@ impl ProtocolMachine {
}
fn push_sent_frame(&mut self, nonce: u64, bytes: Bytes, is_retransmittable: bool) {
if is_retransmittable {
self.cc.on_send(bytes.len() as u64);
}
self.sent_history.push_back(SentFrame {
nonce,
bytes,

View File

@ -28,6 +28,10 @@ android {
targetSdk = flutter.targetSdkVersion
versionCode = flutter.versionCode
versionName = flutter.versionName
ndk {
abiFilters += listOf("armeabi-v7a", "arm64-v8a", "x86_64")
}
}
buildTypes {
@ -35,6 +39,7 @@ android {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig = signingConfigs.getByName("debug")
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
}
}
}

View File

@ -0,0 +1,3 @@
-keep class net.ostp.client.OstpClientSdk { *; }
-keep class com.ospab.ostp_client.OstpVpnService { *; }
-keep class com.ospab.ostp_client.MainActivity { *; }

View File

@ -1,6 +1,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE"/>
@ -9,7 +10,8 @@
<application
android:label="ostp_client"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher"
android:icon="@mipmap/launcher_icon"
android:roundIcon="@mipmap/launcher_icon_round"
android:extractNativeLibs="true">
<activity
android:name=".MainActivity"
@ -32,6 +34,9 @@
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter>
<action android:name="android.service.quicksettings.action.QS_TILE_PREFERENCES"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
@ -42,6 +47,7 @@
<service
android:name=".OstpVpnService"
android:permission="android.permission.BIND_VPN_SERVICE"
android:foregroundServiceType="connectedDevice"
android:exported="false">
<intent-filter>
<action android:name="android.net.VpnService"/>
@ -51,7 +57,7 @@
<!-- Quick Settings Tile -->
<service
android:name=".OstpTileService"
android:icon="@mipmap/ic_launcher"
android:icon="@mipmap/launcher_icon"
android:label="OSTP VPN"
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE"
android:exported="true">

View File

@ -95,6 +95,15 @@ class MainActivity : FlutterActivity() {
result.error("ERROR", e.message, null)
}
}
"runDnsProber" -> {
try {
val domain = call.argument<String>("domain") ?: "example.com"
val json = net.ostp.client.OstpClientSdk.nativeRunDnsProber(domain)
result.success(json)
} catch (e: Throwable) {
result.error("ERROR", e.message, null)
}
}
"getInstalledApps" -> {
try {
val pm = packageManager
@ -133,6 +142,6 @@ class MainActivity : FlutterActivity() {
if (pendingConfigJson != null) {
intent.putExtra("configJson", pendingConfigJson)
}
startService(intent)
androidx.core.content.ContextCompat.startForegroundService(this, intent)
}
}

View File

@ -34,6 +34,19 @@ class OstpTileService : TileService() {
val configJson = prefs.getString("latest_config_json", null)
if (configJson != null) {
// Check if VPN consent is needed
val vpnIntent = android.net.VpnService.prepare(this)
if (vpnIntent != null) {
// Consent needed, launch app
val appIntent = packageManager.getLaunchIntentForPackage(packageName)?.apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
}
if (appIntent != null) {
startActivityAndCollapse(appIntent)
}
return
}
val startIntent = Intent(this, OstpVpnService::class.java).apply {
action = "START"
putExtra("configJson", configJson)

View File

@ -16,6 +16,7 @@ import java.io.IOException
import androidx.annotation.Keep
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.app.ServiceCompat
@Keep
class OstpVpnService : VpnService() {
@ -43,6 +44,7 @@ class OstpVpnService : VpnService() {
private var vpnInterface: ParcelFileDescriptor? = null
private var wakeLock: PowerManager.WakeLock? = null
private var networkCallback: android.net.ConnectivityManager.NetworkCallback? = null
override fun onCreate() {
super.onCreate()
@ -55,7 +57,7 @@ class OstpVpnService : VpnService() {
if (action == "START") {
val configJson = intent.getStringExtra("configJson") ?: return START_NOT_STICKY
// Launch foreground immediately so Android doesn't kill us
startForeground(NOTIF_ID, buildNotification(connecting = true))
ServiceCompat.startForeground(this, NOTIF_ID, buildNotification(connecting = true), ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE)
startVpn(configJson)
} else if (action == "STOP") {
stopVpn()
@ -144,6 +146,41 @@ class OstpVpnService : VpnService() {
}
}
private fun registerNetworkCallback() {
if (networkCallback != null) return
try {
val cm = getSystemService(android.content.Context.CONNECTIVITY_SERVICE) as android.net.ConnectivityManager
networkCallback = object : android.net.ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: android.net.Network) {
super.onAvailable(network)
OstpClientSdk.notifyNetworkChanged()
}
override fun onLost(network: android.net.Network) {
super.onLost(network)
OstpClientSdk.notifyNetworkChanged()
}
}
val request = android.net.NetworkRequest.Builder()
.addCapability(android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET)
.build()
cm.registerNetworkCallback(request, networkCallback!!)
} catch (e: Throwable) {
Log.e("OstpVpnService", "Failed to register NetworkCallback", e)
}
}
private fun unregisterNetworkCallback() {
try {
if (networkCallback != null) {
val cm = getSystemService(android.content.Context.CONNECTIVITY_SERVICE) as android.net.ConnectivityManager
cm.unregisterNetworkCallback(networkCallback!!)
networkCallback = null
}
} catch (e: Throwable) {
Log.e("OstpVpnService", "Failed to unregister NetworkCallback", e)
}
}
private fun startVpn(configJson: String) {
if (vpnInterface != null) return
@ -163,7 +200,12 @@ class OstpVpnService : VpnService() {
.addDnsServer(dnsServer)
.setMtu(Math.max(1280, json.optJSONObject("ostp")?.optInt("mtu", 1140) ?: 1140))
// Always add fallback IPv4 DNS servers
try { builder.addDnsServer("1.1.1.1") } catch (e: Throwable) {}
try { builder.addDnsServer("8.8.8.8") } catch (e: Throwable) {}
// NOTE: Do NOT add IPv6 DNS servers here — Android would send DNS
// queries over IPv6, but our smoltcp TUN stack processes them as
// IPv4 only, causing all DNS to silently fail on LTE (IPv6-only networks).
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
builder.allowBypass()
@ -230,8 +272,13 @@ class OstpVpnService : VpnService() {
} catch (e: Throwable) {
Log.e("OstpVpnService", "Error starting VPN", e)
android.os.Handler(android.os.Looper.getMainLooper()).post {
android.widget.Toast.makeText(applicationContext, "VPN Error: ${e.message}", android.widget.Toast.LENGTH_LONG).show()
}
stopVpn()
}
registerNetworkCallback()
}
private fun stopVpn() {
@ -248,6 +295,7 @@ class OstpVpnService : VpnService() {
stopForeground(true)
OstpTileService.requestListeningState(applicationContext)
unregisterNetworkCallback()
stopSelf()
}

View File

@ -46,4 +46,12 @@ object OstpClientSdk {
@Keep
@JvmStatic
external fun addLog(logMsg: String)
@Keep
@JvmStatic
external fun notifyNetworkChanged()
@Keep
@JvmStatic
external fun nativeRunDnsProber(domain: String): String
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
</adaptive-icon>

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#08080F</color>
</resources>

View File

@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#fff</color>
</resources>

View File

@ -1,2 +1,2 @@
org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
org.gradle.jvmargs=-Xmx4G -XX:MaxMetaspaceSize=1G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
android.useAndroidX=true

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 22 KiB

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