docs: complete v0.3.x documentation rewrite

ospab 2026-06-19 15:02:57 +03:00
parent f1d8fb5bfb
commit bce2dcddd1
8 changed files with 584 additions and 443 deletions

@ -4,110 +4,125 @@
[Russian / Русский](Configuration_ru) [Russian / Русский](Configuration_ru)
OSTP is configured via a single JSON file (supports `//` comments). The `"mode"` field determines whether it runs as a server or client. Starting from version 0.3.1, OSTP uses a modular configuration system based on **inbounds**, **outbounds**, and **routing rules**. This applies to both the server and the client. The configuration is written in JSON (comments with `//` are supported).
```bash ```bash
# Generate a default config with a random access key: # Generate a default configuration file
./ostp --init server # VPS ./ostp --init server
./ostp --init client # Local machine ./ostp --init client
# Validate without running: # Validate a configuration without running
./ostp --check ./ostp --check --config config.json
``` ```
--- ---
## Server Configuration ## Server Configuration
### Core Settings The server configuration defines how it listens for incoming connections (inbounds) and where it routes traffic (outbounds).
| Field | Type | Default | Description | ### Modular Structure
|---|---|---|---|
| `mode` | string | required | Must be `"server"` |
| `listen` | string \| string[] | `"0.0.0.0:50000"` | UDP bind address(es). Supports single string or array for multi-listener |
| `access_keys` | string[] | required | Valid access keys. Hot-reloaded every 5 seconds |
| `turn_server` | string | `null` | STUN/TURN server for NAT traversal |
| `debug` | bool | `false` | Verbose packet-level logging |
### Management API
| Field | Type | Default | Description |
|---|---|---|---|
| `api.enabled` | bool | `false` | Enable the REST Management API |
| `api.bind` | string | `"127.0.0.1:9090"` | API listen address |
| `api.token` | string | `""` | Bearer token for authentication |
See **[Management API](Management-API)** for full endpoint reference.
### Outbound Routing
Route server traffic through an upstream proxy (SOCKS5, HTTP CONNECT).
| Field | Type | Description | | Field | Type | Description |
|---|---|---| |---|---|---|
| `outbound.enabled` | bool | Enable upstream proxy | | `inbounds` | array | List of incoming listeners (`ostp`, `api`, `dns`). |
| `outbound.protocol` | string | `"socks5"` or `"http"` | | `outbounds` | array | List of outgoing proxies (`socks`, `direct`, `block`). |
| `outbound.address` | string | Proxy address | | `routing` | object | Rules to map incoming traffic to outbounds based on domains or IP CIDRs. |
| `outbound.port` | u16 | Proxy port | | `dns` | object | Built-in DNS server for AdBlocking and DoH forwarding (optional). |
| `outbound.default_action` | string | `"proxy"` or `"direct"` | | `debug` | bool | Enable verbose packet-level logging. |
| `outbound.rules` | array | Routing rules (see below) |
#### Routing Rules ### Server Inbounds
| Field | Type | Description | #### 1. OSTP Inbound
|---|---|---| The primary listener for OSTP connections.
| `domain_suffix` | string[] | Domains matching this suffix (e.g., `[".onion"]`) |
| `ip_cidr` | string[] | IP subnets (e.g., `["10.0.0.0/8"]`) |
| `action` | string | `"proxy"` or `"direct"` |
### Fallback Server (Anti-DPI)
Proxy unrecognized TCP connections to a web server, making OSTP look like a regular website during active probing.
| Field | Type | Default | Description |
|---|---|---|---|
| `fallback.enabled` | bool | `false` | Enable TCP fallback proxy |
| `fallback.listen` | string | `"0.0.0.0:443"` | TCP listen address |
| `fallback.target` | string | `"127.0.0.1:8080"` | Target web server (nginx, caddy) |
### Full Server Example
```jsonc ```jsonc
{ {
"mode": "server", "type": "ostp",
// Single address or array: ["0.0.0.0:50000", "[::]:50000"] "tag": "ostp-in",
"listen": "0.0.0.0:50000", "listen": "0.0.0.0",
"access_keys": [ "port": 50000,
"c8a6fde902b4e23910cde882b7cf1612" "access_keys": ["YOUR_SECRET_KEY"], // Array of keys
], "transport": {
"mode": "udp" // Optional. Modes: "udp", "uot" (UDP over TCP), or "wss" (WebSocket)
// Management REST API
"api": {
"enabled": true,
"bind": "127.0.0.1:9090",
"token": "your-secret-token"
}, },
// Upstream proxy routing
"outbound": {
"enabled": false,
"protocol": "socks5",
"address": "127.0.0.1",
"port": 9050,
"default_action": "direct",
"rules": [
{ "domain_suffix": [".onion"], "action": "proxy" }
]
},
// TCP fallback for anti-DPI camouflage
"fallback": { "fallback": {
"enabled": false, "enabled": false,
"listen": "0.0.0.0:443", "target": "127.0.0.1:8080" // Forward unauthenticated TCP probes to a real web server
"target": "127.0.0.1:8080" }
}, }
```
"debug": false #### 2. API Inbound
REST API listener for management panels.
```jsonc
{
"type": "api",
"tag": "api-in",
"listen": "127.0.0.1",
"port": 9090,
"token": "your-secret-token" // Optional Bearer token
}
```
#### 3. DNS Inbound (dnstt Tunneling)
A native `dnstt` server implementation that listens for DNS queries and extracts encapsulated OSTP traffic.
```jsonc
{
"type": "dns",
"tag": "dns-in",
"listen": "0.0.0.0:53",
"domain": "t.yourdomain.com",
"pubkey": "DNSTT_PUBKEY",
"privkey": "DNSTT_PRIVKEY"
}
```
### Server Outbounds
Servers route traffic directly to the internet by default, but can use upstream SOCKS5 proxies.
```jsonc
"outbounds": [
{ "type": "direct", "tag": "direct" },
{ "type": "block", "tag": "block" },
{
"type": "socks",
"tag": "tor-proxy",
"server": "127.0.0.1",
"port": 9050
}
]
```
### Server Routing
Routes traffic based on rules. If no rule matches, it falls back to `default_outbound`.
```jsonc
"routing": {
"default_outbound": "direct",
"rules": [
{ "domain_suffix": [".onion"], "outbound": "tor-proxy" },
{ "ip_cidr": ["10.0.0.0/8"], "outbound": "block" }
]
}
```
### Internal DNS / AdBlock
The server can run a built-in DNS server for clients, parsing AdBlock lists and resolving via DoH.
```jsonc
"dns": {
"enabled": true,
"local_port": 50053,
"doh_upstream": "https://cloudflare-dns.com/dns-query",
"adblock_urls": [
"https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts"
]
} }
``` ```
@ -115,110 +130,107 @@ Proxy unrecognized TCP connections to a web server, making OSTP look like a regu
## Client Configuration ## Client Configuration
### Core Settings The client listens locally (e.g., SOCKS5 or TUN) and sends traffic outbound to an OSTP server.
| Field | Type | Default | Description | ### Modular Structure
|---|---|---|---|
| `mode` | string | required | Must be `"client"` |
| `server` | string | required | Remote OSTP server (`host:port`) |
| `access_key` | string | required | Access key matching a server key |
| `socks5_bind` | string | `"127.0.0.1:1088"` | Local SOCKS5/HTTP proxy address |
| `debug` | bool | `false` | Verbose client logging |
### TUN Mode (Full-System VPN)
| Field | Type | Description | | Field | Type | Description |
|---|---|---| |---|---|---|
| `tun.enable` | bool | Enable TUN virtual adapter | | `version` | string | Configuration version (e.g., `"0.3.1"`). |
| `tun.wintun_path` | string | Path to `wintun.dll` (Windows only) | | `inbounds` | array | Local listeners (`local_proxy`, `tun`). |
| `tun.ipv4_address` | string | IP for the virtual adapter (e.g., `"10.1.0.2/24"`) | | `outbounds` | array | Outgoing connections (`ostp`, `direct`, `selector`, `urltest`). |
| `tun.dns` | string | DNS server for the tunnel | | `routing` | object | Rules to map local traffic to outbounds. |
| `log.level` | string | `"info"`, `"debug"`, or `"warn"`. |
### Exclusions ### Client Inbounds
| Field | Type | Description |
|---|---|---|
| `exclude.domains` | string[] | Domain suffixes to bypass |
| `exclude.ips` | string[] | IP/CIDR subnets to bypass |
| `exclude.processes` | string[] | Process names to bypass (Windows) |
### Multiplexing
| Field | Type | Description |
|---|---|---|
| `mux.enabled` | bool | Distribute streams across multiple sessions |
| `mux.sessions` | int | Number of parallel OSTP sessions |
### xHTTP Stealth (UoT) & XTLS-Reality
Bypass DPI whitelists by wrapping UDP traffic in an obfuscated TCP/TLS stream that looks like standard HTTP/1.1 traffic to the specified SNI, or use XTLS-Reality to masquerade the server as a legitimate TLS endpoint.
| Field | Type | Description |
|---|---|---|
| `transport.mode` | string | `"udp"` (default) or `"uot"` (UDP-over-TCP stealth) |
| `transport.stealth_sni` | string | Whitelisted SNI domain (see recommendations below) |
| `transport.stealth_port` | u16 | Target port (usually `443` or `80`) |
| `reality.enabled` | bool | Enable XTLS-Reality |
| `reality.pbk` | string | Reality public key |
| `reality.sid` | string | Reality short ID |
#### Recommended SNIs for highly censored regions (e.g. RU/CN/IR)
Instead of common domains, try these robust endpoints that DPI systems are hesitant to block:
- **Government / Municipal:** `gosuslugi.ru`, `nalog.gov.ru`, `mos.ru`
- **Banking / Finance:** `sberbank.ru`, `api.sberbank.ru`, `tinkoff.ru`
- **System Updates / Telemetry:** `update.googleapis.com`, `telemetry.microsoft.com`
- **Static CDNs:** `yastatic.net`, `mc.yandex.ru`, `st.mycdn.me`, `sso.passport.yandex.ru`
- **Portals:** `vk.com`, `mail.ru`, `ya.ru`
### Full Client Example
#### 1. Local Proxy (SOCKS5 / HTTP)
```jsonc ```jsonc
{ {
"mode": "client", "type": "local_proxy",
"server": "example.com:50000", "tag": "socks-in",
"access_key": "c8a6fde902b4e23910cde882b7cf1612", "protocol": "socks", // "socks" or "http"
"socks5_bind": "127.0.0.1:1088", "listen": "127.0.0.1",
"port": 1088
"tun": {
"enable": true,
"dns": "1.1.1.1"
},
"exclude": {
"domains": ["bank.com"],
"ips": ["192.168.0.0/16"],
"processes": ["steam.exe"]
},
"mux": {
"enabled": false,
"sessions": 2
},
"transport": {
"mode": "uot",
"stealth_sni": "sberbank.ru",
"stealth_port": 443
},
"reality": {
"enabled": false,
"pbk": "",
"sid": ""
},
"debug": false
} }
``` ```
--- #### 2. TUN Interface
Native system-level routing. Requires elevated privileges.
```jsonc
{
"type": "tun",
"tag": "tun-in",
"auto_route": true,
"mtu": 1140
}
```
## Environment Variables ### Client Outbounds
| Variable | Description | #### 1. OSTP Outbound
|---|---| Connects to an OSTP server.
| `RUST_LOG` | Logging filter (e.g., `RUST_LOG=ostp_server=debug`) |
--- ```jsonc
{
"type": "ostp",
"tag": "proxy",
"server": "192.168.1.100",
"port": 50000,
"access_key": "YOUR_SECRET_KEY",
"transport": {
"type": "udp" // "udp", "uot" (UDP over TCP), or "dns"
},
"multiplex": {
"enabled": true,
"connections": 4
}
}
```
[← Installation](Installation) | [Management API →](Management-API) **DNS Transport (`dnstt`):**
If using DNS transport:
```jsonc
"transport": {
"type": "dns",
"domain": "t.yourdomain.com",
"resolver": "1.1.1.1",
"pubkey": "DNSTT_PUBKEY"
}
```
#### 2. Direct / Block / Socks
Clients can also define `direct` (bypass proxy), `block` (drop traffic), or `socks` outbounds.
#### 3. Selector / URLTest
For load balancing or manual switching between multiple `ostp` outbounds.
```jsonc
{
"type": "selector",
"tag": "select",
"outbounds": ["server1", "server2"],
"default": "server1"
}
```
```jsonc
{
"type": "urltest",
"tag": "auto-balancer",
"outbounds": ["server1", "server2"],
"url": "http://cp.cloudflare.com",
"interval": "5m"
}
```
### Client Routing
Identical to server routing.
```jsonc
"routing": {
"default_outbound": "proxy",
"rules": [
{ "domain_suffix": ["google.com", "youtube.com"], "outbound": "proxy" },
{ "ip_cidr": ["192.168.0.0/16"], "outbound": "direct" }
]
}
```

