This commit is contained in:
2026-09-12 22:54:34 -03:00
parent 162a9dc2d9
commit ede2e9eb89
32 changed files with 8355 additions and 16 deletions
+5
View File
@@ -2,3 +2,8 @@
/BOT_PLAN.md
/SECURITY_REVIEW.md
/DragonCoreSSH-NewWEB.zip
/dist/
/.tmp-bhttp-harness.exe
/Dockerfile.build
/tunnel_pipe_test.go
/docker-build.sh
+214
View File
@@ -152,6 +152,9 @@ O instalador monta `/opt/sshpanel/logs` como tmpfs de 15 MiB quando possível, p
2222 SSH raw interno em 127.0.0.1 (não público)
53/udp DNS público para DNSTT, redirecionado para 5300/udp
5300/udp DNSTT interno
8880 BHTTP (BHP1/BHP2) — desativado por padrão; pode compartilhar 80/8080/443
7300 BTUN TCP — desativado por padrão; pode compartilhar 80/8080/443
7300/udp BTUN UDP — desativado por padrão
9090 Painel web + API pública /check
10086 Xray VLESS
10087 Xray VMess
@@ -278,6 +281,101 @@ Exemplo no `config.json`:
}
```
### BHTTP (BHP1 / BHP2)
O BHTTP é o transporte TCP ofuscado usado pelos apps da família DTunnel. O cliente abre um socket TCP comum, opcionalmente envia uma requisição HTTP como cobertura, e em seguida fala o enquadramento BHTTP (cabeçalho de 29 bytes) com os modos *probe*, *upload*, *download*, *batch* e *ACK*. O BHP2 adiciona *lanes* persistentes com `resume` e ACK cumulativo de upload.
Cada sessão BHTTP é entregue ao **servidor SSH embutido do próprio painel**, exatamente como o DNSTT faz. Não existe conexão com o `sshd` do sistema, nem com PAM ou `/etc/shadow`: as contas, validade, TOTP, `max_connections`, limites de banda e cotas de dados do painel valem sem nenhuma configuração extra.
#### Compartilhar as portas 80, 8080 e 443
O BHTTP pode atender **nas portas que o painel já usa**, sem porta dedicada e sem atrapalhar o resto. Isso funciona porque os três protocolos começam de formas incompatíveis: um quadro BHTTP começa com o número do modo (`0`–`5`), o SSH começa com `S` (`0x53`) e uma linha HTTP começa com a letra do método. O primeiro byte já separa os três.
Como um cliente de injeção HTTP pode mandar lixo antes do payload, um byte baixo sozinho não basta. Então o cabeçalho de 29 bytes também é validado e, nos dois modos que carregam assinatura — o *probe* que abre toda sessão e o *lane hello* do v2 — a assinatura (`BHP1`/`BHP2`, `BLN2`) é descriptografada e conferida. Como a chave vem do próprio session ID do cabeçalho, lixo não passa por acaso. Nada é consumido quando o veredito é negativo: a conexão segue para o caminho HTTP/SSH normal com os bytes intactos.
Ligue em **Configurações → BHTTP → Compartilhar as portas do painel**. Vale para `listen`, `extra_listen` e todos os encaminhadores TLS. Com isso ligado o campo **Listen** pode ficar vazio: o BHTTP passa a existir só nas portas compartilhadas.
Uma única coisa muda para os outros clientes: hoje a porta do proxy responde `HTTP/1.1 101` assim que o socket abre, antes de ler qualquer coisa; com o compartilhamento ligado ela espera os primeiros bytes do cliente (no máximo 3s) antes de decidir. Isso é necessário porque um cliente BHTTP não pode receber esse 101 sem querer. Todo cliente conhecido — de injeção HTTP ou BHTTP — envia seus bytes imediatamente ao conectar, e um cliente que não enviar nada em 3s cai no caminho antigo. Se algum cliente seu aguardar o 101 antes de falar, desmarque a opção.
Configure em **Configurações → BHTTP**:
- **Compartilhar as portas do painel** — aceita BHTTP em 80/8080 e 443 junto com SSH e injeção HTTP, como descrito acima.
- **Listen** — porta dedicada, um endereço por linha, opcional quando o compartilhamento está ligado. As portas 80 e 8080 pertencem ao proxy HTTP+SSH: para usá-las, ligue o compartilhamento em vez de listá-las aqui. O padrão, sem compartilhamento, é `0.0.0.0:8880`.
- **Session Timeout** — tempo sem tráfego antes de derrubar a sessão e fechar seu SSH. Também limita por quanto tempo um `resume` do BHP2 continua possível.
- **Max v2 Lanes Per Session** — teto de lanes simultâneas por sessão (`0` usa 128).
- **Max Sessions** / **Max Client Sockets** — tetos globais. `0` usa o padrão (10000) e `-1` remove o limite. Sockets acima do teto são fechados antes de qualquer trabalho de protocolo.
- **Auto Restart Interval** / **Restart Grace Delay** — restart forte que fecha somente os listeners BHTTP e suas sessões. Não reinicia o painel nem a VPS. Intervalo mínimo de 1m.
- **Disable Console Log** / **Verbose Connection Logs** — os logs continuam disponíveis em `/api/bhttp/logs` mesmo com o console desligado.
O card **Status BHTTP** na mesma aba mostra sessões e sockets ativos, bytes trafegados, probes BHP1/BHP2, lanes anexadas e rejeitadas, falhas ao abrir o alvo SSH e erros de protocolo.
### BTUN (DTUNNEL/1.1)
O BTUN é a VPN nativa por pacotes IP: o cliente faz o handshake `DTUNNEL/1.1 CLIENT_HELLO` em TCP ou UDP, autentica, recebe um IPv4 de uma sub-rede privada e passa a trocar pacotes IP com uma interface TUN criada por este processo.
Diferente do BHTTP e do DNSTT, o BTUN **não** carrega um fluxo SSH — ele carrega pacotes IP. Por isso a autenticação não passa pelo `handleConn`, e sim direto pelo banco de contas do painel: mesmo usuário e senha (ou TOTP), mesma validade, mesmo dono/revendedor, mesma cota de dados e o mesmo `max_connections`. **Não existe caminho PAM nem `/etc/shadow` no BTUN**, e a opção `pam_auth_enabled` (que é uma configuração do SSH) não se aplica a ele.
Cada sessão BTUN conta no `max_connections` da conta junto com as conexões SSH, respeita `limit_mbps_up`/`limit_mbps_down` e consome a mesma cota de dados. Excluir, editar ou expirar um usuário derruba as sessões BTUN dele igual às conexões SSH.
#### Compartilhar as portas 80, 8080 e 443
O BTUN também pode atender nas portas que o painel já usa. A detecção aqui é ainda mais direta que a do BHTTP: uma sessão BTUN começa com o marcador fixo `DTUNNEL/1.1 CLIENT_HELLO`, que nenhum banner SSH e nenhuma linha HTTP pode igualar. A conexão só vai para o BTUN quando esses 25 bytes batem exatamente no início; qualquer outra coisa segue intacta para o caminho normal.
Duas limitações, ambas por natureza do compartilhamento:
- **Vale só para TCP.** O painel não tem porta UDP compartilhada, então clientes UDP continuam precisando de **UDP Listen**.
- **Cover bytes.** Numa porta dedicada o BTUN tolera lixo arbitrário antes do hello. Numa porta compartilhada o marcador precisa estar no começo, porque não dá para guardar um prefixo sem limite enquanto o SSH espera atrás. Cover em forma de requisição HTTP funciona — a limpeza de injeção do painel consome a requisição e o marcador reaparece no início — mas nesse caso o cliente recebe antes a resposta `101`/`200` do painel e precisa ignorá-la. Para qualquer outro formato de cover, use a porta dedicada.
Ligue em **Configurações → BTUN → Compartilhar as portas do painel**. Com isso ligado, **TCP Listen** pode ficar vazio.
Configure em **Configurações → BTUN**:
- **Compartilhar as portas do painel** — aceita BTUN em 80/8080 e 443 junto com SSH, injeção HTTP e BHTTP, como descrito acima. Somente TCP.
- **TCP Listen** / **UDP Listen** — deixe um em branco para desativar aquele transporte. Sem o compartilhamento, pelo menos um é obrigatório; o padrão é `0.0.0.0:7300` nos dois.
- **TUN Interface** — interface criada e usada por este processo (padrão `btun0`). Não pode colidir com uma interface de outro serviço.
- **Client Subnet** / **Gateway** / **MTU** — faixa IPv4 entregue aos clientes (padrão `10.77.0.0/16`), endereço da própria interface (derivado da sub-rede quando vazio) e MTU (padrão 1400).
- **Manage Routing** — quando ligado, o painel configura o endereço da interface, `net.ipv4.ip_forward` e as regras de NAT/forward da sub-rede. Desligue apenas se um script externo já cuidar disso.
- **WAN Interface** — uplink usado no NAT. Vazio detecta pela rota IPv4 padrão, o que é correto numa VPS com um único uplink.
- **Handshake Timeout** / **Idle Timeout** — limite do handshake+autenticação e tempo sem tráfego antes de reciclar a sessão.
- **Max Packet Size** / **Max Cover Bytes** — tamanho máximo do payload de um frame (`0` usa 64 KiB) e quanto lixo um cliente TCP pode enviar antes do `CLIENT_HELLO`, que é o que permite ao BTUN se esconder atrás de um preâmbulo parecido com HTTP.
- **Max Sessions** — teto global de sessões. `0` usa o padrão (10000) e `-1` remove o limite.
- **Auto Restart Interval** / **Restart Grace Delay** — restart forte que recria apenas os listeners e o dispositivo TUN do BTUN.
O BTUN precisa de `/dev/net/tun` e de privilégio para criar a interface e alterar as regras de NAT. O serviço `sshpanel` já roda como root, então em uma VPS comum funciona direto; em containers sem `/dev/net/tun` o card **Status BTUN** mostra o erro de inicialização. Libere as portas escolhidas no firewall:
```bash
sudo ufw allow 8880/tcp
sudo ufw allow 7300/tcp
sudo ufw allow 7300/udp
```
Ambos os serviços vêm **desativados** por padrão, então uma atualização não abre portas novas sozinha. Ative na aba de configurações; a mudança é aplicada ao vivo, sem reiniciar o painel.
### Compilar e testar em Linux com Docker
O painel é um serviço Linux, mas costuma ser desenvolvido em Windows ou macOS, onde três coisas não podem ser verificadas: o código com build tag de Linux (o dispositivo TUN do BTUN), o detector de corrida (precisa de cgo) e qualquer caminho que use `/dev/net/tun`. A imagem `Dockerfile.build` cobre os três.
```bash
docker build -f Dockerfile.build -t dragoncore-build .
# build + vet + testes
docker run --rm -v "$PWD:/src" -v dragoncore-cache:/cache dragoncore-build
# detector de corrida
docker run --rm -v "$PWD:/src" -v dragoncore-cache:/cache dragoncore-build race
# binários de release em dist/ (amd64 e arm64)
docker run --rm -v "$PWD:/src" -v dragoncore-cache:/cache dragoncore-build dist
```
Os testes do TUN do BTUN — criar a interface e instalar/remover as regras de NAT — precisam de privilégios que o container não tem por padrão:
```bash
docker run --rm --cap-add NET_ADMIN --device /dev/net/tun -v "$PWD:/src" -v dragoncore-cache:/cache dragoncore-build tun
```
Sem esses privilégios eles são pulados, e o resto da suíte roda normalmente. O volume `dragoncore-cache` guarda os caches de módulos e de build entre execuções.
### Comandos úteis
Ver status do serviço:
@@ -716,6 +814,9 @@ Admin token
2222 Internal raw SSH on 127.0.0.1 (not public)
53/udp Public DNS for DNSTT, redirected to 5300/udp
5300/udp Internal DNSTT listener
8880 BHTTP (BHP1/BHP2) — disabled by default; can share 80/8080/443
7300 BTUN TCP — disabled by default; can share 80/8080/443
7300/udp BTUN UDP — disabled by default
9090 Web panel + public /check API
10086 Xray VLESS
10087 Xray VMess
@@ -842,6 +943,101 @@ Example `config.json`:
}
```
### BHTTP (BHP1 / BHP2)
BHTTP is the obfuscated TCP transport used by the DTunnel-family clients. The client opens a plain TCP socket, optionally sends an HTTP request as cover, then speaks the BHTTP framing (29-byte header) with the *probe*, *upload*, *download*, *batch* and *ACK* modes. BHP2 adds persistent lanes with `resume` and cumulative upload ACKs.
Every BHTTP session is handed to the panel's **own built-in SSH server**, exactly the way DNSTT does it. Nothing connects to the system `sshd`, PAM or `/etc/shadow`: the panel's accounts, expiry, TOTP, `max_connections`, bandwidth limits and data quotas all apply with no extra setup.
#### Sharing ports 80, 8080 and 443
BHTTP can serve **on the ports the panel already uses**, with no dedicated port and without disturbing anything else. This works because the three protocols open in incompatible ways: a BHTTP frame starts with its mode number (`0`–`5`), SSH starts with `S` (`0x53`), and an HTTP request or status line starts with a method or version letter. The first byte alone separates all three.
Because an HTTP-injection client may send junk before its payload, a low first byte is not proof on its own. So the 29-byte frame header is range-checked too, and for the two modes that carry a signature — the *probe* that opens every session and the v2 *lane hello* — the signature (`BHP1`/`BHP2`, `BLN2`) is decrypted and verified. That check is keyed by the session ID in the same header, so junk cannot pass it by chance. Nothing is consumed on a negative verdict: the connection continues to the normal HTTP/SSH path with its bytes intact.
Turn it on under **Settings → BHTTP → Share the panel's ports**. It covers `listen`, `extra_listen` and every TLS forwarder. With it on, the **Listen** field may be left empty and BHTTP exists only on the shared ports.
Exactly one thing changes for other clients: today the proxy port answers `HTTP/1.1 101` the moment a socket opens, before reading anything; with sharing on it waits for the client's first bytes (at most 3s) before deciding. That is required because a BHTTP client cannot receive that unsolicited 101. Every known client — HTTP-injection or BHTTP — sends immediately on connect, and a client that sends nothing within 3s falls through to the old path. If a client of yours waits for the 101 before speaking, leave the option off.
Configure it under **Settings → BHTTP**:
- **Share the panel's ports** — accepts BHTTP on 80/8080 and 443 alongside SSH and HTTP injection, as described above.
- **Listen** — a dedicated port, one address per line, optional when sharing is on. Ports 80 and 8080 belong to the HTTP+SSH proxy: to use them, turn sharing on rather than listing them here. Without sharing, the default is `0.0.0.0:8880`.
- **Session Timeout** — how long a session may sit with no traffic before it is dropped and its SSH connection closed. It also bounds how long a BHP2 `resume` stays possible.
- **Max v2 Lanes Per Session** — ceiling on concurrent lanes per session (`0` uses 128).
- **Max Sessions** / **Max Client Sockets** — global ceilings. `0` uses the default (10000) and `-1` disables the cap. Sockets past the cap are closed before any protocol work.
- **Auto Restart Interval** / **Restart Grace Delay** — hard restart that closes only the BHTTP listeners and their sessions. It does not restart the panel or the VPS. Minimum interval is 1m.
- **Disable Console Log** / **Verbose Connection Logs** — logs remain available at `/api/bhttp/logs` even with the console output turned off.
The **Status BHTTP** card in the same tab shows active sessions and sockets, bytes moved, BHP1/BHP2 probes, lanes attached and rejected, SSH target failures and protocol errors.
### BTUN (DTUNNEL/1.1)
BTUN is the native IP-packet VPN: the client performs the `DTUNNEL/1.1 CLIENT_HELLO` handshake over TCP or UDP, authenticates, receives an IPv4 address from a private subnet, and then exchanges IP packets with a TUN interface this process creates.
Unlike BHTTP and DNSTT, BTUN does **not** carry an SSH stream — it carries IP packets. Authentication therefore does not go through `handleConn`; it goes straight to the panel's account database: the same username and password (or TOTP), the same expiry, the same reseller owner, the same data quota and the same `max_connections`. **There is no PAM or `/etc/shadow` path in BTUN at all**, and `pam_auth_enabled` (an SSH setting) does not apply to it.
Each BTUN session counts against the account's `max_connections` together with its SSH connections, honours `limit_mbps_up`/`limit_mbps_down`, and draws on the same data quota. Deleting, editing or expiring a user drops its BTUN sessions the same way it drops SSH connections.
#### Sharing ports 80, 8080 and 443
BTUN can serve on the panel's existing ports too. The detection here is even more direct than BHTTP's: a BTUN session opens with the fixed marker `DTUNNEL/1.1 CLIENT_HELLO`, which no SSH banner and no HTTP line can match. A connection is routed to BTUN only when those 25 bytes match at the very start; anything else continues untouched to the normal path.
Two limits, both inherent to sharing:
- **TCP only.** The panel owns no shared UDP port, so UDP clients still need **UDP Listen**.
- **Cover bytes.** On a dedicated port BTUN tolerates arbitrary junk before the hello. On a shared port the marker has to be at the start, because an unbounded prefix cannot be buffered while SSH waits behind it. Cover shaped as an HTTP request does work — the panel's injection cleanup consumes the request and the marker reappears at the start — but the client then receives the panel's `101`/`200` reply first and has to skip it. For any other cover shape, use the dedicated port.
Turn it on under **Settings → BTUN → Share the panel's ports**. With it on, **TCP Listen** may be left empty.
Configure it under **Settings → BTUN**:
- **Share the panel's ports** — accepts BTUN on 80/8080 and 443 alongside SSH, HTTP injection and BHTTP, as described above. TCP only.
- **TCP Listen** / **UDP Listen** — leave one empty to disable that transport. Without sharing at least one is required; both default to `0.0.0.0:7300`.
- **TUN Interface** — the interface this process creates and owns (default `btun0`). It must not collide with an interface another service owns.
- **Client Subnet** / **Gateway** / **MTU** — the IPv4 range handed to clients (default `10.77.0.0/16`), the address on the interface itself (derived from the subnet when empty) and the MTU (default 1400).
- **Manage Routing** — when on, the panel configures the interface address, `net.ipv4.ip_forward` and the subnet's NAT/forward rules itself. Turn it off only when an external script already owns those rules.
- **WAN Interface** — the uplink used for NAT. Empty auto-detects it from the default IPv4 route, which is correct on a single-uplink VPS.
- **Handshake Timeout** / **Idle Timeout** — bound the hello+authentication exchange, and how long a session may sit with no traffic before it is reaped.
- **Max Packet Size** / **Max Cover Bytes** — the largest frame payload (`0` uses 64 KiB) and how much junk a TCP client may send before its `CLIENT_HELLO`, which is what lets BTUN hide behind an HTTP-looking preamble.
- **Max Sessions** — global session ceiling. `0` uses the default (10000) and `-1` disables the cap.
- **Auto Restart Interval** / **Restart Grace Delay** — hard restart that recreates only the BTUN listeners and TUN device.
BTUN needs `/dev/net/tun` and the privilege to create the interface and change NAT rules. The `sshpanel` service already runs as root, so a normal VPS works out of the box; in a container without `/dev/net/tun` the **Status BTUN** card shows the startup error. Open the chosen ports in the firewall:
```bash
sudo ufw allow 8880/tcp
sudo ufw allow 7300/tcp
sudo ufw allow 7300/udp
```
Both services are **disabled** by default, so an update never opens new ports on its own. Enable them in the settings tab; the change is applied live, with no panel restart.
### Building and testing on Linux with Docker
The panel is a Linux service but is often developed on Windows or macOS, where three things cannot be checked: the Linux-tagged code (BTUN's TUN device), the race detector (which needs cgo), and anything touching `/dev/net/tun`. The `Dockerfile.build` image covers all three.
```bash
docker build -f Dockerfile.build -t dragoncore-build .
# build + vet + tests
docker run --rm -v "$PWD:/src" -v dragoncore-cache:/cache dragoncore-build
# race detector
docker run --rm -v "$PWD:/src" -v dragoncore-cache:/cache dragoncore-build race
# release binaries in dist/ (amd64 and arm64)
docker run --rm -v "$PWD:/src" -v dragoncore-cache:/cache dragoncore-build dist
```
The BTUN TUN tests — creating the interface and installing/removing the NAT rules — need privileges the container does not have by default:
```bash
docker run --rm --cap-add NET_ADMIN --device /dev/net/tun -v "$PWD:/src" -v dragoncore-cache:/cache dragoncore-build tun
```
Without those privileges they skip and the rest of the suite runs normally. The `dragoncore-cache` volume keeps the module and build caches between runs.
### Useful commands
Check service status:
@@ -1258,6 +1454,24 @@ Creates or updates (upsert) an SSH user.
---
### BHTTP and BTUN
#### `GET /api/bhttp` — superadmin
- Optional query: `server_id`.
- `200`: BHTTP snapshot: `enabled` (bool), `running` (bool), `listen` (string, omitempty — the dedicated addresses, plus `shared proxy/TLS ports` when port sharing is on), `startedAt` (string); `activeConnections` and `activeSessions` (int64); uint counters `accepted`, `connectionsRejected`, `sessionsRejected`, `sessionsExpired`, `probes`, `probesV2`, `httpUpgrades`, `lanesAttached`, `lanesRejected`, `uploadBytes`, `downloadBytes`, `targetFailures`, `protocolErrors`.
#### `GET /api/bhttp/logs` — superadmin
- `200`: array of log line strings (empty array if uninitialized). Does not proxy to managed servers.
#### `GET /api/btun` — superadmin
- Optional query: `server_id`.
- `200`: BTUN snapshot: `enabled` (bool), `running` (bool), `listen` (string, omitempty — the dedicated listeners, plus `shared proxy/TLS ports` when port sharing is on), `tunName` (string, omitempty), `subnet` (string, omitempty), `startedAt` (string); uint counters `activeSessions`, `accepted`, `authSucceeded`, `authRejected`, `clientPackets`, `internetPackets`, `clientBytes`, `internetBytes`, `droppedPackets`, `sessionsRejected`.
#### `GET /api/btun/logs` — superadmin
- `200`: array of log line strings (empty array if uninitialized). Does not proxy to managed servers.
---
### Resellers (superadmin only)
#### `GET /api/resellers` — superadmin
+319
View File
@@ -156,6 +156,12 @@ async function loadServerConfig() {
document.getElementById("cfgUdpgwRestartGrace").value = u.auto_restart_grace || "";
document.getElementById("cfgUdpgwDebug").checked = !!u.debug;
// BHTTP + BTUN
writeBhttpConfig(c);
writeBtunConfig(c);
loadBhttpHealth();
loadBtunHealth();
// TLS forwarders
tlsForwardersState = c.tls_forwarders || [];
renderTLSForwarders();
@@ -233,6 +239,8 @@ async function saveServerConfig() {
auto_restart_grace: document.getElementById("cfgUdpgwRestartGrace").value.trim(),
debug: document.getElementById("cfgUdpgwDebug").checked,
} : null,
bhttp: readBhttpConfig(),
btun: readBtunConfig(),
tls_forwarders: tlsArr,
xray: {
enabled: document.getElementById("cfgXrayEnabled").checked,
@@ -260,6 +268,8 @@ async function saveServerConfig() {
} else {
st.textContent = "Saved and applied live.";
}
loadBhttpHealth();
loadBtunHealth();
} catch (e) {
if (e.message === "auth") doAuthError();
else st.textContent = "Error: " + e.message;
@@ -692,3 +702,312 @@ async function loadDnsttPubkey() {
else st.textContent = "Error: " + e.message;
}
}
// ─── BHTTP / BTUN ─────────────────────────────────────────────────────────────
// Both transports terminate inside this process: BHTTP hands each session to
// the built-in SSH server, and BTUN authenticates against the panel accounts.
// Neither uses the system sshd or PAM, so there is nothing host-side to set up
// here beyond the listeners and (for BTUN) the TUN/NAT settings.
function toggleBhttpFields(on) {
const el = document.getElementById("bhttpFields");
if (!el) return;
el.style.opacity = on ? "1" : ".4";
el.style.pointerEvents = on ? "" : "none";
}
function toggleBtunFields(on) {
const el = document.getElementById("btunFields");
if (!el) return;
el.style.opacity = on ? "1" : ".4";
el.style.pointerEvents = on ? "" : "none";
}
function readListenLines(id) {
const el = document.getElementById(id);
if (!el) return [];
const seen = new Set();
return el.value.split(/\r?\n|,/).map(s => s.trim()).filter(Boolean).filter(s => {
if (seen.has(s)) return false;
seen.add(s);
return true;
});
}
// ─── Null-safe field access ───────────────────────────────────────────────────
// A browser can hold a cached index.html while loading newer JS. Reading a
// field that does not exist there must not throw, because an exception here
// aborts loadServerConfig() and blanks the entire settings tab. Missing fields
// are simply skipped, so an older panel keeps working against a newer build.
function fieldSet(id, value) {
const el = document.getElementById(id);
if (el) el.value = value;
}
function fieldCheck(id, checked) {
const el = document.getElementById(id);
if (el) el.checked = !!checked;
}
function fieldText(id, fallback = "") {
const el = document.getElementById(id);
return el ? el.value.trim() : fallback;
}
function fieldRaw(id, fallback = "") {
const el = document.getElementById(id);
return el ? el.value : fallback;
}
function fieldInt(id, fallback = 0) {
const el = document.getElementById(id);
if (!el) return fallback;
const n = parseInt(el.value || "0", 10);
return Number.isNaN(n) ? fallback : n;
}
function fieldBool(id, fallback = false) {
const el = document.getElementById(id);
return el ? !!el.checked : fallback;
}
function writeBhttpConfig(c) {
const hasBhttp = !!c.bhttp;
fieldCheck("cfgBhttpEnabled", hasBhttp);
toggleBhttpFields(hasBhttp);
const b = c.bhttp || {};
// Sharing the panel's own ports is the point of enabling BHTTP for most
// setups, so a config that has never had a bhttp block starts with it on.
fieldCheck("cfgBhttpSharedPorts", hasBhttp ? !!b.shared_ports : true);
fieldSet("cfgBhttpListen", (b.listen || []).join("\n"));
fieldSet("cfgBhttpSessionTimeout", b.session_timeout || "");
fieldSet("cfgBhttpMaxLanes", b.max_v2_lanes || 0);
fieldSet("cfgBhttpMaxSessions", b.max_sessions || 0);
fieldSet("cfgBhttpMaxConnections", b.max_connections || 0);
fieldSet("cfgBhttpAutoRestart", b.auto_restart_interval || "");
fieldSet("cfgBhttpRestartGrace", b.auto_restart_grace || "");
fieldCheck("cfgBhttpNoConsole", !!b.disable_console_log);
fieldCheck("cfgBhttpLogConnections", !!b.log_connections);
}
function readBhttpConfig() {
if (!fieldBool("cfgBhttpEnabled")) return null;
const listen = readListenLines("cfgBhttpListen");
const shared = fieldBool("cfgBhttpSharedPorts");
return {
// With shared ports on, a dedicated listener is optional; without it there
// has to be one or nothing would serve BHTTP at all.
listen: listen.length ? listen : (shared ? [] : ["0.0.0.0:8880"]),
shared_ports: shared,
session_timeout: fieldText("cfgBhttpSessionTimeout"),
max_v2_lanes: fieldInt("cfgBhttpMaxLanes"),
max_sessions: fieldInt("cfgBhttpMaxSessions"),
max_connections: fieldInt("cfgBhttpMaxConnections"),
auto_restart_interval: fieldText("cfgBhttpAutoRestart"),
auto_restart_grace: fieldText("cfgBhttpRestartGrace"),
disable_console_log: fieldBool("cfgBhttpNoConsole"),
log_connections: fieldBool("cfgBhttpLogConnections"),
};
}
function writeBtunConfig(c) {
const hasBtun = !!c.btun;
fieldCheck("cfgBtunEnabled", hasBtun);
toggleBtunFields(hasBtun);
const b = c.btun || {};
// Sharing the panel's ports is the least-friction way to reach BTUN, so a
// config that has never had a btun block starts with it on.
fieldCheck("cfgBtunSharedPorts", hasBtun ? !!b.shared_ports : true);
fieldSet("cfgBtunTCPListen", b.tcp_listen || "");
fieldSet("cfgBtunUDPListen", b.udp_listen || "");
fieldSet("cfgBtunTUNName", b.tun_name || "");
fieldSet("cfgBtunSubnet", b.subnet || "");
fieldSet("cfgBtunGateway", b.gateway || "");
fieldSet("cfgBtunMTU", b.mtu || 0);
fieldCheck("cfgBtunManageRouting", !!b.manage_routing);
fieldSet("cfgBtunWAN", b.wan_interface || "");
fieldSet("cfgBtunHandshakeTimeout", b.handshake_timeout || "");
fieldSet("cfgBtunIdleTimeout", b.idle_timeout || "");
fieldSet("cfgBtunMaxPacketSize", b.max_packet_size || 0);
fieldSet("cfgBtunMaxCoverBytes", b.max_cover_bytes || 0);
fieldSet("cfgBtunMaxSessions", b.max_sessions || 0);
fieldSet("cfgBtunAutoRestart", b.auto_restart_interval || "");
fieldSet("cfgBtunRestartGrace", b.auto_restart_grace || "");
fieldCheck("cfgBtunNoConsole", !!b.disable_console_log);
fieldCheck("cfgBtunLogConnections", !!b.log_connections);
}
function readBtunConfig() {
if (!fieldBool("cfgBtunEnabled")) return null;
const tcp = fieldText("cfgBtunTCPListen");
const udp = fieldText("cfgBtunUDPListen");
const shared = fieldBool("cfgBtunSharedPorts");
return {
// The server refuses to start with nothing to serve on, so default both
// listeners rather than saving a config that cannot come up. With shared
// ports on, having neither is a valid TCP-only deployment.
tcp_listen: tcp || (udp || shared ? "" : "0.0.0.0:7300"),
udp_listen: udp || (tcp || shared ? "" : "0.0.0.0:7300"),
shared_ports: shared,
tun_name: fieldText("cfgBtunTUNName"),
subnet: fieldText("cfgBtunSubnet"),
gateway: fieldText("cfgBtunGateway"),
mtu: fieldInt("cfgBtunMTU"),
manage_routing: fieldBool("cfgBtunManageRouting"),
wan_interface: fieldText("cfgBtunWAN"),
handshake_timeout: fieldText("cfgBtunHandshakeTimeout"),
idle_timeout: fieldText("cfgBtunIdleTimeout"),
max_packet_size: fieldInt("cfgBtunMaxPacketSize"),
max_cover_bytes: fieldInt("cfgBtunMaxCoverBytes"),
max_sessions: fieldInt("cfgBtunMaxSessions"),
auto_restart_interval: fieldText("cfgBtunAutoRestart"),
auto_restart_grace: fieldText("cfgBtunRestartGrace"),
disable_console_log: fieldBool("cfgBtunNoConsole"),
log_connections: fieldBool("cfgBtunLogConnections"),
};
}
// renderCounterRows fills a two-column counter table, matching the DNSTT health
// card so all transports read the same way.
function renderCounterRows(bodyId, rows) {
const body = document.getElementById(bodyId);
if (!body) return;
body.innerHTML = "";
for (let i = 0; i < rows.length; i += 2) {
const a = rows[i];
const b = rows[i + 1] || ["", ""];
const tr = document.createElement("tr");
tr.innerHTML = `<td>${escapeHTML(a[0])}</td><td>${escapeHTML(fmtInt(a[1]))}</td>` +
`<td>${escapeHTML(b[0])}</td><td>${b[0] ? escapeHTML(fmtInt(b[1])) : ""}</td>`;
body.appendChild(tr);
}
}
function setServiceChip(chipId, data) {
const chip = document.getElementById(chipId);
if (!chip) return;
if (!data || data.enabled === false) {
chip.textContent = "disabled";
chip.className = "chip";
return;
}
chip.textContent = data.running ? "running" : "stopped";
chip.className = data.running ? "chip green" : "chip red";
}
async function loadBhttpHealth() {
const summary = document.getElementById("bhttpStatusSummary");
if (!summary) return;
try {
const res = await api("/api/bhttp");
if (!res.ok) throw new Error(await res.text());
const d = await res.json();
setServiceChip("bhttpStatusChip", d);
document.getElementById("bhttpActiveSessions").textContent = fmtInt(d.activeSessions);
document.getElementById("bhttpActiveConns").textContent = fmtInt(d.activeConnections);
document.getElementById("bhttpUploadBytes").textContent = fmtBytes(d.uploadBytes || 0);
document.getElementById("bhttpDownloadBytes").textContent = fmtBytes(d.downloadBytes || 0);
renderCounterRows("bhttpHealthBody", [
["Sockets accepted", d.accepted],
["Sockets rejected", d.connectionsRejected],
["Sessions rejected", d.sessionsRejected],
["Sessions expired", d.sessionsExpired],
["Probes (BHP1)", (d.probes || 0) - (d.probesV2 || 0)],
["Probes (BHP2)", d.probesV2],
["HTTP cover upgrades", d.httpUpgrades],
["v2 lanes attached", d.lanesAttached],
["v2 lanes rejected", d.lanesRejected],
["SSH target failures", d.targetFailures],
["Protocol errors", d.protocolErrors],
]);
if (d.enabled === false) {
summary.textContent = "BHTTP está desativado na configuração.";
} else if (!d.running) {
summary.textContent = "BHTTP está ativado mas não está rodando. Verifique se a porta está livre nos logs abaixo.";
} else {
const bad = Number(d.connectionsRejected || 0) + Number(d.sessionsRejected || 0) +
Number(d.targetFailures || 0);
summary.textContent = bad > 0
? `Rodando em ${d.listen || "?"} — atenção: ${fmtInt(bad)} rejeições/falhas acumuladas.`
: `Rodando em ${d.listen || "?"} — sem rejeições nem falhas de alvo.`;
}
} catch (e) {
if (e.message === "auth") doAuthError();
else summary.textContent = "Erro ao carregar status: " + e.message;
}
}
async function loadBhttpLogs() {
const box = document.getElementById("bhttpLogs");
if (!box) return;
box.textContent = "Carregando…";
try {
const res = await api("/api/bhttp/logs");
if (!res.ok) throw new Error(await res.text());
const lines = await res.json();
box.textContent = lines && lines.length ? lines.join("\n") : "Sem logs.";
} catch (e) {
if (e.message === "auth") doAuthError();
else box.textContent = "Erro: " + e.message;
}
}
async function loadBtunHealth() {
const summary = document.getElementById("btunStatusSummary");
if (!summary) return;
try {
const res = await api("/api/btun");
if (!res.ok) throw new Error(await res.text());
const d = await res.json();
setServiceChip("btunStatusChip", d);
document.getElementById("btunActiveSessions").textContent = fmtInt(d.activeSessions);
document.getElementById("btunAuthSucceeded").textContent = fmtInt(d.authSucceeded);
document.getElementById("btunClientBytes").textContent = fmtBytes(d.clientBytes || 0);
document.getElementById("btunInternetBytes").textContent = fmtBytes(d.internetBytes || 0);
renderCounterRows("btunHealthBody", [
["Handshakes accepted", d.accepted],
["Auth rejected", d.authRejected],
["Sessions rejected", d.sessionsRejected],
["Dropped packets", d.droppedPackets],
["Client → net packets", d.clientPackets],
["Net → client packets", d.internetPackets],
]);
if (d.enabled === false) {
summary.textContent = "BTUN está desativado na configuração.";
} else if (!d.running) {
summary.textContent = "BTUN está ativado mas não está rodando. Normalmente falta /dev/net/tun, ou a interface/porta já está em uso — veja os logs.";
} else {
const where = [d.listen, d.tunName, d.subnet].filter(Boolean).join(" · ");
summary.textContent = Number(d.droppedPackets || 0) > 0
? `Rodando em ${where} — ${fmtInt(d.droppedPackets)} pacotes descartados (confira MTU e rota).`
: `Rodando em ${where} — sem pacotes descartados.`;
}
} catch (e) {
if (e.message === "auth") doAuthError();
else summary.textContent = "Erro ao carregar status: " + e.message;
}
}
async function loadBtunLogs() {
const box = document.getElementById("btunLogs");
if (!box) return;
box.textContent = "Carregando…";
try {
const res = await api("/api/btun/logs");
if (!res.ok) throw new Error(await res.text());
const lines = await res.json();
box.textContent = lines && lines.length ? lines.join("\n") : "Sem logs.";
} catch (e) {
if (e.message === "auth") doAuthError();
else box.textContent = "Erro: " + e.message;
}
}
// Inline onchange/onclick handlers in index.html need these on window.
window.toggleBhttpFields = toggleBhttpFields;
window.toggleBtunFields = toggleBtunFields;
window.loadBhttpHealth = loadBhttpHealth;
window.loadBhttpLogs = loadBhttpLogs;
window.loadBtunHealth = loadBtunHealth;
window.loadBtunLogs = loadBtunLogs;
+202 -3
View File
@@ -1231,15 +1231,17 @@
<section class="page-hero" data-tone="blue"><div class="page-hero-copy"><span class="page-kicker">System studio</span><h2>Configurações</h2><p>Rede, SSH, túneis e TLS organizados em blocos visuais e aplicados ao vivo.</p></div></section>
<div class="workspace-nav-shell" data-tone="blue">
<nav class="workspace-section-nav" id="configSectionNav" aria-label="Áreas de configuração" style="--workspace-nav-columns:5">
<nav class="workspace-section-nav" id="configSectionNav" aria-label="Áreas de configuração" style="--workspace-nav-columns:7">
<button class="active" type="button" data-workspace="config" data-workspace-section="general"><span>⌁</span> Rede e SSH</button>
<button type="button" data-workspace="config" data-workspace-section="slowdns"><span>DNS</span> SlowDNS</button>
<button type="button" data-workspace="config" data-workspace-section="udp"><span>⇅</span> UDP Gateway</button>
<button type="button" data-workspace="config" data-workspace-section="bhttp"><span>BH</span> BHTTP</button>
<button type="button" data-workspace="config" data-workspace-section="btun"><span>BT</span> BTUN</button>
<button type="button" data-workspace="config" data-workspace-section="tls"><span>◇</span> TLS</button>
<button type="button" data-workspace="config" data-workspace-section="xray"><span>◆</span> Xray</button>
</nav>
<select id="configSection" class="workspace-section-select" data-workspace-select="config" aria-label="Área de configuração">
<option value="general">Rede e SSH</option><option value="slowdns">SlowDNS</option><option value="udp">UDP Gateway</option><option value="tls">TLS</option><option value="xray">Xray</option>
<option value="general">Rede e SSH</option><option value="slowdns">SlowDNS</option><option value="udp">UDP Gateway</option><option value="bhttp">BHTTP</option><option value="btun">BTUN</option><option value="tls">TLS</option><option value="xray">Xray</option>
</select>
</div>
@@ -1468,8 +1470,205 @@
</section>
<section class="workspace-section" data-workspace-panel="config" data-workspace-section-panel="bhttp">
<div class="workspace-section-heading"><div><span>04 · BHTTP</span><h3>BHTTP (BHP1 / BHP2)</h3><p>Transporte TCP ofuscado dos apps DTunnel. Cada sessão é entregue ao servidor SSH interno do painel — nunca ao sshd do sistema.</p></div></div>
<div class="card" style="margin-top:12px">
<div class="card-hdr">
<div class="card-title">BHTTP Transport</div>
<span class="chip green">live</span>
<label style="font-size:.73rem;display:flex;align-items:center;gap:5px;cursor:pointer;margin-left:auto;">
<input type="checkbox" id="cfgBhttpEnabled" onchange="toggleBhttpFields(this.checked)"/> Enabled
</label>
</div>
<div id="bhttpFields" class="form-grid" style="opacity:.4;pointer-events:none;">
<label style="font-size:.73rem;display:flex;align-items:center;gap:5px;cursor:pointer;grid-column:1/-1">
<input type="checkbox" id="cfgBhttpSharedPorts"/> Compartilhar as portas do painel <span class="hint">80/8080 (proxy) e 443 (TLS)</span>
</label>
<div class="hint" style="grid-column:1/-1;margin-top:-4px;">
Os listeners existentes leem os primeiros bytes de cada conexão e entregam ao BHTTP somente quando o quadro é inconfundível — um quadro BHTTP começa com o número do modo (0–5), enquanto SSH começa com <code>S</code> e HTTP com a letra do método. Clientes SSH e de injeção HTTP na mesma porta continuam iguais.
<strong>Uma mudança existe:</strong> com o compartilhamento ligado, a porta do proxy espera os primeiros bytes do cliente em vez de responder <code>HTTP/1.1 101</code> imediatamente. Todo cliente conhecido envia na hora, mas desligue isto se algum cliente seu aguardar esse 101 antes de falar.
</div>
<div class="field" style="grid-column:1/-1">
<label>Listen <span class="hint">um endereço por linha; vazio = só portas compartilhadas</span></label>
<textarea id="cfgBhttpListen" rows="3" placeholder="0.0.0.0:8880&#10;[::]:8881"></textarea>
<span class="hint">Porta dedicada, opcional. As portas 80 e 8080 já pertencem ao proxy HTTP+SSH: para usá-las, marque o compartilhamento acima em vez de listá-las aqui.</span>
</div>
<div class="field">
<label>Session Timeout <span class="hint">10s..1h</span></label>
<input type="text" id="cfgBhttpSessionTimeout" placeholder="2m"/>
</div>
<div class="field">
<label>Max v2 Lanes Per Session <span class="hint">0 = 128</span></label>
<input type="number" id="cfgBhttpMaxLanes" min="0" placeholder="128"/>
</div>
<div class="field">
<label>Max Sessions <span class="hint">0 = default (10000), -1 = unlimited</span></label>
<input type="number" id="cfgBhttpMaxSessions" placeholder="10000"/>
</div>
<div class="field">
<label>Max Client Sockets <span class="hint">0 = default (10000), -1 = unlimited</span></label>
<input type="number" id="cfgBhttpMaxConnections" placeholder="10000"/>
</div>
<div class="field">
<label>Auto Restart Interval <span class="hint">0s/off disables</span></label>
<input type="text" id="cfgBhttpAutoRestart" placeholder="24h"/>
</div>
<div class="field">
<label>Restart Grace Delay</label>
<input type="text" id="cfgBhttpRestartGrace" placeholder="2s"/>
</div>
<div class="hint" style="grid-column:1/-1;margin-top:-4px;">Restart forte: fecha apenas os listeners BHTTP e suas sessões, depois religa. Não reinicia o painel nem a VPS.</div>
<label style="font-size:.73rem;display:flex;align-items:center;gap:5px;cursor:pointer;grid-column:1/-1">
<input type="checkbox" id="cfgBhttpNoConsole"/> Disable Console Log
</label>
<label style="font-size:.73rem;display:flex;align-items:center;gap:5px;cursor:pointer;grid-column:1/-1">
<input type="checkbox" id="cfgBhttpLogConnections"/> Verbose Connection Logs
</label>
</div>
</div>
<div class="card" style="margin-top:12px">
<div class="card-hdr">
<div class="card-title">Status BHTTP</div>
<span class="chip" id="bhttpStatusChip">—</span>
<button class="btn btn-ghost btn-sm" type="button" onclick="loadBhttpHealth()">Atualizar</button>
</div>
<div class="metrics">
<div class="metric"><div class="m-label">Active Sessions</div><div class="m-val" id="bhttpActiveSessions">--</div></div>
<div class="metric"><div class="m-label">Active Sockets</div><div class="m-val" id="bhttpActiveConns">--</div></div>
<div class="metric"><div class="m-label">Upload</div><div class="m-val" id="bhttpUploadBytes">--</div></div>
<div class="metric"><div class="m-label">Download</div><div class="m-val" id="bhttpDownloadBytes">--</div></div>
</div>
<div class="tbl-wrap" style="margin-top:10px;">
<table>
<thead><tr><th>Counter</th><th>Value</th><th>Counter</th><th>Value</th></tr></thead>
<tbody id="bhttpHealthBody"></tbody>
</table>
</div>
<div class="statusbar"><span id="bhttpStatusSummary">Salve a configuração para iniciar o transporte.</span><span class="hint">Rejeições e falhas de alvo devem normalmente ficar em 0.</span></div>
<div class="card-hdr" style="margin-top:12px">
<div class="card-title">Logs BHTTP</div>
<button class="btn btn-ghost btn-sm" type="button" onclick="loadBhttpLogs()">Carregar logs</button>
</div>
<pre id="bhttpLogs" class="log-box">—</pre>
</div>
</section>
<section class="workspace-section" data-workspace-panel="config" data-workspace-section-panel="btun">
<div class="workspace-section-heading"><div><span>05 · BTUN</span><h3>BTUN (DTUNNEL/1.1)</h3><p>VPN nativa por pacotes IP em TCP e UDP. Autentica nas contas do painel — sem PAM e sem /etc/shadow.</p></div></div>
<div class="card" style="margin-top:12px">
<div class="card-hdr">
<div class="card-title">BTUN Protocol Server</div>
<span class="chip green">live</span>
<label style="font-size:.73rem;display:flex;align-items:center;gap:5px;cursor:pointer;margin-left:auto;">
<input type="checkbox" id="cfgBtunEnabled" onchange="toggleBtunFields(this.checked)"/> Enabled
</label>
</div>
<div id="btunFields" class="form-grid" style="opacity:.4;pointer-events:none;">
<label style="font-size:.73rem;display:flex;align-items:center;gap:5px;cursor:pointer;grid-column:1/-1">
<input type="checkbox" id="cfgBtunSharedPorts"/> Compartilhar as portas do painel <span class="hint">80/8080 (proxy) e 443 (TLS), só TCP</span>
</label>
<div class="hint" style="grid-column:1/-1;margin-top:-4px;">
Os listeners existentes entregam ao BTUN apenas no marcador fixo <code>DTUNNEL/1.1 CLIENT_HELLO</code>, então SSH, injeção HTTP e BHTTP na mesma porta continuam iguais. Vale somente para TCP — o painel não tem porta UDP compartilhada, então clientes UDP ainda precisam do <strong>UDP Listen</strong>.
</div>
<div class="field">
<label>TCP Listen <span class="hint">vazio desativa; opcional com portas compartilhadas</span></label>
<input type="text" id="cfgBtunTCPListen" placeholder="0.0.0.0:7300"/>
</div>
<div class="field">
<label>UDP Listen <span class="hint">empty disables</span></label>
<input type="text" id="cfgBtunUDPListen" placeholder="0.0.0.0:7300"/>
</div>
<div class="field">
<label>TUN Interface</label>
<input type="text" id="cfgBtunTUNName" placeholder="btun0"/>
</div>
<div class="field">
<label>Client Subnet <span class="hint">IPv4 CIDR</span></label>
<input type="text" id="cfgBtunSubnet" placeholder="10.77.0.0/16"/>
</div>
<div class="field">
<label>Gateway <span class="hint">empty derives from subnet</span></label>
<input type="text" id="cfgBtunGateway" placeholder="10.77.0.1/16"/>
</div>
<div class="field">
<label>MTU <span class="hint">576..9000</span></label>
<input type="number" id="cfgBtunMTU" min="576" max="9000" placeholder="1400"/>
</div>
<label style="font-size:.73rem;display:flex;align-items:center;gap:5px;cursor:pointer;grid-column:1/-1">
<input type="checkbox" id="cfgBtunManageRouting"/> Manage Routing <span class="hint">configura o IP da interface, ip_forward e o NAT</span>
</label>
<div class="field">
<label>WAN Interface <span class="hint">empty auto-detects</span></label>
<input type="text" id="cfgBtunWAN" placeholder="eth0"/>
</div>
<div class="field">
<label>Handshake Timeout <span class="hint">1s..5m</span></label>
<input type="text" id="cfgBtunHandshakeTimeout" placeholder="15s"/>
</div>
<div class="field">
<label>Idle Timeout <span class="hint">10s..1h</span></label>
<input type="text" id="cfgBtunIdleTimeout" placeholder="2m"/>
</div>
<div class="field">
<label>Max Packet Size <span class="hint">0 = 64 KiB</span></label>
<input type="number" id="cfgBtunMaxPacketSize" min="0" placeholder="65536"/>
</div>
<div class="field">
<label>Max Cover Bytes <span class="hint">0 = 64 KiB</span></label>
<input type="number" id="cfgBtunMaxCoverBytes" min="0" placeholder="65536"/>
</div>
<div class="field">
<label>Max Sessions <span class="hint">0 = default (10000), -1 = unlimited</span></label>
<input type="number" id="cfgBtunMaxSessions" placeholder="10000"/>
</div>
<div class="field">
<label>Auto Restart Interval <span class="hint">0s/off disables</span></label>
<input type="text" id="cfgBtunAutoRestart" placeholder="24h"/>
</div>
<div class="field">
<label>Restart Grace Delay</label>
<input type="text" id="cfgBtunRestartGrace" placeholder="2s"/>
</div>
<div class="hint" style="grid-column:1/-1;margin-top:-4px;">Cada sessão BTUN conta no <strong>max_connections</strong> da conta, no limite de banda e na cota de dados, junto com as conexões SSH.</div>
<label style="font-size:.73rem;display:flex;align-items:center;gap:5px;cursor:pointer;grid-column:1/-1">
<input type="checkbox" id="cfgBtunNoConsole"/> Disable Console Log
</label>
<label style="font-size:.73rem;display:flex;align-items:center;gap:5px;cursor:pointer;grid-column:1/-1">
<input type="checkbox" id="cfgBtunLogConnections"/> Verbose Connection Logs
</label>
</div>
</div>
<div class="card" style="margin-top:12px">
<div class="card-hdr">
<div class="card-title">Status BTUN</div>
<span class="chip" id="btunStatusChip">—</span>
<button class="btn btn-ghost btn-sm" type="button" onclick="loadBtunHealth()">Atualizar</button>
</div>
<div class="metrics">
<div class="metric"><div class="m-label">Active Sessions</div><div class="m-val" id="btunActiveSessions">--</div></div>
<div class="metric"><div class="m-label">Authenticated</div><div class="m-val" id="btunAuthSucceeded">--</div></div>
<div class="metric"><div class="m-label">Client → Net</div><div class="m-val" id="btunClientBytes">--</div></div>
<div class="metric"><div class="m-label">Net → Client</div><div class="m-val" id="btunInternetBytes">--</div></div>
</div>
<div class="tbl-wrap" style="margin-top:10px;">
<table>
<thead><tr><th>Counter</th><th>Value</th><th>Counter</th><th>Value</th></tr></thead>
<tbody id="btunHealthBody"></tbody>
</table>
</div>
<div class="statusbar"><span id="btunStatusSummary">Salve a configuração para iniciar o servidor.</span><span class="hint">Pacotes descartados indicam MTU ou rota incorreta.</span></div>
<div class="card-hdr" style="margin-top:12px">
<div class="card-title">Logs BTUN</div>
<button class="btn btn-ghost btn-sm" type="button" onclick="loadBtunLogs()">Carregar logs</button>
</div>
<pre id="btunLogs" class="log-box">—</pre>
</div>
</section>
<section class="workspace-section" data-workspace-panel="config" data-workspace-section-panel="tls">
<div class="workspace-section-heading"><div><span>04 · Segurança</span><h3>Encaminhadores TLS</h3><p>Gerencie os certificados do servidor e crie listeners TLS com certificado automático, colado ou armazenado em arquivo.</p></div></div>
<div class="workspace-section-heading"><div><span>06 · Segurança</span><h3>Encaminhadores TLS</h3><p>Gerencie os certificados do servidor e crie listeners TLS com certificado automático, colado ou armazenado em arquivo.</p></div></div>
<!-- TLS Certificates -->
<div class="card" style="margin-top:12px">
File diff suppressed because it is too large Load Diff
+532
View File
@@ -0,0 +1,532 @@
package main
// This file embeds the BHTTP (BHP1/BHP2) transport into the panel. BHTTP is the
// obfuscated TCP transport used by the DTunnel-family clients: a client opens a
// plain TCP socket, optionally sends an HTTP request as cover, then speaks the
// 29-byte-header BHTTP framing (probe, upload, download, batch, ACK and — in
// v2 — persistent lanes with resume and cumulative ACKs).
//
// The transport does NOT talk to the system's OpenSSH daemon. Exactly like the
// DNSTT integration, every BHTTP session is handed to this process's own SSH
// server through handleConn, so panel accounts, expiry, TOTP, per-user
// bandwidth limits, data quotas and connection counters all apply unchanged.
// There is no dependency on sshd, PAM or /etc/shadow anywhere in this path.
import (
"context"
"errors"
"fmt"
"io"
"log"
"net"
"os"
"strings"
"sync"
"time"
"shell2/internal/bhttp"
)
// BHTTPConfig defines the settings for the integrated BHTTP transport. A nil
// *BHTTPConfig in the main config disables it entirely.
type BHTTPConfig struct {
// Listen lists the TCP addresses to bind. IPv6 addresses must use bracket
// form, for example "[::]:8880". Empty uses the default 0.0.0.0:8880.
// Ports 80/8080 normally belong to the HTTP+SSH proxy listeners, so BHTTP
// defaults to a separate port instead of fighting them for the socket.
Listen []string `json:"listen"`
// SharedPorts also accepts BHTTP on the ports the panel already owns: the
// HTTP+SSH proxy listeners (listen and extra_listen, normally 80 and 8080)
// and every TLS forwarder (normally 443). Those listeners read the first
// bytes of each connection and hand it here only when it is unmistakably a
// BHTTP frame, so SSH and HTTP-injection clients on the same port are
// unaffected.
//
// The one behaviour this changes for other clients: the proxy listener
// normally answers with "HTTP/1.1 101" the moment a socket opens, and with
// sharing on it waits for the client's first bytes instead (up to
// bhttpSniffTimeout). Every known client sends immediately on connect, but
// turn this off if a client of yours waits for that 101 before speaking.
SharedPorts bool `json:"shared_ports,omitempty"`
// SessionTimeout is how long a BHTTP session may sit with no traffic before
// it is dropped and its SSH connection closed. Empty defaults to "2m".
// BHTTP v2 clients reconnect lanes into an existing session, so this value
// also bounds how long a resume stays possible.
SessionTimeout string `json:"session_timeout,omitempty"`
// MaxV2Lanes caps the combined number of BHTTP v2 lanes a single session
// may keep attached. Zero uses the protocol default (128).
MaxV2Lanes int `json:"max_v2_lanes,omitempty"`
// MaxSessions caps concurrently tracked BHTTP sessions. Once reached, new
// session IDs are refused while existing sessions keep working. Zero uses a
// safe default; negative disables the cap.
MaxSessions int `json:"max_sessions,omitempty"`
// MaxConnections caps concurrently accepted client sockets across every
// BHTTP listener. Sockets past the cap are closed before any protocol work.
// Zero uses a safe default; negative disables the cap.
MaxConnections int `json:"max_connections,omitempty"`
// DisableConsoleLog keeps BHTTP log lines out of stderr. They are still
// captured in memory and served by /api/bhttp/logs for the panel.
DisableConsoleLog bool `json:"disable_console_log,omitempty"`
// LogConnections enables one log line per accepted socket. Leave it off on
// servers with thousands of users; connection logging can become the
// bottleneck.
LogConnections bool `json:"log_connections,omitempty"`
// AutoRestartInterval controls a watchdog that periodically hard-restarts
// only the BHTTP listeners and drops their sessions. Empty, "0s", "off" or
// "disabled" turns it off. Minimum accepted value is 1m.
AutoRestartInterval string `json:"auto_restart_interval,omitempty"`
// AutoRestartGrace is the delay between closing the old listeners and
// binding them again during an auto restart. Empty defaults to "2s".
AutoRestartGrace string `json:"auto_restart_grace,omitempty"`
}
const (
defaultBHTTPListen = "0.0.0.0:8880"
defaultBHTTPSessionTimeout = 2 * time.Minute
defaultBHTTPMaxSessions = 10000
defaultBHTTPMaxConnections = 10000
// bhttpTargetLabel is the "address" handed to the dialer. BHTTP never dials
// a TCP target, so this is only what shows up in logs.
bhttpTargetLabel = "bhttp"
)
var (
bhttpMu sync.Mutex
bhttpServer *bhttp.Server
bhttpListeners []net.Listener
bhttpAddrs []string
// bhttpSharedPorts mirrors BHTTPConfig.SharedPorts for the running
// instance, so the proxy and TLS listeners can check it without reading the
// whole config on every connection.
bhttpSharedPorts bool
bhttpAutoMu sync.Mutex
bhttpAutoCancel context.CancelFunc
bhttpLog = log.New(os.Stderr, "bhttp: ", log.LstdFlags|log.Lmicroseconds)
bhttpLogBuf *ringLogBuffer
)
// ---------- Log buffer shared by the embedded transports ----------
// ringLogBuffer keeps the most recent log lines in memory so the admin panel
// can show them even when console logging is disabled.
type ringLogBuffer struct {
mu sync.Mutex
lines []string
maxLines int
partial string
}
func newRingLogBuffer(maxLines int) *ringLogBuffer {
if maxLines <= 0 {
maxLines = 100
}
return &ringLogBuffer{lines: make([]string, 0, maxLines), maxLines: maxLines}
}
func (b *ringLogBuffer) Write(p []byte) (int, error) {
b.mu.Lock()
defer b.mu.Unlock()
text := b.partial + string(p)
b.partial = ""
for {
index := strings.IndexByte(text, '\n')
if index < 0 {
b.partial = text
break
}
line := strings.TrimRight(text[:index], "\r")
text = text[index+1:]
if line == "" {
continue
}
if len(b.lines) >= b.maxLines {
copy(b.lines, b.lines[1:])
b.lines = b.lines[:len(b.lines)-1]
}
b.lines = append(b.lines, line)
}
return len(p), nil
}
func (b *ringLogBuffer) GetLines() []string {
if b == nil {
return nil
}
b.mu.Lock()
defer b.mu.Unlock()
out := make([]string, len(b.lines))
copy(out, b.lines)
return out
}
func getBHTTPLogLines() []string { return bhttpLogBuf.GetLines() }
// ---------- Handing a tunnelled stream to the built-in SSH server ----------
// transportAddr is a stable net.Addr placeholder for in-process tunnel streams,
// mirroring how the DNSTT integration labels its streams.
type transportAddr string
func (a transportAddr) Network() string { return string(a) }
func (a transportAddr) String() string { return string(a) }
// dialInternalSSH returns a net.Conn whose other end is being served by this
// process's own SSH server. Nothing leaves the process: no loopback socket, no
// system sshd, no PAM. label only affects log output.
//
// The pair is buffered in both directions (see tunnel_pipe.go), so neither
// side has to be reading for the other to make progress. That keeps the SSH
// server's handshake, which writes and reads in the same goroutine, from
// depending on the transport happening to be draining at that moment.
func dialInternalSSH(label string) (net.Conn, error) {
sshConf := getSSHConfig()
if sshConf == nil {
return nil, fmt.Errorf("%s: internal SSH server is not ready", label)
}
clientSide, serverSide := newTunnelConnPair(label, tunnelPipeBuffer)
go func() {
defer func() {
if r := recover(); r != nil {
log.Printf("%s: recovered panic in SSH handler: %v", label, r)
}
}()
defer serverSide.Close()
handleConn(serverSide, sshConf)
}()
return clientSide, nil
}
// ---------- Lifecycle ----------
// stopBHTTP closes the BHTTP listeners, drops every session and stops the
// optional auto-restart watchdog. It is a no-op if BHTTP is not running.
func stopBHTTP() {
stopBHTTPAutoRestart()
stopBHTTPInstance()
}
// stopBHTTPInstance closes only the listeners and sessions. The auto-restart
// watchdog uses this so it can cycle BHTTP without disabling itself.
func stopBHTTPInstance() {
bhttpMu.Lock()
listeners := bhttpListeners
server := bhttpServer
bhttpListeners = nil
bhttpAddrs = nil
bhttpServer = nil
bhttpSharedPorts = false
bhttpMu.Unlock()
for _, listener := range listeners {
if listener != nil {
_ = listener.Close()
}
}
if server != nil {
server.Close()
}
}
func stopBHTTPAutoRestart() {
bhttpAutoMu.Lock()
defer bhttpAutoMu.Unlock()
if bhttpAutoCancel != nil {
bhttpAutoCancel()
bhttpAutoCancel = nil
}
}
func bhttpRunning() bool {
bhttpMu.Lock()
defer bhttpMu.Unlock()
// The server can legitimately run with no listener of its own when it only
// serves connections handed over from the shared proxy and TLS ports.
return bhttpServer != nil
}
// bhttpListenList describes where BHTTP is reachable, for the panel.
func bhttpListenList() string {
bhttpMu.Lock()
addrs := append([]string(nil), bhttpAddrs...)
shared := bhttpSharedPorts
bhttpMu.Unlock()
if shared {
addrs = append(addrs, "shared proxy/TLS ports")
}
return strings.Join(addrs, ", ")
}
// bhttpShareEnabled reports whether a running BHTTP server wants the shared
// proxy and TLS ports.
func bhttpShareEnabled() bool {
bhttpMu.Lock()
defer bhttpMu.Unlock()
return bhttpServer != nil && bhttpSharedPorts
}
func bhttpEnabledInCurrentConfig() bool {
globalCfgMu.RLock()
defer globalCfgMu.RUnlock()
return globalCfg != nil && globalCfg.BHTTP != nil
}
// startBHTTP starts the integrated BHTTP transport if cfg is non-nil. Startup
// errors are returned so the admin panel can report them, but they never crash
// the panel.
func startBHTTP(cfg *BHTTPConfig) error {
if cfg == nil {
return nil
}
stopBHTTPAutoRestart()
if err := startBHTTPInstance(cfg); err != nil {
return err
}
startBHTTPAutoRestart(cfg)
return nil
}
func startBHTTPInstance(cfg *BHTTPConfig) error {
if cfg == nil {
return nil
}
if bhttpLogBuf == nil {
bhttpLogBuf = newRingLogBuffer(200)
}
if cfg.DisableConsoleLog {
bhttpLog.SetOutput(bhttpLogBuf)
} else {
bhttpLog.SetOutput(io.MultiWriter(bhttpLogBuf, os.Stderr))
}
addrs := normalizeBHTTPListenList(cfg.Listen)
cfg.Listen = addrs
if len(addrs) == 0 && !cfg.SharedPorts {
msg := errors.New("bhttp: needs either a listen address or shared_ports")
bhttpLog.Print(msg.Error())
return msg
}
sessionTimeout := bhttpSessionTimeout(cfg)
maxSessions := cfg.MaxSessions
if maxSessions == 0 {
maxSessions = defaultBHTTPMaxSessions
} else if maxSessions < 0 {
maxSessions = 0 // unlimited
}
maxConnections := cfg.MaxConnections
if maxConnections == 0 {
maxConnections = defaultBHTTPMaxConnections
} else if maxConnections < 0 {
maxConnections = 0 // unlimited
}
server := bhttp.NewServer(bhttp.Config{
TargetAddress: bhttpTargetLabel,
SessionTimeout: sessionTimeout,
MaxV2Lanes: cfg.MaxV2Lanes,
MaxSessions: maxSessions,
MaxConnections: maxConnections,
LogConnections: cfg.LogConnections,
Logger: bhttpLog,
DialTarget: dialInternalSSH,
})
// Release the previous instance first: rebinding the same address while the
// old socket is still open would fail with "address already in use".
stopBHTTPInstance()
// Bind synchronously so the panel immediately knows whether BHTTP really
// started or failed on a busy port.
listeners := make([]net.Listener, 0, len(addrs))
bound := make([]string, 0, len(addrs))
for _, addr := range addrs {
listener, err := net.Listen("tcp", addr)
if err != nil {
for _, opened := range listeners {
_ = opened.Close()
}
server.Close()
msg := fmt.Errorf("bhttp: listen failed on %s: %w", addr, err)
bhttpLog.Print(msg.Error())
return msg
}
listeners = append(listeners, listener)
bound = append(bound, addr)
}
bhttpMu.Lock()
bhttpServer = server
bhttpListeners = listeners
bhttpAddrs = bound
bhttpSharedPorts = cfg.SharedPorts
bhttpMu.Unlock()
bhttpLog.Printf("starting: listen=%q shared_ports=%v session_timeout=%s max_v2_lanes=%d max_sessions=%d max_connections=%d log_connections=%v -> built-in SSH server",
bound, cfg.SharedPorts, sessionTimeout, cfg.MaxV2Lanes, maxSessions, maxConnections, cfg.LogConnections)
for _, listener := range listeners {
go func(current net.Listener) {
defer func() {
if r := recover(); r != nil {
bhttpLog.Printf("recovered panic in accept loop: %v", r)
}
}()
if err := server.Serve(current); err != nil && !isListenerClosed(err) {
bhttpLog.Printf("listener %s stopped: %v", current.Addr(), err)
}
}(listener)
}
return nil
}
func startBHTTPAutoRestart(cfg *BHTTPConfig) {
interval := bhttpAutoRestartInterval(cfg)
if interval <= 0 {
return
}
grace := bhttpAutoRestartGrace(cfg)
cfgCopy := *cfg
cfgCopy.Listen = append([]string(nil), cfg.Listen...)
ctx, cancel := context.WithCancel(context.Background())
bhttpAutoMu.Lock()
if bhttpAutoCancel != nil {
bhttpAutoCancel()
}
bhttpAutoCancel = cancel
bhttpAutoMu.Unlock()
go func() {
ticker := time.NewTicker(interval)
defer ticker.Stop()
bhttpLog.Printf("auto restart enabled: interval=%s grace=%s mode=hard", interval, grace)
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
bhttpLog.Print("auto restart: stopping listeners and sessions")
stopBHTTPInstance()
if !sleepOrContextDone(ctx, grace) {
return
}
for attempt := 1; ; attempt++ {
if err := startBHTTPInstance(&cfgCopy); err != nil {
bhttpLog.Printf("auto restart: start attempt %d failed: %v", attempt, err)
if !sleepOrContextDone(ctx, 10*time.Second) {
return
}
continue
}
bhttpLog.Print("auto restart: listeners rebound")
break
}
}
}
}()
}
func bhttpSessionTimeout(cfg *BHTTPConfig) time.Duration {
if cfg == nil {
return defaultBHTTPSessionTimeout
}
raw := strings.TrimSpace(cfg.SessionTimeout)
if raw == "" {
return defaultBHTTPSessionTimeout
}
d, err := time.ParseDuration(raw)
if err != nil || d <= 0 {
bhttpLog.Printf("invalid session_timeout %q; using default %s", raw, defaultBHTTPSessionTimeout)
return defaultBHTTPSessionTimeout
}
return d
}
func bhttpAutoRestartInterval(cfg *BHTTPConfig) time.Duration {
if cfg == nil {
return 0
}
raw := strings.TrimSpace(cfg.AutoRestartInterval)
if raw == "" || raw == "0" || raw == "0s" || strings.EqualFold(raw, "off") || strings.EqualFold(raw, "disabled") {
return 0
}
d, err := time.ParseDuration(raw)
if err != nil {
bhttpLog.Printf("auto restart disabled: invalid interval %q: %v", raw, err)
return 0
}
if d < time.Minute {
bhttpLog.Printf("auto restart disabled: interval %q is below minimum 1m", raw)
return 0
}
return d
}
func bhttpAutoRestartGrace(cfg *BHTTPConfig) time.Duration {
if cfg == nil || strings.TrimSpace(cfg.AutoRestartGrace) == "" {
return 2 * time.Second
}
d, err := time.ParseDuration(strings.TrimSpace(cfg.AutoRestartGrace))
if err != nil || d < 0 {
bhttpLog.Printf("auto restart: invalid grace %q, using 2s", cfg.AutoRestartGrace)
return 2 * time.Second
}
if d > time.Minute {
return time.Minute
}
return d
}
// normalizeBHTTPListenList trims, de-duplicates and preserves the order of the
// configured listen addresses.
func normalizeBHTTPListenList(addrs []string) []string {
seen := make(map[string]bool, len(addrs))
out := make([]string, 0, len(addrs))
for _, addr := range addrs {
addr = strings.TrimSpace(addr)
if addr == "" || seen[addr] {
continue
}
seen[addr] = true
out = append(out, addr)
}
return out
}
// ---------- Stats ----------
// BHTTPStatsSnapshot is what /api/bhttp returns.
type BHTTPStatsSnapshot struct {
Enabled bool `json:"enabled"`
Running bool `json:"running"`
Listen string `json:"listen,omitempty"`
bhttp.StatsSnapshot
}
// GetBHTTPStatsSnapshot returns the current BHTTP counters. It is safe for
// concurrent use and always returns a copy.
func GetBHTTPStatsSnapshot() BHTTPStatsSnapshot {
snapshot := BHTTPStatsSnapshot{
Enabled: bhttpEnabledInCurrentConfig(),
Running: bhttpRunning(),
Listen: bhttpListenList(),
}
bhttpMu.Lock()
server := bhttpServer
bhttpMu.Unlock()
if server != nil {
snapshot.StatsSnapshot = server.Stats()
}
return snapshot
}
+994
View File
@@ -0,0 +1,994 @@
package main
// This file embeds the BTUN protocol server into the panel. BTUN is the native
// DTunnel VPN transport: a client speaks a "DTUNNEL/1.1 CLIENT_HELLO" handshake
// over TCP or UDP, authenticates, is handed an IPv4 address from a private
// subnet, and then exchanges raw IPv4 packets with a TUN interface owned by
// this process.
//
// Unlike BHTTP or DNSTT, BTUN is not an SSH carrier — it moves IP packets, not
// an SSH stream. Authentication therefore cannot be delegated to handleConn, so
// it is delegated to the panel's own account database instead: the same
// username/password (or TOTP), the same expiry, reseller-owner, data-quota and
// max_connections rules that passwordCallback enforces for SSH. PAM,
// /etc/shadow and password files are deliberately unreachable from this path;
// a BTUN login is a panel login and nothing else.
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"log"
"net"
"os"
"os/exec"
"strconv"
"strings"
"sync"
"time"
"golang.org/x/time/rate"
"shell2/internal/btun"
)
// BTUNConfig defines the settings for the integrated BTUN server. A nil
// *BTUNConfig in the main config disables it entirely.
type BTUNConfig struct {
// TCPListen is the TCP address for BTUN clients. Empty disables the TCP
// transport. IPv6 addresses must use bracket form, e.g. "[::]:7300".
TCPListen string `json:"tcp_listen"`
// UDPListen is the UDP address for BTUN clients. Empty disables the UDP
// transport. At least one of TCPListen/UDPListen must be set.
UDPListen string `json:"udp_listen"`
// SharedPorts also accepts BTUN on the ports the panel already owns: the
// HTTP+SSH proxy listeners (listen and extra_listen, normally 80 and 8080)
// and every TLS forwarder (normally 443). Those listeners read the first
// bytes of each connection and hand it here only on the fixed
// "DTUNNEL/1.1 CLIENT_HELLO" marker, so SSH and HTTP-injection clients on
// the same port are unaffected.
//
// This covers the TCP transport only: the panel owns no shared UDP port, so
// UDP clients still need UDPListen. A TCP client that prepends cover bytes
// is matched when that cover is an HTTP request (the panel's own HTTP
// cleanup consumes it first); other cover shapes need TCPListen, because a
// shared port cannot buffer an unbounded prefix while SSH waits behind it.
SharedPorts bool `json:"shared_ports,omitempty"`
// TUNName is the TUN interface this server creates and owns. Default
// "btun0". It must not collide with an interface another service owns.
TUNName string `json:"tun_name,omitempty"`
// Subnet is the private IPv4 range handed out to clients, in CIDR form.
// Default "10.77.0.0/16". It must have room for at least four addresses.
Subnet string `json:"subnet,omitempty"`
// Gateway is the address configured on the TUN interface itself, in CIDR
// form, and is the first usable address of Subnet by convention. Empty
// derives it from Subnet (for 10.77.0.0/16 that is 10.77.0.1/16).
Gateway string `json:"gateway,omitempty"`
// MTU is set on the TUN interface. Default 1400, which leaves headroom for
// the BTUN framing plus an outer TCP/UDP header on a 1500-byte path.
MTU int `json:"mtu,omitempty"`
// ManageRouting lets the panel configure the interface address, MTU,
// net.ipv4.ip_forward and the NAT/forward rules for Subnet itself. Turn it
// off only when an external script (or an existing btun-routing unit)
// already owns those rules.
ManageRouting bool `json:"manage_routing,omitempty"`
// WANInterface is the uplink used for NAT. Empty auto-detects it from the
// default IPv4 route, which is correct on a single-uplink VPS.
WANInterface string `json:"wan_interface,omitempty"`
// HandshakeTimeout bounds the hello + authentication exchange. Empty
// defaults to "15s".
HandshakeTimeout string `json:"handshake_timeout,omitempty"`
// IdleTimeout drops a session that sends nothing for this long. Empty
// defaults to "2m". Clients send keep-alives, so this only reaps dead peers.
IdleTimeout string `json:"idle_timeout,omitempty"`
// MaxPacketSize limits a single BTUN frame payload in bytes. Zero uses the
// protocol default (64 KiB); the hard ceiling is 4 MiB.
MaxPacketSize int `json:"max_packet_size,omitempty"`
// MaxCoverBytes is how much junk a TCP client may send before its
// CLIENT_HELLO, which is what lets BTUN hide behind an HTTP-looking
// preamble. Zero uses the default (64 KiB).
MaxCoverBytes int `json:"max_cover_bytes,omitempty"`
// MaxSessions caps concurrent BTUN sessions across both transports. Zero
// uses a safe default; negative disables the cap. Per-account limits still
// come from each user's max_connections.
MaxSessions int `json:"max_sessions,omitempty"`
// DisableConsoleLog keeps BTUN log lines out of stderr. They are still
// captured in memory and served by /api/btun/logs for the panel.
DisableConsoleLog bool `json:"disable_console_log,omitempty"`
// LogConnections enables one log line per session start/stop.
LogConnections bool `json:"log_connections,omitempty"`
// AutoRestartInterval controls a watchdog that periodically hard-restarts
// only the BTUN listeners and TUN device. Empty, "0s", "off" or "disabled"
// turns it off. Minimum accepted value is 1m.
AutoRestartInterval string `json:"auto_restart_interval,omitempty"`
// AutoRestartGrace is the delay between tearing the old instance down and
// bringing a new one up during an auto restart. Empty defaults to "2s".
AutoRestartGrace string `json:"auto_restart_grace,omitempty"`
}
const (
defaultBTUNTCPListen = "0.0.0.0:7300"
defaultBTUNUDPListen = "0.0.0.0:7300"
defaultBTUNName = "btun0"
defaultBTUNSubnet = "10.77.0.0/16"
defaultBTUNMTU = 1400
defaultBTUNHandshakeTimeout = 15 * time.Second
defaultBTUNIdleTimeout = 2 * time.Minute
defaultBTUNMaxSessions = 10000
btunMaxPacketCeiling = 4 * 1024 * 1024
btunRouteCommandTimeout = 10 * time.Second
)
var (
btunMu sync.Mutex
btunServer *btun.Server
btunDevice btun.PacketDevice
btunTCP net.Listener
btunUDP net.PacketConn
btunListenTCP string
btunListenUDP string
// btunSharedPorts mirrors BTUNConfig.SharedPorts for the running instance,
// so the proxy and TLS listeners can check it without reading the whole
// config on every connection.
btunSharedPorts bool
// btunRoutingApplied records the settings used to add routing rules, so the
// exact same rules can be removed on shutdown even after the config changed.
btunRoutingApplied *btunRoutingSpec
btunAutoMu sync.Mutex
btunAutoCancel context.CancelFunc
btunLog = log.New(os.Stderr, "btun: ", log.LstdFlags|log.Lmicroseconds)
btunLogBuf *ringLogBuffer
// btunSessionsMu guards the per-account session registry used for
// max_connections and for forced disconnects from the panel.
btunSessionsMu sync.Mutex
btunSessions = make(map[string]map[*btunLedger]struct{})
)
func getBTUNLogLines() []string { return btunLogBuf.GetLines() }
// ---------- Panel-backed authentication ----------
// btunPanelAuthenticator verifies a BTUN credential against the panel's own
// account database. It is intentionally the only authenticator wired into the
// BTUN server: there is no PAM, /etc/shadow or password-file path here, and
// pam_auth_enabled does not apply to BTUN.
type btunPanelAuthenticator struct{}
func (btunPanelAuthenticator) Name() string { return "panel" }
func (btunPanelAuthenticator) Authenticate(username, password string) error {
// Mirrors passwordCallback's panel-credential branch. Kept as a separate
// implementation because passwordCallback is bound to ssh.ConnMetadata and
// also owns the (unrelated) system-login path.
u, ok := userMgr.Get(username)
if !ok {
return errors.New("invalid username or password")
}
now := time.Now()
if u.ExpiresAt != nil && now.After(*u.ExpiresAt) {
return errors.New("account expired")
}
if sshUserQuotaBlocked(u) {
return errDataQuotaExceeded
}
if err := ownerIsActive(u.Cfg.OwnerUsername); err != nil {
return errors.New("invalid username or password")
}
u.mu.Lock()
cfg := u.Cfg
u.mu.Unlock()
if strings.TrimSpace(cfg.TOTPSecret) != "" {
if matchTOTPPassword(u, password, now) {
return nil
}
if cfg.AllowStaticPassword && cfg.Password == password {
return nil
}
return errors.New("invalid username or password")
}
if cfg.Password != password {
return errors.New("invalid username or password")
}
return nil
}
// ---------- Panel-backed accounting ----------
// btunPanelAccountant admits authenticated BTUN sessions and meters their
// traffic against the same per-user counters the SSH path uses, so a user's
// bandwidth limits, data quota and connection count cover both transports.
type btunPanelAccountant struct{}
func (btunPanelAccountant) Admit(username, remote string, closer io.Closer) (btun.Ledger, error) {
u, ok := userMgr.Get(username)
if !ok {
return nil, errors.New("account not found")
}
u.mu.Lock()
cfg := u.Cfg
// max_connections is shared with SSH: BTUN sessions and SSH connections
// count against the same allowance, so a user cannot double their limit by
// mixing transports.
active := len(u.conns) + u.btunConns
if cfg.MaxConnections > 0 && active >= cfg.MaxConnections {
u.mu.Unlock()
return nil, fmt.Errorf("connection limit reached (%d)", cfg.MaxConnections)
}
u.btunConns++
u.ActiveConns = len(u.conns) + u.btunConns
u.mu.Unlock()
limitUp, limitDown := cfg.LimitMbpsUp, cfg.LimitMbpsDown
if limitUp == 0 || limitDown == 0 {
defUp, defDown := getDefaultLimits()
if limitUp == 0 {
limitUp = defUp
}
if limitDown == 0 {
limitDown = defDown
}
}
ledger := &btunLedger{
user: u,
username: username,
remote: remote,
closer: closer,
up: btunRateLimiter(limitUp),
down: btunRateLimiter(limitDown),
}
btunSessionsMu.Lock()
if btunSessions[username] == nil {
btunSessions[username] = make(map[*btunLedger]struct{})
}
btunSessions[username][ledger] = struct{}{}
btunSessionsMu.Unlock()
updateUserDisplay()
return ledger, nil
}
// btunRateLimiter builds a per-session limiter for an Mbps value. The burst is
// never smaller than one maximum-size IP packet, otherwise WaitN would reject
// a legitimate packet outright instead of pacing it.
func btunRateLimiter(mbps int) *rate.Limiter {
if mbps <= 0 {
return nil
}
bps := mbpsToBytesPerSec(mbps)
burst := int(bps)
if burst < 64*1024 {
burst = 64 * 1024
}
return rate.NewLimiter(rate.Limit(bps), burst)
}
// btunLedger meters one BTUN session against its panel account.
type btunLedger struct {
user *UserState
username string
remote string
closer io.Closer
up *rate.Limiter
down *rate.Limiter
once sync.Once
}
func (l *btunLedger) Uplink(ctx context.Context, n int) error {
return l.meter(ctx, true, l.up, n)
}
func (l *btunLedger) Downlink(ctx context.Context, n int) error {
return l.meter(ctx, false, l.down, n)
}
// meter reserves quota for one IP packet, paces it, and commits the bytes.
// BTUN forwards whole packets, so a partial quota allowance cannot be honoured:
// the reservation is released and the session ends instead of sending a
// truncated packet.
func (l *btunLedger) meter(ctx context.Context, uplink bool, limiter *rate.Limiter, n int) error {
if l.user == nil || n <= 0 {
return nil
}
// Held for the same reason sshQuotaWriter holds it: a traffic reset must not
// interleave with a reservation.
l.user.trafficMu.RLock()
defer l.user.trafficMu.RUnlock()
allowed, quotaLimiter, stopAfter := reserveSSHUserBytes(l.user, n)
if allowed <= 0 {
return errDataQuotaExceeded
}
if allowed < n {
finishSSHUserReservation(l.user, uplink, allowed, 0)
return errDataQuotaExceeded
}
if limiter != nil {
if err := limiter.WaitN(ctx, n); err != nil {
finishSSHUserReservation(l.user, uplink, allowed, 0)
return err
}
}
if quotaLimiter != nil {
if err := quotaLimiter.WaitN(ctx, allowed); err != nil {
finishSSHUserReservation(l.user, uplink, allowed, 0)
return err
}
}
finishSSHUserReservation(l.user, uplink, allowed, allowed)
if stopAfter {
return errDataQuotaExceeded
}
return nil
}
func (l *btunLedger) Close() {
l.once.Do(func() {
btunSessionsMu.Lock()
if set := btunSessions[l.username]; set != nil {
delete(set, l)
if len(set) == 0 {
delete(btunSessions, l.username)
}
}
btunSessionsMu.Unlock()
if l.user != nil {
l.user.mu.Lock()
if l.user.btunConns > 0 {
l.user.btunConns--
}
l.user.ActiveConns = len(l.user.conns) + l.user.btunConns
l.user.mu.Unlock()
}
updateUserDisplay()
})
}
// btunDisconnectUser closes every BTUN session belonging to username. It is
// called from UserManager.DisconnectUser so panel actions (delete, edit,
// expire) drop BTUN sessions the same way they drop SSH connections.
func btunDisconnectUser(username string) int {
btunSessionsMu.Lock()
ledgers := make([]*btunLedger, 0, len(btunSessions[username]))
for ledger := range btunSessions[username] {
ledgers = append(ledgers, ledger)
}
btunSessionsMu.Unlock()
for _, ledger := range ledgers {
if ledger.closer != nil {
_ = ledger.closer.Close()
}
}
return len(ledgers)
}
// btunDisconnectAll closes every tracked BTUN session.
func btunDisconnectAll() int {
btunSessionsMu.Lock()
ledgers := make([]*btunLedger, 0, len(btunSessions))
for _, set := range btunSessions {
for ledger := range set {
ledgers = append(ledgers, ledger)
}
}
btunSessionsMu.Unlock()
for _, ledger := range ledgers {
if ledger.closer != nil {
_ = ledger.closer.Close()
}
}
return len(ledgers)
}
// ---------- Lifecycle ----------
// stopBTUN tears down the BTUN listeners, TUN device, routing rules and the
// optional auto-restart watchdog. It is a no-op if BTUN is not running.
func stopBTUN() {
stopBTUNAutoRestart()
stopBTUNInstance()
}
// stopBTUNInstance closes only the running instance. The auto-restart watchdog
// uses this so it can cycle BTUN without disabling itself.
func stopBTUNInstance() {
btunMu.Lock()
server := btunServer
device := btunDevice
tcpListener := btunTCP
udpConn := btunUDP
routing := btunRoutingApplied
btunServer = nil
btunDevice = nil
btunTCP = nil
btunUDP = nil
btunListenTCP = ""
btunListenUDP = ""
btunSharedPorts = false
btunRoutingApplied = nil
btunMu.Unlock()
if tcpListener != nil {
_ = tcpListener.Close()
}
if udpConn != nil {
_ = udpConn.Close()
}
if server != nil {
// Server.Close also closes the TUN device it was given.
if err := server.Close(); err != nil {
btunLog.Printf("shutdown: %v", err)
}
server.Wait()
} else if device != nil {
_ = device.Close()
}
if routing != nil {
removeBTUNRouting(*routing)
}
}
func stopBTUNAutoRestart() {
btunAutoMu.Lock()
defer btunAutoMu.Unlock()
if btunAutoCancel != nil {
btunAutoCancel()
btunAutoCancel = nil
}
}
func btunRunning() bool {
btunMu.Lock()
defer btunMu.Unlock()
return btunServer != nil
}
// btunListenList reports the addresses currently bound, for the panel.
func btunListenList() string {
btunMu.Lock()
defer btunMu.Unlock()
parts := make([]string, 0, 3)
if btunListenTCP != "" {
parts = append(parts, "tcp "+btunListenTCP)
}
if btunListenUDP != "" {
parts = append(parts, "udp "+btunListenUDP)
}
if btunSharedPorts {
parts = append(parts, "shared proxy/TLS ports")
}
return strings.Join(parts, ", ")
}
// btunShareEnabled reports whether a running BTUN server wants the shared proxy
// and TLS ports.
func btunShareEnabled() bool {
btunMu.Lock()
defer btunMu.Unlock()
return btunServer != nil && btunSharedPorts
}
// btunConfiguredListen describes the addresses a config asks for, used in
// status reports when the server failed to bind them.
func btunConfiguredListen(cfg *BTUNConfig) string {
if cfg == nil {
return ""
}
parts := make([]string, 0, 3)
if addr := strings.TrimSpace(cfg.TCPListen); addr != "" {
parts = append(parts, "tcp "+addr)
}
if addr := strings.TrimSpace(cfg.UDPListen); addr != "" {
parts = append(parts, "udp "+addr)
}
if cfg.SharedPorts {
parts = append(parts, "shared proxy/TLS ports")
}
return strings.Join(parts, ", ")
}
func btunEnabledInCurrentConfig() bool {
globalCfgMu.RLock()
defer globalCfgMu.RUnlock()
return globalCfg != nil && globalCfg.BTUN != nil
}
// startBTUN starts the integrated BTUN server if cfg is non-nil. Startup errors
// are returned so the admin panel can report them, but they never crash the
// panel.
func startBTUN(cfg *BTUNConfig) error {
if cfg == nil {
return nil
}
stopBTUNAutoRestart()
if err := startBTUNInstance(cfg); err != nil {
return err
}
startBTUNAutoRestart(cfg)
return nil
}
func startBTUNInstance(cfg *BTUNConfig) error {
if cfg == nil {
return nil
}
if btunLogBuf == nil {
btunLogBuf = newRingLogBuffer(200)
}
if cfg.DisableConsoleLog {
btunLog.SetOutput(btunLogBuf)
} else {
btunLog.SetOutput(io.MultiWriter(btunLogBuf, os.Stderr))
}
normalizeBTUNConfig(cfg)
if cfg.TCPListen == "" && cfg.UDPListen == "" && !cfg.SharedPorts {
msg := errors.New("btun: needs tcp_listen, udp_listen or shared_ports")
btunLog.Print(msg.Error())
return msg
}
// Release the previous instance first: the TUN interface name and the
// listen addresses cannot be held twice.
stopBTUNInstance()
device, err := btun.OpenTUN(cfg.TUNName)
if err != nil {
msg := fmt.Errorf("btun: open TUN %s: %w", cfg.TUNName, err)
btunLog.Print(msg.Error())
return msg
}
maxSessions := cfg.MaxSessions
if maxSessions == 0 {
maxSessions = defaultBTUNMaxSessions
} else if maxSessions < 0 {
maxSessions = 0 // unlimited
}
server, err := btun.NewServer(btun.Config{
Subnet: cfg.Subnet,
Authenticator: btunPanelAuthenticator{},
Accountant: btunPanelAccountant{},
Logger: btunLog,
HandshakeTimeout: btunDurationOrDefault(cfg.HandshakeTimeout, defaultBTUNHandshakeTimeout, "handshake_timeout"),
IdleTimeout: btunDurationOrDefault(cfg.IdleTimeout, defaultBTUNIdleTimeout, "idle_timeout"),
MaxPacketSize: cfg.MaxPacketSize,
MaxCoverBytes: cfg.MaxCoverBytes,
MaxSessions: maxSessions,
LogConnections: cfg.LogConnections,
}, device)
if err != nil {
_ = device.Close()
msg := fmt.Errorf("btun: %w", err)
btunLog.Print(msg.Error())
return msg
}
var tcpListener net.Listener
if cfg.TCPListen != "" {
tcpListener, err = net.Listen("tcp", cfg.TCPListen)
if err != nil {
_ = server.Close()
msg := fmt.Errorf("btun: listen TCP %s: %w", cfg.TCPListen, err)
btunLog.Print(msg.Error())
return msg
}
}
var udpConn net.PacketConn
if cfg.UDPListen != "" {
udpConn, err = net.ListenPacket("udp", cfg.UDPListen)
if err != nil {
if tcpListener != nil {
_ = tcpListener.Close()
}
_ = server.Close()
msg := fmt.Errorf("btun: listen UDP %s: %w", cfg.UDPListen, err)
btunLog.Print(msg.Error())
return msg
}
}
var routing *btunRoutingSpec
if cfg.ManageRouting {
spec, routeErr := applyBTUNRouting(cfg, device.Name())
if routeErr != nil {
// Routing is a host-configuration concern: the tunnel itself is up,
// so keep serving and surface the problem instead of refusing to
// start. Without NAT clients reach the server but not the internet.
btunLog.Printf("routing not fully applied: %v", routeErr)
}
routing = &spec
}
btunMu.Lock()
btunServer = server
btunDevice = device
btunTCP = tcpListener
btunUDP = udpConn
btunListenTCP = cfg.TCPListen
btunListenUDP = cfg.UDPListen
btunSharedPorts = cfg.SharedPorts
btunRoutingApplied = routing
btunMu.Unlock()
btunLog.Printf("starting: tun=%s subnet=%s gateway=%s mtu=%d tcp=%q udp=%q shared_ports=%v auth=panel manage_routing=%v max_sessions=%d log_connections=%v",
device.Name(), cfg.Subnet, cfg.Gateway, cfg.MTU, cfg.TCPListen, cfg.UDPListen,
cfg.SharedPorts, cfg.ManageRouting, maxSessions, cfg.LogConnections)
if tcpListener != nil {
go func() {
defer btunRecover("ServeTCP")
if err := server.ServeTCP(tcpListener); err != nil && !isListenerClosed(err) {
btunLog.Printf("TCP listener stopped: %v", err)
}
}()
}
if udpConn != nil {
go func() {
defer btunRecover("ServeUDP")
if err := server.ServeUDP(udpConn); err != nil && !isListenerClosed(err) {
btunLog.Printf("UDP listener stopped: %v", err)
}
}()
}
return nil
}
func btunRecover(where string) {
if r := recover(); r != nil {
btunLog.Printf("recovered panic in %s: %v", where, r)
}
}
func startBTUNAutoRestart(cfg *BTUNConfig) {
interval := btunAutoRestartInterval(cfg)
if interval <= 0 {
return
}
grace := btunAutoRestartGrace(cfg)
cfgCopy := *cfg
ctx, cancel := context.WithCancel(context.Background())
btunAutoMu.Lock()
if btunAutoCancel != nil {
btunAutoCancel()
}
btunAutoCancel = cancel
btunAutoMu.Unlock()
go func() {
ticker := time.NewTicker(interval)
defer ticker.Stop()
btunLog.Printf("auto restart enabled: interval=%s grace=%s mode=hard", interval, grace)
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
btunLog.Print("auto restart: stopping listeners, sessions and TUN device")
stopBTUNInstance()
if !sleepOrContextDone(ctx, grace) {
return
}
for attempt := 1; ; attempt++ {
if err := startBTUNInstance(&cfgCopy); err != nil {
btunLog.Printf("auto restart: start attempt %d failed: %v", attempt, err)
if !sleepOrContextDone(ctx, 10*time.Second) {
return
}
continue
}
btunLog.Print("auto restart: server restarted")
break
}
}
}
}()
}
func btunAutoRestartInterval(cfg *BTUNConfig) time.Duration {
if cfg == nil {
return 0
}
raw := strings.TrimSpace(cfg.AutoRestartInterval)
if raw == "" || raw == "0" || raw == "0s" || strings.EqualFold(raw, "off") || strings.EqualFold(raw, "disabled") {
return 0
}
d, err := time.ParseDuration(raw)
if err != nil {
btunLog.Printf("auto restart disabled: invalid interval %q: %v", raw, err)
return 0
}
if d < time.Minute {
btunLog.Printf("auto restart disabled: interval %q is below minimum 1m", raw)
return 0
}
return d
}
func btunAutoRestartGrace(cfg *BTUNConfig) time.Duration {
if cfg == nil || strings.TrimSpace(cfg.AutoRestartGrace) == "" {
return 2 * time.Second
}
d, err := time.ParseDuration(strings.TrimSpace(cfg.AutoRestartGrace))
if err != nil || d < 0 {
btunLog.Printf("auto restart: invalid grace %q, using 2s", cfg.AutoRestartGrace)
return 2 * time.Second
}
if d > time.Minute {
return time.Minute
}
return d
}
func btunDurationOrDefault(raw string, fallback time.Duration, field string) time.Duration {
raw = strings.TrimSpace(raw)
if raw == "" {
return fallback
}
d, err := time.ParseDuration(raw)
if err != nil || d <= 0 {
btunLog.Printf("invalid %s %q; using default %s", field, raw, fallback)
return fallback
}
return d
}
// normalizeBTUNConfig fills in defaults and derives the gateway address. It
// mutates cfg so the value persisted by the admin API matches what runs.
func normalizeBTUNConfig(cfg *BTUNConfig) {
cfg.TCPListen = strings.TrimSpace(cfg.TCPListen)
cfg.UDPListen = strings.TrimSpace(cfg.UDPListen)
cfg.TUNName = strings.TrimSpace(cfg.TUNName)
if cfg.TUNName == "" {
cfg.TUNName = defaultBTUNName
}
cfg.Subnet = strings.TrimSpace(cfg.Subnet)
if cfg.Subnet == "" {
cfg.Subnet = defaultBTUNSubnet
}
cfg.Gateway = strings.TrimSpace(cfg.Gateway)
if cfg.Gateway == "" {
if derived, err := btunGatewayForSubnet(cfg.Subnet); err == nil {
cfg.Gateway = derived
}
}
if cfg.MTU <= 0 {
cfg.MTU = defaultBTUNMTU
}
if cfg.MaxPacketSize > btunMaxPacketCeiling {
btunLog.Printf("max_packet_size %d exceeds the %d ceiling; clamping",
cfg.MaxPacketSize, btunMaxPacketCeiling)
cfg.MaxPacketSize = btunMaxPacketCeiling
}
cfg.WANInterface = strings.TrimSpace(cfg.WANInterface)
}
// btunGatewayForSubnet returns the first usable address of subnet in CIDR form,
// which is the address the TUN interface takes. For 10.77.0.0/16 that is
// 10.77.0.1/16.
func btunGatewayForSubnet(subnet string) (string, error) {
ip, network, err := net.ParseCIDR(subnet)
if err != nil {
return "", err
}
if ip.To4() == nil {
return "", errors.New("BTUN subnet must be IPv4")
}
ones, bits := network.Mask.Size()
if bits != 32 || ones > 30 {
return "", errors.New("BTUN subnet must contain at least four IPv4 addresses")
}
base := network.IP.To4()
gateway := net.IPv4(base[0], base[1], base[2], base[3]).To4()
gateway[3] |= 1
return fmt.Sprintf("%s/%d", gateway.String(), ones), nil
}
// ---------- Host routing ----------
// btunRoutingSpec records exactly which rules were installed, so the same ones
// can be removed later even if the configuration changed in between.
type btunRoutingSpec struct {
TUNName string
Subnet string
Gateway string
MTU int
WAN string
}
// applyBTUNRouting configures the TUN interface and the NAT/forward rules that
// let BTUN clients reach the internet. It mirrors deploy/btun/btun-routing from
// the standalone deployment, but runs in-process so the panel owns the state.
func applyBTUNRouting(cfg *BTUNConfig, tunName string) (btunRoutingSpec, error) {
spec := btunRoutingSpec{
TUNName: tunName,
Subnet: cfg.Subnet,
Gateway: cfg.Gateway,
MTU: cfg.MTU,
WAN: cfg.WANInterface,
}
if spec.WAN == "" {
detected, err := detectDefaultWANInterface()
if err != nil {
return spec, fmt.Errorf("detect WAN interface: %w (set wan_interface explicitly)", err)
}
spec.WAN = detected
btunLog.Printf("routing: detected WAN interface %s", detected)
}
var problems []string
run := func(name string, args ...string) {
if out, err := runBTUNCommand(name, args...); err != nil {
problems = append(problems, fmt.Sprintf("%s %s: %v%s", name, strings.Join(args, " "), err, out))
}
}
if spec.Gateway != "" {
run("ip", "address", "replace", spec.Gateway, "dev", spec.TUNName)
}
run("ip", "link", "set", "dev", spec.TUNName, "mtu", strconv.Itoa(spec.MTU), "up")
// Only write the sysctl when forwarding is actually off. On most hosts it
// is already on, and the write is denied in restricted environments
// (containers, hardened kernels) where forwarding nonetheless works, which
// would otherwise report a failure for something already correct.
if !ipForwardingEnabled() {
run("sysctl", "-w", "net.ipv4.ip_forward=1")
}
// Each rule is added only when an identical one is not already present, so
// repeated restarts do not stack duplicates in the tables.
ensure := func(check, add []string) {
if _, err := runBTUNCommand("iptables", check...); err == nil {
return
}
if out, err := runBTUNCommand("iptables", add...); err != nil {
problems = append(problems, fmt.Sprintf("iptables %s: %v%s", strings.Join(add, " "), err, out))
}
}
ensure(
[]string{"-t", "nat", "-C", "POSTROUTING", "-s", spec.Subnet, "-o", spec.WAN, "-j", "MASQUERADE"},
[]string{"-t", "nat", "-A", "POSTROUTING", "-s", spec.Subnet, "-o", spec.WAN, "-j", "MASQUERADE"},
)
ensure(
[]string{"-C", "FORWARD", "-i", spec.TUNName, "-o", spec.WAN, "-j", "ACCEPT"},
[]string{"-A", "FORWARD", "-i", spec.TUNName, "-o", spec.WAN, "-j", "ACCEPT"},
)
ensure(
[]string{"-C", "FORWARD", "-i", spec.WAN, "-o", spec.TUNName, "-m", "conntrack", "--ctstate", "RELATED,ESTABLISHED", "-j", "ACCEPT"},
[]string{"-A", "FORWARD", "-i", spec.WAN, "-o", spec.TUNName, "-m", "conntrack", "--ctstate", "RELATED,ESTABLISHED", "-j", "ACCEPT"},
)
if len(problems) > 0 {
return spec, errors.New(strings.Join(problems, "; "))
}
btunLog.Printf("routing: %s %s up, NAT via %s", spec.TUNName, spec.Gateway, spec.WAN)
return spec, nil
}
// removeBTUNRouting deletes the rules applyBTUNRouting installed. Failures are
// logged and ignored: the rules may already be gone, or the interface may have
// disappeared with the TUN device.
func removeBTUNRouting(spec btunRoutingSpec) {
if spec.WAN == "" || spec.TUNName == "" {
return
}
deletes := [][]string{
{"-t", "nat", "-D", "POSTROUTING", "-s", spec.Subnet, "-o", spec.WAN, "-j", "MASQUERADE"},
{"-D", "FORWARD", "-i", spec.TUNName, "-o", spec.WAN, "-j", "ACCEPT"},
{"-D", "FORWARD", "-i", spec.WAN, "-o", spec.TUNName, "-m", "conntrack", "--ctstate", "RELATED,ESTABLISHED", "-j", "ACCEPT"},
}
for _, args := range deletes {
if _, err := runBTUNCommand("iptables", args...); err != nil {
btunLog.Printf("routing cleanup: iptables %s: %v", strings.Join(args, " "), err)
}
}
}
// ipForwardingEnabled reports whether the kernel already forwards IPv4. A read
// error is treated as "not enabled" so the caller still attempts the write.
func ipForwardingEnabled() bool {
data, err := os.ReadFile("/proc/sys/net/ipv4/ip_forward")
if err != nil {
return false
}
return strings.TrimSpace(string(data)) == "1"
}
// detectDefaultWANInterface reads the uplink from the default IPv4 route, the
// same way the standalone btun-routing script does.
func detectDefaultWANInterface() (string, error) {
out, err := runBTUNCommand("ip", "-4", "route", "show", "default")
if err != nil {
return "", err
}
for _, line := range strings.Split(out, "\n") {
fields := strings.Fields(line)
for index := 0; index+1 < len(fields); index++ {
if fields[index] == "dev" {
return fields[index+1], nil
}
}
}
return "", errors.New("no default IPv4 route")
}
// runBTUNCommand runs a short host command with a timeout and returns its
// combined output. The output is included in error strings so a failing
// iptables rule is diagnosable from the panel.
func runBTUNCommand(name string, args ...string) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), btunRouteCommandTimeout)
defer cancel()
var output bytes.Buffer
command := exec.CommandContext(ctx, name, args...)
command.Stdout = &output
command.Stderr = &output
err := command.Run()
text := strings.TrimSpace(output.String())
if text != "" {
text = ": " + text
}
return text, err
}
// ---------- Stats ----------
// BTUNStatsSnapshot is what /api/btun returns.
type BTUNStatsSnapshot struct {
Enabled bool `json:"enabled"`
Running bool `json:"running"`
Listen string `json:"listen,omitempty"`
TUNName string `json:"tunName,omitempty"`
Subnet string `json:"subnet,omitempty"`
btun.StatsSnapshot
}
// GetBTUNStatsSnapshot returns the current BTUN counters. It is safe for
// concurrent use and always returns a copy.
func GetBTUNStatsSnapshot() BTUNStatsSnapshot {
snapshot := BTUNStatsSnapshot{
Enabled: btunEnabledInCurrentConfig(),
Running: btunRunning(),
Listen: btunListenList(),
}
btunMu.Lock()
server := btunServer
device := btunDevice
btunMu.Unlock()
if device != nil {
snapshot.TUNName = device.Name()
}
if server != nil {
snapshot.StatsSnapshot = server.Stats()
}
globalCfgMu.RLock()
if globalCfg != nil && globalCfg.BTUN != nil {
snapshot.Subnet = globalCfg.BTUN.Subnet
}
globalCfgMu.RUnlock()
return snapshot
}
+184
View File
@@ -0,0 +1,184 @@
//go:build linux
package main
// These tests exercise the parts of BTUN that only exist on Linux and need real
// privileges: creating the TUN interface, and installing and removing the
// NAT/forward rules that let clients reach the internet. Nothing else in the
// suite can reach that code, so without these it ships unexecuted.
//
// They are opt-in because they need NET_ADMIN and /dev/net/tun. Run them with:
//
// docker run --rm --cap-add NET_ADMIN --device /dev/net/tun \
// -v "$PWD:/src" dragoncore-build tun
import (
"os"
"os/exec"
"strings"
"testing"
"time"
"shell2/internal/btun"
)
// requireTUN skips unless the environment can actually create a TUN device.
func requireTUN(t *testing.T) {
t.Helper()
if os.Getenv("BTUN_TUN_TESTS") == "" {
t.Skip("set BTUN_TUN_TESTS=1 and grant NET_ADMIN + /dev/net/tun to run this")
}
if _, err := os.Stat("/dev/net/tun"); err != nil {
t.Skipf("/dev/net/tun is unavailable: %v", err)
}
}
// OpenTUN is the call that fails on a container without /dev/net/tun and is the
// single most common reason BTUN does not start. This checks that it really
// creates the interface it names, and really releases it on Close.
func TestBTUNOpenTUNCreatesAndReleasesTheInterface(t *testing.T) {
requireTUN(t)
const name = "btuntest0"
device, err := btun.OpenTUN(name)
if err != nil {
t.Fatalf("OpenTUN(%q): %v", name, err)
}
if device.Name() != name {
t.Fatalf("device name = %q, want %q", device.Name(), name)
}
if !interfaceExists(t, name) {
t.Fatalf("interface %s was not created in the kernel", name)
}
if err := device.Close(); err != nil {
t.Fatalf("close: %v", err)
}
// The kernel removes the interface once the last handle is gone, which may
// take a moment.
deadline := time.Now().Add(5 * time.Second)
for interfaceExists(t, name) {
if time.Now().After(deadline) {
t.Fatalf("interface %s survived the device being closed", name)
}
time.Sleep(50 * time.Millisecond)
}
}
// An interface name the kernel cannot accept has to fail cleanly rather than
// leaving a half-open device behind.
func TestBTUNOpenTUNRejectsInvalidNames(t *testing.T) {
requireTUN(t)
for _, name := range []string{"", "this-name-is-far-too-long"} {
if device, err := btun.OpenTUN(name); err == nil {
_ = device.Close()
t.Fatalf("OpenTUN(%q) succeeded, want an error", name)
}
}
}
// The managed-routing path configures the interface and installs NAT. This runs
// it for real and then checks the rules it claims to have added are present,
// and that removing them leaves the tables as they were.
func TestBTUNManagedRoutingInstallsAndRemovesItsRules(t *testing.T) {
requireTUN(t)
if _, err := exec.LookPath("iptables"); err != nil {
t.Skip("iptables is not installed")
}
const name = "btuntest1"
const subnet = "10.79.0.0/24"
device, err := btun.OpenTUN(name)
if err != nil {
t.Fatalf("OpenTUN: %v", err)
}
defer device.Close()
cfg := &BTUNConfig{
TCPListen: "127.0.0.1:0",
Subnet: subnet,
TUNName: name,
MTU: 1400,
ManageRouting: true,
WANInterface: "eth0",
}
normalizeBTUNConfig(cfg)
if cfg.Gateway != "10.79.0.1/24" {
t.Fatalf("derived gateway = %q, want 10.79.0.1/24", cfg.Gateway)
}
spec, err := applyBTUNRouting(cfg, device.Name())
if err != nil {
t.Fatalf("applyBTUNRouting: %v", err)
}
t.Cleanup(func() { removeBTUNRouting(spec) })
if !interfaceHasAddress(t, name, "10.79.0.1") {
t.Fatalf("gateway address was not configured on %s", name)
}
if !natRuleExists(t, subnet) {
t.Fatalf("MASQUERADE rule for %s was not installed", subnet)
}
if got := readSysctl(t, "net.ipv4.ip_forward"); got != "1" {
t.Fatalf("net.ipv4.ip_forward = %q, want 1", got)
}
// Re-applying must not stack duplicates, which is what would happen on
// every panel restart if the rules were added unconditionally.
if _, err := applyBTUNRouting(cfg, device.Name()); err != nil {
t.Fatalf("second applyBTUNRouting: %v", err)
}
if count := natRuleCount(t, subnet); count != 1 {
t.Fatalf("MASQUERADE rule appears %d times after re-applying, want 1", count)
}
removeBTUNRouting(spec)
if natRuleExists(t, subnet) {
t.Fatalf("MASQUERADE rule for %s survived removal", subnet)
}
}
func interfaceExists(t *testing.T, name string) bool {
t.Helper()
return exec.Command("ip", "link", "show", name).Run() == nil
}
func interfaceHasAddress(t *testing.T, name, address string) bool {
t.Helper()
out, err := exec.Command("ip", "-4", "addr", "show", "dev", name).CombinedOutput()
if err != nil {
t.Fatalf("ip addr show %s: %v (%s)", name, err, out)
}
return strings.Contains(string(out), address)
}
func natRuleCount(t *testing.T, subnet string) int {
t.Helper()
out, err := exec.Command("iptables", "-t", "nat", "-S", "POSTROUTING").CombinedOutput()
if err != nil {
t.Fatalf("iptables -S POSTROUTING: %v (%s)", err, out)
}
count := 0
for _, line := range strings.Split(string(out), "\n") {
if strings.Contains(line, subnet) && strings.Contains(line, "MASQUERADE") {
count++
}
}
return count
}
func natRuleExists(t *testing.T, subnet string) bool {
t.Helper()
return natRuleCount(t, subnet) > 0
}
func readSysctl(t *testing.T, key string) string {
t.Helper()
path := "/proc/sys/" + strings.ReplaceAll(key, ".", "/")
data, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read %s: %v", path, err)
}
return strings.TrimSpace(string(data))
}
+1 -1
View File
@@ -59,7 +59,7 @@ func checkSSHUser(w http.ResponseWriter, username string) {
}
u.mu.Lock()
activeConns := len(u.conns)
activeConns := len(u.conns) + u.btunConns
u.ActiveConns = activeConns
maxConns := u.Cfg.MaxConnections
expiresAt := u.ExpiresAt
+202
View File
@@ -17,6 +17,58 @@ const (
defaultUDPGWListen = "0.0.0.0:7400"
)
// normalizeDurationField validates one optional duration setting in place. An
// invalid value is cleared so the service falls back to its own default rather
// than starting with a nonsense timeout.
func normalizeDurationField(value *string, label string, minimum, maximum time.Duration, warn func(string, ...interface{})) {
*value = strings.TrimSpace(*value)
if *value == "" {
return
}
d, err := time.ParseDuration(*value)
if err != nil || d <= 0 {
warn("%s %q is invalid; using the service default", label, *value)
*value = ""
return
}
if minimum > 0 && d < minimum {
warn("%s %q is below the minimum %s; clamping", label, *value, minimum)
*value = minimum.String()
return
}
if maximum > 0 && d > maximum {
warn("%s %q is above the maximum %s; clamping", label, *value, maximum)
*value = maximum.String()
}
}
// normalizeAutoRestartFields applies the shared auto-restart rules used by
// every embedded service: an interval below 1m disables the watchdog, and the
// grace delay is capped at 1m.
func normalizeAutoRestartFields(interval, grace *string, label string, warn func(string, ...interface{})) {
*interval = strings.TrimSpace(*interval)
if *interval != "" && *interval != "0" && *interval != "0s" &&
!strings.EqualFold(*interval, "off") && !strings.EqualFold(*interval, "disabled") {
if d, err := time.ParseDuration(*interval); err != nil {
warn("%s auto restart interval %q is invalid; disabling auto restart", label, *interval)
*interval = ""
} else if d < time.Minute {
warn("%s auto restart interval %q is below minimum 1m; disabling auto restart", label, *interval)
*interval = ""
}
}
*grace = strings.TrimSpace(*grace)
if *grace != "" {
if d, err := time.ParseDuration(*grace); err != nil || d < 0 {
warn("%s auto restart grace %q is invalid; using default 2s", label, *grace)
*grace = ""
} else if d > time.Minute {
warn("%s auto restart grace %q is above 1m; clamping to 1m", label, *grace)
*grace = "1m"
}
}
}
func normalizeRuntimePorts(cfg *Config) []string {
var warnings []string
warn := func(format string, args ...interface{}) {
@@ -258,9 +310,159 @@ func normalizeRuntimePorts(cfg *Config) []string {
}
}
if cfg.BHTTP != nil {
addrs := normalizeBHTTPListenList(cfg.BHTTP.Listen)
if len(addrs) == 0 && !cfg.BHTTP.SharedPorts {
// With no dedicated listener and no shared ports nothing would
// serve BHTTP at all, so fall back to a port of its own.
addrs = []string{defaultBHTTPListen}
warn("BHTTP has no listen address and shared ports are off; using default %s", defaultBHTTPListen)
}
kept := make([]string, 0, len(addrs))
for _, addr := range addrs {
if err := tcpAddrAvailableForBHTTP(addr); err != nil {
warn("BHTTP listener %s is unavailable (%v)", addr, err)
continue
}
kept = append(kept, addr)
}
if len(addrs) > 0 && len(kept) == 0 {
warn("no BHTTP listener could be opened; keeping the configured addresses so the panel reports the failure")
kept = addrs
}
cfg.BHTTP.Listen = kept
normalizeDurationField(&cfg.BHTTP.SessionTimeout, "BHTTP session_timeout", 10*time.Second, time.Hour, warn)
if cfg.BHTTP.MaxV2Lanes < 0 {
warn("BHTTP max_v2_lanes %d is invalid; using the protocol default", cfg.BHTTP.MaxV2Lanes)
cfg.BHTTP.MaxV2Lanes = 0
}
if cfg.BHTTP.MaxSessions < -1 {
warn("BHTTP max_sessions %d is invalid; using unlimited (-1)", cfg.BHTTP.MaxSessions)
cfg.BHTTP.MaxSessions = -1
}
if cfg.BHTTP.MaxConnections < -1 {
warn("BHTTP max_connections %d is invalid; using unlimited (-1)", cfg.BHTTP.MaxConnections)
cfg.BHTTP.MaxConnections = -1
}
normalizeAutoRestartFields(&cfg.BHTTP.AutoRestartInterval, &cfg.BHTTP.AutoRestartGrace, "BHTTP", warn)
}
if cfg.BTUN != nil {
normalizeBTUNConfig(cfg.BTUN)
if cfg.BTUN.TCPListen == "" && cfg.BTUN.UDPListen == "" && !cfg.BTUN.SharedPorts {
// With no listener and no shared ports nothing would serve BTUN at
// all, so fall back to ports of its own.
cfg.BTUN.TCPListen = defaultBTUNTCPListen
cfg.BTUN.UDPListen = defaultBTUNUDPListen
warn("BTUN has no listener and shared ports are off; using defaults tcp/udp %s", defaultBTUNTCPListen)
}
if cfg.BTUN.TCPListen != "" {
if err := tcpAddrAvailableForBTUN(cfg.BTUN.TCPListen); err != nil {
warn("BTUN TCP listener %s is unavailable (%v)", cfg.BTUN.TCPListen, err)
}
}
if cfg.BTUN.UDPListen != "" {
if err := udpAddrAvailableForBTUN(cfg.BTUN.UDPListen); err != nil {
warn("BTUN UDP listener %s is unavailable (%v)", cfg.BTUN.UDPListen, err)
}
}
if _, _, err := net.ParseCIDR(cfg.BTUN.Subnet); err != nil {
warn("BTUN subnet %q is invalid (%v); using default %s", cfg.BTUN.Subnet, err, defaultBTUNSubnet)
cfg.BTUN.Subnet = defaultBTUNSubnet
cfg.BTUN.Gateway = ""
}
if gateway, err := btunGatewayForSubnet(cfg.BTUN.Subnet); err != nil {
warn("BTUN subnet %q cannot host clients (%v); using default %s", cfg.BTUN.Subnet, err, defaultBTUNSubnet)
cfg.BTUN.Subnet = defaultBTUNSubnet
cfg.BTUN.Gateway, _ = btunGatewayForSubnet(defaultBTUNSubnet)
} else if cfg.BTUN.Gateway == "" {
cfg.BTUN.Gateway = gateway
} else if _, _, err := net.ParseCIDR(cfg.BTUN.Gateway); err != nil {
warn("BTUN gateway %q is invalid (%v); deriving %s from the subnet", cfg.BTUN.Gateway, err, gateway)
cfg.BTUN.Gateway = gateway
}
if cfg.BTUN.MTU < 576 || cfg.BTUN.MTU > 9000 {
warn("BTUN mtu %d is out of the 576..9000 range; using default %d", cfg.BTUN.MTU, defaultBTUNMTU)
cfg.BTUN.MTU = defaultBTUNMTU
}
normalizeDurationField(&cfg.BTUN.HandshakeTimeout, "BTUN handshake_timeout", time.Second, 5*time.Minute, warn)
normalizeDurationField(&cfg.BTUN.IdleTimeout, "BTUN idle_timeout", 10*time.Second, time.Hour, warn)
if cfg.BTUN.MaxPacketSize < 0 {
warn("BTUN max_packet_size %d is invalid; using the protocol default", cfg.BTUN.MaxPacketSize)
cfg.BTUN.MaxPacketSize = 0
}
if cfg.BTUN.MaxCoverBytes < 0 {
warn("BTUN max_cover_bytes %d is invalid; using the protocol default", cfg.BTUN.MaxCoverBytes)
cfg.BTUN.MaxCoverBytes = 0
}
if cfg.BTUN.MaxSessions < -1 {
warn("BTUN max_sessions %d is invalid; using unlimited (-1)", cfg.BTUN.MaxSessions)
cfg.BTUN.MaxSessions = -1
}
normalizeAutoRestartFields(&cfg.BTUN.AutoRestartInterval, &cfg.BTUN.AutoRestartGrace, "BTUN", warn)
}
return warnings
}
// tcpAddrAvailableForBHTTP reports whether a BHTTP listen address can be bound.
// An address this process already serves for BHTTP is treated as available, so
// saving an unchanged config does not report a false conflict.
func tcpAddrAvailableForBHTTP(addr string) error {
if addr == "" {
return nil
}
if bhttpRunning() {
for _, current := range strings.Split(bhttpListenList(), ", ") {
if strings.TrimSpace(current) == addr {
return nil
}
}
}
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
return ln.Close()
}
func tcpAddrAvailableForBTUN(addr string) error {
if addr == "" {
return nil
}
btunMu.Lock()
current := btunListenTCP
running := btunServer != nil
btunMu.Unlock()
if running && current == addr {
return nil
}
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
return ln.Close()
}
func udpAddrAvailableForBTUN(addr string) error {
if addr == "" {
return nil
}
btunMu.Lock()
current := btunListenUDP
running := btunServer != nil
btunMu.Unlock()
if running && current == addr {
return nil
}
pc, err := net.ListenPacket("udp", addr)
if err != nil {
return err
}
return pc.Close()
}
// normalizeLocalSSHListen guarantees that the raw integration endpoint can
// only bind to this machine. Hostnames and wildcard/non-loopback addresses are
// deliberately rejected: a changed hosts file must not turn an internal SSH
+27
View File
@@ -450,6 +450,33 @@ func applyFullConfigReload(newCfg *Config) ConfigReloadReport {
report.Services["udpgw"] = ServiceReloadStatus{Enabled: false, Running: false}
}
// BHTTP — stop current instance (no-op if not running) then start new one.
stopBHTTP()
if newCfg.BHTTP != nil {
if err := startBHTTP(newCfg.BHTTP); err != nil {
report.warnf("BHTTP failed to start: %v", err)
report.Services["bhttp"] = ServiceReloadStatus{Enabled: true, Running: false, Listen: joinAddrs(newCfg.BHTTP.Listen), Error: err.Error()}
} else {
report.Services["bhttp"] = ServiceReloadStatus{Enabled: true, Running: bhttpRunning(), Listen: bhttpListenList()}
}
} else {
report.Services["bhttp"] = ServiceReloadStatus{Enabled: false, Running: false}
}
// BTUN — same pattern. A failure here is usually a missing /dev/net/tun or
// an interface name already taken, both of which the panel surfaces.
stopBTUN()
if newCfg.BTUN != nil {
if err := startBTUN(newCfg.BTUN); err != nil {
report.warnf("BTUN failed to start: %v", err)
report.Services["btun"] = ServiceReloadStatus{Enabled: true, Running: false, Listen: btunConfiguredListen(newCfg.BTUN), Error: err.Error()}
} else {
report.Services["btun"] = ServiceReloadStatus{Enabled: true, Running: btunRunning(), Listen: btunListenList()}
}
} else {
report.Services["btun"] = ServiceReloadStatus{Enabled: false, Running: false}
}
// Xray — update stored config then restart/stop as needed.
if newCfg.Xray != nil {
newCfg.Xray.NormalizeDefaults()
+124
View File
@@ -0,0 +1,124 @@
package bhttp
import (
"crypto/sha256"
"encoding/binary"
"errors"
"io"
)
const (
ModeProbe byte = 0
ModeUpload byte = 1
ModeDownload byte = 2
ModeBatch byte = 3
ModeACK byte = 4
ModeLane byte = 5
StatusOK byte = 0
StatusError byte = 1
StatusData byte = 2
HeaderSize = 29
MaxPayload = 524288
MaxDownloadSize = 524284
)
type SessionID [16]byte
type Request struct {
Mode byte
SID SessionID
Seq uint64
Value uint32
Payload []byte
}
func Crypt(data []byte, sid SessionID, mode byte, seq uint64, response bool) []byte {
if len(data) == 0 {
return nil
}
seed := make([]byte, 26)
copy(seed[:16], sid[:])
seed[16] = mode
binary.BigEndian.PutUint64(seed[17:25], seq)
if response {
seed[25] = 1
}
out := make([]byte, len(data))
blockInput := make([]byte, 30)
copy(blockInput, seed)
for offset, counter := 0, uint32(0); offset < len(data); offset, counter = offset+32, counter+1 {
binary.BigEndian.PutUint32(blockInput[26:30], counter)
key := sha256.Sum256(blockInput)
end := offset + len(key)
if end > len(data) {
end = len(data)
}
for index := offset; index < end; index++ {
out[index] = data[index] ^ key[index-offset]
}
}
return out
}
func ReadRequest(reader io.Reader) (Request, error) {
var request Request
var header [HeaderSize]byte
if _, err := io.ReadFull(reader, header[:]); err != nil {
return request, err
}
request.Mode = header[0]
if request.Mode > ModeLane {
return request, errors.New("unknown BHTTP mode")
}
copy(request.SID[:], header[1:17])
request.Seq = binary.BigEndian.Uint64(header[17:25])
request.Value = binary.BigEndian.Uint32(header[25:29])
// Mode 2 overloads Value as a size hint. Mode 4 is an empty cumulative ACK.
if request.Mode == ModeDownload || request.Mode == ModeACK {
return request, nil
}
if request.Value > MaxPayload {
return request, errors.New("BHTTP request is too large")
}
if request.Value > 0 {
request.Payload = make([]byte, int(request.Value))
if _, err := io.ReadFull(reader, request.Payload); err != nil {
return request, err
}
}
return request, nil
}
func WriteStatus(writer io.Writer, status byte, data []byte) error {
packet := make([]byte, 5+len(data))
packet[0] = status
binary.BigEndian.PutUint32(packet[1:5], uint32(len(data)))
copy(packet[5:], data)
return writeAll(writer, packet)
}
func WriteDownload(writer io.Writer, sid SessionID, mode byte, seq uint64, data []byte) error {
encrypted := Crypt(data, sid, mode, seq, true)
packet := make([]byte, 9+len(encrypted))
packet[0] = StatusData
binary.BigEndian.PutUint32(packet[1:5], uint32(4+len(encrypted)))
binary.BigEndian.PutUint32(packet[5:9], uint32(len(data)))
copy(packet[9:], encrypted)
return writeAll(writer, packet)
}
func writeAll(writer io.Writer, data []byte) error {
for len(data) > 0 {
count, err := writer.Write(data)
if err != nil {
return err
}
if count <= 0 {
return io.ErrShortWrite
}
data = data[count:]
}
return nil
}
+256
View File
@@ -0,0 +1,256 @@
package bhttp
import (
"bytes"
"encoding/binary"
"encoding/hex"
"io"
"net"
"testing"
"time"
)
func TestCryptMatchesRestoredPythonServer(t *testing.T) {
var sid SessionID
for index := range sid {
sid[index] = byte(index)
}
tests := []struct {
clearHex string
mode byte
seq uint64
response bool
wantHex string
}{
{"42696c6f6c612d4248545450", 1, 0, false, "7ca4d6c962b839cf1fb68990"},
{"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f", 3, 123456789, true, "ccd73e4b14777caaa138d17c7016770da44fe50c4d7322a759298098a47230347567293f767bb2f8069a2ede76ac97ec5e031832b023b44f69918e02c6f313ea"},
{"42485031010300000008", 0, 0, false, "1185931614521a40b889"},
}
for _, test := range tests {
clear, _ := hex.DecodeString(test.clearHex)
want, _ := hex.DecodeString(test.wantHex)
got := Crypt(clear, sid, test.mode, test.seq, test.response)
if !bytes.Equal(got, want) {
t.Fatalf("mode=%d seq=%d got=%x want=%x", test.mode, test.seq, got, want)
}
if decoded := Crypt(got, sid, test.mode, test.seq, test.response); !bytes.Equal(decoded, clear) {
t.Fatalf("cipher did not round-trip mode=%d seq=%d", test.mode, test.seq)
}
}
}
func writeTestRequest(writer io.Writer, mode byte, sid SessionID, sequence uint64, payload []byte, value uint32) error {
if mode != ModeDownload && mode != ModeACK {
value = uint32(len(payload))
}
packet := make([]byte, HeaderSize+len(payload))
packet[0] = mode
copy(packet[1:17], sid[:])
binary.BigEndian.PutUint64(packet[17:25], sequence)
binary.BigEndian.PutUint32(packet[25:29], value)
copy(packet[29:], payload)
return writeAll(writer, packet)
}
func readTestResponse(reader io.Reader) (byte, []byte, []byte, error) {
var header [5]byte
if _, err := io.ReadFull(reader, header[:]); err != nil {
return 0, nil, nil, err
}
size := binary.BigEndian.Uint32(header[1:5])
body := make([]byte, int(size))
if _, err := io.ReadFull(reader, body); err != nil {
return 0, nil, nil, err
}
raw := append(append([]byte(nil), header[:]...), body...)
return header[0], body, raw, nil
}
func waitBuffered(t *testing.T, session *Session, minimum int) {
t.Helper()
deadline := time.Now().Add(time.Second)
for time.Now().Before(deadline) {
session.readyMu.Lock()
available := session.downloadBuffer.available()
session.readyMu.Unlock()
if available >= minimum {
return
}
time.Sleep(time.Millisecond)
}
t.Fatal("target bytes were not buffered")
}
func TestServerSSHRelayBatchRetryAndACK(t *testing.T) {
targetServer, targetPeer := net.Pipe()
defer targetPeer.Close()
dialed := false
server := NewServer(Config{
TargetAddress: "test:22",
DialTarget: func(address string) (net.Conn, error) {
if address != "test:22" || dialed {
t.Fatalf("unexpected target dial %q repeated=%v", address, dialed)
}
dialed = true
return targetServer, nil
},
})
defer server.Close()
accepted, client := net.Pipe()
done := make(chan error, 1)
go func() {
done <- server.handleConnection(accepted)
accepted.Close()
}()
defer func() {
client.Close()
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("connection handler did not stop")
}
}()
_ = client.SetDeadline(time.Now().Add(3 * time.Second))
var sid SessionID
copy(sid[:], []byte("bilola-test-sid!"))
if err := writeTestRequest(client, ModeUpload, sid, 0, nil, 0); err != nil {
t.Fatal(err)
}
status, _, _, err := readTestResponse(client)
if err != nil || status != StatusOK {
t.Fatalf("registration status=%d err=%v", status, err)
}
session := server.sessions.GetOrCreate(sid)
banner := []byte("SSH-2.0-BilolaGo\r\n")
go targetPeer.Write(banner)
waitBuffered(t, session, len(banner))
if err := writeTestRequest(client, ModeDownload, sid, 0, nil, 65536); err != nil {
t.Fatal(err)
}
status, body, _, err := readTestResponse(client)
if err != nil || status != StatusData || len(body) < 4 {
t.Fatalf("banner response status=%d len=%d err=%v", status, len(body), err)
}
plainSize := int(binary.BigEndian.Uint32(body[:4]))
decoded := Crypt(body[4:], sid, ModeDownload, 0, true)
if plainSize != len(banner) || !bytes.Equal(decoded, banner) {
t.Fatalf("banner got=%q size=%d", decoded, plainSize)
}
upload := []byte("SSH upload sequence zero")
encryptedUpload := Crypt(upload, sid, ModeUpload, 0, false)
targetUpload := make(chan []byte, 1)
go func() {
read := make([]byte, len(upload))
if _, readErr := io.ReadFull(targetPeer, read); readErr != nil {
targetUpload <- nil
return
}
targetUpload <- read
}()
if err := writeTestRequest(client, ModeUpload, sid, 0, encryptedUpload, 0); err != nil {
t.Fatal(err)
}
status, _, _, err = readTestResponse(client)
if err != nil || status != StatusOK {
t.Fatalf("upload status=%d err=%v", status, err)
}
targetRead := <-targetUpload
if !bytes.Equal(targetRead, upload) {
t.Fatalf("target upload=%q", targetRead)
}
downstream := make([]byte, 3000)
for index := range downstream {
downstream[index] = byte(index * 17)
}
go targetPeer.Write(downstream)
waitBuffered(t, session, len(downstream))
batchClear := make([]byte, 6)
binary.BigEndian.PutUint32(batchClear[:4], 1399)
binary.BigEndian.PutUint16(batchClear[4:6], 3)
batchRequest := Crypt(batchClear, sid, ModeBatch, 1, false)
if err := writeTestRequest(client, ModeBatch, sid, 1, batchRequest, 0); err != nil {
t.Fatal(err)
}
var firstRaw [][]byte
var downloaded []byte
var raw []byte
for offset := 0; offset < 3; offset++ {
status, body, raw, err = readTestResponse(client)
if err != nil || status != StatusData || len(body) < 4 {
t.Fatalf("batch %d status=%d len=%d err=%v", offset, status, len(body), err)
}
plainSize = int(binary.BigEndian.Uint32(body[:4]))
decoded = Crypt(body[4:], sid, ModeBatch, 1+uint64(offset), true)
if len(decoded) != plainSize {
t.Fatalf("batch %d declared=%d decoded=%d", offset, plainSize, len(decoded))
}
downloaded = append(downloaded, decoded...)
firstRaw = append(firstRaw, raw)
}
if !bytes.Equal(downloaded, downstream) {
t.Fatalf("batch data mismatch got=%d want=%d", len(downloaded), len(downstream))
}
if err := writeTestRequest(client, ModeBatch, sid, 1, batchRequest, 0); err != nil {
t.Fatal(err)
}
for offset := 0; offset < 3; offset++ {
_, _, raw, err := readTestResponse(client)
if err != nil || !bytes.Equal(raw, firstRaw[offset]) {
t.Fatalf("retry frame %d changed err=%v", offset, err)
}
}
if err := writeTestRequest(client, ModeACK, sid, 3, nil, 0); err != nil {
t.Fatal(err)
}
status, _, _, err = readTestResponse(client)
if err != nil || status != StatusOK {
t.Fatalf("ACK status=%d err=%v", status, err)
}
session.downloadMu.Lock()
remaining := len(session.downloadFrames)
session.downloadMu.Unlock()
if remaining != 0 {
t.Fatalf("ACK retained %d replay frames", remaining)
}
}
func TestProbeEchoMatchesBHP1(t *testing.T) {
server, client := net.Pipe()
done := make(chan error, 1)
go func() {
request, err := ReadRequest(server)
if err == nil {
err = handleProbe(server, request)
}
done <- err
server.Close()
}()
defer client.Close()
var sid SessionID
for index := range sid {
sid[index] = byte(index)
}
clear := []byte{'B', 'H', 'P', '1', 1, ModeDownload, 0, 0, 2, 0}
encrypted := Crypt(clear, sid, ModeProbe, 7, false)
if err := writeTestRequest(client, ModeProbe, sid, 7, encrypted, 0); err != nil {
t.Fatal(err)
}
status, body, _, err := readTestResponse(client)
if err != nil || status != StatusOK {
t.Fatalf("probe status=%d err=%v", status, err)
}
decoded := Crypt(body, sid, ModeProbe, 7, true)
if len(decoded) != 512 || !bytes.Equal(decoded[:10], clear) {
t.Fatalf("probe response len=%d prefix=%x", len(decoded), decoded[:10])
}
if err := <-done; err != nil {
t.Fatal(err)
}
}
+589
View File
@@ -0,0 +1,589 @@
package bhttp
import (
"bufio"
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"log"
"net"
"strings"
"sync"
"sync/atomic"
"time"
)
type Config struct {
TargetAddress string
SessionTimeout time.Duration
DialTimeout time.Duration
MaxV2Lanes int
Logger *log.Logger
DialTarget func(string) (net.Conn, error)
// MaxConnections caps concurrently accepted client sockets across every
// listener served by this server. Zero or negative disables the cap.
MaxConnections int
// MaxSessions caps concurrently tracked BHTTP sessions. Zero or negative
// disables the cap. A session is one logical tunnel; BHTTP v2 attaches
// several sockets ("lanes") to the same session.
MaxSessions int
// LogConnections enables one log line per accepted socket. Leave it off on
// busy servers.
LogConnections bool
}
// StatsSnapshot is the counter set the admin panel reads.
type StatsSnapshot struct {
StartedAt time.Time `json:"startedAt"`
ActiveConnections int64 `json:"activeConnections"`
ActiveSessions int64 `json:"activeSessions"`
Accepted uint64 `json:"accepted"`
ConnectionsRejected uint64 `json:"connectionsRejected"`
SessionsRejected uint64 `json:"sessionsRejected"`
SessionsExpired uint64 `json:"sessionsExpired"`
Probes uint64 `json:"probes"`
ProbesV2 uint64 `json:"probesV2"`
HTTPUpgrades uint64 `json:"httpUpgrades"`
LanesAttached uint64 `json:"lanesAttached"`
LanesRejected uint64 `json:"lanesRejected"`
UploadBytes uint64 `json:"uploadBytes"`
DownloadBytes uint64 `json:"downloadBytes"`
TargetFailures uint64 `json:"targetFailures"`
ProtocolErrors uint64 `json:"protocolErrors"`
}
type counters struct {
accepted atomic.Uint64
connectionsRejected atomic.Uint64
sessionsRejected atomic.Uint64
sessionsExpired atomic.Uint64
probes atomic.Uint64
probesV2 atomic.Uint64
httpUpgrades atomic.Uint64
lanesAttached atomic.Uint64
lanesRejected atomic.Uint64
uploadBytes atomic.Uint64
downloadBytes atomic.Uint64
targetFailures atomic.Uint64
protocolErrors atomic.Uint64
activeConnections atomic.Int64
}
type Server struct {
config Config
sessions *SessionManager
closed chan struct{}
once sync.Once
wait sync.WaitGroup
connMu sync.Mutex
active map[net.Conn]struct{}
started time.Time
stats counters
}
const (
bhttpV2Version = 2
bhttpV2FeatureLanes = 1 << 0
bhttpV2FeatureResume = 1 << 1
bhttpV2FeatureAck = 1 << 2
bhttpV2MaxLanes = 128
laneUpload = 1
laneDownload = 2
laneDuplex = 3
)
func NewServer(config Config) *Server {
if config.TargetAddress == "" {
config.TargetAddress = "127.0.0.1:22"
}
if config.SessionTimeout <= 0 {
config.SessionTimeout = 2 * time.Minute
}
if config.DialTimeout <= 0 {
config.DialTimeout = 10 * time.Second
}
if config.MaxV2Lanes <= 0 {
config.MaxV2Lanes = bhttpV2MaxLanes
}
if config.Logger == nil {
config.Logger = log.Default()
}
if config.DialTarget == nil {
dialer := net.Dialer{Timeout: config.DialTimeout, KeepAlive: 30 * time.Second}
config.DialTarget = func(address string) (net.Conn, error) {
connection, err := dialer.Dial("tcp", address)
if err == nil {
if tcp, ok := connection.(*net.TCPConn); ok {
_ = tcp.SetNoDelay(true)
}
}
return connection, err
}
}
server := &Server{
config: config,
sessions: NewSessionManager(config.SessionTimeout),
closed: make(chan struct{}),
active: make(map[net.Conn]struct{}),
started: time.Now(),
}
server.sessions.limit = config.MaxSessions
server.sessions.rejected = &server.stats.sessionsRejected
server.wait.Add(1)
go server.cleanupLoop()
return server
}
func (server *Server) cleanupLoop() {
defer server.wait.Done()
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for {
select {
case now := <-ticker.C:
removed := server.sessions.Cleanup(now)
if removed > 0 {
server.stats.sessionsExpired.Add(uint64(removed))
server.config.Logger.Printf("cleaned %d stale BHTTP sessions", removed)
}
case <-server.closed:
return
}
}
}
func (server *Server) Serve(listener net.Listener) error {
for {
connection, err := listener.Accept()
if err != nil {
select {
case <-server.closed:
return nil
default:
return err
}
}
if tcp, ok := connection.(*net.TCPConn); ok {
_ = tcp.SetNoDelay(true)
}
server.stats.accepted.Add(1)
if !server.track(connection) {
continue
}
server.wait.Add(1)
go func() {
defer server.wait.Done()
server.run(connection)
}()
}
}
// ServeConn serves one already-accepted connection, for listeners this server
// does not own. A port shared with SSH or HTTP routes a client here once the
// first bytes have been identified as BHTTP; the connection is then counted,
// capped and closed exactly like one from Serve's own accept loop.
//
// It blocks until the connection ends. It reports whether the connection was
// admitted: a refused connection has already been closed, and the caller must
// not keep using it either way.
func (server *Server) ServeConn(connection net.Conn) bool {
select {
case <-server.closed:
_ = connection.Close()
return false
default:
}
server.stats.accepted.Add(1)
if !server.track(connection) {
return false
}
server.wait.Add(1)
defer server.wait.Done()
server.run(connection)
return true
}
// track registers a connection against the socket cap. It reports whether the
// connection was admitted; a rejected connection is closed here.
func (server *Server) track(connection net.Conn) bool {
server.connMu.Lock()
// Reject past the socket cap before any protocol work, so a surge cannot
// exhaust memory the way an unbounded accept loop would.
if limit := server.config.MaxConnections; limit > 0 && len(server.active) >= limit {
server.connMu.Unlock()
rejected := server.stats.connectionsRejected.Add(1)
if rejected == 1 || rejected%1000 == 0 {
server.config.Logger.Printf("connection cap reached (%d); rejected %d client(s) so far",
limit, rejected)
}
_ = connection.Close()
return false
}
server.active[connection] = struct{}{}
server.connMu.Unlock()
server.stats.activeConnections.Add(1)
if server.config.LogConnections {
server.config.Logger.Printf("client %s connected", connection.RemoteAddr())
}
return true
}
// run drives one tracked connection to completion and releases it.
func (server *Server) run(connection net.Conn) {
defer func() {
server.connMu.Lock()
delete(server.active, connection)
server.connMu.Unlock()
server.stats.activeConnections.Add(-1)
_ = connection.Close()
if server.config.LogConnections {
server.config.Logger.Printf("client %s disconnected", connection.RemoteAddr())
}
}()
if err := server.handleConnection(connection); err != nil && !isNormalClose(err) {
server.stats.protocolErrors.Add(1)
server.config.Logger.Printf("client %s: %v", connection.RemoteAddr(), err)
}
}
func isNormalClose(err error) bool {
return errors.Is(err, io.EOF) || errors.Is(err, net.ErrClosed) || strings.Contains(err.Error(), "connection reset")
}
func (server *Server) handleConnection(connection net.Conn) error {
reader := bufio.NewReader(connection)
first, err := reader.Peek(1)
if err != nil {
return err
}
if first[0] == ModeProbe {
request, err := ReadRequest(reader)
if err != nil {
return err
}
server.stats.probes.Add(1)
if isV2Probe(request) {
server.stats.probesV2.Add(1)
}
return handleProbeLimit(connection, request, server.config.MaxV2Lanes)
}
if first[0] > ModeLane {
if err := handleHTTPUpgrade(reader, connection); err != nil {
return err
}
server.stats.httpUpgrades.Add(1)
}
var laneRole byte
var laneLease *LaneLease
defer func() {
if laneLease != nil {
laneLease.ReleaseLane()
}
}()
for {
request, err := ReadRequest(reader)
if err != nil {
return err
}
if request.Mode == ModeLane {
if laneLease != nil {
return errors.New("BHTTP v2 lane already attached")
}
role, attached, attachErr := server.attachLane(connection, request)
if attachErr != nil {
return attachErr
}
laneRole = role
laneLease = attached
continue
}
if laneRole == laneUpload && request.Mode != ModeUpload {
return errors.New("BHTTP v2 upload lane received non-upload request")
}
if laneRole == laneDownload && request.Mode != ModeDownload &&
request.Mode != ModeBatch && request.Mode != ModeACK {
return errors.New("BHTTP v2 download lane received invalid request")
}
session := server.sessions.GetOrCreate(request.SID)
if session == nil {
_ = WriteStatus(connection, StatusError, []byte("BHTTP session limit reached"))
return errors.New("BHTTP session limit reached")
}
session.touch()
if err := server.handleRequest(connection, session, request, laneRole != 0); err != nil {
return err
}
}
}
func handleHTTPUpgrade(reader *bufio.Reader, writer io.Writer) error {
var request bytes.Buffer
for request.Len() < 64*1024 {
value, err := reader.ReadByte()
if err != nil {
return err
}
request.WriteByte(value)
if bytes.HasSuffix(request.Bytes(), []byte("\r\n\r\n")) {
return writeAll(writer, []byte("HTTP/1.1 101 DTunnel\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\nHTTP/1.1 200 DTunnel\r\n\r\n"))
}
}
return errors.New("HTTP upgrade header is too large")
}
// isV2Probe reports whether a probe payload announces the BHP2 capability
// handshake rather than the original BHP1 profile.
func isV2Probe(request Request) bool {
clear := Crypt(request.Payload, request.SID, ModeProbe, request.Seq, false)
return len(clear) == 10 && bytes.Equal(clear[:4], []byte("BHP2")) && clear[4] == bhttpV2Version
}
// Stats returns a snapshot of the server counters for the admin panel.
func (server *Server) Stats() StatsSnapshot {
return StatsSnapshot{
StartedAt: server.started,
ActiveConnections: server.stats.activeConnections.Load(),
ActiveSessions: int64(server.sessions.Len()),
Accepted: server.stats.accepted.Load(),
ConnectionsRejected: server.stats.connectionsRejected.Load(),
SessionsRejected: server.stats.sessionsRejected.Load(),
SessionsExpired: server.stats.sessionsExpired.Load(),
Probes: server.stats.probes.Load(),
ProbesV2: server.stats.probesV2.Load(),
HTTPUpgrades: server.stats.httpUpgrades.Load(),
LanesAttached: server.stats.lanesAttached.Load(),
LanesRejected: server.stats.lanesRejected.Load(),
UploadBytes: server.stats.uploadBytes.Load(),
DownloadBytes: server.stats.downloadBytes.Load(),
TargetFailures: server.stats.targetFailures.Load(),
ProtocolErrors: server.stats.protocolErrors.Load(),
}
}
func handleProbe(writer io.Writer, request Request) error {
return handleProbeLimit(writer, request, bhttpV2MaxLanes)
}
func handleProbeLimit(writer io.Writer, request Request, maxLanes int) error {
clear := Crypt(request.Payload, request.SID, ModeProbe, request.Seq, false)
if len(clear) == 10 && bytes.Equal(clear[:4], []byte("BHP2")) && clear[4] == bhttpV2Version {
response := make([]byte, 14)
copy(response[:4], []byte("BHP2"))
response[4] = bhttpV2Version
binary.BigEndian.PutUint32(response[6:10], bhttpV2FeatureLanes|bhttpV2FeatureResume|bhttpV2FeatureAck)
binary.BigEndian.PutUint32(response[10:14], uint32(maxLanes))
return WriteStatus(writer, StatusOK, Crypt(response, request.SID, ModeProbe, request.Seq, true))
}
if len(clear) < 10 || !bytes.Equal(clear[:4], []byte("BHP1")) || clear[4] != 1 {
return WriteStatus(writer, StatusError, []byte("invalid BHTTP v1 probe"))
}
submode := clear[5]
parameter := int(binary.BigEndian.Uint32(clear[6:10]))
if submode > ModeACK {
return WriteStatus(writer, StatusError, []byte("unsupported BHTTP probe mode"))
}
expected := 10
if submode == ModeUpload && parameter >= 10 {
expected = parameter
}
if len(clear) != expected {
return WriteStatus(writer, StatusError, []byte("invalid BHTTP v1 probe length"))
}
for index := 10; index < len(clear); index++ {
if clear[index] != byte(index*31) {
return WriteStatus(writer, StatusError, []byte("invalid BHTTP v1 probe pattern"))
}
}
responseSize := 10
if submode == ModeDownload && parameter > responseSize {
responseSize = parameter
}
if responseSize > MaxPayload {
return WriteStatus(writer, StatusError, []byte("BHTTP v1 probe too large"))
}
response := make([]byte, responseSize)
copy(response[:4], []byte("BHP1"))
response[4] = 1
response[5] = submode
binary.BigEndian.PutUint32(response[6:10], uint32(parameter))
for index := 10; index < len(response); index++ {
response[index] = byte(index * 31)
}
encrypted := Crypt(response, request.SID, ModeProbe, request.Seq, true)
count := 1
if submode == ModeACK {
count = parameter
if count < 1 {
count = 1
}
if count > 256 {
count = 256
}
}
for index := 0; index < count; index++ {
if err := WriteStatus(writer, StatusOK, encrypted); err != nil {
return err
}
}
return nil
}
func (server *Server) handleRequest(writer io.Writer, session *Session, request Request, version2 bool) error {
switch request.Mode {
case ModeUpload:
payload := request.Payload
if len(payload) > 0 {
payload = Crypt(payload, request.SID, request.Mode, request.Seq, false)
}
if request.Seq == 0 && len(payload) == 0 {
if err := session.OpenTarget(server.config.TargetAddress, server.config.DialTarget); err != nil {
server.stats.targetFailures.Add(1)
return WriteStatus(writer, StatusError, []byte("SSH target unavailable"))
}
return WriteStatus(writer, StatusOK, nil)
}
if err := session.OpenTarget(server.config.TargetAddress, server.config.DialTarget); err != nil {
server.stats.targetFailures.Add(1)
return WriteStatus(writer, StatusError, []byte("SSH target unavailable"))
}
if err := session.WriteUpload(request.Seq, payload); err != nil {
return WriteStatus(writer, StatusError, []byte("SSH upload failed"))
}
server.stats.uploadBytes.Add(uint64(len(payload)))
if !version2 {
return WriteStatus(writer, StatusOK, nil)
}
ack := make([]byte, 9)
if sequence, ok := session.UploadCommitted(); ok {
ack[0] = 1
binary.BigEndian.PutUint64(ack[1:], sequence)
}
return WriteStatus(writer, StatusOK, ack)
case ModeDownload:
chunks := session.AssignDownload(request.Seq, 1, 65536)
server.stats.downloadBytes.Add(uint64(len(chunks[0])))
return WriteDownload(writer, request.SID, request.Mode, request.Seq, chunks[0])
case ModeBatch:
clear := Crypt(request.Payload, request.SID, request.Mode, request.Seq, false)
if len(clear) != 6 {
return WriteStatus(writer, StatusError, []byte("invalid BHTTP batch request"))
}
limit := int(binary.BigEndian.Uint32(clear[:4]))
count := int(binary.BigEndian.Uint16(clear[4:6]))
if limit < 1 {
limit = 1
}
if limit > MaxDownloadSize {
limit = MaxDownloadSize
}
if count < 1 {
count = 1
}
if count > 256 {
count = 256
}
chunks := session.AssignDownload(request.Seq, count, limit)
for offset, chunk := range chunks {
server.stats.downloadBytes.Add(uint64(len(chunk)))
if err := WriteDownload(writer, request.SID, request.Mode, request.Seq+uint64(offset), chunk); err != nil {
return err
}
}
return nil
case ModeACK:
session.Acknowledge(request.Seq)
return WriteStatus(writer, StatusOK, nil)
}
return fmt.Errorf("unsupported BHTTP mode %d", request.Mode)
}
func (server *Server) attachLane(writer io.Writer, request Request) (byte, *LaneLease, error) {
clear := Crypt(request.Payload, request.SID, ModeLane, request.Seq, false)
if len(clear) != 12 || !bytes.Equal(clear[:4], []byte("BLN2")) || clear[4] != bhttpV2Version {
server.stats.lanesRejected.Add(1)
_ = WriteStatus(writer, StatusError, []byte("invalid BHTTP v2 lane hello"))
return 0, nil, errors.New("invalid BHTTP v2 lane hello")
}
role := clear[5]
if role != laneUpload && role != laneDownload && role != laneDuplex {
server.stats.lanesRejected.Add(1)
_ = WriteStatus(writer, StatusError, []byte("invalid BHTTP v2 lane role"))
return 0, nil, errors.New("invalid BHTTP v2 lane role")
}
requireResume := binary.BigEndian.Uint16(clear[6:8])&1 != 0
laneID := binary.BigEndian.Uint32(clear[8:12])
session, resumed := server.sessions.Get(request.SID)
if requireResume && !resumed {
server.stats.lanesRejected.Add(1)
_ = WriteStatus(writer, StatusError, []byte("BHTTP v2 session expired"))
return 0, nil, errors.New("BHTTP v2 resume rejected: session expired")
}
if !resumed {
session, _ = server.sessions.GetOrCreateState(request.SID)
if session == nil {
server.stats.lanesRejected.Add(1)
_ = WriteStatus(writer, StatusError, []byte("BHTTP session limit reached"))
return 0, nil, errors.New("BHTTP session limit reached")
}
}
lease, acquired := session.AcquireLane(laneID, server.config.MaxV2Lanes)
if !acquired {
server.stats.lanesRejected.Add(1)
_ = WriteStatus(writer, StatusError, []byte("BHTTP v2 lane limit exceeded"))
return 0, nil, errors.New("BHTTP v2 lane limit exceeded")
}
attached := true
defer func() {
if attached {
lease.ReleaseLane()
}
}()
if err := session.OpenTarget(server.config.TargetAddress, server.config.DialTarget); err != nil {
server.stats.targetFailures.Add(1)
_ = WriteStatus(writer, StatusError, []byte("SSH target unavailable"))
return 0, nil, err
}
response := make([]byte, 18)
copy(response[:4], []byte("BOK2"))
response[4] = bhttpV2Version
if resumed {
response[5] = 1
}
binary.BigEndian.PutUint32(response[6:10], bhttpV2FeatureLanes|bhttpV2FeatureResume|bhttpV2FeatureAck)
if sequence, ok := session.UploadCommitted(); ok {
binary.BigEndian.PutUint64(response[10:18], sequence+1)
}
encoded := Crypt(response, request.SID, ModeLane, request.Seq, true)
if err := WriteStatus(writer, StatusOK, encoded); err != nil {
return 0, nil, err
}
session.touch()
attached = false
server.stats.lanesAttached.Add(1)
return role, lease, nil
}
func (server *Server) Close() {
server.once.Do(func() {
close(server.closed)
server.connMu.Lock()
connections := make([]net.Conn, 0, len(server.active))
for connection := range server.active {
connections = append(connections, connection)
}
server.connMu.Unlock()
for _, connection := range connections {
_ = connection.Close()
}
server.sessions.Close()
})
}
func (server *Server) Wait() {
server.wait.Wait()
}
+415
View File
@@ -0,0 +1,415 @@
package bhttp
import (
"errors"
"io"
"net"
"sync"
"sync/atomic"
"time"
)
type byteQueue struct {
data []byte
offset int
}
func (queue *byteQueue) append(data []byte) {
queue.data = append(queue.data, data...)
}
func (queue *byteQueue) available() int {
return len(queue.data) - queue.offset
}
func (queue *byteQueue) take(limit int) []byte {
if queue.available() == 0 {
return nil
}
end := queue.offset + limit
if end > len(queue.data) {
end = len(queue.data)
}
out := append([]byte(nil), queue.data[queue.offset:end]...)
queue.offset = end
if queue.offset == len(queue.data) {
queue.data = queue.data[:0]
queue.offset = 0
} else if queue.offset >= 1<<20 && queue.offset*2 >= len(queue.data) {
copy(queue.data, queue.data[queue.offset:])
queue.data = queue.data[:len(queue.data)-queue.offset]
queue.offset = 0
}
return out
}
type Session struct {
sid SessionID
openOnce sync.Once
openErr error
target net.Conn
uploadMu sync.Mutex
uploadPending map[uint64][]byte
uploadNext uint64
laneMu sync.Mutex
activeLanes map[uint32]uint64
nextLaneLease uint64
readyMu sync.Mutex
readySignal chan struct{}
downloadBuffer byteQueue
bannerDelivered bool
targetEOF bool
targetError error
downloadMu sync.Mutex
downloadSignal chan struct{}
downloadNext uint64
downloadAcked uint64
hasACK bool
downloadClosed bool
downloadFrames map[uint64][]byte
lastSeen atomic.Int64
closeOnce sync.Once
}
type LaneLease struct {
session *Session
laneID uint32
generation uint64
once sync.Once
}
// AcquireLane gives a stable lane ID a new generation. Reconnecting the same
// logical lane replaces its previous socket immediately instead of consuming
// another slot until the old handler notices the close.
func (session *Session) AcquireLane(laneID uint32, maximum int) (*LaneLease, bool) {
session.laneMu.Lock()
defer session.laneMu.Unlock()
if _, replacing := session.activeLanes[laneID]; !replacing &&
maximum > 0 && len(session.activeLanes) >= maximum {
return nil, false
}
session.nextLaneLease++
generation := session.nextLaneLease
session.activeLanes[laneID] = generation
return &LaneLease{session: session, laneID: laneID, generation: generation}, true
}
func (lease *LaneLease) ReleaseLane() {
if lease == nil || lease.session == nil {
return
}
lease.once.Do(func() {
lease.session.laneMu.Lock()
if lease.session.activeLanes[lease.laneID] == lease.generation {
delete(lease.session.activeLanes, lease.laneID)
}
lease.session.laneMu.Unlock()
})
}
func NewSession(sid SessionID) *Session {
session := &Session{
sid: sid,
uploadPending: make(map[uint64][]byte),
activeLanes: make(map[uint32]uint64),
readySignal: make(chan struct{}),
downloadSignal: make(chan struct{}),
downloadFrames: make(map[uint64][]byte),
}
session.touch()
return session
}
func (session *Session) touch() {
session.lastSeen.Store(time.Now().UnixNano())
}
func (session *Session) LastSeen() time.Time {
return time.Unix(0, session.lastSeen.Load())
}
func (session *Session) signalReadyLocked() {
close(session.readySignal)
session.readySignal = make(chan struct{})
}
func (session *Session) signalDownloadLocked() {
close(session.downloadSignal)
session.downloadSignal = make(chan struct{})
}
func (session *Session) OpenTarget(address string, dialer func(string) (net.Conn, error)) error {
session.openOnce.Do(func() {
target, err := dialer(address)
if err != nil {
session.openErr = err
session.readyMu.Lock()
session.targetError = err
session.targetEOF = true
session.signalReadyLocked()
session.readyMu.Unlock()
return
}
session.target = target
go session.readTarget()
})
return session.openErr
}
func (session *Session) readTarget() {
buffer := make([]byte, 65536)
for {
count, err := session.target.Read(buffer)
if count > 0 {
session.readyMu.Lock()
session.downloadBuffer.append(buffer[:count])
session.touch()
session.signalReadyLocked()
session.readyMu.Unlock()
}
if err != nil {
session.readyMu.Lock()
if !errors.Is(err, io.EOF) {
session.targetError = err
}
session.targetEOF = true
session.signalReadyLocked()
session.readyMu.Unlock()
session.downloadMu.Lock()
session.downloadClosed = true
session.signalDownloadLocked()
session.downloadMu.Unlock()
return
}
}
}
func (session *Session) WriteUpload(sequence uint64, payload []byte) error {
session.uploadMu.Lock()
defer session.uploadMu.Unlock()
if sequence < session.uploadNext {
return nil
}
if _, exists := session.uploadPending[sequence]; !exists {
session.uploadPending[sequence] = append([]byte(nil), payload...)
}
for {
chunk, exists := session.uploadPending[session.uploadNext]
if !exists {
return nil
}
delete(session.uploadPending, session.uploadNext)
if len(chunk) > 0 && session.target != nil {
if err := writeAll(session.target, chunk); err != nil {
return err
}
}
session.uploadNext++
session.touch()
}
}
// UploadCommitted reports the highest contiguous upload sequence written to
// the target. Receipt alone is not a commit when lanes arrive out of order.
func (session *Session) UploadCommitted() (uint64, bool) {
session.uploadMu.Lock()
defer session.uploadMu.Unlock()
if session.uploadNext == 0 {
return 0, false
}
return session.uploadNext - 1, true
}
func (session *Session) TakeDownload(sequence uint64, limit int, bannerTimeout time.Duration) []byte {
if limit < 1 {
limit = 1
}
if limit > MaxDownloadSize {
limit = MaxDownloadSize
}
deadline := time.NewTimer(bannerTimeout)
defer deadline.Stop()
session.readyMu.Lock()
defer session.readyMu.Unlock()
if !session.bannerDelivered && sequence != 0 {
return nil
}
for session.downloadBuffer.available() == 0 && !session.targetEOF {
if session.bannerDelivered {
return nil
}
signal := session.readySignal
session.readyMu.Unlock()
select {
case <-signal:
case <-deadline.C:
session.readyMu.Lock()
return nil
}
session.readyMu.Lock()
}
chunk := session.downloadBuffer.take(limit)
if len(chunk) == 0 {
return nil
}
session.bannerDelivered = true
session.touch()
return chunk
}
func (session *Session) AssignDownload(sequence uint64, count int, limit int) [][]byte {
session.downloadMu.Lock()
for sequence > session.downloadNext && !session.downloadClosed {
signal := session.downloadSignal
session.downloadMu.Unlock()
<-signal
session.downloadMu.Lock()
}
isNew := sequence == session.downloadNext
chunks := make([][]byte, count)
for offset := 0; offset < count; offset++ {
current := sequence + uint64(offset)
if isNew {
chunk := session.TakeDownload(current, limit, 5*time.Second)
if len(chunk) > 0 {
session.downloadFrames[current] = chunk
}
chunks[offset] = chunk
} else {
chunks[offset] = append([]byte(nil), session.downloadFrames[current]...)
}
}
if isNew {
session.downloadNext += uint64(count)
session.signalDownloadLocked()
}
session.downloadMu.Unlock()
return chunks
}
func (session *Session) Acknowledge(sequence uint64) {
session.downloadMu.Lock()
defer session.downloadMu.Unlock()
if session.hasACK && sequence <= session.downloadAcked {
return
}
session.hasACK = true
session.downloadAcked = sequence
for number := range session.downloadFrames {
if number <= sequence {
delete(session.downloadFrames, number)
}
}
}
func (session *Session) Close() {
session.closeOnce.Do(func() {
if session.target != nil {
_ = session.target.Close()
}
session.readyMu.Lock()
session.targetEOF = true
session.signalReadyLocked()
session.readyMu.Unlock()
session.downloadMu.Lock()
session.downloadClosed = true
session.signalDownloadLocked()
session.downloadMu.Unlock()
})
}
type SessionManager struct {
mu sync.RWMutex
sessions map[SessionID]*Session
timeout time.Duration
// limit caps concurrently tracked sessions. Zero or negative disables it.
limit int
// rejected, when set, counts sessions turned away at the limit.
rejected *atomic.Uint64
}
func NewSessionManager(timeout time.Duration) *SessionManager {
return &SessionManager{sessions: make(map[SessionID]*Session), timeout: timeout}
}
// GetOrCreate returns the session for sid, creating it if needed. It returns
// nil when the session limit is already reached and sid is not known yet.
func (manager *SessionManager) GetOrCreate(sid SessionID) *Session {
session, _ := manager.GetOrCreateState(sid)
return session
}
// GetOrCreateState reports whether the returned session already existed. A nil
// session means the manager is at its configured limit.
func (manager *SessionManager) GetOrCreateState(sid SessionID) (*Session, bool) {
manager.mu.RLock()
session := manager.sessions[sid]
manager.mu.RUnlock()
if session != nil {
return session, true
}
manager.mu.Lock()
defer manager.mu.Unlock()
if session = manager.sessions[sid]; session != nil {
return session, true
}
if manager.limit > 0 && len(manager.sessions) >= manager.limit {
if manager.rejected != nil {
manager.rejected.Add(1)
}
return nil, false
}
session = NewSession(sid)
manager.sessions[sid] = session
return session, false
}
// Len reports how many sessions are currently tracked.
func (manager *SessionManager) Len() int {
manager.mu.RLock()
defer manager.mu.RUnlock()
return len(manager.sessions)
}
func (manager *SessionManager) Get(sid SessionID) (*Session, bool) {
manager.mu.RLock()
session := manager.sessions[sid]
manager.mu.RUnlock()
return session, session != nil
}
func (manager *SessionManager) Cleanup(now time.Time) int {
manager.mu.Lock()
var stale []*Session
for sid, session := range manager.sessions {
if now.Sub(session.LastSeen()) > manager.timeout {
delete(manager.sessions, sid)
stale = append(stale, session)
}
}
manager.mu.Unlock()
for _, session := range stale {
session.Close()
}
return len(stale)
}
func (manager *SessionManager) Close() {
manager.mu.Lock()
sessions := make([]*Session, 0, len(manager.sessions))
for sid, session := range manager.sessions {
delete(manager.sessions, sid)
sessions = append(sessions, session)
}
manager.mu.Unlock()
for _, session := range sessions {
session.Close()
}
}
+99
View File
@@ -0,0 +1,99 @@
package bhttp
import (
"bytes"
"encoding/binary"
)
// Verdict is the result of inspecting the first bytes of a connection.
type Verdict int
const (
// VerdictNo means the bytes cannot begin a BHTTP frame.
VerdictNo Verdict = iota
// VerdictMore means the bytes so far are consistent with BHTTP but more
// are needed to decide. The caller should peek further and ask again.
VerdictMore
// VerdictYes means the bytes begin a BHTTP frame.
VerdictYes
)
// SniffLimit is the largest number of bytes SniffFrame will ever ask for. It
// covers a full frame header plus a probe/lane payload, which is where the
// magic strings that make the decision conclusive live.
const SniffLimit = HeaderSize + 4096
// SniffFrame reports whether data begins a BHTTP frame, so a listener shared
// with other protocols can route the connection without consuming anything.
//
// The first byte alone already separates BHTTP from the protocols it shares a
// port with: a BHTTP frame opens with a mode number (0..5), while SSH opens
// with 'S' (0x53) and an HTTP request or status line opens with a method or
// version letter. Every one of those is far above ModeLane, so a single byte
// rejects them outright and costs nothing.
//
// A low first byte is not proof on its own, because HTTP-injection clients may
// prepend arbitrary junk. So the frame header is range-checked, and for the two
// modes that carry a magic string — the probe that opens every client session
// and the v2 lane hello — the magic is decrypted and verified. That check is
// keyed by the session ID in the same header, so junk cannot pass it by chance.
func SniffFrame(data []byte) Verdict {
if len(data) == 0 {
return VerdictMore
}
mode := data[0]
if mode > ModeLane {
return VerdictNo
}
if len(data) < HeaderSize {
return VerdictMore
}
request := Request{Mode: mode}
copy(request.SID[:], data[1:17])
request.Seq = binary.BigEndian.Uint64(data[17:25])
request.Value = binary.BigEndian.Uint32(data[25:29])
// Modes 2 and 4 overload Value as a size hint and an empty cumulative ACK,
// so they carry no payload to verify.
if mode == ModeDownload || mode == ModeACK {
return VerdictYes
}
if request.Value > MaxPayload {
return VerdictNo
}
magic, ok := frameMagic(mode)
if !ok {
// Modes 1 and 3 have no magic string. A sane header is all there is.
return VerdictYes
}
// An oversized payload cannot be a probe or lane hello, both of which are
// short, so the magic would not be where it belongs.
if int(request.Value) > SniffLimit-HeaderSize {
return VerdictNo
}
end := HeaderSize + int(request.Value)
if len(data) < end {
return VerdictMore
}
clear := Crypt(data[HeaderSize:end], request.SID, mode, request.Seq, false)
if len(clear) < len(magic) || !bytes.Equal(clear[:len(magic)], magic) {
return VerdictNo
}
return VerdictYes
}
// frameMagic returns the plaintext prefix a mode's payload must start with,
// and whether that mode has one at all.
func frameMagic(mode byte) ([]byte, bool) {
switch mode {
case ModeProbe:
// A probe is either the BHP1 profile or the BHP2 capability handshake;
// both share the first three bytes, which is what is checked here.
return []byte("BHP"), true
case ModeLane:
return []byte("BLN2"), true
}
return nil, false
}
+164
View File
@@ -0,0 +1,164 @@
package bhttp
import (
"encoding/binary"
"testing"
)
// frame builds a wire frame for the sniffer to inspect.
func frame(mode byte, sid SessionID, sequence uint64, clear []byte) []byte {
payload := Crypt(clear, sid, mode, sequence, false)
out := make([]byte, HeaderSize+len(payload))
out[0] = mode
copy(out[1:17], sid[:])
binary.BigEndian.PutUint64(out[17:25], sequence)
binary.BigEndian.PutUint32(out[25:29], uint32(len(payload)))
copy(out[HeaderSize:], payload)
return out
}
func probeClear(magic string, submode byte, parameter uint32) []byte {
clear := make([]byte, 10)
copy(clear[:4], magic)
clear[4] = 1
clear[5] = submode
binary.BigEndian.PutUint32(clear[6:10], parameter)
return clear
}
// Everything BHTTP shares a port with has to be rejected on the first byte,
// otherwise sharing the port would break SSH and HTTP-injection clients.
func TestSniffRejectsTheProtocolsItSharesPortsWith(t *testing.T) {
tests := map[string]string{
"SSH identification": "SSH-2.0-OpenSSH_9.6\r\n",
"HTTP GET": "GET / HTTP/1.1\r\nHost: x\r\n\r\n",
"HTTP POST": "POST /path HTTP/1.1\r\n\r\n",
"HTTP HEAD": "HEAD / HTTP/1.0\r\n\r\n",
"HTTP CONNECT": "CONNECT host:443 HTTP/1.1\r\n\r\n",
"HTTP OPTIONS": "OPTIONS / HTTP/1.1\r\n\r\n",
"HTTP PATCH": "PATCH / HTTP/1.1\r\n\r\n",
"HTTP status line": "HTTP/1.1 200 OK\r\n\r\n",
"TLS client hello": "\x16\x03\x01\x02\x00\x01\x00\x01\xfc\x03\x03",
"bare CRLF": "\r\n\r\n",
}
for name, input := range tests {
t.Run(name, func(t *testing.T) {
if got := SniffFrame([]byte(input)); got != VerdictNo {
t.Fatalf("SniffFrame(%q) = %v, want VerdictNo", input, got)
}
})
}
}
func TestSniffAcceptsProbeFrames(t *testing.T) {
var sid SessionID
copy(sid[:], "sniff-probe-sid1")
bhp1 := frame(ModeProbe, sid, 0, probeClear("BHP1", ModeUpload, 0))
if got := SniffFrame(bhp1); got != VerdictYes {
t.Fatalf("BHP1 probe = %v, want VerdictYes", got)
}
capability := make([]byte, 10)
copy(capability[:4], "BHP2")
capability[4] = 2
bhp2 := frame(ModeProbe, sid, 3, capability)
if got := SniffFrame(bhp2); got != VerdictYes {
t.Fatalf("BHP2 probe = %v, want VerdictYes", got)
}
}
func TestSniffAcceptsLaneAndDataFrames(t *testing.T) {
var sid SessionID
copy(sid[:], "sniff-lane-sid01")
hello := make([]byte, 12)
copy(hello[:4], "BLN2")
hello[4] = 2
hello[5] = laneUpload
binary.BigEndian.PutUint32(hello[8:], 4)
if got := SniffFrame(frame(ModeLane, sid, 9, hello)); got != VerdictYes {
t.Fatalf("v2 lane hello = %v, want VerdictYes", got)
}
// Modes 2 and 4 carry no payload; a sane header is the whole signal.
if got := SniffFrame(frame(ModeDownload, sid, 1, nil)); got != VerdictYes {
t.Fatalf("download frame = %v, want VerdictYes", got)
}
if got := SniffFrame(frame(ModeACK, sid, 2, nil)); got != VerdictYes {
t.Fatalf("ACK frame = %v, want VerdictYes", got)
}
if got := SniffFrame(frame(ModeUpload, sid, 0, nil)); got != VerdictYes {
t.Fatalf("session-open upload frame = %v, want VerdictYes", got)
}
}
// An injection client may prepend arbitrary junk, and some of that junk starts
// with a low byte. The magic check on the frame types that carry one is what
// keeps such a connection out of BHTTP.
func TestSniffRejectsLowByteJunk(t *testing.T) {
var sid SessionID
copy(sid[:], "sniff-junk-sid01")
// A probe-shaped frame whose payload is not a BHP probe at all.
bogus := frame(ModeProbe, sid, 0, []byte("not-a-probe-payload"))
if got := SniffFrame(bogus); got != VerdictNo {
t.Fatalf("probe with wrong magic = %v, want VerdictNo", got)
}
// A lane-shaped frame whose payload is not a BLN2 hello.
bogusLane := frame(ModeLane, sid, 0, make([]byte, 12))
if got := SniffFrame(bogusLane); got != VerdictNo {
t.Fatalf("lane with wrong magic = %v, want VerdictNo", got)
}
// Unencrypted plaintext magic must also fail: the sniff decrypts with the
// session ID from the same header, so a copied magic string does not pass.
plaintext := make([]byte, HeaderSize+10)
plaintext[0] = ModeProbe
copy(plaintext[1:17], sid[:])
binary.BigEndian.PutUint32(plaintext[25:29], 10)
copy(plaintext[HeaderSize:], "BHP1")
if got := SniffFrame(plaintext); got != VerdictNo {
t.Fatalf("plaintext magic = %v, want VerdictNo", got)
}
// A declared payload larger than the protocol allows is not a frame.
oversized := make([]byte, HeaderSize)
oversized[0] = ModeUpload
binary.BigEndian.PutUint32(oversized[25:29], MaxPayload+1)
if got := SniffFrame(oversized); got != VerdictNo {
t.Fatalf("oversized payload = %v, want VerdictNo", got)
}
// A probe claiming more payload than a probe can hold is not a probe.
longProbe := make([]byte, HeaderSize)
longProbe[0] = ModeProbe
binary.BigEndian.PutUint32(longProbe[25:29], SniffLimit)
if got := SniffFrame(longProbe); got != VerdictNo {
t.Fatalf("over-long probe = %v, want VerdictNo", got)
}
}
func TestSniffAsksForMoreBytesWhenUndecided(t *testing.T) {
var sid SessionID
copy(sid[:], "sniff-partial-s1")
full := frame(ModeProbe, sid, 0, probeClear("BHP1", ModeUpload, 0))
if got := SniffFrame(nil); got != VerdictMore {
t.Fatalf("empty input = %v, want VerdictMore", got)
}
if got := SniffFrame(full[:1]); got != VerdictMore {
t.Fatalf("mode byte only = %v, want VerdictMore", got)
}
if got := SniffFrame(full[:HeaderSize-1]); got != VerdictMore {
t.Fatalf("partial header = %v, want VerdictMore", got)
}
// Header complete but the probe payload still missing.
if got := SniffFrame(full[:HeaderSize]); got != VerdictMore {
t.Fatalf("header without payload = %v, want VerdictMore", got)
}
if got := SniffFrame(full); got != VerdictYes {
t.Fatalf("complete probe = %v, want VerdictYes", got)
}
}
+369
View File
@@ -0,0 +1,369 @@
package bhttp
import (
"bytes"
"encoding/binary"
"io"
"net"
"testing"
"time"
)
func v2Request(mode byte, sid SessionID, sequence uint64, clear []byte) Request {
return Request{
Mode: mode, SID: sid, Seq: sequence,
Payload: Crypt(clear, sid, mode, sequence, false),
}
}
func TestBHTTPV2CapabilityIsExplicitAndVersioned(t *testing.T) {
var sid SessionID
copy(sid[:], "capability-v2")
clear := make([]byte, 10)
copy(clear[:4], "BHP2")
clear[4] = bhttpV2Version
request := v2Request(ModeProbe, sid, 0, clear)
var response bytes.Buffer
if err := handleProbe(&response, request); err != nil {
t.Fatal(err)
}
status, body, _, err := readTestResponse(&response)
if err != nil || status != StatusOK {
t.Fatalf("status=%d err=%v", status, err)
}
decoded := Crypt(body, sid, ModeProbe, 0, true)
if len(decoded) != 14 || string(decoded[:4]) != "BHP2" || decoded[4] != 2 {
t.Fatalf("invalid capability response %x", decoded)
}
features := binary.BigEndian.Uint32(decoded[6:10])
if features != bhttpV2FeatureLanes|bhttpV2FeatureResume|bhttpV2FeatureAck {
t.Fatalf("features=%x", features)
}
if maximum := binary.BigEndian.Uint32(decoded[10:14]); maximum != bhttpV2MaxLanes {
t.Fatalf("max lanes=%d", maximum)
}
}
func TestBHTTPV2LaneResumeAndCommittedUploadACK(t *testing.T) {
targetServer, targetPeer := net.Pipe()
defer targetPeer.Close()
server := NewServer(Config{DialTarget: func(string) (net.Conn, error) {
return targetServer, nil
}})
defer server.Close()
var sid SessionID
copy(sid[:], "lane-resume-v2!!")
hello := make([]byte, 12)
copy(hello[:4], "BLN2")
hello[4] = 2
hello[5] = laneUpload
binary.BigEndian.PutUint32(hello[8:], 7)
request := v2Request(ModeLane, sid, 7, hello)
var first bytes.Buffer
role, firstSession, err := server.attachLane(&first, request)
if err != nil || role != laneUpload {
t.Fatalf("first attach role=%d err=%v", role, err)
}
defer firstSession.ReleaseLane()
_, firstBody, _, err := readTestResponse(&first)
if err != nil {
t.Fatal(err)
}
firstDecoded := Crypt(firstBody, sid, ModeLane, 7, true)
if firstDecoded[5] != 0 {
t.Fatal("first lane unexpectedly resumed")
}
hello[7] = 1
request = v2Request(ModeLane, sid, 8, hello)
var resumed bytes.Buffer
_, resumedSession, err := server.attachLane(&resumed, request)
if err != nil {
t.Fatal(err)
}
defer resumedSession.ReleaseLane()
_, resumedBody, _, _ := readTestResponse(&resumed)
resumedDecoded := Crypt(resumedBody, sid, ModeLane, 8, true)
if resumedDecoded[5] != 1 {
t.Fatal("replacement lane did not resume existing SID")
}
session := server.sessions.GetOrCreate(sid)
var outOfOrder bytes.Buffer
request = v2Request(ModeUpload, sid, 1, []byte("one"))
if err := server.handleRequest(&outOfOrder, session, request, true); err != nil {
t.Fatal(err)
}
_, ackBody, _, _ := readTestResponse(&outOfOrder)
if len(ackBody) != 9 || ackBody[0] != 0 {
t.Fatalf("out-of-order frame was incorrectly committed: %x", ackBody)
}
targetRead := make(chan []byte, 1)
go func() {
value := make([]byte, len("zeroone"))
_, _ = io.ReadFull(targetPeer, value)
targetRead <- value
}()
var ordered bytes.Buffer
request = v2Request(ModeUpload, sid, 0, []byte("zero"))
if err := server.handleRequest(&ordered, session, request, true); err != nil {
t.Fatal(err)
}
_, ackBody, _, _ = readTestResponse(&ordered)
if len(ackBody) != 9 || ackBody[0] != 1 || binary.BigEndian.Uint64(ackBody[1:]) != 1 {
t.Fatalf("cumulative committed ACK invalid: %x", ackBody)
}
select {
case value := <-targetRead:
if string(value) != "zeroone" {
t.Fatalf("target received %q", value)
}
case <-time.After(time.Second):
t.Fatal("ordered upload did not reach target")
}
}
func TestBHTTPV2ResumeNeverCreatesExpiredSession(t *testing.T) {
server := NewServer(Config{})
defer server.Close()
var sid SessionID
copy(sid[:], "expired-resume")
hello := make([]byte, 12)
copy(hello[:4], "BLN2")
hello[4] = 2
hello[5] = laneDownload
hello[7] = 1
var response bytes.Buffer
if _, _, err := server.attachLane(&response, v2Request(ModeLane, sid, 1, hello)); err == nil {
t.Fatal("expired resume was accepted")
}
if _, exists := server.sessions.Get(sid); exists {
t.Fatal("resume rejection silently created a new session")
}
}
func TestBHTTPV2PersistentLaneCarriesMultipleRequests(t *testing.T) {
targetServer, targetPeer := net.Pipe()
defer targetPeer.Close()
server := NewServer(Config{DialTarget: func(string) (net.Conn, error) {
return targetServer, nil
}})
defer server.Close()
accepted, client := net.Pipe()
done := make(chan error, 1)
go func() { done <- server.handleConnection(accepted) }()
defer func() {
_ = client.Close()
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("persistent handler did not stop")
}
}()
_ = client.SetDeadline(time.Now().Add(2 * time.Second))
var sid SessionID
copy(sid[:], "persistent-v2")
hello := make([]byte, 12)
copy(hello[:4], "BLN2")
hello[4] = 2
hello[5] = laneUpload
binary.BigEndian.PutUint32(hello[8:], 11)
request := v2Request(ModeLane, sid, 11, hello)
if err := writeTestRequest(client, request.Mode, request.SID, request.Seq, request.Payload, 0); err != nil {
t.Fatal(err)
}
status, _, _, err := readTestResponse(client)
if err != nil || status != StatusOK {
t.Fatalf("lane attach status=%d err=%v", status, err)
}
want := []byte("firstsecond")
received := make(chan []byte, 1)
go func() {
value := make([]byte, len(want))
_, _ = io.ReadFull(targetPeer, value)
received <- value
}()
for sequence, clear := range [][]byte{[]byte("first"), []byte("second")} {
request = v2Request(ModeUpload, sid, uint64(sequence), clear)
if err := writeTestRequest(client, request.Mode, request.SID, request.Seq, request.Payload, 0); err != nil {
t.Fatal(err)
}
status, body, _, readErr := readTestResponse(client)
if readErr != nil || status != StatusOK || len(body) != 9 || body[0] != 1 {
t.Fatalf("upload %d status=%d body=%x err=%v", sequence, status, body, readErr)
}
if committed := binary.BigEndian.Uint64(body[1:]); committed != uint64(sequence) {
t.Fatalf("upload %d committed=%d", sequence, committed)
}
}
select {
case got := <-received:
if !bytes.Equal(got, want) {
t.Fatalf("persistent lane target=%q", got)
}
case <-time.After(time.Second):
t.Fatal("persistent lane did not forward both requests")
}
}
func TestBHTTPV2ReplayAfterLaneReplacementDoesNotDuplicateBytes(t *testing.T) {
targetServer, targetPeer := net.Pipe()
defer targetPeer.Close()
server := NewServer(Config{DialTarget: func(string) (net.Conn, error) {
return targetServer, nil
}})
defer server.Close()
var sid SessionID
copy(sid[:], "replay-lane-v2")
hello := make([]byte, 12)
copy(hello[:4], "BLN2")
hello[4] = 2
hello[5] = laneUpload
firstRequest := v2Request(ModeLane, sid, 1, hello)
var first bytes.Buffer
_, firstSession, err := server.attachLane(&first, firstRequest)
if err != nil {
t.Fatal(err)
}
firstSession.ReleaseLane()
want := []byte("firstsecond")
received := make(chan []byte, 1)
go func() {
value := make([]byte, len(want))
_, _ = io.ReadFull(targetPeer, value)
received <- value
}()
session := server.sessions.GetOrCreate(sid)
var response bytes.Buffer
if err := server.handleRequest(&response, session,
v2Request(ModeUpload, sid, 0, []byte("first")), true); err != nil {
t.Fatal(err)
}
hello[7] = 1
var replacement bytes.Buffer
_, replacementSession, err := server.attachLane(&replacement,
v2Request(ModeLane, sid, 2, hello))
if err != nil {
t.Fatal(err)
}
defer replacementSession.ReleaseLane()
response.Reset()
if err := server.handleRequest(&response, session,
v2Request(ModeUpload, sid, 0, []byte("first")), true); err != nil {
t.Fatal(err)
}
response.Reset()
if err := server.handleRequest(&response, session,
v2Request(ModeUpload, sid, 1, []byte("second")), true); err != nil {
t.Fatal(err)
}
select {
case got := <-received:
if !bytes.Equal(got, want) {
t.Fatalf("replayed target bytes=%q", got)
}
case <-time.After(time.Second):
t.Fatal("replacement lane did not finish upload")
}
}
func TestBHTTPV2LaneLimitIsEnforced(t *testing.T) {
targetServer, targetPeer := net.Pipe()
defer targetPeer.Close()
server := NewServer(Config{MaxV2Lanes: 1, DialTarget: func(string) (net.Conn, error) {
return targetServer, nil
}})
defer server.Close()
var sid SessionID
copy(sid[:], "lane-limit-v2")
hello := make([]byte, 12)
copy(hello[:4], "BLN2")
hello[4] = 2
hello[5] = laneUpload
var first bytes.Buffer
_, session, err := server.attachLane(&first, v2Request(ModeLane, sid, 1, hello))
if err != nil {
t.Fatal(err)
}
defer session.ReleaseLane()
hello[5] = laneDownload
hello[7] = 1
binary.BigEndian.PutUint32(hello[8:], 2)
var rejected bytes.Buffer
if _, _, err := server.attachLane(&rejected,
v2Request(ModeLane, sid, 2, hello)); err == nil {
t.Fatal("second lane exceeded configured limit")
}
}
func TestBHTTPV2LaneReplacementKeepsSingleLogicalSlot(t *testing.T) {
session := NewSession(SessionID{})
first, ok := session.AcquireLane(7, 1)
if !ok {
t.Fatal("first logical lane was rejected")
}
replacement, ok := session.AcquireLane(7, 1)
if !ok {
t.Fatal("replacement of the same lane ID consumed another slot")
}
first.ReleaseLane()
if _, ok := session.AcquireLane(8, 1); ok {
t.Fatal("stale release removed the replacement generation")
}
replacement.ReleaseLane()
if final, ok := session.AcquireLane(8, 1); !ok {
t.Fatal("released replacement did not free its logical slot")
} else {
final.ReleaseLane()
}
}
func TestServerCloseAbortsIdlePersistentConnections(t *testing.T) {
server := NewServer(Config{})
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
serveDone := make(chan error, 1)
go func() { serveDone <- server.Serve(listener) }()
connection, err := net.Dial("tcp", listener.Addr().String())
if err != nil {
t.Fatal(err)
}
defer connection.Close()
deadline := time.Now().Add(time.Second)
for {
server.connMu.Lock()
active := len(server.active)
server.connMu.Unlock()
if active == 1 {
break
}
if time.Now().After(deadline) {
t.Fatal("server did not track idle connection")
}
time.Sleep(time.Millisecond)
}
_ = listener.Close()
server.Close()
waitDone := make(chan struct{})
go func() {
server.Wait()
close(waitDone)
}()
select {
case <-waitDone:
case <-time.After(time.Second):
t.Fatal("server shutdown waited on idle persistent connection")
}
select {
case <-serveDone:
case <-time.After(time.Second):
t.Fatal("Serve did not return after listener close")
}
}
+62
View File
@@ -0,0 +1,62 @@
package btun
import (
"context"
"io"
)
// Authenticator verifies a BTUN credential. The panel supplies its own
// implementation backed by the same account database the built-in SSH server
// uses, so a BTUN login is exactly as strong as an SSH login on this server.
//
// This package deliberately ships no PAM, /etc/shadow or password-file
// backend: BTUN accounts are panel accounts and nothing else.
type Authenticator interface {
Authenticate(username, password string) error
Name() string
}
// AllowAuthenticator accepts every credential. It exists only for the package
// tests, which exercise the wire protocol rather than the account database. It
// is never selectable from the panel configuration.
type AllowAuthenticator struct{}
func (AllowAuthenticator) Authenticate(_, _ string) error { return nil }
func (AllowAuthenticator) Name() string { return "allow-insecure" }
// Accountant lets the embedding application admit a freshly authenticated
// session and then meter its traffic. It is optional: when Config.Accountant
// is nil, sessions are admitted unconditionally and no metering happens.
type Accountant interface {
// Admit is called once per session, immediately after the credential was
// accepted. Returning an error refuses the session, which is how
// per-account connection limits are enforced. The returned Ledger is
// closed exactly once when the session ends.
//
// closer ends this session on demand, so the application can force a
// disconnect (an account being deleted, edited, or hit by a panel-wide
// restart) without waiting for the next packet to be metered.
Admit(username, remote string, closer io.Closer) (Ledger, error)
}
// Ledger meters one BTUN session. Uplink and Downlink are called before the
// corresponding packet is forwarded, so returning an error drops the session
// instead of letting it exceed its allowance. Implementations must be safe for
// concurrent use: Uplink runs on the session's reader goroutine while Downlink
// runs on the shared TUN reader goroutine.
type Ledger interface {
// Uplink accounts for n bytes travelling client -> internet. It may block
// while rate limiting and returns an error when the session must end.
Uplink(ctx context.Context, n int) error
// Downlink accounts for n bytes travelling internet -> client.
Downlink(ctx context.Context, n int) error
// Close releases whatever the ledger reserved for this session.
Close()
}
// nopLedger is used when no Accountant is configured.
type nopLedger struct{}
func (nopLedger) Uplink(context.Context, int) error { return nil }
func (nopLedger) Downlink(context.Context, int) error { return nil }
func (nopLedger) Close() {}
+73
View File
@@ -0,0 +1,73 @@
package btun
import (
"encoding/binary"
"errors"
"fmt"
"net"
"sync"
)
type AddressPool struct {
mu sync.Mutex
network uint32
first uint32
last uint32
next uint32
used map[uint32]struct{}
}
func NewAddressPool(cidr string) (*AddressPool, error) {
ip, network, err := net.ParseCIDR(cidr)
if err != nil {
return nil, fmt.Errorf("parse subnet: %w", err)
}
v4 := ip.To4()
if v4 == nil {
return nil, errors.New("BTUN subnet must be IPv4")
}
ones, bits := network.Mask.Size()
if bits != 32 || ones > 30 {
return nil, errors.New("BTUN subnet must contain at least four IPv4 addresses")
}
base := binary.BigEndian.Uint32(v4) & binary.BigEndian.Uint32(network.Mask)
size := uint64(1) << uint(32-ones)
last := uint32(uint64(base) + size - 2)
first := base + 2
if first > last {
return nil, errors.New("BTUN subnet has no client addresses")
}
return &AddressPool{network: base, first: first, last: last, next: first, used: make(map[uint32]struct{})}, nil
}
func (pool *AddressPool) Acquire() (net.IP, error) {
pool.mu.Lock()
defer pool.mu.Unlock()
capacity := uint64(pool.last) - uint64(pool.first) + 1
for checked := uint64(0); checked < capacity; checked++ {
candidate := pool.next
pool.next++
if pool.next > pool.last {
pool.next = pool.first
}
if _, exists := pool.used[candidate]; exists {
continue
}
pool.used[candidate] = struct{}{}
var raw [4]byte
binary.BigEndian.PutUint32(raw[:], candidate)
return net.IPv4(raw[0], raw[1], raw[2], raw[3]), nil
}
return nil, errors.New("BTUN address pool exhausted")
}
func (pool *AddressPool) Release(ip net.IP) {
v4 := ip.To4()
if v4 == nil {
return
}
value := binary.BigEndian.Uint32(v4)
pool.mu.Lock()
delete(pool.used, value)
pool.mu.Unlock()
}
+161
View File
@@ -0,0 +1,161 @@
package btun
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"net"
)
const (
PacketAuth byte = 1
PacketAuthResponse byte = 2
PacketIP byte = 3
PacketData byte = 4
PacketKeepAlive byte = 5
HeaderSize = 6
DefaultMaxPacket = 64 * 1024
)
var (
ClientHello = []byte("DTUNNEL/1.1 CLIENT_HELLO\r\n")
ServerHello = []byte("DTUNNEL/1.1 SERVER_HELLO\r\n")
)
type Packet struct {
Type byte
Flags byte
Payload []byte
}
func MarshalPacket(packet Packet, maxPayload int) ([]byte, error) {
if maxPayload <= 0 {
maxPayload = DefaultMaxPacket
}
if len(packet.Payload) > maxPayload {
return nil, fmt.Errorf("packet payload too large: %d", len(packet.Payload))
}
encoded := make([]byte, HeaderSize+len(packet.Payload))
encoded[0] = packet.Type
encoded[1] = packet.Flags
binary.BigEndian.PutUint32(encoded[2:6], uint32(len(packet.Payload)))
copy(encoded[HeaderSize:], packet.Payload)
return encoded, nil
}
func ReadPacket(reader io.Reader, maxPayload int) (Packet, error) {
if maxPayload <= 0 {
maxPayload = DefaultMaxPacket
}
var header [HeaderSize]byte
if _, err := io.ReadFull(reader, header[:]); err != nil {
return Packet{}, err
}
length := int(binary.BigEndian.Uint32(header[2:6]))
if length > maxPayload {
return Packet{}, fmt.Errorf("packet payload too large: %d", length)
}
payload := make([]byte, length)
if _, err := io.ReadFull(reader, payload); err != nil {
return Packet{}, err
}
return Packet{Type: header[0], Flags: header[1], Payload: payload}, nil
}
func ParseDatagram(datagram []byte, maxPayload int) (Packet, error) {
if len(datagram) < HeaderSize {
return Packet{}, errors.New("datagram is shorter than the packet header")
}
if maxPayload <= 0 {
maxPayload = DefaultMaxPacket
}
length := int(binary.BigEndian.Uint32(datagram[2:6]))
if length > maxPayload {
return Packet{}, fmt.Errorf("packet payload too large: %d", length)
}
if len(datagram) != HeaderSize+length {
return Packet{}, fmt.Errorf("invalid datagram length: got %d, want %d", len(datagram), HeaderSize+length)
}
payload := append([]byte(nil), datagram[HeaderSize:]...)
return Packet{Type: datagram[0], Flags: datagram[1], Payload: payload}, nil
}
func ReadClientHello(reader io.Reader, maxCoverBytes int) (int, error) {
if maxCoverBytes < 0 {
maxCoverBytes = 0
}
readLimit := maxCoverBytes + len(ClientHello)
window := make([]byte, 0, len(ClientHello))
var one [1]byte
for consumed := 0; consumed < readLimit; consumed++ {
if _, err := io.ReadFull(reader, one[:]); err != nil {
return consumed, err
}
if len(window) == cap(window) {
copy(window, window[1:])
window = window[:len(window)-1]
}
window = append(window, one[0])
if bytes.Equal(window, ClientHello) {
return consumed + 1 - len(ClientHello), nil
}
}
return maxCoverBytes, errors.New("client hello not found")
}
func ParseCredential(payload []byte) (string, string, error) {
separator := bytes.IndexByte(payload, ':')
if separator <= 0 {
return "", "", errors.New("invalid credential")
}
username := string(payload[:separator])
password := string(payload[separator+1:])
if len(username) > 256 || len(password) > 4096 || bytes.IndexByte(payload, 0) >= 0 {
return "", "", errors.New("invalid credential")
}
return username, password, nil
}
func AuthResponse(accepted bool, message string) Packet {
payload := make([]byte, 1, 1+len(message))
if accepted {
payload[0] = 1
}
payload = append(payload, message...)
return Packet{Type: PacketAuthResponse, Payload: payload}
}
func ParseIPv4Packet(packet []byte) (source [4]byte, destination [4]byte, ok bool) {
source, destination, _, ok = parseIPv4Packet(packet)
return source, destination, ok
}
func parseIPv4Packet(packet []byte) (source [4]byte, destination [4]byte, totalLength int, ok bool) {
if len(packet) < 20 || packet[0]>>4 != 4 {
return source, destination, 0, false
}
headerLength := int(packet[0]&0x0f) * 4
if headerLength < 20 || headerLength > len(packet) {
return source, destination, 0, false
}
totalLength = int(binary.BigEndian.Uint16(packet[2:4]))
if totalLength < headerLength || totalLength > len(packet) {
return source, destination, 0, false
}
copy(source[:], packet[12:16])
copy(destination[:], packet[16:20])
return source, destination, totalLength, true
}
func ipKey(ip net.IP) ([4]byte, bool) {
var key [4]byte
v4 := ip.To4()
if v4 == nil {
return key, false
}
copy(key[:], v4)
return key, true
}
+68
View File
@@ -0,0 +1,68 @@
package btun
import (
"bytes"
"encoding/binary"
"net"
"testing"
)
func TestPacketRoundTrip(t *testing.T) {
want := Packet{Type: PacketData, Payload: []byte{1, 2, 3, 4}}
encoded, err := MarshalPacket(want, 1024)
if err != nil {
t.Fatal(err)
}
got, err := ReadPacket(bytes.NewReader(encoded), 1024)
if err != nil {
t.Fatal(err)
}
if got.Type != want.Type || got.Flags != want.Flags || !bytes.Equal(got.Payload, want.Payload) {
t.Fatalf("packet mismatch: %#v != %#v", got, want)
}
}
func TestReadClientHelloAfterCoverBytes(t *testing.T) {
cover := []byte("GET / HTTP/1.1\r\nHost: example.test\r\n\r\n")
stream := append(append([]byte(nil), cover...), ClientHello...)
consumed, err := ReadClientHello(bytes.NewReader(stream), len(cover))
if err != nil {
t.Fatal(err)
}
if consumed != len(cover) {
t.Fatalf("cover bytes = %d, want %d", consumed, len(cover))
}
}
func TestAddressPool(t *testing.T) {
pool, err := NewAddressPool("10.77.0.0/29")
if err != nil {
t.Fatal(err)
}
first, err := pool.Acquire()
if err != nil {
t.Fatal(err)
}
if !first.Equal(net.IPv4(10, 77, 0, 2)) {
t.Fatalf("first address = %s", first)
}
pool.Release(first)
}
func TestIPv4ParserAcceptsTransportPadding(t *testing.T) {
packet := make([]byte, 28)
packet[0] = 0x45
binary.BigEndian.PutUint16(packet[2:4], 20)
copy(packet[12:16], []byte{10, 77, 0, 2})
copy(packet[16:20], []byte{1, 1, 1, 1})
source, destination, totalLength, ok := parseIPv4Packet(packet)
if !ok {
t.Fatal("padded IPv4 packet was rejected")
}
if source != [4]byte{10, 77, 0, 2} || destination != [4]byte{1, 1, 1, 1} {
t.Fatalf("unexpected addresses: %v -> %v", source, destination)
}
if totalLength != 20 {
t.Fatalf("IPv4 length = %d, want 20", totalLength)
}
}
+798
View File
@@ -0,0 +1,798 @@
package btun
import (
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"io"
"log"
"net"
"os"
"strings"
"sync"
"sync/atomic"
"time"
)
type PacketDevice interface {
io.ReadWriteCloser
Name() string
}
type Config struct {
Subnet string
Authenticator Authenticator
// Accountant is an optional hook the embedding application uses to admit
// authenticated sessions and meter their traffic. Nil admits every session
// and meters nothing.
Accountant Accountant
Logger *log.Logger
HandshakeTimeout time.Duration
IdleTimeout time.Duration
MaxPacketSize int
MaxCoverBytes int
// MaxSessions caps concurrently tracked sessions across both transports.
// Zero or negative disables the cap.
MaxSessions int
// LogConnections enables one log line per session start/stop. Leave it off
// on busy servers.
LogConnections bool
}
type StatsSnapshot struct {
StartedAt time.Time `json:"startedAt"`
ActiveSessions uint64 `json:"activeSessions"`
Accepted uint64 `json:"accepted"`
AuthSucceeded uint64 `json:"authSucceeded"`
AuthRejected uint64 `json:"authRejected"`
ClientPackets uint64 `json:"clientPackets"`
InternetPackets uint64 `json:"internetPackets"`
ClientBytes uint64 `json:"clientBytes"`
InternetBytes uint64 `json:"internetBytes"`
DroppedPackets uint64 `json:"droppedPackets"`
SessionsRejected uint64 `json:"sessionsRejected"`
}
type counters struct {
activeSessions atomic.Uint64
accepted atomic.Uint64
authSucceeded atomic.Uint64
authRejected atomic.Uint64
clientPackets atomic.Uint64
internetPackets atomic.Uint64
clientBytes atomic.Uint64
internetBytes atomic.Uint64
droppedPackets atomic.Uint64
sessionsRejected atomic.Uint64
}
type Server struct {
config Config
tun PacketDevice
pool *AddressPool
started time.Time
stats counters
mu sync.RWMutex
sessions map[*session]struct{}
byIP map[[4]byte]*session
udpByAddr map[string]*session
closers []io.Closer
tunWriteMu sync.Mutex
closed chan struct{}
closeOnce sync.Once
wait sync.WaitGroup
}
type session struct {
server *Server
transport sessionTransport
udpKey string
user string
ledger Ledger
ctx context.Context
cancel context.CancelFunc
mu sync.Mutex
authenticated bool
assignedIP net.IP
lastActive time.Time
handleMu sync.Mutex
closeOnce sync.Once
invalidFrames uint64
}
type sessionTransport interface {
Send(Packet, int) (int, error)
Close() error
Remote() string
}
type tcpTransport struct {
connection net.Conn
writeMu sync.Mutex
}
func (transport *tcpTransport) Send(packet Packet, maxPayload int) (int, error) {
encoded, err := MarshalPacket(packet, maxPayload)
if err != nil {
return 0, err
}
transport.writeMu.Lock()
defer transport.writeMu.Unlock()
return len(encoded), writeFull(transport.connection, encoded)
}
func (transport *tcpTransport) Close() error { return transport.connection.Close() }
func (transport *tcpTransport) Remote() string { return transport.connection.RemoteAddr().String() }
type udpTransport struct {
connection net.PacketConn
address net.Addr
writeMu sync.Mutex
}
func (transport *udpTransport) Send(packet Packet, maxPayload int) (int, error) {
encoded, err := MarshalPacket(packet, maxPayload)
if err != nil {
return 0, err
}
transport.writeMu.Lock()
defer transport.writeMu.Unlock()
written, err := transport.connection.WriteTo(encoded, transport.address)
if err == nil && written != len(encoded) {
err = io.ErrShortWrite
}
return written, err
}
func (transport *udpTransport) Close() error { return nil }
func (transport *udpTransport) Remote() string { return transport.address.String() }
func NewServer(config Config, tun PacketDevice) (*Server, error) {
if tun == nil {
return nil, errors.New("TUN device is required")
}
if config.Authenticator == nil {
return nil, errors.New("authenticator is required")
}
if config.Subnet == "" {
config.Subnet = "10.77.0.0/16"
}
if config.Logger == nil {
config.Logger = log.Default()
}
if config.HandshakeTimeout <= 0 {
config.HandshakeTimeout = 15 * time.Second
}
if config.IdleTimeout <= 0 {
config.IdleTimeout = 2 * time.Minute
}
if config.MaxPacketSize <= 0 {
config.MaxPacketSize = DefaultMaxPacket
}
if config.MaxPacketSize > 4*1024*1024 {
return nil, errors.New("maximum packet size cannot exceed 4 MiB")
}
if config.MaxCoverBytes <= 0 {
config.MaxCoverBytes = 64 * 1024
}
pool, err := NewAddressPool(config.Subnet)
if err != nil {
return nil, err
}
server := &Server{
config: config, tun: tun, pool: pool, started: time.Now(),
sessions: make(map[*session]struct{}), byIP: make(map[[4]byte]*session),
udpByAddr: make(map[string]*session), closed: make(chan struct{}),
}
server.wait.Add(2)
go server.tunLoop()
go server.cleanupLoop()
return server, nil
}
func (server *Server) ServeTCP(listener net.Listener) error {
server.addCloser(listener)
server.config.Logger.Printf("BTUN TCP listening on %s", listener.Addr())
for {
connection, err := listener.Accept()
if err != nil {
if server.isClosed() || errors.Is(err, net.ErrClosed) {
return nil
}
return err
}
server.stats.accepted.Add(1)
if tcp, ok := connection.(*net.TCPConn); ok {
_ = tcp.SetNoDelay(true)
_ = tcp.SetKeepAlive(true)
_ = tcp.SetKeepAlivePeriod(30 * time.Second)
}
server.wait.Add(1)
go func() {
defer server.wait.Done()
server.runTCP(connection)
}()
}
}
// ServeConn serves one already-accepted TCP connection, for listeners this
// server does not own. A port shared with SSH or HTTP routes a client here once
// its hello has been identified; the session is then authenticated, counted and
// closed exactly like one from ServeTCP's own accept loop.
//
// It blocks until the session ends, and reports whether the server was still
// running when the connection arrived. A refused connection is closed here, and
// the caller must not keep using the connection either way.
func (server *Server) ServeConn(connection net.Conn) bool {
if server.isClosed() {
_ = connection.Close()
return false
}
server.stats.accepted.Add(1)
server.wait.Add(1)
defer server.wait.Done()
server.runTCP(connection)
return true
}
// runTCP drives one TCP connection to completion.
func (server *Server) runTCP(connection net.Conn) {
if err := server.handleTCP(connection); err != nil && !normalClose(err) {
server.config.Logger.Printf("BTUN TCP %s: %v", connection.RemoteAddr(), err)
}
}
func (server *Server) handleTCP(connection net.Conn) error {
transport := &tcpTransport{connection: connection}
current := server.newSession(transport, "")
if current == nil {
return errors.New("BTUN session limit reached")
}
defer current.close()
_ = connection.SetDeadline(time.Now().Add(server.config.HandshakeTimeout))
coverBytes, err := ReadClientHello(connection, server.config.MaxCoverBytes)
if err != nil {
return fmt.Errorf("handshake: %w", err)
}
if coverBytes > 0 {
server.config.Logger.Printf("BTUN TCP %s accepted %d cover bytes", transport.Remote(), coverBytes)
}
if err := writeFull(connection, ServerHello); err != nil {
return fmt.Errorf("write server hello: %w", err)
}
authPacket, err := ReadPacket(connection, server.config.MaxPacketSize)
if err != nil {
return fmt.Errorf("read authentication: %w", err)
}
if err := server.authenticate(current, authPacket); err != nil {
return err
}
_ = connection.SetDeadline(time.Time{})
for {
if server.config.IdleTimeout > 0 {
_ = connection.SetReadDeadline(time.Now().Add(server.config.IdleTimeout))
}
packet, err := ReadPacket(connection, server.config.MaxPacketSize)
if err != nil {
return err
}
if err := server.handleClientPacket(current, packet); err != nil {
return err
}
}
}
func (server *Server) ServeUDP(connection net.PacketConn) error {
server.addCloser(connection)
server.config.Logger.Printf("BTUN UDP listening on %s", connection.LocalAddr())
buffer := make([]byte, server.config.MaxPacketSize+HeaderSize)
for {
length, address, err := connection.ReadFrom(buffer)
if err != nil {
if server.isClosed() || errors.Is(err, net.ErrClosed) {
return nil
}
return err
}
datagram := append([]byte(nil), buffer[:length]...)
if bytes.Equal(datagram, ClientHello) {
server.startUDPSession(connection, address)
continue
}
server.mu.RLock()
current := server.udpByAddr[address.String()]
server.mu.RUnlock()
if current == nil {
server.stats.droppedPackets.Add(1)
continue
}
packet, err := ParseDatagram(datagram, server.config.MaxPacketSize)
if err != nil {
server.stats.droppedPackets.Add(1)
continue
}
current.handleMu.Lock()
if !current.isAuthenticated() {
err = server.authenticate(current, packet)
} else {
err = server.handleClientPacket(current, packet)
}
current.handleMu.Unlock()
if err != nil {
server.config.Logger.Printf("BTUN UDP %s: %v", address, err)
current.close()
}
}
}
func (server *Server) startUDPSession(connection net.PacketConn, address net.Addr) {
server.stats.accepted.Add(1)
key := address.String()
transport := &udpTransport{connection: connection, address: address}
current := server.newSession(transport, key)
if current == nil {
return
}
server.mu.Lock()
previous := server.udpByAddr[key]
server.udpByAddr[key] = current
server.mu.Unlock()
if previous != nil && previous != current {
previous.close()
}
if _, err := connection.WriteTo(ServerHello, address); err != nil {
current.close()
return
}
server.config.Logger.Printf("BTUN UDP handshake from %s", address)
}
func (server *Server) authenticate(current *session, packet Packet) error {
if packet.Type != PacketAuth || packet.Flags != 0 {
server.stats.authRejected.Add(1)
_ = current.send(AuthResponse(false, "authentication required"))
return errors.New("authentication packet required")
}
username, password, err := ParseCredential(packet.Payload)
if err != nil {
server.stats.authRejected.Add(1)
_ = current.send(AuthResponse(false, "invalid credential"))
return err
}
if err := server.config.Authenticator.Authenticate(username, password); err != nil {
server.stats.authRejected.Add(1)
_ = current.send(AuthResponse(false, "invalid username or password"))
return errors.New("authentication rejected")
}
// Admission comes after the credential check so per-account connection
// limits and data quotas are enforced by the same code path the built-in
// SSH server uses. A refusal here is a policy decision, not a bad password,
// and is reported to the client as such.
if server.config.Accountant != nil {
ledger, err := server.config.Accountant.Admit(username, current.transport.Remote(), sessionCloser{session: current})
if err != nil {
server.stats.authRejected.Add(1)
_ = current.send(AuthResponse(false, err.Error()))
return fmt.Errorf("session refused for %s: %w", username, err)
}
if ledger == nil {
ledger = nopLedger{}
}
current.mu.Lock()
current.ledger = ledger
current.mu.Unlock()
}
current.mu.Lock()
current.authenticated = true
current.user = username
current.lastActive = time.Now()
current.mu.Unlock()
server.stats.authSucceeded.Add(1)
if err := current.send(AuthResponse(true, "authenticated")); err != nil {
return fmt.Errorf("write authentication response: %w", err)
}
if server.config.LogConnections {
server.config.Logger.Printf("BTUN %s authenticated user=%s via %s", current.transport.Remote(), username, server.config.Authenticator.Name())
}
return nil
}
func (server *Server) handleClientPacket(current *session, packet Packet) error {
current.touch()
if packet.Flags != 0 {
return errors.New("unsupported packet flags")
}
switch packet.Type {
case PacketIP:
if len(packet.Payload) != 0 {
return errors.New("invalid IP request")
}
ip, err := server.assignIP(current)
if err != nil {
return err
}
return current.send(Packet{Type: PacketIP, Payload: append([]byte(nil), ip.To4()...)})
case PacketData:
source, _, totalLength, ok := parseIPv4Packet(packet.Payload)
assigned, assignedOK := current.ipKey()
if !ok {
server.stats.droppedPackets.Add(1)
server.logDroppedFrame(current, "invalid IPv4", packet.Payload, assigned, assignedOK)
return nil
}
if !assignedOK || source != assigned {
server.stats.droppedPackets.Add(1)
server.logDroppedFrame(current, "source mismatch", packet.Payload, assigned, assignedOK)
return nil
}
payload := packet.Payload[:totalLength]
if err := current.meter(true, len(payload)); err != nil {
return err
}
server.tunWriteMu.Lock()
written, err := server.tun.Write(payload)
server.tunWriteMu.Unlock()
if err != nil {
return fmt.Errorf("write TUN: %w", err)
}
if written != len(payload) {
return io.ErrShortWrite
}
server.stats.clientPackets.Add(1)
server.stats.clientBytes.Add(uint64(written))
return nil
case PacketKeepAlive:
if len(packet.Payload) != 0 {
return errors.New("invalid keep-alive packet")
}
return nil
default:
return fmt.Errorf("unknown packet type %d", packet.Type)
}
}
func (server *Server) logDroppedFrame(current *session, reason string, payload []byte,
assigned [4]byte, assignedOK bool) {
current.mu.Lock()
current.invalidFrames++
count := current.invalidFrames
current.mu.Unlock()
if count > 3 {
return
}
version := byte(0)
declared := 0
if len(payload) > 0 {
version = payload[0] >> 4
}
if len(payload) >= 4 {
declared = int(binary.BigEndian.Uint16(payload[2:4]))
}
source := "n/a"
if len(payload) >= 16 {
source = net.IP(payload[12:16]).String()
}
assignedText := "none"
if assignedOK {
assignedText = net.IP(assigned[:]).String()
}
server.config.Logger.Printf(
"BTUN %s dropped data frame (%s): frameLen=%d ipVersion=%d ipLen=%d source=%s assigned=%s",
current.transport.Remote(), reason, len(payload), version, declared, source, assignedText)
}
func (server *Server) assignIP(current *session) (net.IP, error) {
current.mu.Lock()
if current.assignedIP != nil {
ip := append(net.IP(nil), current.assignedIP...)
current.mu.Unlock()
return ip, nil
}
current.mu.Unlock()
ip, err := server.pool.Acquire()
if err != nil {
return nil, err
}
key, _ := ipKey(ip)
server.mu.Lock()
if existing := server.byIP[key]; existing != nil && existing != current {
server.mu.Unlock()
server.pool.Release(ip)
return nil, errors.New("address collision")
}
current.mu.Lock()
if current.assignedIP == nil {
current.assignedIP = append(net.IP(nil), ip.To4()...)
server.byIP[key] = current
} else {
server.pool.Release(ip)
ip = append(net.IP(nil), current.assignedIP...)
}
current.mu.Unlock()
server.mu.Unlock()
server.config.Logger.Printf("BTUN %s assigned %s", current.transport.Remote(), ip)
return ip, nil
}
func (server *Server) tunLoop() {
defer server.wait.Done()
buffer := make([]byte, server.config.MaxPacketSize)
for {
length, err := server.tun.Read(buffer)
if err != nil {
if !server.isClosed() && !errors.Is(err, net.ErrClosed) && !errors.Is(err, io.EOF) {
server.config.Logger.Printf("BTUN TUN read stopped: %v", err)
}
return
}
packet := append([]byte(nil), buffer[:length]...)
_, destination, ok := ParseIPv4Packet(packet)
if !ok {
server.stats.droppedPackets.Add(1)
continue
}
server.mu.RLock()
current := server.byIP[destination]
server.mu.RUnlock()
if current == nil {
server.stats.droppedPackets.Add(1)
continue
}
if err := current.meter(false, length); err != nil {
current.close()
continue
}
if err := current.send(Packet{Type: PacketData, Payload: packet}); err != nil {
current.close()
continue
}
server.stats.internetPackets.Add(1)
server.stats.internetBytes.Add(uint64(length))
}
}
func (server *Server) cleanupLoop() {
defer server.wait.Done()
interval := server.config.IdleTimeout / 2
if interval < time.Second {
interval = time.Second
}
if interval > 30*time.Second {
interval = 30 * time.Second
}
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case now := <-ticker.C:
server.mu.RLock()
candidates := make([]*session, 0, len(server.sessions))
for current := range server.sessions {
candidates = append(candidates, current)
}
server.mu.RUnlock()
for _, current := range candidates {
if now.Sub(current.lastSeen()) > server.config.IdleTimeout {
current.close()
}
}
case <-server.closed:
return
}
}
}
func (server *Server) newSession(transport sessionTransport, udpKey string) *session {
ctx, cancel := context.WithCancel(context.Background())
current := &session{
server: server, transport: transport, udpKey: udpKey,
lastActive: time.Now(), ledger: nopLedger{}, ctx: ctx, cancel: cancel,
}
server.mu.Lock()
if maximum := server.config.MaxSessions; maximum > 0 && len(server.sessions) >= maximum {
server.mu.Unlock()
cancel()
server.stats.sessionsRejected.Add(1)
rejected := server.stats.sessionsRejected.Load()
if rejected == 1 || rejected%1000 == 0 {
server.config.Logger.Printf("BTUN session cap reached (%d); rejected %d session(s) so far",
maximum, rejected)
}
_ = transport.Close()
return nil
}
server.sessions[current] = struct{}{}
server.mu.Unlock()
server.stats.activeSessions.Add(1)
return current
}
func (current *session) send(packet Packet) error {
written, err := current.transport.Send(packet, current.server.config.MaxPacketSize)
if err == nil {
current.touch()
_ = written
}
return err
}
func (current *session) touch() {
current.mu.Lock()
current.lastActive = time.Now()
current.mu.Unlock()
}
func (current *session) lastSeen() time.Time {
current.mu.Lock()
defer current.mu.Unlock()
return current.lastActive
}
func (current *session) isAuthenticated() bool {
current.mu.Lock()
defer current.mu.Unlock()
return current.authenticated
}
func (current *session) ipKey() ([4]byte, bool) {
current.mu.Lock()
defer current.mu.Unlock()
return ipKey(current.assignedIP)
}
func (current *session) close() {
current.closeOnce.Do(func() {
if current.cancel != nil {
current.cancel()
}
// The ledger is installed by authenticate under this lock, so it has to
// be read under it too.
current.mu.Lock()
ledger := current.ledger
current.ledger = nil
current.mu.Unlock()
if ledger != nil {
ledger.Close()
}
_ = current.transport.Close()
server := current.server
server.mu.Lock()
delete(server.sessions, current)
if current.udpKey != "" && server.udpByAddr[current.udpKey] == current {
delete(server.udpByAddr, current.udpKey)
}
current.mu.Lock()
assigned := append(net.IP(nil), current.assignedIP...)
current.assignedIP = nil
current.mu.Unlock()
if key, ok := ipKey(assigned); ok && server.byIP[key] == current {
delete(server.byIP, key)
}
server.mu.Unlock()
if assigned != nil {
server.pool.Release(assigned)
}
server.stats.activeSessions.Add(^uint64(0))
if server.config.LogConnections {
server.config.Logger.Printf("BTUN session end: remote=%s user=%s", current.transport.Remote(), current.username())
}
})
}
// sessionCloser lets an Accountant end a session it previously admitted.
type sessionCloser struct{ session *session }
func (c sessionCloser) Close() error {
c.session.close()
return nil
}
// meter runs the session's ledger for n forwarded bytes. Uplink is
// client -> internet; downlink is internet -> client. An error means the
// account ran out of allowance (or was closed) and the session must end.
func (current *session) meter(uplink bool, n int) error {
if n <= 0 {
return nil
}
current.mu.Lock()
ledger := current.ledger
current.mu.Unlock()
if ledger == nil {
return nil
}
if uplink {
return ledger.Uplink(current.ctx, n)
}
return ledger.Downlink(current.ctx, n)
}
func (current *session) username() string {
current.mu.Lock()
defer current.mu.Unlock()
return current.user
}
func (server *Server) addCloser(closer io.Closer) {
server.mu.Lock()
server.closers = append(server.closers, closer)
server.mu.Unlock()
}
func (server *Server) isClosed() bool {
select {
case <-server.closed:
return true
default:
return false
}
}
func (server *Server) Close() error {
var closeError error
server.closeOnce.Do(func() {
close(server.closed)
server.mu.RLock()
closers := append([]io.Closer(nil), server.closers...)
sessions := make([]*session, 0, len(server.sessions))
for current := range server.sessions {
sessions = append(sessions, current)
}
server.mu.RUnlock()
for _, closer := range closers {
if err := closer.Close(); err != nil && closeError == nil && !errors.Is(err, net.ErrClosed) {
closeError = err
}
}
for _, current := range sessions {
current.close()
}
if err := server.tun.Close(); err != nil && closeError == nil && !errors.Is(err, os.ErrClosed) {
closeError = err
}
})
return closeError
}
func (server *Server) Wait() { server.wait.Wait() }
func (server *Server) Stats() StatsSnapshot {
return StatsSnapshot{
StartedAt: server.started, ActiveSessions: server.stats.activeSessions.Load(),
Accepted: server.stats.accepted.Load(), AuthSucceeded: server.stats.authSucceeded.Load(),
AuthRejected: server.stats.authRejected.Load(), ClientPackets: server.stats.clientPackets.Load(),
InternetPackets: server.stats.internetPackets.Load(), ClientBytes: server.stats.clientBytes.Load(),
InternetBytes: server.stats.internetBytes.Load(), DroppedPackets: server.stats.droppedPackets.Load(),
SessionsRejected: server.stats.sessionsRejected.Load(),
}
}
func writeFull(writer io.Writer, data []byte) error {
for len(data) > 0 {
written, err := writer.Write(data)
if err != nil {
return err
}
if written == 0 {
return io.ErrShortWrite
}
data = data[written:]
}
return nil
}
func normalClose(err error) bool {
if err == nil || errors.Is(err, io.EOF) || errors.Is(err, net.ErrClosed) {
return true
}
var networkError net.Error
if errors.As(err, &networkError) && networkError.Timeout() {
return true
}
message := strings.ToLower(err.Error())
return strings.Contains(message, "connection reset") || strings.Contains(message, "broken pipe")
}
+253
View File
@@ -0,0 +1,253 @@
package btun
import (
"bytes"
"encoding/binary"
"io"
"log"
"net"
"sync"
"testing"
"time"
)
type fakeTUN struct {
reads chan []byte
writes chan []byte
closed chan struct{}
once sync.Once
}
func newFakeTUN() *fakeTUN {
return &fakeTUN{reads: make(chan []byte, 4), writes: make(chan []byte, 4), closed: make(chan struct{})}
}
func (tun *fakeTUN) Name() string { return "test0" }
func (tun *fakeTUN) Read(buffer []byte) (int, error) {
select {
case packet := <-tun.reads:
return copy(buffer, packet), nil
case <-tun.closed:
return 0, io.EOF
}
}
func (tun *fakeTUN) Write(packet []byte) (int, error) {
copyOfPacket := append([]byte(nil), packet...)
select {
case tun.writes <- copyOfPacket:
return len(packet), nil
case <-tun.closed:
return 0, io.ErrClosedPipe
}
}
func (tun *fakeTUN) Close() error {
tun.once.Do(func() { close(tun.closed) })
return nil
}
func TestTCPAuthenticationAndPacketRouting(t *testing.T) {
tun := newFakeTUN()
server, err := NewServer(Config{
Subnet: "10.77.0.0/29", Authenticator: AllowAuthenticator{},
Logger: log.New(io.Discard, "", 0), HandshakeTimeout: time.Second,
IdleTimeout: time.Minute,
}, tun)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_ = server.Close()
server.Wait()
})
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
serveDone := make(chan error, 1)
go func() { serveDone <- server.ServeTCP(listener) }()
connection, err := net.DialTimeout("tcp", listener.Addr().String(), time.Second)
if err != nil {
t.Fatal(err)
}
defer connection.Close()
_ = connection.SetDeadline(time.Now().Add(2 * time.Second))
if _, err := connection.Write(append([]byte("cover request\r\n"), ClientHello...)); err != nil {
t.Fatal(err)
}
hello := make([]byte, len(ServerHello))
if _, err := io.ReadFull(connection, hello); err != nil {
t.Fatal(err)
}
if !bytes.Equal(hello, ServerHello) {
t.Fatalf("server hello = %q", hello)
}
writeTestPacket(t, connection, Packet{Type: PacketAuth, Payload: []byte("user:password")})
auth := readTestPacket(t, connection)
if auth.Type != PacketAuthResponse || len(auth.Payload) == 0 || auth.Payload[0] != 1 {
t.Fatalf("unexpected auth response: %#v", auth)
}
writeTestPacket(t, connection, Packet{Type: PacketIP})
ipResponse := readTestPacket(t, connection)
if ipResponse.Type != PacketIP || len(ipResponse.Payload) != 4 {
t.Fatalf("unexpected IP response: %#v", ipResponse)
}
assigned := net.IP(ipResponse.Payload)
// DT5 may emit a non-IPv4 frame while its TUN is coming up. The server
// must drop it without destroying the authenticated stream.
writeTestPacket(t, connection, Packet{Type: PacketData, Payload: []byte{0x60, 0, 0, 0}})
outbound := ipv4Packet(assigned, net.IPv4(1, 1, 1, 1), []byte("out"))
writeTestPacket(t, connection, Packet{Type: PacketData, Payload: outbound})
select {
case got := <-tun.writes:
if !bytes.Equal(got, outbound) {
t.Fatal("outbound TUN packet mismatch")
}
case <-time.After(time.Second):
t.Fatal("outbound packet did not reach TUN")
}
inbound := ipv4Packet(net.IPv4(1, 1, 1, 1), assigned, []byte("in"))
tun.reads <- inbound
data := readTestPacket(t, connection)
if data.Type != PacketData || !bytes.Equal(data.Payload, inbound) {
t.Fatalf("unexpected inbound packet: %#v", data)
}
_ = server.Close()
server.Wait()
if err := <-serveDone; err != nil {
t.Fatal(err)
}
}
func TestUDPAuthenticationAndPacketRouting(t *testing.T) {
tun := newFakeTUN()
server, err := NewServer(Config{
Subnet: "10.77.1.0/29", Authenticator: AllowAuthenticator{},
Logger: log.New(io.Discard, "", 0), IdleTimeout: time.Minute,
}, tun)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_ = server.Close()
server.Wait()
})
packetConnection, err := net.ListenPacket("udp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
serveDone := make(chan error, 1)
go func() { serveDone <- server.ServeUDP(packetConnection) }()
connection, err := net.Dial("udp", packetConnection.LocalAddr().String())
if err != nil {
t.Fatal(err)
}
defer connection.Close()
_ = connection.SetDeadline(time.Now().Add(2 * time.Second))
if _, err := connection.Write(ClientHello); err != nil {
t.Fatal(err)
}
hello := make([]byte, len(ServerHello))
if _, err := io.ReadFull(connection, hello); err != nil {
t.Fatal(err)
}
if !bytes.Equal(hello, ServerHello) {
t.Fatalf("server hello = %q", hello)
}
writeUDPTestPacket(t, connection, Packet{Type: PacketAuth, Payload: []byte("user:password")})
auth := readUDPTestPacket(t, connection)
if auth.Type != PacketAuthResponse || len(auth.Payload) == 0 || auth.Payload[0] != 1 {
t.Fatalf("unexpected auth response: %#v", auth)
}
writeUDPTestPacket(t, connection, Packet{Type: PacketIP})
ipResponse := readUDPTestPacket(t, connection)
if ipResponse.Type != PacketIP || len(ipResponse.Payload) != 4 {
t.Fatalf("unexpected IP response: %#v", ipResponse)
}
assigned := net.IP(ipResponse.Payload)
outbound := ipv4Packet(assigned, net.IPv4(8, 8, 8, 8), []byte("udp-out"))
writeUDPTestPacket(t, connection, Packet{Type: PacketData, Payload: outbound})
select {
case got := <-tun.writes:
if !bytes.Equal(got, outbound) {
t.Fatal("outbound UDP TUN packet mismatch")
}
case <-time.After(time.Second):
t.Fatal("outbound UDP packet did not reach TUN")
}
inbound := ipv4Packet(net.IPv4(8, 8, 8, 8), assigned, []byte("udp-in"))
tun.reads <- inbound
data := readUDPTestPacket(t, connection)
if data.Type != PacketData || !bytes.Equal(data.Payload, inbound) {
t.Fatalf("unexpected inbound UDP packet: %#v", data)
}
_ = server.Close()
server.Wait()
if err := <-serveDone; err != nil {
t.Fatal(err)
}
}
func writeTestPacket(t *testing.T, writer io.Writer, packet Packet) {
t.Helper()
encoded, err := MarshalPacket(packet, DefaultMaxPacket)
if err != nil {
t.Fatal(err)
}
if err := writeFull(writer, encoded); err != nil {
t.Fatal(err)
}
}
func readTestPacket(t *testing.T, reader io.Reader) Packet {
t.Helper()
packet, err := ReadPacket(reader, DefaultMaxPacket)
if err != nil {
t.Fatal(err)
}
return packet
}
func writeUDPTestPacket(t *testing.T, writer io.Writer, packet Packet) {
t.Helper()
encoded, err := MarshalPacket(packet, DefaultMaxPacket)
if err != nil {
t.Fatal(err)
}
written, err := writer.Write(encoded)
if err != nil {
t.Fatal(err)
}
if written != len(encoded) {
t.Fatal(io.ErrShortWrite)
}
}
func readUDPTestPacket(t *testing.T, reader io.Reader) Packet {
t.Helper()
buffer := make([]byte, DefaultMaxPacket+HeaderSize)
length, err := reader.Read(buffer)
if err != nil {
t.Fatal(err)
}
packet, err := ParseDatagram(buffer[:length], DefaultMaxPacket)
if err != nil {
t.Fatal(err)
}
return packet
}
func ipv4Packet(source, destination net.IP, payload []byte) []byte {
packet := make([]byte, 20+len(payload))
packet[0] = 0x45
binary.BigEndian.PutUint16(packet[2:4], uint16(len(packet)))
packet[8] = 64
packet[9] = 17
copy(packet[12:16], source.To4())
copy(packet[16:20], destination.To4())
copy(packet[20:], payload)
return packet
}
+47
View File
@@ -0,0 +1,47 @@
package btun
import "bytes"
// Verdict is the result of inspecting the first bytes of a connection.
type Verdict int
const (
// VerdictNo means the bytes cannot begin a BTUN handshake.
VerdictNo Verdict = iota
// VerdictMore means the bytes so far are consistent with one but more are
// needed to decide. The caller should peek further and ask again.
VerdictMore
// VerdictYes means the bytes begin a BTUN handshake.
VerdictYes
)
// SniffLimit is the largest number of bytes SniffClientHello ever needs.
var SniffLimit = len(ClientHello)
// SniffClientHello reports whether data begins with the BTUN client hello, so
// a listener shared with other protocols can route the connection without
// consuming anything.
//
// The hello is a fixed 25-byte ASCII marker, which makes this decisive in a
// way a length or range check never is: no SSH identification and no HTTP
// request line can match it, and the very first byte already rejects both in
// the overwhelming majority of cases.
//
// The match is anchored at offset zero. A TCP client may legitimately prepend
// cover bytes before its hello, and ServeTCP still tolerates that on a
// dedicated BTUN port, but a shared port cannot buffer an unbounded prefix
// while some other protocol waits to be recognised. Cover that is itself an
// HTTP request is still handled: the panel's HTTP cleanup consumes it, which
// leaves the hello at offset zero for a second look.
func SniffClientHello(data []byte) Verdict {
if len(data) >= len(ClientHello) {
if bytes.Equal(data[:len(ClientHello)], ClientHello) {
return VerdictYes
}
return VerdictNo
}
if bytes.Equal(data, ClientHello[:len(data)]) {
return VerdictMore
}
return VerdictNo
}
+46
View File
@@ -0,0 +1,46 @@
package btun
import "testing"
// Everything BTUN shares a port with has to be rejected, and the marker itself
// has to be accepted, or sharing the port would break SSH and HTTP clients.
func TestSniffClientHello(t *testing.T) {
tests := []struct {
name string
input string
want Verdict
}{
{name: "exact marker", input: string(ClientHello), want: VerdictYes},
{name: "marker then payload", input: string(ClientHello) + "\x01\x02", want: VerdictYes},
{name: "partial marker", input: "DTUNNEL/1.1 CLI", want: VerdictMore},
{name: "first byte only", input: "D", want: VerdictMore},
{name: "empty", input: "", want: VerdictMore},
{name: "SSH identification", input: "SSH-2.0-OpenSSH_9.6\r\n", want: VerdictNo},
{name: "HTTP GET", input: "GET / HTTP/1.1\r\n\r\n", want: VerdictNo},
{name: "HTTP DELETE shares a first byte", input: "DELETE / HTTP/1.1\r\n\r\n", want: VerdictNo},
{name: "TLS client hello", input: "\x16\x03\x01\x02\x00", want: VerdictNo},
{name: "BHTTP frame", input: "\x00\x01\x02\x03", want: VerdictNo},
{name: "wrong version", input: "DTUNNEL/2.0 CLIENT_HELLO\r\n", want: VerdictNo},
{name: "marker not at offset zero", input: "xxDTUNNEL/1.1 CLIENT_HELLO\r\n", want: VerdictNo},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := SniffClientHello([]byte(tt.input)); got != tt.want {
t.Fatalf("SniffClientHello(%q) = %v, want %v", tt.input, got, tt.want)
}
})
}
}
// A partial marker must never be mistaken for a complete one, however it is
// split across reads.
func TestSniffClientHelloIsProgressive(t *testing.T) {
for cut := 0; cut < len(ClientHello); cut++ {
if got := SniffClientHello(ClientHello[:cut]); got != VerdictMore {
t.Fatalf("SniffClientHello(first %d bytes) = %v, want VerdictMore", cut, got)
}
}
if got := SniffClientHello(ClientHello); got != VerdictYes {
t.Fatalf("SniffClientHello(full marker) = %v, want VerdictYes", got)
}
}
+164
View File
@@ -0,0 +1,164 @@
//go:build linux
package btun
import (
"bytes"
"fmt"
"io"
"os"
"sync"
"syscall"
"time"
"unsafe"
)
const (
tunSetIFF = 0x400454ca
iffTUN = 0x0001
iffNoPI = 0x1000
)
type linuxTUN struct {
file *os.File
fd int
name string
closed chan struct{}
readerDone chan struct{}
packets chan []byte
readErrors chan error
fdMu sync.RWMutex
closeOnce sync.Once
closeErr error
}
func OpenTUN(requestedName string) (PacketDevice, error) {
if len(requestedName) == 0 || len(requestedName) >= 16 {
return nil, fmt.Errorf("invalid TUN interface name %q", requestedName)
}
file, err := os.OpenFile("/dev/net/tun", os.O_RDWR, 0)
if err != nil {
return nil, fmt.Errorf("open /dev/net/tun: %w", err)
}
var request [40]byte
copy(request[:16], requestedName)
*(*uint16)(unsafe.Pointer(&request[16])) = iffTUN | iffNoPI
fd := int(file.Fd())
_, _, errno := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), tunSetIFF, uintptr(unsafe.Pointer(&request[0])))
if errno != 0 {
file.Close()
return nil, fmt.Errorf("TUNSETIFF %s: %w", requestedName, errno)
}
if err := syscall.SetNonblock(fd, true); err != nil {
file.Close()
return nil, fmt.Errorf("set TUN nonblocking: %w", err)
}
nameLength := bytes.IndexByte(request[:16], 0)
if nameLength < 0 {
nameLength = 16
}
actual := string(request[:nameLength])
tun := &linuxTUN{
file: file, fd: fd, name: actual, closed: make(chan struct{}),
readerDone: make(chan struct{}), packets: make(chan []byte, 64),
readErrors: make(chan error, 1),
}
go tun.readLoop()
return tun, nil
}
func (tun *linuxTUN) Read(buffer []byte) (int, error) {
select {
case packet := <-tun.packets:
if len(packet) > len(buffer) {
return 0, io.ErrShortBuffer
}
return copy(buffer, packet), nil
case err := <-tun.readErrors:
return 0, err
case <-tun.closed:
return 0, os.ErrClosed
}
}
func (tun *linuxTUN) readLoop() {
defer close(tun.readerDone)
buffer := make([]byte, DefaultMaxPacket)
for {
select {
case <-tun.closed:
return
default:
}
tun.fdMu.RLock()
length, err := syscall.Read(tun.fd, buffer)
tun.fdMu.RUnlock()
if err == nil && length > 0 {
packet := append([]byte(nil), buffer[:length]...)
select {
case tun.packets <- packet:
case <-tun.closed:
return
}
continue
}
if err == nil {
continue
}
if err == syscall.EINTR {
continue
}
if err != syscall.EAGAIN && err != syscall.EWOULDBLOCK {
select {
case tun.readErrors <- err:
case <-tun.closed:
}
return
}
select {
case <-tun.closed:
return
case <-time.After(25 * time.Millisecond):
}
}
}
func (tun *linuxTUN) Write(buffer []byte) (int, error) {
for {
select {
case <-tun.closed:
return 0, os.ErrClosed
default:
}
tun.fdMu.RLock()
length, err := syscall.Write(tun.fd, buffer)
tun.fdMu.RUnlock()
if err == nil {
return length, nil
}
if err == syscall.EINTR {
continue
}
if err != syscall.EAGAIN && err != syscall.EWOULDBLOCK {
return 0, err
}
select {
case <-tun.closed:
return 0, os.ErrClosed
case <-time.After(25 * time.Millisecond):
}
}
}
func (tun *linuxTUN) Close() error {
tun.closeOnce.Do(func() {
close(tun.closed)
<-tun.readerDone
tun.fdMu.Lock()
tun.closeErr = tun.file.Close()
tun.fdMu.Unlock()
})
return tun.closeErr
}
func (tun *linuxTUN) Name() string { return tun.name }
+9
View File
@@ -0,0 +1,9 @@
//go:build !linux
package btun
import "errors"
func OpenTUN(_ string) (PacketDevice, error) {
return nil, errors.New("BTUN TUN is only supported on Linux")
}
+144 -8
View File
@@ -152,6 +152,17 @@ type Config struct {
// Xray holds configuration for the integrated Xray-core process. If nil
// the Xray subprocess is not started. See xray_integration.go.
Xray *XrayConfig `json:"xray"`
// BHTTP holds configuration for the integrated BHTTP (BHP1/BHP2) transport.
// If nil, the transport is disabled. Sessions are relayed to this process's
// own SSH server, never to the system sshd. See bhttp_integration.go.
BHTTP *BHTTPConfig `json:"bhttp"`
// BTUN holds configuration for the integrated BTUN protocol server. If nil,
// the server is disabled. BTUN moves IP packets rather than an SSH stream,
// so it authenticates against the panel's own account database — never PAM
// or /etc/shadow. See btun_integration.go.
BTUN *BTUNConfig `json:"btun"`
}
// DNSTTConfig defines the settings for the integrated dnstt server. See
@@ -392,6 +403,10 @@ type UserState struct {
mu sync.Mutex
ActiveConns int
conns map[*ssh.ServerConn]struct{} // active SSH connections for this user
// btunConns counts active BTUN sessions for this user. BTUN carries IP
// packets instead of an SSH stream, so it has no *ssh.ServerConn to track;
// it shares max_connections with SSH through this counter.
btunConns int
// Persistent per-user tunnel traffic. totalBytes includes reservations made
// by concurrent copy loops, while directional totals only include bytes that
@@ -467,7 +482,7 @@ func (m *UserManager) ReplaceAllPreserveRuntime(newUsers map[string]*UserState)
ou.conns = make(map[*ssh.ServerConn]struct{})
}
// Self-heal any previously stale counter by trusting the live connection map.
ou.ActiveConns = len(ou.conns)
ou.ActiveConns = len(ou.conns) + ou.btunConns
ou.mu.Unlock()
newUsers[username] = ou
@@ -498,6 +513,9 @@ func (m *UserManager) DisconnectUser(username string) {
for _, c := range conns {
_ = c.Close()
}
// BTUN sessions belong to the same account allowance, so a panel-driven
// disconnect has to drop them too.
btunDisconnectUser(username)
}
// DisconnectAll closes every authenticated SSH connection currently tracked by
@@ -526,7 +544,7 @@ func (m *UserManager) DisconnectAll() int {
for c := range seen {
_ = c.Close()
}
return len(seen)
return len(seen) + btunDisconnectAll()
}
// Global state
@@ -1707,6 +1725,10 @@ func startAdminAPI(store *Store, addr string, adminDir string) {
mux.Handle("/api/system/update-status", saSession(http.HandlerFunc(handleUpdateStatus)))
mux.Handle("/api/dnstt", saSession(http.HandlerFunc(handleDnsttStats)))
mux.Handle("/api/dnstt/logs", saSession(http.HandlerFunc(handleDnsttLogs)))
mux.Handle("/api/bhttp", saSession(http.HandlerFunc(handleBHTTPStats)))
mux.Handle("/api/bhttp/logs", saSession(http.HandlerFunc(handleBHTTPLogs)))
mux.Handle("/api/btun", saSession(http.HandlerFunc(handleBTUNStats)))
mux.Handle("/api/btun/logs", saSession(http.HandlerFunc(handleBTUNLogs)))
// Superadmin-only: reseller management
mux.Handle("/api/resellers", saSession(http.HandlerFunc(handleListResellers(store))))
@@ -1834,7 +1856,7 @@ func handleListUsers(w http.ResponseWriter, r *http.Request) {
out := make([]UserDTO, 0, len(states))
for _, u := range states {
u.mu.Lock()
c := len(u.conns)
c := len(u.conns) + u.btunConns
u.ActiveConns = c
cfg := u.Cfg
expires := u.ExpiresAt
@@ -2274,6 +2296,60 @@ func handleDnsttLogs(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode(lines)
}
// handleBHTTPStats returns the current BHTTP transport counters.
func handleBHTTPStats(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
if proxyManagedServerFromRequest(w, r, statsStore, "/api/bhttp", nil, "") {
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(GetBHTTPStatsSnapshot())
}
// handleBHTTPLogs returns the recent BHTTP log lines as a JSON array.
func handleBHTTPLogs(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
lines := getBHTTPLogLines()
if lines == nil {
lines = []string{}
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(lines)
}
// handleBTUNStats returns the current BTUN protocol server counters.
func handleBTUNStats(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
if proxyManagedServerFromRequest(w, r, statsStore, "/api/btun", nil, "") {
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(GetBTUNStatsSnapshot())
}
// handleBTUNLogs returns the recent BTUN log lines as a JSON array.
func handleBTUNLogs(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
lines := getBTUNLogLines()
if lines == nil {
lines = []string{}
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(lines)
}
// ---------- Auth helpers ----------
func normalizeBase32Secret(secret string) string {
@@ -2491,7 +2567,9 @@ func handleConn(tcpConn net.Conn, config *ssh.ServerConfig) {
if u.conns == nil {
u.conns = make(map[*ssh.ServerConn]struct{})
}
activeConns := len(u.conns)
// BTUN sessions count against the same allowance, so a user cannot double
// their limit by mixing transports.
activeConns := len(u.conns) + u.btunConns
u.ActiveConns = activeConns
if u.Cfg.MaxConnections > 0 && activeConns >= u.Cfg.MaxConnections {
u.mu.Unlock()
@@ -2500,7 +2578,7 @@ func handleConn(tcpConn net.Conn, config *ssh.ServerConfig) {
return
}
u.conns[sshConn] = struct{}{}
u.ActiveConns = len(u.conns)
u.ActiveConns = len(u.conns) + u.btunConns
u.mu.Unlock()
// Use per-user limit if set; otherwise fall back to the global config default.
@@ -2535,7 +2613,7 @@ func handleConn(tcpConn net.Conn, config *ssh.ServerConfig) {
close(idleDone)
u.mu.Lock()
delete(u.conns, sshConn)
u.ActiveConns = len(u.conns)
u.ActiveConns = len(u.conns) + u.btunConns
u.mu.Unlock()
updateUserDisplay()
@@ -2659,7 +2737,7 @@ func updateUserDisplay() {
parts := make([]string, 0, len(userStates))
for _, u := range userStates {
u.mu.Lock()
c := len(u.conns)
c := len(u.conns) + u.btunConns
u.ActiveConns = c
name := u.Cfg.Username
u.mu.Unlock()
@@ -2845,6 +2923,18 @@ func handleHTTP80Conn(raw net.Conn, sshConfig *ssh.ServerConfig) {
// Clear deadline before SSH handshake begins.
_ = raw.SetReadDeadline(time.Time{})
// A tunnel client may use an HTTP request as cover, exactly like the
// injection clients this cleanup exists for. The cleanup above consumed
// that cover and already answered 101/200, so what remains is either the
// SSH banner or a tunnel handshake; only the latter is handed over.
if tunnelShareEnabled() {
reader, taken := tunnelTakeSharedConn(raw, br)
if taken {
return
}
br = reader
}
// Hand off to SSH server, ensuring any buffered bytes are preserved.
handleConn(&bufferedConn{Conn: raw, r: br}, sshConfig)
}
@@ -2863,10 +2953,34 @@ func serveHTTP80(ln net.Listener) {
log.Printf("accept error on %s: %v", ln.Addr().String(), err)
continue
}
go handleHTTP80Conn(tcpConn, getSSHConfig())
go handleProxyConn(tcpConn, getSSHConfig())
}
}
// handleProxyConn owns one connection accepted on a public proxy port. When
// BHTTP shares these ports it gets first look, because a BHTTP client speaks
// immediately and must not receive the unsolicited "HTTP/1.1 101" that the
// HTTP-injection path opens with. Anything that is not a BHTTP frame falls
// through to handleHTTP80Conn with its bytes untouched.
func handleProxyConn(raw net.Conn, sshConfig *ssh.ServerConfig) {
// Best-effort TCP tuning here too: the sniff may wrap the connection, and
// handleHTTP80Conn's own type assertion would then no longer see a TCPConn.
if tc, ok := raw.(*net.TCPConn); ok {
_ = tc.SetKeepAlive(true)
_ = tc.SetKeepAlivePeriod(30 * time.Second)
_ = tc.SetNoDelay(true)
}
if !tunnelShareEnabled() {
handleHTTP80Conn(raw, sshConfig)
return
}
reader, taken := tunnelTakeSharedConn(raw, nil)
if taken {
return
}
handleHTTP80Conn(&bufferedConn{Conn: raw, r: reader}, sshConfig)
}
// serveRawSSH accepts connections on ln and passes each directly into
// handleConn. Unlike serveHTTP80 it does not perform HTTP cleanup
// and starts the SSH handshake immediately. This is used by local proxy and
@@ -2910,6 +3024,17 @@ func serveTLSSSH(ln net.Listener) {
}
}
_ = client.SetDeadline(time.Time{})
// Inside TLS the stream is either the SSH banner or, when a tunnel
// transport shares this port, its handshake. The sniff decides on
// the decrypted bytes, so the TLS certificate and SNI are untouched.
if tunnelShareEnabled() {
reader, taken := tunnelTakeSharedConn(client, nil)
if taken {
return
}
handleConn(&bufferedConn{Conn: client, r: reader}, getSSHConfig())
return
}
handleConn(client, getSSHConfig())
}(c)
}
@@ -3498,6 +3623,17 @@ func main() {
log.Printf("udpgw auto-start failed: %v", err)
}
// Start the integrated BHTTP transport and BTUN protocol server. Both relay
// into this process (BHTTP into the built-in SSH server, BTUN into its own
// TUN device with panel-backed authentication), so neither depends on the
// system sshd. Startup errors are logged and surfaced in the admin UI.
if err := startBHTTP(cfg.BHTTP); err != nil {
log.Printf("bhttp auto-start failed: %v", err)
}
if err := startBTUN(cfg.BTUN); err != nil {
log.Printf("btun auto-start failed: %v", err)
}
// Start public SSH listeners (listen + extra_listen).
publicAddrs := append([]string{cfg.Listen}, cfg.ExtraListen...)
for _, e := range publicPool.Sync(publicAddrs) {
+14 -4
View File
@@ -87,11 +87,15 @@ func serverConfigPost(w http.ResponseWriter, r *http.Request) {
http.Error(w, "config exceeds 512 KiB", http.StatusRequestEntityTooLarge)
return
}
// Keep track of optional field presence separately from its boolean value.
// This protects a newly-added setting from being reset by a stale cached
// panel bundle that does not know how to send the field yet.
// Keep track of optional field presence separately from its value. This
// protects a newly-added setting from being reset by a stale cached panel
// bundle that does not know how to send the field yet. For the service
// blocks the distinction matters twice over: a missing key must keep the
// running service, while an explicit null is the panel disabling it.
var fieldPresence struct {
PAMAuthEnabled *bool `json:"pam_auth_enabled"`
PAMAuthEnabled *bool `json:"pam_auth_enabled"`
BHTTP *json.RawMessage `json:"bhttp"`
BTUN *json.RawMessage `json:"btun"`
}
if err := json.Unmarshal(body, &fieldPresence); err != nil {
http.Error(w, "invalid JSON: "+err.Error(), http.StatusBadRequest)
@@ -118,6 +122,12 @@ func serverConfigPost(w http.ResponseWriter, r *http.Request) {
if fieldPresence.PAMAuthEnabled == nil {
newCfg.PAMAuthEnabled = globalCfg.PAMAuthEnabled
}
if fieldPresence.BHTTP == nil {
newCfg.BHTTP = globalCfg.BHTTP
}
if fieldPresence.BTUN == nil {
newCfg.BTUN = globalCfg.BTUN
}
}
globalCfgMu.RUnlock()
+263
View File
@@ -0,0 +1,263 @@
package main
// This file provides the in-memory connection that carries a tunnelled session
// into this process's own SSH server.
//
// The obvious choice, net.Pipe, is unbuffered: every Write blocks until the
// peer Reads the same bytes. That couples the two sides in lock step, so a
// transport goroutine that is momentarily writing cannot also be draining, and
// each direction pays a scheduler round trip per write. A small buffer in each
// direction removes both problems and matches how a real TCP socket behaves,
// which is what the SSH server on the other end is written against.
import (
"errors"
"io"
"net"
"os"
"sync"
"time"
)
// tunnelPipeBuffer is the per-direction buffer, chosen to hold a full SSH
// handshake plus a couple of maximum-size packets without blocking. It bounds
// memory: two of these per tunnelled session, and nothing grows past them.
const tunnelPipeBuffer = 256 * 1024
// tunnelPipe is one direction of the connection: a bounded byte queue with
// deadline-aware blocking reads and writes.
type tunnelPipe struct {
mu sync.Mutex
data []byte
offset int
max int
// signal is closed and replaced whenever the queue changes, so waiters can
// select on it alongside a deadline. This mirrors how the transports in
// this codebase already signal readiness.
signal chan struct{}
closed bool
}
func newTunnelPipe(max int) *tunnelPipe {
return &tunnelPipe{max: max, signal: make(chan struct{})}
}
// broadcastLocked wakes every waiter. The caller must hold mu.
func (p *tunnelPipe) broadcastLocked() {
close(p.signal)
p.signal = make(chan struct{})
}
func (p *tunnelPipe) availableLocked() int { return len(p.data) - p.offset }
// compactLocked reclaims the consumed prefix once it is worth the copy.
func (p *tunnelPipe) compactLocked() {
if p.offset == 0 {
return
}
if p.offset == len(p.data) {
p.data = p.data[:0]
p.offset = 0
return
}
if p.offset >= p.max/2 {
copy(p.data, p.data[p.offset:])
p.data = p.data[:len(p.data)-p.offset]
p.offset = 0
}
}
// write copies data into the queue, blocking while it is full. It returns the
// number of bytes accepted, which is all of them unless the pipe closed or the
// deadline fired.
func (p *tunnelPipe) write(data []byte, deadline func() time.Time) (int, error) {
written := 0
for len(data) > 0 {
p.mu.Lock()
if p.closed {
p.mu.Unlock()
return written, io.ErrClosedPipe
}
p.compactLocked()
room := p.max - p.availableLocked()
if room > 0 {
if room > len(data) {
room = len(data)
}
p.data = append(p.data, data[:room]...)
data = data[room:]
written += room
p.broadcastLocked()
p.mu.Unlock()
continue
}
wait := p.signal
p.mu.Unlock()
if err := waitWithDeadline(wait, deadline); err != nil {
return written, err
}
}
return written, nil
}
// read copies out whatever is queued, blocking until at least one byte is
// available, the pipe closes, or the deadline fires.
func (p *tunnelPipe) read(out []byte, deadline func() time.Time) (int, error) {
if len(out) == 0 {
return 0, nil
}
for {
p.mu.Lock()
if available := p.availableLocked(); available > 0 {
n := copy(out, p.data[p.offset:])
p.offset += n
p.compactLocked()
p.broadcastLocked()
p.mu.Unlock()
return n, nil
}
if p.closed {
p.mu.Unlock()
return 0, io.EOF
}
wait := p.signal
p.mu.Unlock()
if err := waitWithDeadline(wait, deadline); err != nil {
return 0, err
}
}
}
// close marks the direction finished. Queued bytes stay readable so a peer can
// drain what was already sent, matching how a closed TCP socket behaves.
func (p *tunnelPipe) close() {
p.mu.Lock()
if !p.closed {
p.closed = true
p.broadcastLocked()
}
p.mu.Unlock()
}
// waitWithDeadline blocks until the pipe signals, or the deadline passes.
func waitWithDeadline(signal <-chan struct{}, deadline func() time.Time) error {
at := deadline()
if at.IsZero() {
<-signal
return nil
}
delay := time.Until(at)
if delay <= 0 {
return os.ErrDeadlineExceeded
}
timer := time.NewTimer(delay)
defer timer.Stop()
select {
case <-signal:
return nil
case <-timer.C:
return os.ErrDeadlineExceeded
}
}
// tunnelConn is one end of a buffered in-memory connection. It satisfies
// net.Conn, deadlines included, because the SSH server relies on
// SetReadDeadline to bound an unfinished handshake.
type tunnelConn struct {
recv *tunnelPipe
send *tunnelPipe
addr transportAddr
deadlineMu sync.RWMutex
readDeadline time.Time
writeDeadline time.Time
closeOnce sync.Once
}
// newTunnelConnPair returns the two ends of a buffered connection. Bytes
// written to one end are readable from the other.
func newTunnelConnPair(label string, buffer int) (*tunnelConn, *tunnelConn) {
if buffer <= 0 {
buffer = tunnelPipeBuffer
}
toServer := newTunnelPipe(buffer)
toClient := newTunnelPipe(buffer)
addr := transportAddr(label)
client := &tunnelConn{recv: toClient, send: toServer, addr: addr}
server := &tunnelConn{recv: toServer, send: toClient, addr: addr}
return client, server
}
func (c *tunnelConn) Read(p []byte) (int, error) {
return c.recv.read(p, c.currentReadDeadline)
}
func (c *tunnelConn) Write(p []byte) (int, error) {
n, err := c.send.write(p, c.currentWriteDeadline)
if errors.Is(err, io.ErrClosedPipe) && n < len(p) {
return n, io.ErrClosedPipe
}
return n, err
}
// Close shuts both directions. The peer's pending reads drain what was already
// queued and then see EOF.
func (c *tunnelConn) Close() error {
c.closeOnce.Do(func() {
c.send.close()
c.recv.close()
})
return nil
}
func (c *tunnelConn) LocalAddr() net.Addr { return c.addr }
func (c *tunnelConn) RemoteAddr() net.Addr { return c.addr }
func (c *tunnelConn) SetDeadline(t time.Time) error {
c.deadlineMu.Lock()
c.readDeadline = t
c.writeDeadline = t
c.deadlineMu.Unlock()
c.wakeWaiters()
return nil
}
func (c *tunnelConn) SetReadDeadline(t time.Time) error {
c.deadlineMu.Lock()
c.readDeadline = t
c.deadlineMu.Unlock()
c.wakeWaiters()
return nil
}
func (c *tunnelConn) SetWriteDeadline(t time.Time) error {
c.deadlineMu.Lock()
c.writeDeadline = t
c.deadlineMu.Unlock()
c.wakeWaiters()
return nil
}
// wakeWaiters re-evaluates blocked readers and writers so a deadline set while
// they are parked takes effect instead of being seen only on the next wakeup.
func (c *tunnelConn) wakeWaiters() {
c.recv.mu.Lock()
c.recv.broadcastLocked()
c.recv.mu.Unlock()
c.send.mu.Lock()
c.send.broadcastLocked()
c.send.mu.Unlock()
}
func (c *tunnelConn) currentReadDeadline() time.Time {
c.deadlineMu.RLock()
defer c.deadlineMu.RUnlock()
return c.readDeadline
}
func (c *tunnelConn) currentWriteDeadline() time.Time {
c.deadlineMu.RLock()
defer c.deadlineMu.RUnlock()
return c.writeDeadline
}
+188
View File
@@ -0,0 +1,188 @@
package main
// This file lets the tunnel transports share the ports the panel already owns:
// the HTTP+SSH proxy listeners (listen and extra_listen, normally 80 and 8080)
// and the TLS forwarders (normally 443).
//
// It works because the protocols on these ports open in mutually incompatible
// ways. A BHTTP frame starts with its mode number (0..5). A BTUN session starts
// with the fixed ASCII marker "DTUNNEL/1.1 CLIENT_HELLO". SSH starts with "SSH-"
// and an HTTP request or status line starts with a method or version letter.
// Each transport's own package owns the check for its wire format, so the rules
// live next to the protocol they describe.
//
// Nothing is ever consumed on a negative verdict: the bytes stay in the
// returned reader, and the caller continues with its normal handling as if this
// file did not exist.
import (
"bufio"
"encoding/binary"
"net"
"time"
"shell2/internal/bhttp"
"shell2/internal/btun"
)
// tunnelSniffTimeout bounds how long a shared listener waits for a client's
// first bytes. Every protocol here speaks immediately on connect, so a client
// that says nothing for this long is handed to the normal HTTP/SSH path rather
// than being held any longer.
const tunnelSniffTimeout = 3 * time.Second
// tunnelSharedReaderSize must hold the largest prefix any sniff can ask for.
const tunnelSharedReaderSize = bhttp.SniffLimit + 64
// tunnelShareEnabled reports whether any transport wants the shared ports, so
// the listeners can skip all of this when none do.
func tunnelShareEnabled() bool {
return bhttpShareEnabled() || btunShareEnabled()
}
// tunnelTakeSharedConn inspects the front of a connection that arrived on a
// port owned by another protocol and, when it belongs to a tunnel transport,
// serves it to completion.
//
// It returns the reader to keep using and whether the connection was consumed.
// When it returns false the caller continues with its normal handling, and the
// returned reader holds every byte that was inspected.
func tunnelTakeSharedConn(conn net.Conn, reader *bufio.Reader) (*bufio.Reader, bool) {
if reader == nil {
reader = bufio.NewReaderSize(conn, tunnelSharedReaderSize)
}
bhttpOn := bhttpShareEnabled()
btunOn := btunShareEnabled()
if !bhttpOn && !btunOn {
return reader, false
}
// The sniff needs its own deadline: the caller has not set one yet, and a
// client that connects without sending must not wedge this goroutine.
_ = conn.SetReadDeadline(time.Now().Add(tunnelSniffTimeout))
defer func() { _ = conn.SetReadDeadline(time.Time{}) }()
// BTUN is checked first because its marker is a fixed string that either
// matches from the first byte or does not. The two transports cannot both
// claim a connection: a BHTTP frame opens with a byte below 6 and the BTUN
// marker opens with 'D'.
if btunOn && tunnelSniff(reader, btunSniffStep) {
return reader, btunServeShared(conn, reader)
}
if bhttpOn && tunnelSniff(reader, bhttpSniffStep) {
return reader, bhttpServeShared(conn, reader)
}
return reader, false
}
// sniffStep inspects the bytes peeked so far. It returns the protocol's verdict
// and, when undecided, how many bytes to peek before asking again.
type sniffStep func(peeked []byte) (verdict int, want int)
// The verdicts a sniffStep may return, shared by both transports.
const (
sniffNo = iota
sniffMore
sniffYes
)
// tunnelSniff runs one protocol's check, peeking progressively so a protocol
// that is rejected on its first byte costs exactly one byte of lookahead.
func tunnelSniff(reader *bufio.Reader, step sniffStep) bool {
want := 1
for {
peeked, err := reader.Peek(want)
verdict, next := sniffNo, want
if len(peeked) > 0 {
verdict, next = step(peeked)
}
switch {
case verdict == sniffYes:
return true
case verdict == sniffNo:
return false
case err != nil:
// Not enough bytes arrived to decide, so this is not the protocol
// as far as this listener is concerned.
return false
case next <= len(peeked):
// A step that cannot make progress would loop forever.
return false
}
want = next
}
}
// btunSniffStep matches the fixed BTUN client hello.
func btunSniffStep(peeked []byte) (int, int) {
switch btun.SniffClientHello(peeked) {
case btun.VerdictYes:
return sniffYes, 0
case btun.VerdictMore:
return sniffMore, btun.SniffLimit
}
return sniffNo, 0
}
// bhttpSniffStep matches a BHTTP frame: the header first, then the payload the
// header declares, which is where the magic strings that settle it live.
func bhttpSniffStep(peeked []byte) (int, int) {
switch bhttp.SniffFrame(peeked) {
case bhttp.VerdictYes:
return sniffYes, 0
case bhttp.VerdictMore:
if len(peeked) < bhttp.HeaderSize {
return sniffMore, bhttp.HeaderSize
}
want := bhttp.HeaderSize + int(binary.BigEndian.Uint32(peeked[25:29]))
if want > bhttp.SniffLimit {
want = bhttp.SniffLimit
}
return sniffMore, want
}
return sniffNo, 0
}
// bhttpServeShared hands an identified connection to the running BHTTP server.
func bhttpServeShared(conn net.Conn, reader *bufio.Reader) bool {
bhttpMu.Lock()
server := bhttpServer
bhttpMu.Unlock()
if server == nil {
return false
}
if bhttpLogConnections() {
bhttpLog.Printf("shared port: %s -> %s handed to BHTTP", conn.RemoteAddr(), conn.LocalAddr())
}
// The inspected bytes live in the reader, so the server has to read through
// it rather than from the socket.
server.ServeConn(&bufferedConn{Conn: conn, r: reader})
return true
}
// btunServeShared hands an identified connection to the running BTUN server.
func btunServeShared(conn net.Conn, reader *bufio.Reader) bool {
btunMu.Lock()
server := btunServer
btunMu.Unlock()
if server == nil {
return false
}
if btunLogConnections() {
btunLog.Printf("shared port: %s -> %s handed to BTUN", conn.RemoteAddr(), conn.LocalAddr())
}
server.ServeConn(&bufferedConn{Conn: conn, r: reader})
return true
}
func bhttpLogConnections() bool {
globalCfgMu.RLock()
defer globalCfgMu.RUnlock()
return globalCfg != nil && globalCfg.BHTTP != nil && globalCfg.BHTTP.LogConnections
}
func btunLogConnections() bool {
globalCfgMu.RLock()
defer globalCfgMu.RUnlock()
return globalCfg != nil && globalCfg.BTUN != nil && globalCfg.BTUN.LogConnections
}