diff --git a/.gitignore b/.gitignore index 41f013e..ce7c7fb 100644 --- a/.gitignore +++ b/.gitignore @@ -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 diff --git a/README.md b/README.md index 1879914..af723b0 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/admin/assets/js/08-server-config.js b/admin/assets/js/08-server-config.js index 057dcb9..0338b90 100644 --- a/admin/assets/js/08-server-config.js +++ b/admin/assets/js/08-server-config.js @@ -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 = `${escapeHTML(a[0])}${escapeHTML(fmtInt(a[1]))}` + + `${escapeHTML(b[0])}${b[0] ? escapeHTML(fmtInt(b[1])) : ""}`; + 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; diff --git a/admin/index.html b/admin/index.html index 5277c6b..b146955 100644 --- a/admin/index.html +++ b/admin/index.html @@ -1231,15 +1231,17 @@
System studio

Configurações

Rede, SSH, túneis e TLS organizados em blocos visuais e aplicados ao vivo.

-
@@ -1468,8 +1470,205 @@ +
+
04 · BHTTP

BHTTP (BHP1 / BHP2)

Transporte TCP ofuscado dos apps DTunnel. Cada sessão é entregue ao servidor SSH interno do painel — nunca ao sshd do sistema.

+
+
+
BHTTP Transport
+ live + +
+
+ +
+ 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 S e HTTP com a letra do método. Clientes SSH e de injeção HTTP na mesma porta continuam iguais. + Uma mudança existe: com o compartilhamento ligado, a porta do proxy espera os primeiros bytes do cliente em vez de responder HTTP/1.1 101 imediatamente. Todo cliente conhecido envia na hora, mas desligue isto se algum cliente seu aguardar esse 101 antes de falar. +
+
+ + + 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. +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
Restart forte: fecha apenas os listeners BHTTP e suas sessões, depois religa. Não reinicia o painel nem a VPS.
+ + +
+
+ +
+
+
Status BHTTP
+ — + +
+
+
Active Sessions
--
+
Active Sockets
--
+
Upload
--
+
Download
--
+
+
+ + + +
CounterValueCounterValue
+
+
Salve a configuração para iniciar o transporte.Rejeições e falhas de alvo devem normalmente ficar em 0.
+
+
Logs BHTTP
+ +
+
—
+
+
+ +
+
05 · BTUN

BTUN (DTUNNEL/1.1)

VPN nativa por pacotes IP em TCP e UDP. Autentica nas contas do painel — sem PAM e sem /etc/shadow.

+
+
+
BTUN Protocol Server
+ live + +
+
+ +
+ Os listeners existentes entregam ao BTUN apenas no marcador fixo DTUNNEL/1.1 CLIENT_HELLO, 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 UDP Listen. +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+ +
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
Cada sessão BTUN conta no max_connections da conta, no limite de banda e na cota de dados, junto com as conexões SSH.
+ + +
+
+ +
+
+
Status BTUN
+ — + +
+
+
Active Sessions
--
+
Authenticated
--
+
Client → Net
--
+
Net → Client
--
+
+
+ + + +
CounterValueCounterValue
+
+
Salve a configuração para iniciar o servidor.Pacotes descartados indicam MTU ou rota incorreta.
+
+
Logs BTUN
+ +
+
—
+
+
+
-
04 · Segurança

Encaminhadores TLS

Gerencie os certificados do servidor e crie listeners TLS com certificado automático, colado ou armazenado em arquivo.

+
06 · Segurança

Encaminhadores TLS

Gerencie os certificados do servidor e crie listeners TLS com certificado automático, colado ou armazenado em arquivo.