@ -2,112 +2,127 @@
![GitHub Release](https://img.shields.io/github/v/release/ospab/ostp?style=flat-square&color=blue) ![GitHub Release](https://img.shields.io/github/v/release/ospab/ostp?style=flat-square&color=blue)
[English version](Configuration) [English](Configuration)
OSTP настраивается через единый JSON-файл (поддерживает `//` комментарии). Поле `"mode"` определяет режим работы — сервер или клиент. Начиная с версии 0.3.1, OSTP использует модульную систему конфигурации, основанную на **inbounds** (входящие соединения), **outbounds** (исходящие соединения) и **routing** (правила маршрутизации). Это относится как к серверу, так и к клиенту. Конфигурация пишется в формате JSON (поддерживаются комментарии `//`).
```bash ```bash
# Генерация конфига с случайным ключом доступа: # Генерация базового конфига
./ostp --init server # VPS ./ostp --init server
./ostp --init client # Локальная машина ./ostp --init client
# Проверка конфига без запуска: # Проверка конфигурации на ошибки
./ostp --check ./ostp --check --config config.json
``` ```
--- ---
## Конфигурация сервера ## Конфигурация сервера
### Основные настройки Конфигурация сервера определяет порты и протоколы для прослушивания (inbounds) и куда направляется исходящий трафик (outbounds).
| Поле | Тип | По умолчанию | Описание | ### Модульная структура
|---|---|---|---|
| `mode` | string | обязательно | Должно быть `"server"` |
| `listen` | string \| string[] | `"0.0.0.0:50000"` | UDP-адрес(а) для привязки. Поддерживает строку или массив для multi-listener |
| `access_keys` | string[] | обязательно | Валидные ключи доступа. Автоматически перезагружаются каждые 5 секунд |
| `turn_server` | string | `null` | STUN/TURN-сервер для NAT traversal |
| `debug` | bool | `false` | Подробное логирование на уровне пакетов |
### API управления
| Поле | Тип | По умолчанию | Описание |
|---|---|---|---|
| `api.enabled` | bool | `false` | Включить REST API управления |
| `api.bind` | string | `"127.0.0.1:9090"` | Адрес для API |
| `api.token` | string | `""` | Bearer-токен для аутентификации |
Полный справочник: **[API управления](Management-API_ru)**.
### Маршрутизация исходящего трафика
Направление серверного трафика через вышестоящий прокси (SOCKS5, HTTP CONNECT).
| Поле | Тип | Описание | | Поле | Тип | Описание |
|---|---|---| |---|---|---|
| `outbound.enabled` | bool | Включить вышестоящий прокси | | `inbounds` | array | Список слушателей (`ostp`, `api`, `dns`). |
| `outbound.protocol` | string | `"socks5"` или `"http"` | | `outbounds` | array | Список исходящих прокси (`socks`, `direct`, `block`). |
| `outbound.address` | string | Адрес прокси | | `routing` | object | Правила перенаправления трафика в outbounds на основе доменов или IP CIDR. |
| `outbound.port` | u16 | Порт прокси | | `dns` | object | Встроенный DNS-сервер для AdBlock и DoH форвардинга (опционально). |
| `outbound.default_action` | string | `"proxy"` или `"direct"` | | `debug` | bool | Включить подробное логгирование пакетов. |
| `outbound.rules` | array | Правила маршрутизации (см. ниже) |
#### Правила маршрутизации ### Server Inbounds (Входящие подключения)
| Поле | Тип | Описание | #### 1. OSTP Inbound
|---|---|---| Основной слушатель для соединений OSTP.
| `domain_suffix` | string[] | Домены, срабатывающие на правило (напр. `[".onion"]`) |
| `ip_cidr` | string[] | IP-подсети (напр. `["10.0.0.0/8"]`) |
| `action` | string | `"proxy"` или `"direct"` |
### Fallback-сервер (анти-DPI)
Проксирование нераспознанных TCP-соединений на веб-сервер, что делает OSTP неотличимым от обычного сайта при активном зондировании.
| Поле | Тип | По умолчанию | Описание |
|---|---|---|---|
| `fallback.enabled` | bool | `false` | Включить TCP fallback proxy |
| `fallback.listen` | string | `"0.0.0.0:443"` | TCP-адрес для прослушивания |
| `fallback.target` | string | `"127.0.0.1:8080"` | Целевой веб-сервер (nginx, caddy) |
### Полный пример сервера
```jsonc ```jsonc
{ {
"mode": "server", "type": "ostp",
// Один адрес или массив: ["0.0.0.0:50000", "[::]:50000"] "tag": "ostp-in",
"listen": "0.0.0.0:50000", "listen": "0.0.0.0",
"access_keys": [ "port": 50000,
"c8a6fde902b4e23910cde882b7cf1612" "access_keys": ["ВАШ_СЕКРЕТНЫЙ_КЛЮЧ"], // Массив ключей
], "transport": {
"mode": "udp" // Доступно: "udp", "uot" (UDP over TCP), или "wss" (WebSocket)
// REST API управления
"api": {
"enabled": true,
"bind": "127.0.0.1:9090",
"token": "ваш-секретный-токен"
}, },
// Маршрутизация через вышестоящий прокси
"outbound": {
"enabled": false,
"protocol": "socks5",
"address": "127.0.0.1",
"port": 9050,
"default_action": "direct",
"rules": [
{ "domain_suffix": [".onion"], "action": "proxy" }
]
},
// TCP fallback для камуфляжа от DPI
"fallback": { "fallback": {
"enabled": false, "enabled": false,
"listen": "0.0.0.0:443", "target": "127.0.0.1:8080" // Перенаправление неавторизованного TCP трафика на веб-сервер
"target": "127.0.0.1:8080" }
}, }
```
"debug": false #### 2. API Inbound
Слушатель REST API для панелей управления.
```jsonc
{
"type": "api",
"tag": "api-in",
"listen": "127.0.0.1",
"port": 9090,
"token": "ваш-секретный-токен" // Опционально (Bearer token)
}
```
#### 3. DNS Inbound (Туннелирование dnstt)
Нативная реализация `dnstt` сервера, которая слушает DNS-запросы и извлекает инкапсулированный трафик OSTP.
```jsonc
{
"type": "dns",
"tag": "dns-in",
"listen": "0.0.0.0:53",
"domain": "t.yourdomain.com",
"pubkey": "DNSTT_PUBKEY",
"privkey": "DNSTT_PRIVKEY"
}
```
### Server Outbounds (Исходящие подключения)
По умолчанию сервер направляет трафик напрямую в интернет, но может использовать вышестоящие SOCKS5 прокси.
```jsonc
"outbounds": [
{ "type": "direct", "tag": "direct" },
{ "type": "block", "tag": "block" },
{
"type": "socks",
"tag": "tor-proxy",
"server": "127.0.0.1",
"port": 9050
}
]
```
### Server Routing (Маршрутизация)
Маршрутизирует трафик по правилам. Если ни одно правило не совпало, используется `default_outbound`.
```jsonc
"routing": {
"default_outbound": "direct",
"rules": [
{ "domain_suffix": [".onion"], "outbound": "tor-proxy" },
{ "ip_cidr": ["10.0.0.0/8"], "outbound": "block" }
]
}
```
### Внутренний DNS / AdBlock
Сервер может запустить встроенный DNS для клиентов, парсить списки AdBlock и резолвить через DoH.
```jsonc
"dns": {
"enabled": true,
"local_port": 50053,
"doh_upstream": "https://cloudflare-dns.com/dns-query",
"adblock_urls": [
"https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts"
]
} }
``` ```
@ -115,110 +130,107 @@ OSTP настраивается через единый JSON-файл (подд
## Конфигурация клиента ## Конфигурация клиента
### Основные настройки Клиент слушает локальные порты (SOCKS5 или TUN) и отправляет трафик на сервер OSTP.
| Поле | Тип | По умолчанию | Описание | ### Модульная структура
|---|---|---|---|
| `mode` | string | обязательно | Должно быть `"client"` |
| `server` | string | обязательно | Адрес удалённого OSTP-сервера (`host:port`) |
| `access_key` | string | обязательно | Ключ доступа, совпадающий с ключом на сервере |
| `socks5_bind` | string | `"127.0.0.1:1088"` | Локальный адрес SOCKS5/HTTP прокси |
| `debug` | bool | `false` | Подробное логирование клиента |
### TUN-режим (полносистемный VPN)
| Поле | Тип | Описание | | Поле | Тип | Описание |
|---|---|---| |---|---|---|
| `tun.enable` | bool | Включить виртуальный TUN-адаптер | | `version` | string | Версия конфига (например, `"0.3.1"`). |
| `tun.wintun_path` | string | Путь к `wintun.dll` (только Windows) | | `inbounds` | array | Локальные слушатели (`local_proxy`, `tun`). |
| `tun.ipv4_address` | string | IP виртуального адаптера (напр. `"10.1.0.2/24"`) | | `outbounds` | array | Исходящие подключения (`ostp`, `direct`, `selector`, `urltest`). |
| `tun.dns` | string | DNS-сервер для туннеля | | `routing` | object | Правила перенаправления локального трафика в outbounds. |
| `log.level` | string | `"info"`, `"debug"` или `"warn"`. |
### Исключения ### Client Inbounds
| Поле | Тип | Описание |
|---|---|---|
| `exclude.domains` | string[] | Суффиксы доменов для обхода |
| `exclude.ips` | string[] | IP/CIDR-подсети для обхода |
| `exclude.processes` | string[] | Имена процессов для обхода (Windows) |
### Мультиплексирование
| Поле | Тип | Описание |
|---|---|---|
| `mux.enabled` | bool | Распределение потоков по нескольким сессиям |
| `mux.sessions` | int | Количество параллельных OSTP-сессий |
### xHTTP Стелс (UoT) & XTLS-Reality
Обход белых списков ТСПУ/DPI за счёт заворачивания UDP-трафика в обфусцированный TCP/TLS стрим, который выглядит как обычный HTTP/1.1 трафик к разрешённому SNI. Либо использование XTLS-Reality для полноценной маскировки сервера под существующий TLS-эндпоинт.
| Поле | Тип | Описание |
|---|---|---|
| `transport.mode` | string | `"udp"` (по умолчанию) или `"uot"` (UDP-over-TCP стелс) |
| `transport.stealth_sni` | string | Домен из белого списка (см. рекомендации ниже) |
| `transport.stealth_port` | u16 | Целевой порт (обычно `443` или `80`) |
| `reality.enabled` | bool | Включить XTLS-Reality |
| `reality.pbk` | string | Публичный ключ Reality |
| `reality.sid` | string | Short ID для Reality |
#### Рекомендованные SNI для стран с активными блокировками (ТСПУ)
Вместо заезженных доменов используйте те, блокировка которых критична для инфраструктуры или бизнеса:
- **Гос. сектор:** `gosuslugi.ru`, `nalog.gov.ru`, `mos.ru`
- **Банки:** `sberbank.ru`, `api.sberbank.ru`, `tinkoff.ru`
- **Системные CDN и телеметрия:** `update.googleapis.com`, `telemetry.microsoft.com`
- **Крупные статические CDN:** `yastatic.net`, `mc.yandex.ru`, `st.mycdn.me`, `sso.passport.yandex.ru`
- **Порталы:** `vk.com`, `mail.ru`, `ya.ru`
### Полный пример клиента
#### 1. Локальный прокси (SOCKS5 / HTTP)
```jsonc ```jsonc
{ {
"mode": "client", "type": "local_proxy",
"server": "example.com:50000", "tag": "socks-in",
"access_key": "c8a6fde902b4e23910cde882b7cf1612", "protocol": "socks", // "socks" или "http"
"socks5_bind": "127.0.0.1:1088", "listen": "127.0.0.1",
"port": 1088
"tun": {
"enable": true,
"dns": "1.1.1.1"
},
"exclude": {
"domains": ["bank.com"],
"ips": ["192.168.0.0/16"],
"processes": ["steam.exe"]
},
"mux": {
"enabled": false,
"sessions": 2
},
"transport": {
"mode": "uot",
"stealth_sni": "sberbank.ru",
"stealth_port": 443
},
"reality": {
"enabled": false,
"pbk": "",
"sid": ""
},
"debug": false
} }
``` ```
--- #### 2. TUN Интерфейс
Полноценная маршрутизация через виртуальный сетевой адаптер. Требует прав администратора.
```jsonc
{
"type": "tun",
"tag": "tun-in",
"auto_route": true,
"mtu": 1140
}
```
## Переменные окружения ### Client Outbounds
| Переменная | Описание | #### 1. OSTP Outbound
|---|---| Подключение к удаленному серверу OSTP.
| `RUST_LOG` | Фильтр логирования (напр. `RUST_LOG=ostp_server=debug`) |
--- ```jsonc
{
"type": "ostp",
"tag": "proxy",
"server": "192.168.1.100",
"port": 50000,
"access_key": "ВАШ_СЕКРЕТНЫЙ_КЛЮЧ",
"transport": {
"type": "udp" // "udp", "uot" (UDP over TCP), или "dns"
},
"multiplex": {
"enabled": true,
"connections": 4
}
}
```
[← Установка](Installation_ru) | [API управления →](Management-API_ru) **DNS Транспорт (`dnstt`):**
При использовании DNS туннеля:
```jsonc
"transport": {
"type": "dns",
"domain": "t.yourdomain.com",
"resolver": "1.1.1.1",
"pubkey": "DNSTT_PUBKEY"
}
```
#### 2. Direct / Block / Socks
Клиенты также могут использовать `direct` (в обход прокси), `block` (блокировка) или `socks`.
#### 3. Selector / URLTest
Для балансировки или ручного переключения между серверами `ostp`.
```jsonc
{
"type": "selector",
"tag": "select",
"outbounds": ["server1", "server2"],
"default": "server1"
}
```
```jsonc
{
"type": "urltest",
"tag": "auto-balancer",
"outbounds": ["server1", "server2"],
"url": "http://cp.cloudflare.com",
"interval": "5m"
}
```
### Client Routing (Маршрутизация)
Полностью аналогична серверной.
```jsonc
"routing": {
"default_outbound": "proxy",
"rules": [
{ "domain_suffix": ["google.com", "youtube.com"], "outbound": "proxy" },
{ "ip_cidr": ["192.168.0.0/16", "10.0.0.0/8"], "outbound": "direct" }
]
}
```

@ -1,51 +1,86 @@
# DNS Tunneling with OSTP # DNS Tunneling with OSTP (Native dnstt)
OSTP operates over UDP and perfectly masks its traffic as random noise. In some environments (like captive portals, restricted corporate networks, or public Wi-Fi hotspots), standard ports may be blocked, but DNS queries (UDP port 53) are often allowed through the firewall. OSTP natively implements the `dnstt` (DNS Tunnel) protocol. This allows you to encapsulate encrypted OSTP traffic inside standard DNS queries (`TXT` and `NULL` records), which can bypass restrictive firewalls or captive portals that only allow UDP port 53.
You can exploit this by running OSTP over UDP port 53, effectively bypassing the firewall. This is often referred to as "DNS Tunneling" or "Port 53 bypass". Unlike other tools, you **do not** need to install a standalone `dnstt-server` or `dnstt-client`. The OSTP server has a built-in `dnstt` listener, and the client natively encodes payloads.
## Prerequisites ## Prerequisites
1. A VPS where no other DNS server (like `systemd-resolved`, `bind9`, `dnsmasq`) is listening on the public IP at port `53`. 1. A domain name (e.g., `yourdomain.com`).
2. OSTP server installed and configured. 2. You need to configure **NS records** to delegate a sub-domain to your server's IP address.
## Server Configuration ## Step 1: DNS Setup
You need to change the `listen` directive in your server's `config.json` to bind to port 53. 1. Go to your domain registrar's DNS panel.
2. Create an **A record** pointing to your server's IP address:
- Type: `A`
- Name: `tunsrv`
- Value: `YOUR_SERVER_IP`
3. Create an **NS record** delegating the tunneling sub-domain to that A record:
- Type: `NS`
- Name: `t`
- Value: `tunsrv.yourdomain.com`
This means any DNS query for `*.t.yourdomain.com` will be sent directly to your server!
## Step 2: Generate Keys
DNS Tunneling uses its own Ed25519 keypair to prevent abuse. You must generate a pubkey/privkey pair (using the `dnstt-server -gen-key` tool or OSTP API).
## Step 3: Server Configuration
Add the `dns` inbound to your server's `config.json`. The server must run with sufficient privileges to bind to port `53` (e.g., using `sudo setcap 'cap_net_bind_service=+ep' /path/to/ostp`).
```jsonc ```jsonc
{ {
"mode": "server", "mode": "server",
"listen": "0.0.0.0:53", "inbounds": [
"access_keys": ["YOUR_SECRET_KEY"] // Your normal OSTP listener
{
"type": "ostp",
"tag": "ostp-in",
"listen": "0.0.0.0",
"port": 50000,
"access_keys": ["YOUR_SECRET_KEY"]
},
// The native dnstt listener
{
"type": "dns",
"tag": "dns-in",
"listen": "0.0.0.0:53",
"domain": "t.yourdomain.com",
"pubkey": "YOUR_PUBKEY_HERE",
"privkey": "YOUR_PRIVKEY_HERE"
}
],
"outbounds": [
{ "type": "direct", "tag": "direct" }
]
} }
``` ```
If you are running the server as a non-root user on Linux, binding to port 53 (a privileged port) will result in a "Permission denied" error. You must either run OSTP as root or grant the binary the `CAP_NET_BIND_SERVICE` capability: ## Step 4: Client Configuration
```bash On the client, configure your `ostp` outbound to use the `dns` transport. You must specify the exact domain, a public resolver (like `1.1.1.1` or `8.8.8.8`), and the server's public key.
sudo setcap 'cap_net_bind_service=+ep' /path/to/ostp
```
Restart your OSTP server.
## Client Configuration
On the client side, update your `outbounds` to point to port 53:
```jsonc ```jsonc
"outbounds": [ "outbounds": [
{ {
"type": "ostp", "type": "ostp",
"tag": "proxy", "tag": "proxy",
"server": "YOUR_SERVER_IP", "server": "YOUR_SERVER_IP", // Used for logical routing
"port": 53, "port": 50000,
"access_key": "YOUR_SECRET_KEY", "access_key": "YOUR_SECRET_KEY",
"transport": { "type": "udp" } "transport": {
"type": "dns",
"domain": "t.yourdomain.com",
"resolver": "1.1.1.1",
"pubkey": "YOUR_PUBKEY_HERE"
}
} }
] ]
``` ```
## Security Considerations ## Security Considerations
Because OSTP traffic does not look like standard DNS queries (it is pure random noise without standard DNS packet structures), advanced DPI (Deep Packet Inspection) systems may detect that this is not real DNS traffic and block it. However, simple port-based firewalls and standard captive portals will allow the connection without issues. Because OSTP traffic does not look like standard DNS queries (the TXT records contain high-entropy base32 noise), advanced DPI systems might flag it as an anomaly if they inspect the contents of DNS TXT records. However, for bypassing captive portals (hotel Wi-Fi, airplane Wi-Fi) or simple firewalls, it is incredibly effective.

@ -1,51 +1,86 @@
# DNS-туннелирование с помощью OSTP # DNS-туннелирование с OSTP (Нативный dnstt)
OSTP работает поверх UDP и маскирует свой трафик под случайный шум. В некоторых сетях (например, в публичном Wi-Fi с авторизацией (captive portals) или строгих корпоративных сетях) обычные порты могут быть заблокированы, но DNS-запросы (UDP порт 53) часто разрешены без ограничений. OSTP имеет нативную реализацию протокола `dnstt` (DNS Tunnel). Это позволяет инкапсулировать зашифрованный трафик OSTP внутри стандартных DNS-запросов (записи `TXT` и `NULL`), что позволяет обходить строгие файрволы или captive portals (авторизация в публичных Wi-Fi), которые пропускают только трафик по порту UDP 53.
Вы можете использовать это, настроив сервер OSTP на прослушивание UDP порта 53. Это позволит обойти блокировку по портам. В отличие от других инструментов, вам **не нужно** устанавливать сторонние программы вроде `dnstt-server` или `dnstt-client`. Сервер OSTP имеет встроенный слушатель `dnstt`, а клиент нативно кодирует трафик.
## Требования ## Требования
1. VPS, на котором никакой другой DNS-сервер (например, `systemd-resolved`, `bind9`, `dnsmasq`) не занимает публичный IP-адрес на порту `53`. 1. Собственное доменное имя (например, `yourdomain.com`).
2. Установленный OSTP сервер. 2. Настроенные **NS записи** для делегирования поддомена на IP-адрес вашего сервера.
## Настройка сервера ## Шаг 1: Настройка DNS
Измените параметр `listen` в вашем файле `config.json` на стороне сервера, чтобы прослушивать порт 53. 1. Зайдите в панель управления DNS вашего регистратора.
2. Создайте **A запись**, указывающую на IP вашего сервера:
- Тип: `A`
- Имя: `tunsrv`
- Значение: `IP_ВАШЕГО_СЕРВЕРА`
3. Создайте **NS запись**, которая делегирует поддомен туннеля на созданную выше A-запись:
- Тип: `NS`
- Имя: `t`
- Значение: `tunsrv.yourdomain.com`
Теперь любые DNS-запросы к `*.t.yourdomain.com` будут отправляться напрямую на ваш сервер!
## Шаг 2: Генерация ключей
Туннель DNS использует собственную пару ключей Ed25519 для предотвращения злоупотреблений. Вы должны сгенерировать публичный и приватный ключ (с помощью инструмента `dnstt-server -gen-key` или API OSTP).
## Шаг 3: Настройка Сервера
Добавьте inbound с типом `dns` в ваш файл `config.json` на сервере. Сервер должен быть запущен с правами, достаточными для прослушивания порта `53` (например, выдав права через `sudo setcap 'cap_net_bind_service=+ep' /path/to/ostp`).
```jsonc ```jsonc
{ {
"mode": "server", "mode": "server",
"listen": "0.0.0.0:53", "inbounds": [
"access_keys": ["ВАШ_КЛЮЧ"] // Обычный слушатель OSTP
{
"type": "ostp",
"tag": "ostp-in",
"listen": "0.0.0.0",
"port": 50000,
"access_keys": ["ВАШ_СЕКРЕТНЫЙ_КЛЮЧ"]
},
// Нативный слушатель dnstt
{
"type": "dns",
"tag": "dns-in",
"listen": "0.0.0.0:53",
"domain": "t.yourdomain.com",
"pubkey": "ВАШ_ПРИВАТНЫЙ_КЛЮЧ_ЗДЕСЬ",
"privkey": "ВАШ_ПРИВАТНЫЙ_КЛЮЧ_ЗДЕСЬ"
}
],
"outbounds": [
{ "type": "direct", "tag": "direct" }
]
} }
``` ```
Если вы запускаете сервер от обычного пользователя (не root) на Linux, попытка занять порт 53 (привилегированный порт) приведет к ошибке "Permission denied". Вы должны запустить OSTP от имени root или выдать бинарному файлу права `CAP_NET_BIND_SERVICE`: ## Шаг 4: Настройка Клиента
```bash На клиенте настройте outbound типа `ostp` на использование транспорта `dns`. Вы должны указать точный домен, публичный резолвер (например `1.1.1.1` или `8.8.8.8`) и публичный ключ сервера.
sudo setcap 'cap_net_bind_service=+ep' /путь/к/ostp
```
Перезапустите ваш OSTP сервер.
## Настройка клиента
На клиенте обновите конфигурацию `outbounds`, указав порт 53:
```jsonc ```jsonc
"outbounds": [ "outbounds": [
{ {
"type": "ostp", "type": "ostp",
"tag": "proxy", "tag": "proxy",
"server": "IP_СЕРВЕРА", "server": "IP_ВАШЕГО_СЕРВЕРА", // Для логической маршрутизации
"port": 53, "port": 50000,
"access_key": "ВАШ_КЛЮЧ", "access_key": "ВАШ_СЕКРЕТНЫЙ_КЛЮЧ",
"transport": { "type": "udp" } "transport": {
"type": "dns",
"domain": "t.yourdomain.com",
"resolver": "1.1.1.1",
"pubkey": "ВАШ_ПУБЛИЧНЫЙ_КЛЮЧ_ЗДЕСЬ"
}
} }
] ]
``` ```
## Предупреждение (DPI) ## Предупреждение (DPI)
Поскольку трафик OSTP не имеет структуры стандартных DNS-запросов (это чистый белый шум), продвинутые системы DPI (Deep Packet Inspection) могут обнаружить, что это не настоящий DNS-трафик, и заблокировать его. Тем не менее, простые файрволы (блокирующие всё, кроме 53 порта) и стандартные captive portals будут успешно пройдены. Поскольку трафик OSTP внутри DNS не похож на обычные читаемые текстовые записи (TXT-записи содержат base32 шум с высокой энтропией), продвинутые системы DPI могут распознать аномалию. Однако для обхода простых файрволов, captive portals в отелях или самолетах этот метод невероятно эффективен.

@ -8,28 +8,31 @@ OSTP includes a built-in REST API for remote server management. This API enables
## Enabling the API ## Enabling the API
Add the `api` block to your server `config.json`: Add an `api` inbound to your server `config.json`'s `inbounds` array:
```jsonc ```jsonc
{ {
"mode": "server", "mode": "server",
"listen": "0.0.0.0:50000", "inbounds": [
"access_keys": ["..."], {
"api": { "type": "api",
"enabled": true, "tag": "api-in",
"bind": "127.0.0.1:9090", "listen": "127.0.0.1",
"token": "your-secret-api-token" "port": 9090,
} "token": "your-secret-api-token"
}
]
} }
``` ```
| Field | Type | Default | Description | | Field | Type | Default | Description |
|---|---|---|---| |---|---|---|---|
| `enabled` | bool | `false` | Enable/disable the API server | | `type` | string | required | Must be `"api"` |
| `bind` | string | `"127.0.0.1:9090"` | Address and port for the API to listen on | | `listen` | string | required | Address for the API to listen on (e.g. `"127.0.0.1"`) |
| `token` | string | `""` | Bearer token for authentication. **Required for production.** | | `port` | u16 | required | Port for the API to listen on (e.g. `9090`) |
| `token` | string | `null` | Bearer token for authentication. **Required for production.** |
> ⚠️ **Security**: Always set a strong `token` in production. If empty, the API assumes a trusted local environment. > ⚠️ **Security**: Always set a strong `token` in production. If omitted, the API assumes a trusted local environment.
> 💡 **Tip**: Bind to `127.0.0.1` and use a reverse proxy (nginx/caddy) with TLS for remote access. > 💡 **Tip**: Bind to `127.0.0.1` and use a reverse proxy (nginx/caddy) with TLS for remote access.

@ -8,28 +8,31 @@ OSTP включает встроенный REST API для удалённого
## Включение API ## Включение API
Добавьте блок `api` в серверный `config.json`: Добавьте inbound с типом `api` в массив `inbounds` вашего серверного `config.json`:
```jsonc ```jsonc
{ {
"mode": "server", "mode": "server",
"listen": "0.0.0.0:50000", "inbounds": [
"access_keys": ["..."], {
"api": { "type": "api",
"enabled": true, "tag": "api-in",
"bind": "127.0.0.1:9090", "listen": "127.0.0.1",
"token": "ваш-секретный-токен" "port": 9090,
} "token": "ваш-секретный-токен"
}
]
} }
``` ```
| Поле | Тип | По умолчанию | Описание | | Поле | Тип | По умолчанию | Описание |
|---|---|---|---| |---|---|---|---|
| `enabled` | bool | `false` | Включить/выключить API-сервер | | `type` | string | обязательное | Должно быть `"api"` |
| `bind` | string | `"127.0.0.1:9090"` | Адрес и порт для API | | `listen` | string | обязательное | IP-адрес для прослушивания (например `"127.0.0.1"`) |
| `token` | string | `""` | Bearer-токен для аутентификации. **Обязателен для продакшена.** | | `port` | u16 | обязательное | Порт (например `9090`) |
| `token` | string | `null` | Bearer-токен для аутентификации. **Обязателен для продакшена.** |
> **Безопасность**: всегда устанавливайте надёжный `token` в продакшене. Если пустой, API считает окружение доверенным. > **Безопасность**: всегда устанавливайте надёжный `token` в продакшене. Если токен не указан, API считает окружение доверенным.
> **Совет**: привяжите к `127.0.0.1` и используйте реверс-прокси (nginx/caddy) с TLS для удалённого доступа. > **Совет**: привяжите к `127.0.0.1` и используйте реверс-прокси (nginx/caddy) с TLS для удалённого доступа.

@ -2,13 +2,15 @@
[Russian / Русский](Share-Links_ru) [Russian / Русский](Share-Links_ru)
OSTP supports sharing configuration profiles via standard URI links. These links can be easily imported into the CLI or GUI clients.
## Format ## Format
``` ```
ostp://ACCESS_KEY@HOST:PORT#LABEL ostp://ACCESS_KEY@HOST:PORT/?query_parameters#LABEL
``` ```
### Components ### Base Components
| Component | Required | Description | | Component | Required | Description |
|---|---|---| |---|---|---|
@ -17,27 +19,42 @@ ostp://ACCESS_KEY@HOST:PORT#LABEL
| `PORT` | Yes | Server port | | `PORT` | Yes | Server port |
| `LABEL` | No | URL-encoded server label | | `LABEL` | No | URL-encoded server label |
### Examples ### Query Parameters
You can customize the imported configuration using URL query parameters (`?key=value&...`).
| Parameter | Type | Default | Description |
|---|---|---|---|
| `type` | string | `udp` | Transport mode. Values: `udp`, `uot`, `dns` |
| `tun` | bool | `false` | Enable TUN interface routing (`true` / `false`) |
| `domain` | string | `null` | Required if `type=dns`. The tunneling domain |
| `pubkey` | string | `null` | Required if `type=dns`. The dnstt public key |
## Examples
**1. Basic UDP connection**
``` ```
ostp://my-secret-key@example.com:50000#My%20Server ostp://abc123456789@example.com:50000#My%20Server
ostp://abc123@192.168.1.100:50000
ostp://complex%2Fkey%3Dwith%20special@server.com:443#Production
``` ```
### Parsing Rules **2. UDP over TCP (UoT) with TUN enabled**
```
ostp://abc123456789@example.com:50000/?type=uot&tun=true#Gaming%20VPN
```
1. Scheme must be `ostp://` **3. DNS Tunneling**
2. Access key is extracted from the `username` component of the URL ```
3. Host and port from the `host` component ostp://abc123456789@1.1.1.1:53/?type=dns&domain=t.yourdomain.com&pubkey=f1...4a#DNS%20Bypass
4. Label (server name) from the `fragment` (`#`) ```
*(Note: For DNS, the HOST is usually a public resolver like `1.1.1.1` rather than your actual server IP).*
### Client Import ## Client Import
The OSTP GUI and CLI support importing share links: The OSTP GUI and CLI support importing share links:
- **GUI**: Paste into the import field on the Settings screen - **GUI**: Paste into the import field on the Settings screen.
- **CLI**: `ostp --import "ostp://key@host:port"` - **CLI**: `ostp --import "ostp://key@host:port/..."`
- **Instant Launch**: `ostp --url "ostp://key@host:port/..."` (Creates a temporary config and runs it).
--- ---

@ -2,13 +2,15 @@
[English / Английский](Share-Links) | [← Главная](Home_ru) [English / Английский](Share-Links) | [← Главная](Home_ru)
OSTP поддерживает шеринг профилей конфигурации через стандартные URI ссылки. Эти ссылки легко импортируются в CLI и GUI клиенты.
## Формат ## Формат
``` ```
ostp://КЛЮЧ_ДОСТУПА@ХОСТ:ПОРТ#МЕТКА ostp://КЛЮЧ_ДОСТУПА@ХОСТ:ПОРТ/?параметры_запроса#МЕТКА
``` ```
### Компоненты ### Базовые компоненты
| Компонент | Обязательно | Описание | | Компонент | Обязательно | Описание |
|---|---|---| |---|---|---|
@ -17,18 +19,40 @@ ostp://КЛЮЧ_ДОСТУПА@ХОСТ:ПОРТ#МЕТКА
| `ПОРТ` | Да | Порт сервера | | `ПОРТ` | Да | Порт сервера |
| `МЕТКА` | Нет | URL-кодированное название сервера | | `МЕТКА` | Нет | URL-кодированное название сервера |
### Примеры ### Параметры запроса (Query Parameters)
Вы можете настроить параметры импортируемого конфига с помощью URL-параметров (`?key=value&...`).
| Параметр | Тип | По умолчанию | Описание |
|---|---|---|---|
| `type` | string | `udp` | Режим транспорта. Значения: `udp`, `uot`, `dns` |
| `tun` | bool | `false` | Включить TUN-интерфейс (`true` / `false`) |
| `domain` | string | `null` | Обязателен при `type=dns`. Домен туннеля. |
| `pubkey` | string | `null` | Обязателен при `type=dns`. Публичный ключ dnstt. |
## Примеры
**1. Базовое UDP-подключение**
``` ```
ostp://мой-ключ@example.com:50000#Сервер%201 ostp://abc123456789@example.com:50000#Мой%20Сервер
ostp://abc123@192.168.1.100:50000
ostp://сложный%2Fключ@server.com:443#Продакшен
``` ```
### Импорт в клиент **2. UDP over TCP (UoT) с включенным TUN**
```
ostp://abc123456789@example.com:50000/?type=uot&tun=true#Игровой%20VPN
```
- **GUI**: Вставьте ссылку в поле импорта на экране настроек **3. DNS-туннель**
- **CLI**: `ostp --import "ostp://ключ@хост:порт"` ```
ostp://abc123456789@1.1.1.1:53/?type=dns&domain=t.yourdomain.com&pubkey=f1...4a#Обход%20Каптив-портала
```
*(Примечание: для DNS транспортом ХОСТ обычно является IP публичного резолвера (например `1.1.1.1`), а не вашего сервера).*
## Импорт в клиент
- **GUI**: Вставьте ссылку в поле импорта на экране настроек.
- **CLI**: `ostp --import "ostp://ключ@хост:порт/..."`
- **Быстрый запуск**: `ostp --url "ostp://ключ@хост:порт/..."` (создает временный конфиг и сразу запускает клиент).
--- ---