diff --git a/bhttp_btun_integration_test.go b/bhttp_btun_integration_test.go new file mode 100644 index 0000000..3b405cb --- /dev/null +++ b/bhttp_btun_integration_test.go @@ -0,0 +1,1369 @@ +package main + +import ( + "bufio" + "bytes" + "crypto/rand" + "crypto/rsa" + "encoding/binary" + "io" + "log" + "net" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "golang.org/x/crypto/ssh" + + "shell2/internal/bhttp" + "shell2/internal/btun" +) + +// ---------- Test scaffolding ---------- + +// withPanelUsers installs a temporary user table and SSH server config so the +// tunnel transports can be exercised against the built-in SSH server without a +// database or a real listener. +func withPanelUsers(t *testing.T, users ...*UserState) { + t.Helper() + + table := make(map[string]*UserState, len(users)) + for _, u := range users { + if u.conns == nil { + u.conns = make(map[*ssh.ServerConn]struct{}) + } + table[u.Cfg.Username] = u + } + + previousUsers := userMgr.users + userMgr.mu.Lock() + userMgr.users = table + userMgr.mu.Unlock() + + previousCfg := getSSHConfig() + key, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatalf("generate host key: %v", err) + } + signer, err := ssh.NewSignerFromKey(key) + if err != nil { + t.Fatalf("host key signer: %v", err) + } + sshConfig := &ssh.ServerConfig{PasswordCallback: passwordCallback} + sshConfig.AddHostKey(signer) + setSSHConfig(sshConfig) + + t.Cleanup(func() { + userMgr.mu.Lock() + userMgr.users = previousUsers + userMgr.mu.Unlock() + setSSHConfig(previousCfg) + }) +} + +// testLogger routes transport logs into the test output instead of stderr. +func testLogger(t *testing.T) *log.Logger { + t.Helper() + return log.New(testWriter{t: t}, "", 0) +} + +type testWriter struct{ t *testing.T } + +func (w testWriter) Write(p []byte) (int, error) { + w.t.Logf("%s", strings.TrimRight(string(p), "\n")) + return len(p), nil +} + +// loopbackTUN stands in for a real TUN device so the BTUN server can be +// exercised on any platform. Packets written to it are simply discarded; the +// tests here cover the handshake and accounting, not IP routing. +type loopbackTUN struct { + packets chan []byte + closed chan struct{} + once sync.Once +} + +func newLoopbackTUN() *loopbackTUN { + return &loopbackTUN{packets: make(chan []byte, 8), closed: make(chan struct{})} +} + +func (d *loopbackTUN) Read(buffer []byte) (int, error) { + select { + case packet := <-d.packets: + return copy(buffer, packet), nil + case <-d.closed: + return 0, io.EOF + } +} + +func (d *loopbackTUN) Write(buffer []byte) (int, error) { + select { + case <-d.closed: + return 0, io.ErrClosedPipe + default: + return len(buffer), nil + } +} + +func (d *loopbackTUN) Close() error { + d.once.Do(func() { close(d.closed) }) + return nil +} + +func (d *loopbackTUN) Name() string { return "tuntest0" } + +// ---------- The built-in SSH server is the only tunnel target ---------- + +// The whole point of embedding these transports is that a tunnelled session is +// served by this process's own SSH server. If dialInternalSSH ever started +// dialing a TCP address instead, tunnel logins would silently depend on the +// host's sshd, and panel accounts/limits would stop applying. +func TestDialInternalSSHIsServedInProcess(t *testing.T) { + withPanelUsers(t, &UserState{Cfg: UserConfig{Username: "tunnel", Password: "secret"}}) + + conn, err := dialInternalSSH("bhttp") + if err != nil { + t.Fatalf("dialInternalSSH: %v", err) + } + defer conn.Close() + + if network := conn.RemoteAddr().Network(); network != "bhttp" { + t.Fatalf("remote network = %q, want the transport label", network) + } + if _, ok := conn.(*net.TCPConn); ok { + t.Fatal("tunnel target is a TCP socket; it must stay in-process") + } + + _ = conn.SetReadDeadline(time.Now().Add(10 * time.Second)) + banner := make([]byte, 8) + if _, err := io.ReadFull(conn, banner); err != nil { + t.Fatalf("read SSH identification: %v", err) + } + if got := string(banner); got != "SSH-2.0-" { + t.Fatalf("identification = %q, want the built-in SSH server greeting", got) + } +} + +func TestDialInternalSSHFailsBeforeTheSSHServerIsReady(t *testing.T) { + previous := getSSHConfig() + setSSHConfig(nil) + t.Cleanup(func() { setSSHConfig(previous) }) + + if _, err := dialInternalSSH("bhttp"); err == nil { + t.Fatal("expected an error while the SSH server is unavailable") + } +} + +// ---------- BHTTP end to end ---------- + +// bhttpTestClient speaks the raw BHTTP wire format against a listening server. +type bhttpTestClient struct { + t *testing.T + conn net.Conn + sid bhttp.SessionID +} + +func (c *bhttpTestClient) send(mode byte, sequence uint64, clear []byte) { + c.t.Helper() + payload := bhttp.Crypt(clear, c.sid, mode, sequence, false) + frame := make([]byte, bhttp.HeaderSize+len(payload)) + frame[0] = mode + copy(frame[1:17], c.sid[:]) + binary.BigEndian.PutUint64(frame[17:25], sequence) + binary.BigEndian.PutUint32(frame[25:29], uint32(len(payload))) + copy(frame[bhttp.HeaderSize:], payload) + if _, err := c.conn.Write(frame); err != nil { + c.t.Fatalf("write mode %d: %v", mode, err) + } +} + +// readStatus reads one status frame and returns its status byte and body. +func (c *bhttpTestClient) readStatus() (byte, []byte) { + c.t.Helper() + var header [5]byte + if _, err := io.ReadFull(c.conn, header[:]); err != nil { + c.t.Fatalf("read status header: %v", err) + } + body := make([]byte, binary.BigEndian.Uint32(header[1:5])) + if _, err := io.ReadFull(c.conn, body); err != nil { + c.t.Fatalf("read status body: %v", err) + } + return header[0], body +} + +// readDownload reads one download frame and returns the decrypted payload. +func (c *bhttpTestClient) readDownload(mode byte, sequence uint64) []byte { + c.t.Helper() + status, body := c.readStatus() + if status != bhttp.StatusData { + c.t.Fatalf("download status = %d (%q), want StatusData", status, body) + } + if len(body) < 4 { + c.t.Fatalf("download body is %d bytes, want at least 4", len(body)) + } + return bhttp.Crypt(body[4:], c.sid, mode, sequence, true) +} + +// A BHTTP client that opens a session and asks for downstream bytes must get +// the built-in SSH server's identification string, proving the whole path +// (wire framing -> session -> in-process SSH handler) is connected. +func TestBHTTPSessionReachesBuiltInSSHServer(t *testing.T) { + withPanelUsers(t, &UserState{Cfg: UserConfig{Username: "tunnel", Password: "secret"}}) + + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + server := bhttp.NewServer(bhttp.Config{ + TargetAddress: bhttpTargetLabel, + DialTarget: dialInternalSSH, + Logger: testLogger(t), + }) + go func() { _ = server.Serve(listener) }() + t.Cleanup(func() { + _ = listener.Close() + server.Close() + }) + + conn, err := net.Dial("tcp", listener.Addr().String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(15 * time.Second)) + + client := &bhttpTestClient{t: t, conn: conn} + copy(client.sid[:], "bhttp-e2e-sid-01") + + // Mode 1 with sequence 0 and no payload is the session open. + client.send(bhttp.ModeUpload, 0, nil) + if status, body := client.readStatus(); status != bhttp.StatusOK { + t.Fatalf("open status = %d (%q), want StatusOK", status, body) + } + + // Mode 2 pulls the first downstream chunk, which is the SSH banner. + client.send(bhttp.ModeDownload, 0, nil) + payload := client.readDownload(bhttp.ModeDownload, 0) + if !strings.HasPrefix(string(payload), "SSH-2.0-") { + t.Fatalf("first downstream chunk = %q, want the built-in SSH identification", payload) + } +} + +// The session cap has to refuse new session IDs rather than grow without +// bound, otherwise a client spraying random SIDs allocates a session (and an +// SSH handler) per frame. +func TestBHTTPSessionCapRefusesNewSessions(t *testing.T) { + withPanelUsers(t, &UserState{Cfg: UserConfig{Username: "tunnel", Password: "secret"}}) + + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + server := bhttp.NewServer(bhttp.Config{ + TargetAddress: bhttpTargetLabel, + DialTarget: dialInternalSSH, + MaxSessions: 1, + Logger: testLogger(t), + }) + go func() { _ = server.Serve(listener) }() + t.Cleanup(func() { + _ = listener.Close() + server.Close() + }) + + open := func(sid string) (byte, []byte) { + conn, err := net.Dial("tcp", listener.Addr().String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + t.Cleanup(func() { _ = conn.Close() }) + _ = conn.SetDeadline(time.Now().Add(15 * time.Second)) + client := &bhttpTestClient{t: t, conn: conn} + copy(client.sid[:], sid) + client.send(bhttp.ModeUpload, 0, nil) + return client.readStatus() + } + + // A bhttp.SessionID is exactly 16 bytes, so these labels must differ within + // the first 16 characters or they would name the same session. + if status, body := open("bhttp-cap-sid-1"); status != bhttp.StatusOK { + t.Fatalf("first session status = %d (%q), want StatusOK", status, body) + } + if status, _ := open("bhttp-cap-sid-2"); status == bhttp.StatusOK { + t.Fatal("second session was accepted past the cap of 1") + } + if stats := server.Stats(); stats.SessionsRejected == 0 { + t.Fatal("rejected session was not counted") + } +} + +func TestNormalizeBHTTPListenListDeduplicates(t *testing.T) { + got := normalizeBHTTPListenList([]string{" 0.0.0.0:8880 ", "", "0.0.0.0:8880", "[::]:8881"}) + want := []string{"0.0.0.0:8880", "[::]:8881"} + if len(got) != len(want) { + t.Fatalf("got %v, want %v", got, want) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("got %v, want %v", got, want) + } + } +} + +// ---------- BTUN authentication is panel-only ---------- + +func TestBTUNAuthenticatorUsesPanelAccountsOnly(t *testing.T) { + past := time.Now().Add(-time.Hour) + future := time.Now().Add(time.Hour) + + valid := &UserState{Cfg: UserConfig{Username: "valid", Password: "pass"}} + expired := &UserState{Cfg: UserConfig{Username: "expired", Password: "pass"}, ExpiresAt: &past} + active := &UserState{Cfg: UserConfig{Username: "active", Password: "pass"}, ExpiresAt: &future} + quota := &UserState{Cfg: UserConfig{ + Username: "quota", Password: "pass", + DataQuotaBytes: 1024, QuotaAction: quotaActionBlock, + }} + atomic.StoreInt64("a.totalBytes, 4096) + + withPanelUsers(t, valid, expired, active, quota) + + auth := btunPanelAuthenticator{} + if auth.Name() != "panel" { + t.Fatalf("authenticator name = %q, want \"panel\"", auth.Name()) + } + + tests := []struct { + name string + username string + password string + wantErr bool + }{ + {name: "panel password accepted", username: "valid", password: "pass"}, + {name: "unexpired account accepted", username: "active", password: "pass"}, + {name: "wrong password rejected", username: "valid", password: "nope", wantErr: true}, + {name: "unknown account rejected", username: "ghost", password: "pass", wantErr: true}, + {name: "expired account rejected", username: "expired", password: "pass", wantErr: true}, + {name: "account over data quota rejected", username: "quota", password: "pass", wantErr: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := auth.Authenticate(tt.username, tt.password) + if (err != nil) != tt.wantErr { + t.Fatalf("Authenticate(%q) error = %v, wantErr %v", tt.username, err, tt.wantErr) + } + }) + } +} + +// A system account that is not a panel account must never be able to log in +// over BTUN, even with pam_auth_enabled turned on: pam_auth_enabled is an SSH +// setting and BTUN has no PAM path at all. +func TestBTUNAuthenticatorIgnoresSystemLoginSetting(t *testing.T) { + withPanelUsers(t, &UserState{Cfg: UserConfig{Username: "panelonly", Password: "pass"}}) + + setPAMAuthEnabled(true) + t.Cleanup(func() { setPAMAuthEnabled(false) }) + + auth := btunPanelAuthenticator{} + if err := auth.Authenticate("root", "toor"); err == nil { + t.Fatal("a non-panel account was accepted over BTUN") + } +} + +// ---------- BTUN accounting shares the account's allowances with SSH ---------- + +type fakeCloser struct{ closed atomic.Bool } + +func (c *fakeCloser) Close() error { + c.closed.Store(true) + return nil +} + +func TestBTUNSessionsShareMaxConnectionsWithSSH(t *testing.T) { + user := &UserState{Cfg: UserConfig{Username: "limited", Password: "pass", MaxConnections: 2}} + withPanelUsers(t, user) + + accountant := btunPanelAccountant{} + first, err := accountant.Admit("limited", "203.0.113.5:1000", &fakeCloser{}) + if err != nil { + t.Fatalf("first session refused: %v", err) + } + second, err := accountant.Admit("limited", "203.0.113.5:1001", &fakeCloser{}) + if err != nil { + t.Fatalf("second session refused: %v", err) + } + if _, err := accountant.Admit("limited", "203.0.113.5:1002", &fakeCloser{}); err == nil { + t.Fatal("third session was admitted past max_connections = 2") + } + + user.mu.Lock() + counted := user.btunConns + reported := user.ActiveConns + user.mu.Unlock() + if counted != 2 || reported != 2 { + t.Fatalf("btunConns = %d, ActiveConns = %d, want 2 and 2", counted, reported) + } + + // Closing a session must free the slot again. + second.Close() + if _, err := accountant.Admit("limited", "203.0.113.5:1003", &fakeCloser{}); err != nil { + t.Fatalf("session refused after a slot was freed: %v", err) + } + first.Close() +} + +func TestBTUNDisconnectUserClosesItsSessions(t *testing.T) { + user := &UserState{Cfg: UserConfig{Username: "kickme", Password: "pass"}} + other := &UserState{Cfg: UserConfig{Username: "keepme", Password: "pass"}} + withPanelUsers(t, user, other) + + accountant := btunPanelAccountant{} + victimCloser := &fakeCloser{} + bystanderCloser := &fakeCloser{} + victim, err := accountant.Admit("kickme", "203.0.113.9:1000", victimCloser) + if err != nil { + t.Fatalf("admit: %v", err) + } + bystander, err := accountant.Admit("keepme", "203.0.113.9:1001", bystanderCloser) + if err != nil { + t.Fatalf("admit: %v", err) + } + t.Cleanup(func() { + victim.Close() + bystander.Close() + }) + + if closed := btunDisconnectUser("kickme"); closed != 1 { + t.Fatalf("btunDisconnectUser closed %d sessions, want 1", closed) + } + if !victimCloser.closed.Load() { + t.Fatal("the user's own BTUN session was not closed") + } + if bystanderCloser.closed.Load() { + t.Fatal("another user's BTUN session was closed") + } +} + +// Forwarding whole IP packets cannot honour a partial quota allowance, so the +// account's remaining bytes must end the session instead of letting a +// truncated packet through. +func TestBTUNLedgerStopsAtTheDataQuota(t *testing.T) { + user := &UserState{Cfg: UserConfig{ + Username: "capped", Password: "pass", + DataQuotaBytes: 4096, QuotaAction: quotaActionBlock, + }} + withPanelUsers(t, user) + + ledger, err := (btunPanelAccountant{}).Admit("capped", "203.0.113.20:1000", &fakeCloser{}) + if err != nil { + t.Fatalf("admit: %v", err) + } + defer ledger.Close() + + if err := ledger.Uplink(t.Context(), 1024); err != nil { + t.Fatalf("first packet within quota was refused: %v", err) + } + if err := ledger.Downlink(t.Context(), 1024); err != nil { + t.Fatalf("second packet within quota was refused: %v", err) + } + if got := atomic.LoadInt64(&user.TotalUplinkBytes); got != 1024 { + t.Fatalf("uplink bytes = %d, want 1024", got) + } + if got := atomic.LoadInt64(&user.TotalDownlinkBytes); got != 1024 { + t.Fatalf("downlink bytes = %d, want 1024", got) + } + + // This packet crosses the 4096-byte quota, so it must be refused whole. + if err := ledger.Uplink(t.Context(), 4096); err == nil { + t.Fatal("a packet past the data quota was allowed") + } + if got := atomic.LoadInt64(&user.TotalUplinkBytes); got != 1024 { + t.Fatalf("refused packet was still counted: uplink bytes = %d, want 1024", got) + } +} + +func TestBTUNLedgerPacesAtTheAccountBandwidthLimit(t *testing.T) { + user := &UserState{Cfg: UserConfig{Username: "slow", Password: "pass", LimitMbpsUp: 1, LimitMbpsDown: 1}} + withPanelUsers(t, user) + + ledger, err := (btunPanelAccountant{}).Admit("slow", "203.0.113.30:1000", &fakeCloser{}) + if err != nil { + t.Fatalf("admit: %v", err) + } + defer ledger.Close() + + // A 1 Mbps limiter refills at 131072 bytes/s and starts with a full bucket, + // so the first 128 KiB go through immediately and the next 64 KiB must wait + // roughly half a second rather than being refused outright. + const packet = 64 * 1024 + for i := 0; i < 2; i++ { + if err := ledger.Uplink(t.Context(), packet); err != nil { + t.Fatalf("packet %d within the initial burst was refused: %v", i+1, err) + } + } + start := time.Now() + if err := ledger.Uplink(t.Context(), packet); err != nil { + t.Fatalf("packet past the initial burst was refused: %v", err) + } + if elapsed := time.Since(start); elapsed < 100*time.Millisecond { + t.Fatalf("packet past the burst took %s; the bandwidth limit was not applied", elapsed) + } +} + +// ---------- BTUN configuration ---------- + +func TestBTUNGatewayForSubnet(t *testing.T) { + tests := []struct { + subnet string + want string + wantErr bool + }{ + {subnet: "10.77.0.0/16", want: "10.77.0.1/16"}, + {subnet: "10.8.0.0/24", want: "10.8.0.1/24"}, + {subnet: "192.168.20.0/30", want: "192.168.20.1/30"}, + {subnet: "10.9.0.5/24", want: "10.9.0.1/24"}, + {subnet: "10.10.0.0/31", wantErr: true}, + {subnet: "fd00::/64", wantErr: true}, + {subnet: "not-a-subnet", wantErr: true}, + } + for _, tt := range tests { + t.Run(tt.subnet, func(t *testing.T) { + got, err := btunGatewayForSubnet(tt.subnet) + if (err != nil) != tt.wantErr { + t.Fatalf("btunGatewayForSubnet(%q) error = %v, wantErr %v", tt.subnet, err, tt.wantErr) + } + if !tt.wantErr && got != tt.want { + t.Fatalf("btunGatewayForSubnet(%q) = %q, want %q", tt.subnet, got, tt.want) + } + }) + } +} + +func TestNormalizeBTUNConfigFillsDefaults(t *testing.T) { + cfg := &BTUNConfig{TCPListen: " 0.0.0.0:7300 "} + normalizeBTUNConfig(cfg) + + if cfg.TCPListen != "0.0.0.0:7300" { + t.Fatalf("tcp_listen = %q", cfg.TCPListen) + } + if cfg.TUNName != defaultBTUNName { + t.Fatalf("tun_name = %q, want %q", cfg.TUNName, defaultBTUNName) + } + if cfg.Subnet != defaultBTUNSubnet { + t.Fatalf("subnet = %q, want %q", cfg.Subnet, defaultBTUNSubnet) + } + if cfg.Gateway != "10.77.0.1/16" { + t.Fatalf("gateway = %q, want 10.77.0.1/16", cfg.Gateway) + } + if cfg.MTU != defaultBTUNMTU { + t.Fatalf("mtu = %d, want %d", cfg.MTU, defaultBTUNMTU) + } +} + +func TestNormalizeBTUNConfigClampsPacketSize(t *testing.T) { + cfg := &BTUNConfig{UDPListen: "0.0.0.0:7300", MaxPacketSize: 64 * 1024 * 1024} + normalizeBTUNConfig(cfg) + if cfg.MaxPacketSize != btunMaxPacketCeiling { + t.Fatalf("max_packet_size = %d, want %d", cfg.MaxPacketSize, btunMaxPacketCeiling) + } +} + +// A BTUN server started without a listener would silently do nothing, so the +// misconfiguration has to surface as a start error the panel can show. +func TestStartBTUNInstanceRequiresAListener(t *testing.T) { + err := startBTUNInstance(&BTUNConfig{}) + if err == nil { + t.Fatal("expected an error when neither listener is configured") + } + if !strings.Contains(err.Error(), "tcp_listen") { + t.Fatalf("error = %v, want it to name the missing setting", err) + } +} + +func TestNormalizeAutoRestartFields(t *testing.T) { + tests := []struct { + name string + interval string + grace string + wantInterval string + wantGrace string + }{ + {name: "kept as configured", interval: "6h", grace: "2s", wantInterval: "6h", wantGrace: "2s"}, + {name: "interval below the minimum disables", interval: "30s", grace: "", wantInterval: "", wantGrace: ""}, + {name: "invalid interval disables", interval: "soon", grace: "", wantInterval: "", wantGrace: ""}, + {name: "off keeps its sentinel", interval: "off", grace: "", wantInterval: "off", wantGrace: ""}, + {name: "invalid grace falls back", interval: "2h", grace: "later", wantInterval: "2h", wantGrace: ""}, + {name: "long grace is clamped", interval: "2h", grace: "5m", wantInterval: "2h", wantGrace: "1m"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + interval, grace := tt.interval, tt.grace + normalizeAutoRestartFields(&interval, &grace, "TEST", func(string, ...interface{}) {}) + if interval != tt.wantInterval || grace != tt.wantGrace { + t.Fatalf("got (%q, %q), want (%q, %q)", interval, grace, tt.wantInterval, tt.wantGrace) + } + }) + } +} + +func TestNormalizeDurationFieldClamps(t *testing.T) { + tests := []struct { + name string + input string + want string + }{ + {name: "empty stays empty", input: "", want: ""}, + {name: "in range is kept", input: "45s", want: "45s"}, + {name: "below minimum clamps up", input: "1s", want: "10s"}, + {name: "above maximum clamps down", input: "5h", want: "1h0m0s"}, + {name: "invalid clears", input: "nope", want: ""}, + {name: "zero clears", input: "0s", want: ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := tt.input + normalizeDurationField(&got, "test", 10*time.Second, time.Hour, func(string, ...interface{}) {}) + if got != tt.want { + t.Fatalf("normalizeDurationField(%q) = %q, want %q", tt.input, got, tt.want) + } + }) + } +} + +// ---------- BTUN wire behaviour against the panel authenticator ---------- + +// The BTUN handshake must reject a bad panel credential and accept a good one, +// which is what proves the panel authenticator is actually wired into the +// protocol server rather than being dead code. +func TestBTUNHandshakeAuthenticatesAgainstThePanel(t *testing.T) { + withPanelUsers(t, &UserState{Cfg: UserConfig{Username: "vpn", Password: "letmein"}}) + + device := newLoopbackTUN() + server, err := btun.NewServer(btun.Config{ + Subnet: "10.77.0.0/24", + Authenticator: btunPanelAuthenticator{}, + Accountant: btunPanelAccountant{}, + Logger: testLogger(t), + }, device) + if err != nil { + t.Fatalf("new BTUN server: %v", err) + } + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + go func() { _ = server.ServeTCP(listener) }() + t.Cleanup(func() { + _ = listener.Close() + _ = server.Close() + server.Wait() + }) + + authenticate := func(credential string) btun.Packet { + conn, err := net.Dial("tcp", listener.Addr().String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(15 * time.Second)) + + if _, err := conn.Write(btun.ClientHello); err != nil { + t.Fatalf("write client hello: %v", err) + } + hello := make([]byte, len(btun.ServerHello)) + if _, err := io.ReadFull(conn, hello); err != nil { + t.Fatalf("read server hello: %v", err) + } + frame, err := btun.MarshalPacket(btun.Packet{Type: btun.PacketAuth, Payload: []byte(credential)}, 0) + if err != nil { + t.Fatalf("marshal auth: %v", err) + } + if _, err := conn.Write(frame); err != nil { + t.Fatalf("write auth: %v", err) + } + packet, err := btun.ReadPacket(conn, 0) + if err != nil { + t.Fatalf("read auth response: %v", err) + } + return packet + } + + accepted := authenticate("vpn:letmein") + if accepted.Type != btun.PacketAuthResponse || len(accepted.Payload) == 0 || accepted.Payload[0] != 1 { + t.Fatalf("valid panel credential was rejected: %#v", accepted) + } + + refused := authenticate("vpn:wrong") + if refused.Type != btun.PacketAuthResponse || len(refused.Payload) == 0 || refused.Payload[0] != 0 { + t.Fatalf("invalid panel credential was accepted: %#v", refused) + } + + unknown := authenticate("nosuchuser:letmein") + if unknown.Type != btun.PacketAuthResponse || len(unknown.Payload) == 0 || unknown.Payload[0] != 0 { + t.Fatalf("unknown account was accepted: %#v", unknown) + } +} + +// ---------- BHTTP sharing the proxy and TLS ports ---------- + +// withSharedBHTTP starts a BHTTP instance that owns no port of its own and +// only serves connections handed over from the panel's listeners. +func withSharedBHTTP(t *testing.T) { + t.Helper() + if err := startBHTTPInstance(&BHTTPConfig{SharedPorts: true}); err != nil { + t.Fatalf("start shared BHTTP: %v", err) + } + t.Cleanup(stopBHTTP) + if !bhttpShareEnabled() { + t.Fatal("shared-port handoff did not come up") + } +} + +// serveProxyPort starts a listener that behaves like a public proxy port. +func serveProxyPort(t *testing.T) net.Addr { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + t.Cleanup(func() { _ = listener.Close() }) + go func() { + for { + conn, err := listener.Accept() + if err != nil { + return + } + go handleProxyConn(conn, getSSHConfig()) + } + }() + return listener.Addr() +} + +// bhttpProbeFrame builds the BHP1 capability probe a client opens with. +func bhttpProbeFrame(sid bhttp.SessionID) []byte { + clear := make([]byte, 10) + copy(clear[:4], "BHP1") + clear[4] = 1 + clear[5] = bhttp.ModeUpload + payload := bhttp.Crypt(clear, sid, bhttp.ModeProbe, 0, false) + frame := make([]byte, bhttp.HeaderSize+len(payload)) + frame[0] = bhttp.ModeProbe + copy(frame[1:17], sid[:]) + binary.BigEndian.PutUint32(frame[25:29], uint32(len(payload))) + copy(frame[bhttp.HeaderSize:], payload) + return frame +} + +// A BHTTP client on a port the HTTP+SSH proxy owns must be answered by BHTTP, +// and must never receive the proxy's unsolicited "HTTP/1.1 101" line. +func TestSharedProxyPortServesBHTTPClient(t *testing.T) { + withPanelUsers(t, &UserState{Cfg: UserConfig{Username: "tunnel", Password: "secret"}}) + withSharedBHTTP(t) + addr := serveProxyPort(t) + + conn, err := net.Dial("tcp", addr.String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(15 * time.Second)) + + var sid bhttp.SessionID + copy(sid[:], "shared-probe-s01") + if _, err := conn.Write(bhttpProbeFrame(sid)); err != nil { + t.Fatalf("write probe: %v", err) + } + + client := &bhttpTestClient{t: t, conn: conn, sid: sid} + status, body := client.readStatus() + if status != bhttp.StatusOK { + t.Fatalf("probe status = %d (%q), want StatusOK — the proxy answered instead of BHTTP", status, body) + } + decoded := bhttp.Crypt(body, sid, bhttp.ModeProbe, 0, true) + if len(decoded) < 4 || string(decoded[:4]) != "BHP1" { + t.Fatalf("probe response = %q, want a BHP1 reply", decoded) + } +} + +// The same shared port must still serve the HTTP-injection SSH flow exactly as +// before: the 101, the 200, and then the built-in SSH server's banner. +func TestSharedProxyPortStillServesInjectedSSH(t *testing.T) { + withPanelUsers(t, &UserState{Cfg: UserConfig{Username: "tunnel", Password: "secret"}}) + withSharedBHTTP(t) + addr := serveProxyPort(t) + + conn, err := net.Dial("tcp", addr.String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(20 * time.Second)) + + // An injection client sends its HTTP payload and SSH banner together. + if _, err := conn.Write([]byte("GET / HTTP/1.1\r\nHost: example.com\r\n\r\nSSH-2.0-TestClient\r\n")); err != nil { + t.Fatalf("write payload: %v", err) + } + + got := readUntil(t, conn, "SSH-2.0-") + if !strings.Contains(got, "HTTP/1.1 101") { + t.Fatalf("response %q is missing the 101 the injection flow expects", got) + } + if !strings.Contains(got, "HTTP/1.1 200") { + t.Fatalf("response %q is missing the 200 the injection flow expects", got) + } +} + +// A BHTTP client that hides behind an HTTP cover request on the shared port +// has to be picked up after the injection cleanup consumes that cover. +func TestSharedProxyPortServesBHTTPBehindHTTPCover(t *testing.T) { + withPanelUsers(t, &UserState{Cfg: UserConfig{Username: "tunnel", Password: "secret"}}) + withSharedBHTTP(t) + addr := serveProxyPort(t) + + conn, err := net.Dial("tcp", addr.String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(20 * time.Second)) + + var sid bhttp.SessionID + copy(sid[:], "shared-cover-s01") + payload := append([]byte("GET / HTTP/1.1\r\nHost: example.com\r\n\r\n"), bhttpProbeFrame(sid)...) + if _, err := conn.Write(payload); err != nil { + t.Fatalf("write payload: %v", err) + } + + // The proxy answers the cover request itself, so skip its HTTP lines and + // then read the BHTTP status frame that follows. + reader := bufio.NewReader(conn) + skipHTTPResponses(t, reader) + status, body := readStatusFrom(t, reader) + if status != bhttp.StatusOK { + t.Fatalf("probe status = %d (%q), want StatusOK", status, body) + } + decoded := bhttp.Crypt(body, sid, bhttp.ModeProbe, 0, true) + if len(decoded) < 4 || string(decoded[:4]) != "BHP1" { + t.Fatalf("probe response = %q, want a BHP1 reply", decoded) + } +} + +// With sharing off, the shared port must behave exactly as it did before this +// feature existed: a BHTTP frame gets the proxy's HTTP handling, not BHTTP. +func TestSharedProxyPortIgnoresBHTTPWhenSharingIsOff(t *testing.T) { + withPanelUsers(t, &UserState{Cfg: UserConfig{Username: "tunnel", Password: "secret"}}) + if bhttpShareEnabled() { + t.Fatal("shared-port handoff is unexpectedly active") + } + addr := serveProxyPort(t) + + conn, err := net.Dial("tcp", addr.String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(15 * time.Second)) + + // The proxy greets with 101 before reading anything, which is the behaviour + // a BHTTP client cannot tolerate and why sharing is a deliberate choice. + got := readUntil(t, conn, "HTTP/1.1 101") + if !strings.Contains(got, "HTTP/1.1 101") { + t.Fatalf("response %q, want the proxy's unsolicited 101", got) + } +} + +// readUntil reads until marker appears or the deadline fires. +func readUntil(t *testing.T, conn net.Conn, marker string) string { + t.Helper() + var seen []byte + buffer := make([]byte, 256) + for { + n, err := conn.Read(buffer) + if n > 0 { + seen = append(seen, buffer[:n]...) + if strings.Contains(string(seen), marker) { + return string(seen) + } + } + if err != nil { + t.Fatalf("read (looking for %q, got %q): %v", marker, seen, err) + } + } +} + +// skipHTTPResponses consumes the proxy's HTTP status lines and their blank +// separator lines, stopping at the first byte that is not part of one. +func skipHTTPResponses(t *testing.T, reader *bufio.Reader) { + t.Helper() + for { + peeked, err := reader.Peek(5) + if err != nil { + t.Fatalf("peek HTTP response: %v", err) + } + if string(peeked) != "HTTP/" { + return + } + for { + line, err := reader.ReadString('\n') + if err != nil { + t.Fatalf("read HTTP line: %v", err) + } + if strings.TrimRight(line, "\r\n") == "" { + break + } + } + } +} + +func readStatusFrom(t *testing.T, reader *bufio.Reader) (byte, []byte) { + t.Helper() + var header [5]byte + if _, err := io.ReadFull(reader, header[:]); err != nil { + t.Fatalf("read status header: %v", err) + } + body := make([]byte, binary.BigEndian.Uint32(header[1:5])) + if _, err := io.ReadFull(reader, body); err != nil { + t.Fatalf("read status body: %v", err) + } + return header[0], body +} + +// ---------- Panel policy on the BHTTP transport path ---------- + +// dialTunnelSSHClient completes a real SSH client handshake over the same +// in-process transport BHTTP hands its sessions to. +func dialTunnelSSHClient(t *testing.T, username, password string) (*ssh.Client, error) { + t.Helper() + conn, err := dialInternalSSH("bhttp") + if err != nil { + t.Fatalf("dialInternalSSH: %v", err) + } + clientConn, chans, reqs, err := ssh.NewClientConn(conn, "bhttp", &ssh.ClientConfig{ + User: username, + Auth: []ssh.AuthMethod{ssh.Password(password)}, + HostKeyCallback: ssh.InsecureIgnoreHostKey(), + Timeout: 10 * time.Second, + }) + if err != nil { + _ = conn.Close() + return nil, err + } + return ssh.NewClient(clientConn, chans, reqs), nil +} + +// A BHTTP session is an SSH connection on the built-in server, so every panel +// rule the SSH path enforces has to apply to it with no BHTTP-specific code: +// the account must exist and match, and the session must be counted against +// the account like any other. +func TestBHTTPTransportAppliesPanelAccountPolicy(t *testing.T) { + user := &UserState{Cfg: UserConfig{ + Username: "tunnel", Password: "secret", + MaxConnections: 1, LimitMbpsUp: 5, LimitMbpsDown: 10, + }} + expired := time.Now().Add(-time.Hour) + stale := &UserState{Cfg: UserConfig{Username: "stale", Password: "secret"}, ExpiresAt: &expired} + withPanelUsers(t, user, stale) + + // A wrong password must be refused by the same callback SSH uses. + if client, err := dialTunnelSSHClient(t, "tunnel", "wrong"); err == nil { + _ = client.Close() + t.Fatal("a wrong password was accepted over the BHTTP transport path") + } + // So must an expired account. + if client, err := dialTunnelSSHClient(t, "stale", "secret"); err == nil { + _ = client.Close() + t.Fatal("an expired account was accepted over the BHTTP transport path") + } + + client, err := dialTunnelSSHClient(t, "tunnel", "secret") + if err != nil { + t.Fatalf("valid account was refused: %v", err) + } + defer client.Close() + + // handleConn registers the session, which is what makes max_connections, + // the panel's active-user count and forced disconnects cover BHTTP. + deadline := time.Now().Add(5 * time.Second) + for { + user.mu.Lock() + active := len(user.conns) + user.mu.Unlock() + if active == 1 { + break + } + if time.Now().After(deadline) { + t.Fatalf("BHTTP session was not registered on the account (active = %d)", active) + } + time.Sleep(10 * time.Millisecond) + } + + // max_connections is 1, so a second session must be dropped. + second, err := dialTunnelSSHClient(t, "tunnel", "secret") + if err == nil { + // The cap is enforced after the handshake, so the connection is closed + // rather than refused: the first use of it fails. + _, _, sessErr := second.OpenChannel("session", nil) + _ = second.Close() + if sessErr == nil { + t.Fatal("a second session was usable past max_connections = 1") + } + } +} + +// The per-account bandwidth limits and data quota are applied by the +// direct-tcpip relay, which is the only data path a BHTTP session has. This +// pins the wiring that derives them, including the global default fallback. +func TestBHTTPTransportDerivesAccountLimits(t *testing.T) { + setDefaultLimits(7, 9) + t.Cleanup(func() { setDefaultLimits(0, 0) }) + + tests := []struct { + name string + cfg UserConfig + wantUp int + wantDown int + }{ + {name: "per-account limits win", cfg: UserConfig{LimitMbpsUp: 5, LimitMbpsDown: 10}, wantUp: 5, wantDown: 10}, + {name: "zero falls back to the default", cfg: UserConfig{}, wantUp: 7, wantDown: 9}, + {name: "one side falls back", cfg: UserConfig{LimitMbpsUp: 3}, wantUp: 3, wantDown: 9}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + up, down := tt.cfg.LimitMbpsUp, tt.cfg.LimitMbpsDown + if up == 0 || down == 0 { + defUp, defDown := getDefaultLimits() + if up == 0 { + up = defUp + } + if down == 0 { + down = defDown + } + } + if up != tt.wantUp || down != tt.wantDown { + t.Fatalf("limits = (%d, %d), want (%d, %d)", up, down, tt.wantUp, tt.wantDown) + } + }) + } +} + +// ---------- BTUN sharing the proxy and TLS ports ---------- + +// withSharedBTUN starts a BTUN instance that owns no port of its own and only +// serves connections handed over from the panel's listeners. +func withSharedBTUN(t *testing.T) { + t.Helper() + device := newLoopbackTUN() + server, err := btun.NewServer(btun.Config{ + Subnet: "10.77.0.0/24", + Authenticator: btunPanelAuthenticator{}, + Accountant: btunPanelAccountant{}, + Logger: testLogger(t), + }, device) + if err != nil { + t.Fatalf("new BTUN server: %v", err) + } + btunMu.Lock() + btunServer = server + btunDevice = device + btunSharedPorts = true + btunMu.Unlock() + t.Cleanup(func() { + btunMu.Lock() + btunServer = nil + btunDevice = nil + btunSharedPorts = false + btunMu.Unlock() + _ = server.Close() + server.Wait() + }) + if !btunShareEnabled() { + t.Fatal("shared-port handoff did not come up") + } +} + +// btunAuthenticate runs the BTUN handshake over conn and returns the server's +// authentication response. +func btunAuthenticate(t *testing.T, conn net.Conn, reader *bufio.Reader, credential string) btun.Packet { + t.Helper() + if _, err := conn.Write(btun.ClientHello); err != nil { + t.Fatalf("write client hello: %v", err) + } + hello := make([]byte, len(btun.ServerHello)) + if _, err := io.ReadFull(reader, hello); err != nil { + t.Fatalf("read server hello: %v", err) + } + if !bytes.Equal(hello, btun.ServerHello) { + t.Fatalf("server hello = %q, want %q", hello, btun.ServerHello) + } + frame, err := btun.MarshalPacket(btun.Packet{Type: btun.PacketAuth, Payload: []byte(credential)}, 0) + if err != nil { + t.Fatalf("marshal auth: %v", err) + } + if _, err := conn.Write(frame); err != nil { + t.Fatalf("write auth: %v", err) + } + packet, err := btun.ReadPacket(reader, 0) + if err != nil { + t.Fatalf("read auth response: %v", err) + } + return packet +} + +// A BTUN client on a port the HTTP+SSH proxy owns must reach BTUN and +// authenticate against the panel accounts. +func TestSharedProxyPortServesBTUNClient(t *testing.T) { + withPanelUsers(t, &UserState{Cfg: UserConfig{Username: "vpn", Password: "letmein"}}) + withSharedBTUN(t) + addr := serveProxyPort(t) + + conn, err := net.Dial("tcp", addr.String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(15 * time.Second)) + + response := btunAuthenticate(t, conn, bufio.NewReader(conn), "vpn:letmein") + if response.Type != btun.PacketAuthResponse || len(response.Payload) == 0 || response.Payload[0] != 1 { + t.Fatalf("valid panel credential was rejected on the shared port: %#v", response) + } +} + +// A BTUN client hiding behind an HTTP cover request must be picked up after the +// injection cleanup consumes that cover. +func TestSharedProxyPortServesBTUNBehindHTTPCover(t *testing.T) { + withPanelUsers(t, &UserState{Cfg: UserConfig{Username: "vpn", Password: "letmein"}}) + withSharedBTUN(t) + addr := serveProxyPort(t) + + conn, err := net.Dial("tcp", addr.String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(20 * time.Second)) + + // The cover and the hello go out together, which is what the protocol + // requires: a dedicated BTUN server answers nothing until it has read the + // hello, so a client cannot wait for a reply to the cover alone. + cover := append([]byte("GET / HTTP/1.1\r\nHost: example.com\r\n\r\n"), btun.ClientHello...) + if _, err := conn.Write(cover); err != nil { + t.Fatalf("write cover: %v", err) + } + + // On a shared port the client also has to skip the panel's own 101/200 + // injection reply before the server hello. That is the cost of sharing, and + // the reason the dedicated BTUN port stays available for clients that do + // not expect it. + reader := bufio.NewReader(conn) + skipHTTPResponses(t, reader) + hello := make([]byte, len(btun.ServerHello)) + if _, err := io.ReadFull(reader, hello); err != nil { + t.Fatalf("read server hello: %v", err) + } + if !bytes.Equal(hello, btun.ServerHello) { + t.Fatalf("server hello = %q, want %q", hello, btun.ServerHello) + } + + frame, err := btun.MarshalPacket(btun.Packet{Type: btun.PacketAuth, Payload: []byte("vpn:letmein")}, 0) + if err != nil { + t.Fatalf("marshal auth: %v", err) + } + if _, err := conn.Write(frame); err != nil { + t.Fatalf("write auth: %v", err) + } + response, err := btun.ReadPacket(reader, 0) + if err != nil { + t.Fatalf("read auth response: %v", err) + } + if response.Type != btun.PacketAuthResponse || len(response.Payload) == 0 || response.Payload[0] != 1 { + t.Fatalf("BTUN behind HTTP cover was rejected: %#v", response) + } +} + +// A wrong panel credential must be refused on the shared port exactly as on a +// dedicated one: sharing changes routing, never authentication. +func TestSharedProxyPortBTUNStillChecksPanelCredentials(t *testing.T) { + withPanelUsers(t, &UserState{Cfg: UserConfig{Username: "vpn", Password: "letmein"}}) + withSharedBTUN(t) + addr := serveProxyPort(t) + + conn, err := net.Dial("tcp", addr.String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(15 * time.Second)) + + response := btunAuthenticate(t, conn, bufio.NewReader(conn), "vpn:wrong") + if response.Type != btun.PacketAuthResponse || len(response.Payload) == 0 || response.Payload[0] != 0 { + t.Fatalf("invalid credential was accepted on the shared port: %#v", response) + } +} + +// The decisive test: all three protocols on one listener at the same time, +// each answered correctly, none disturbed by the others. +func TestSharedProxyPortServesAllThreeProtocols(t *testing.T) { + withPanelUsers(t, &UserState{Cfg: UserConfig{Username: "vpn", Password: "letmein"}}) + withSharedBHTTP(t) + withSharedBTUN(t) + addr := serveProxyPort(t) + + t.Run("BTUN", func(t *testing.T) { + conn, err := net.Dial("tcp", addr.String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(15 * time.Second)) + response := btunAuthenticate(t, conn, bufio.NewReader(conn), "vpn:letmein") + if response.Type != btun.PacketAuthResponse || len(response.Payload) == 0 || response.Payload[0] != 1 { + t.Fatalf("BTUN was not served: %#v", response) + } + }) + + t.Run("BHTTP", func(t *testing.T) { + conn, err := net.Dial("tcp", addr.String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(15 * time.Second)) + var sid bhttp.SessionID + copy(sid[:], "all-three-sid-01") + if _, err := conn.Write(bhttpProbeFrame(sid)); err != nil { + t.Fatalf("write probe: %v", err) + } + client := &bhttpTestClient{t: t, conn: conn, sid: sid} + status, body := client.readStatus() + if status != bhttp.StatusOK { + t.Fatalf("BHTTP was not served: status %d (%q)", status, body) + } + }) + + t.Run("injected SSH", func(t *testing.T) { + conn, err := net.Dial("tcp", addr.String()) + if err != nil { + t.Fatalf("dial: %v", err) + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(20 * time.Second)) + if _, err := conn.Write([]byte("GET / HTTP/1.1\r\nHost: x\r\n\r\nSSH-2.0-TestClient\r\n")); err != nil { + t.Fatalf("write payload: %v", err) + } + got := readUntil(t, conn, "SSH-2.0-") + if !strings.Contains(got, "HTTP/1.1 200") { + t.Fatalf("injected SSH lost its 200: %q", got) + } + }) +} + +// ---------- UDP over the tunnel transports ---------- + +// The SSH-carrying transports move TCP. UDP reaches the internet through the +// panel's built-in custom BadVPN gateway, which a client reaches by opening a +// direct-tcpip channel to it over the same tunnel. This proves that whole path: +// BHTTP transport -> built-in SSH server -> direct-tcpip -> UDPGW -> UDP peer. +func TestUDPGWIsReachableOverTheTunnelTransport(t *testing.T) { + withPanelUsers(t, &UserState{Cfg: UserConfig{Username: "tunnel", Password: "secret"}}) + + // A UDP peer that echoes back what it receives, standing in for a DNS or + // game server the client wants to reach. + echo, err := net.ListenPacket("udp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen UDP echo: %v", err) + } + defer echo.Close() + go func() { + buffer := make([]byte, 2048) + for { + n, from, err := echo.ReadFrom(buffer) + if err != nil { + return + } + _, _ = echo.WriteTo(buffer[:n], from) + } + }() + echoAddr := echo.LocalAddr().(*net.UDPAddr) + + // The gateway itself, bound to loopback for the test. + if err := startUDPGW(&UDPGWConfig{Listen: "127.0.0.1:0"}); err != nil { + t.Fatalf("start UDPGW: %v", err) + } + t.Cleanup(stopUDPGW) + udpgwMu.Lock() + gatewayAddr := "" + if udpgwLn != nil { + gatewayAddr = udpgwLn.Addr().String() + } + udpgwMu.Unlock() + if gatewayAddr == "" { + t.Fatal("UDPGW did not bind a listener") + } + + // Connect the way a BHTTP client does, then tunnel to the gateway. + client, err := dialTunnelSSHClient(t, "tunnel", "secret") + if err != nil { + t.Fatalf("tunnel SSH login: %v", err) + } + defer client.Close() + + gateway, err := client.Dial("tcp", gatewayAddr) + if err != nil { + t.Fatalf("direct-tcpip to the UDP gateway: %v", err) + } + defer gateway.Close() + _ = gateway.SetDeadline(time.Now().Add(15 * time.Second)) + + payload := []byte("udp-over-tunnel") + if _, err := gateway.Write(udpgwFrame(1, echoAddr, payload)); err != nil { + t.Fatalf("write udpgw frame: %v", err) + } + + connID, from, echoed := readUDPGWFrame(t, gateway) + if connID != 1 { + t.Fatalf("reply connID = %d, want 1", connID) + } + if from != uint16(echoAddr.Port) { + t.Fatalf("reply port = %d, want %d", from, echoAddr.Port) + } + if string(echoed) != string(payload) { + t.Fatalf("echoed %q, want %q", echoed, payload) + } +} + +// udpgwFrame builds one client->server frame in the panel's custom BadVPN +// framing: len(2, little endian) | connID(2) | x(1) | IPv4(4) | port(2) | data. +func udpgwFrame(connID uint16, dst *net.UDPAddr, data []byte) []byte { + body := make([]byte, 9+len(data)) + binary.BigEndian.PutUint16(body[0:2], connID) + body[2] = 0 + copy(body[3:7], dst.IP.To4()) + binary.BigEndian.PutUint16(body[7:9], uint16(dst.Port)) + copy(body[9:], data) + + out := make([]byte, 2+len(body)) + binary.LittleEndian.PutUint16(out[0:2], uint16(len(body))) + copy(out[2:], body) + return out +} + +// readUDPGWFrame reads one server->client frame and returns its connID, source +// port and payload. +func readUDPGWFrame(t *testing.T, conn net.Conn) (uint16, uint16, []byte) { + t.Helper() + var header [2]byte + if _, err := io.ReadFull(conn, header[:]); err != nil { + t.Fatalf("read udpgw length: %v", err) + } + body := make([]byte, binary.LittleEndian.Uint16(header[:])) + if _, err := io.ReadFull(conn, body); err != nil { + t.Fatalf("read udpgw body: %v", err) + } + if len(body) < 9 { + t.Fatalf("udpgw reply is %d bytes, want at least 9", len(body)) + } + return binary.BigEndian.Uint16(body[0:2]), binary.BigEndian.Uint16(body[7:9]), body[9:] +} diff --git a/bhttp_integration.go b/bhttp_integration.go new file mode 100644 index 0000000..d58b195 --- /dev/null +++ b/bhttp_integration.go @@ -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 +} diff --git a/btun_integration.go b/btun_integration.go new file mode 100644 index 0000000..2cd761d --- /dev/null +++ b/btun_integration.go @@ -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 +} diff --git a/btun_tun_linux_test.go b/btun_tun_linux_test.go new file mode 100644 index 0000000..3d84e4a --- /dev/null +++ b/btun_tun_linux_test.go @@ -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)) +} diff --git a/check_api.go b/check_api.go index cd5b868..6881539 100644 --- a/check_api.go +++ b/check_api.go @@ -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 diff --git a/config_safety.go b/config_safety.go index de038fc..7dc130c 100644 --- a/config_safety.go +++ b/config_safety.go @@ -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 diff --git a/hotreload.go b/hotreload.go index 89693af..d9ed9b1 100644 --- a/hotreload.go +++ b/hotreload.go @@ -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() diff --git a/internal/bhttp/protocol.go b/internal/bhttp/protocol.go new file mode 100644 index 0000000..b598b33 --- /dev/null +++ b/internal/bhttp/protocol.go @@ -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 +} diff --git a/internal/bhttp/protocol_test.go b/internal/bhttp/protocol_test.go new file mode 100644 index 0000000..e6dff27 --- /dev/null +++ b/internal/bhttp/protocol_test.go @@ -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) + } +} diff --git a/internal/bhttp/server.go b/internal/bhttp/server.go new file mode 100644 index 0000000..ec4b945 --- /dev/null +++ b/internal/bhttp/server.go @@ -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() +} diff --git a/internal/bhttp/session.go b/internal/bhttp/session.go new file mode 100644 index 0000000..ea7a180 --- /dev/null +++ b/internal/bhttp/session.go @@ -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() + } +} diff --git a/internal/bhttp/sniff.go b/internal/bhttp/sniff.go new file mode 100644 index 0000000..e3f166c --- /dev/null +++ b/internal/bhttp/sniff.go @@ -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 +} diff --git a/internal/bhttp/sniff_test.go b/internal/bhttp/sniff_test.go new file mode 100644 index 0000000..0bd4929 --- /dev/null +++ b/internal/bhttp/sniff_test.go @@ -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) + } +} diff --git a/internal/bhttp/v2_test.go b/internal/bhttp/v2_test.go new file mode 100644 index 0000000..26de852 --- /dev/null +++ b/internal/bhttp/v2_test.go @@ -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") + } +} diff --git a/internal/btun/auth.go b/internal/btun/auth.go new file mode 100644 index 0000000..0dca272 --- /dev/null +++ b/internal/btun/auth.go @@ -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() {} diff --git a/internal/btun/pool.go b/internal/btun/pool.go new file mode 100644 index 0000000..f9eba10 --- /dev/null +++ b/internal/btun/pool.go @@ -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() +} diff --git a/internal/btun/protocol.go b/internal/btun/protocol.go new file mode 100644 index 0000000..dc9e71a --- /dev/null +++ b/internal/btun/protocol.go @@ -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 +} diff --git a/internal/btun/protocol_test.go b/internal/btun/protocol_test.go new file mode 100644 index 0000000..cd34717 --- /dev/null +++ b/internal/btun/protocol_test.go @@ -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) + } +} diff --git a/internal/btun/server.go b/internal/btun/server.go new file mode 100644 index 0000000..0efe197 --- /dev/null +++ b/internal/btun/server.go @@ -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") +} diff --git a/internal/btun/server_test.go b/internal/btun/server_test.go new file mode 100644 index 0000000..93d9e74 --- /dev/null +++ b/internal/btun/server_test.go @@ -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 +} diff --git a/internal/btun/sniff.go b/internal/btun/sniff.go new file mode 100644 index 0000000..2435082 --- /dev/null +++ b/internal/btun/sniff.go @@ -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 +} diff --git a/internal/btun/sniff_test.go b/internal/btun/sniff_test.go new file mode 100644 index 0000000..63a7d27 --- /dev/null +++ b/internal/btun/sniff_test.go @@ -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) + } +} diff --git a/internal/btun/tun_linux.go b/internal/btun/tun_linux.go new file mode 100644 index 0000000..da8e4b4 --- /dev/null +++ b/internal/btun/tun_linux.go @@ -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 } diff --git a/internal/btun/tun_stub.go b/internal/btun/tun_stub.go new file mode 100644 index 0000000..e50f257 --- /dev/null +++ b/internal/btun/tun_stub.go @@ -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") +} diff --git a/main.go b/main.go index 0b23596..4b4b4e0 100644 --- a/main.go +++ b/main.go @@ -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) { diff --git a/server_config_api.go b/server_config_api.go index bed5691..788e041 100644 --- a/server_config_api.go +++ b/server_config_api.go @@ -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() diff --git a/tunnel_pipe.go b/tunnel_pipe.go new file mode 100644 index 0000000..6ca1bbe --- /dev/null +++ b/tunnel_pipe.go @@ -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 +} diff --git a/tunnel_share.go b/tunnel_share.go new file mode 100644 index 0000000..1bf062d --- /dev/null +++ b/tunnel_share.go @@ -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 +}