From 2b5a8c445233024b2de3f51dea6996f3d464d029 Mon Sep 17 00:00:00 2001 From: penguinehis Date: Sun, 13 Sep 2026 22:31:36 -0300 Subject: [PATCH] HCR SUPPORT --- README.md | 43 + admin/assets/js/08-server-config.js | 108 +++ admin/index.html | 97 ++- bhttp_btun_integration_test.go | 209 +++++ config_safety.go | 61 ++ hcr_integration.go | 437 ++++++++++ hotreload.go | 13 + internal/hcr/server.go | 1182 +++++++++++++++++++++++++++ internal/hcr/sniff.go | 84 ++ internal/hcr/sniff_test.go | 83 ++ main.go | 38 + server_config_api.go | 4 + tunnel_share.go | 39 +- 13 files changed, 2393 insertions(+), 5 deletions(-) create mode 100644 hcr_integration.go create mode 100644 internal/hcr/server.go create mode 100644 internal/hcr/sniff.go create mode 100644 internal/hcr/sniff_test.go diff --git a/README.md b/README.md index af723b0..3aabdf6 100644 --- a/README.md +++ b/README.md @@ -154,6 +154,7 @@ O instalador monta `/opt/sshpanel/logs` como tmpfs de 15 MiB quando possível, p 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 +8181 HCR (HTTP/Custom Relay) — 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 @@ -376,6 +377,23 @@ docker run --rm --cap-add NET_ADMIN --device /dev/net/tun -v "$PWD:/src" -v dr 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. +### HCR (HTTP/Custom Relay) + +O HCR é um túnel de requisição/resposta do ecossistema UDP-Custom: o cliente envia quadros com cabeçalho fixo de 62 bytes (connect, data, poll, ack, close, ping) e o servidor relaciona o fluxo a um alvo. Como o BHTTP, cada sessão HCR é entregue ao **servidor SSH interno do painel**, então as contas, validade, TOTP, `max_connections`, limites de banda e cotas de dados valem sem configuração extra — sem `sshd`, PAM ou `/etc/shadow`. + +O ponto central: o HCR foi feito para **coexistir com o BHTTP na mesma porta**. Os dois se sobrepõem no primeiro byte (opcodes 1..4 significam upload/download nos dois), mas o HCR tem cabeçalho de 62 bytes e byte de versão fixo `0x01` em `[1]`, enquanto o BHTTP tem cabeçalho de 29 bytes cujo byte `[1]` é aleatório. O classificador confere o cabeçalho completo do HCR **antes** do BHTTP; um quadro BHTTP limpo é rejeitado em dois bytes, sem espera. Assim SSH, injeção HTTP, BHTTP e HCR ficam todos ligados na mesma porta ao mesmo tempo. + +Configure em **Configurações → HCR**: + +- **Compartilhar as portas do painel** — aceita HCR em 80/8080 e 443 junto com BHTTP e o resto. Com isso ligado, o campo Listen pode ficar vazio. +- **Listen** — porta dedicada opcional; sem compartilhamento o padrão é `0.0.0.0:8181`. +- **Max Sessions / Max Connections / Max Sessions Per IP** — tetos; `0` usa o padrão e `-1` (nas duas primeiras) remove o limite. +- **Max Download Frame** — maior registro lido do alvo por quadro (padrão 16384). +- **Download Poll Timeout / Idle Session Timeout** — tempo de um long-poll sem dados e tempo ocioso antes de reciclar a sessão. +- **Auto Restart Interval / Restart Grace Delay** — restart forte só dos listeners HCR. + +O card **Status HCR** mostra sessões e sockets ativos, bytes trafegados, sessões criadas/rejeitadas e erros de protocolo. + ### Comandos úteis Ver status do serviço: @@ -816,6 +834,7 @@ Admin token 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 +8181 HCR (HTTP/Custom Relay) — disabled by default; can share 80/8080/443 7300/udp BTUN UDP — disabled by default 9090 Web panel + public /check API 10086 Xray VLESS @@ -1038,6 +1057,23 @@ docker run --rm --cap-add NET_ADMIN --device /dev/net/tun -v "$PWD:/src" -v dr 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. +### HCR (HTTP/Custom Relay) + +HCR is a request/response tunnel from the UDP-Custom ecosystem: the client sends 62-byte-header frames (connect, data, poll, ack, close, ping) and the server relays the stream to a target. Like BHTTP, every HCR session is handed to the panel's **own built-in SSH server**, so the panel's accounts, expiry, TOTP, `max_connections`, bandwidth limits and data quotas all apply with no extra setup — no system `sshd`, PAM or `/etc/shadow`. + +The key point: HCR is built to **coexist with BHTTP on the same port**. The two overlap on the first byte (opcodes 1..4 mean upload/download in both), but HCR has a 62-byte header with a fixed version byte `0x01` at `[1]`, while a BHTTP frame has a 29-byte header whose byte `[1]` is random. The classifier checks HCR's full header **before** BHTTP; a clean BHTTP frame is rejected at two bytes with no wait. So SSH, HTTP injection, BHTTP and HCR are all live on the same port at once. + +Configure it under **Settings → HCR**: + +- **Share the panel's ports** — accepts HCR on 80/8080 and 443 alongside BHTTP and the rest. With it on, the Listen field may be empty. +- **Listen** — an optional dedicated port; without sharing the default is `0.0.0.0:8181`. +- **Max Sessions / Max Connections / Max Sessions Per IP** — ceilings; `0` uses the default and `-1` (on the first two) disables the cap. +- **Max Download Frame** — the largest record read from the target per frame (default 16384). +- **Download Poll Timeout / Idle Session Timeout** — how long a long-poll waits with no data, and how long a session may sit idle before it is reaped. +- **Auto Restart Interval / Restart Grace Delay** — a hard restart of the HCR listeners only. + +The **Status HCR** card shows active sessions and sockets, bytes moved, sessions created/rejected and protocol errors. + ### Useful commands Check service status: @@ -1470,6 +1506,13 @@ Creates or updates (upsert) an SSH user. #### `GET /api/btun/logs` — superadmin - `200`: array of log line strings (empty array if uninitialized). Does not proxy to managed servers. +#### `GET /api/hcr` — superadmin +- Optional query: `server_id`. +- `200`: HCR 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`, `sessionsCreated`, `sessionsRejected`, `uploadBytes`, `downloadBytes`, `protocolErrors`. + +#### `GET /api/hcr/logs` — superadmin +- `200`: array of log line strings (empty array if uninitialized). Does not proxy to managed servers. + --- ### Resellers (superadmin only) diff --git a/admin/assets/js/08-server-config.js b/admin/assets/js/08-server-config.js index 0338b90..ad5613f 100644 --- a/admin/assets/js/08-server-config.js +++ b/admin/assets/js/08-server-config.js @@ -159,8 +159,10 @@ async function loadServerConfig() { // BHTTP + BTUN writeBhttpConfig(c); writeBtunConfig(c); + writeHcrConfig(c); loadBhttpHealth(); loadBtunHealth(); + loadHcrHealth(); // TLS forwarders tlsForwardersState = c.tls_forwarders || []; @@ -241,6 +243,7 @@ async function saveServerConfig() { } : null, bhttp: readBhttpConfig(), btun: readBtunConfig(), + hcr: readHcrConfig(), tls_forwarders: tlsArr, xray: { enabled: document.getElementById("cfgXrayEnabled").checked, @@ -270,6 +273,7 @@ async function saveServerConfig() { } loadBhttpHealth(); loadBtunHealth(); + loadHcrHealth(); } catch (e) { if (e.message === "auth") doAuthError(); else st.textContent = "Error: " + e.message; @@ -1011,3 +1015,107 @@ window.loadBhttpHealth = loadBhttpHealth; window.loadBhttpLogs = loadBhttpLogs; window.loadBtunHealth = loadBtunHealth; window.loadBtunLogs = loadBtunLogs; + + +function toggleHcrFields(on) { + const el = document.getElementById("hcrFields"); + if (!el) return; + el.style.opacity = on ? "1" : ".4"; + el.style.pointerEvents = on ? "" : "none"; +} + +function writeHcrConfig(c) { + const has = !!c.hcr; + fieldCheck("cfgHcrEnabled", has); + toggleHcrFields(has); + const h = c.hcr || {}; + // Sharing the panel's ports (alongside BHTTP) is the least-friction setup, so + // a config that never had an hcr block starts with it on. + fieldCheck("cfgHcrSharedPorts", has ? !!h.shared_ports : true); + fieldSet("cfgHcrListen", (h.listen || []).join("\n")); + fieldSet("cfgHcrMaxSessions", h.max_sessions || 0); + fieldSet("cfgHcrMaxConnections", h.max_connections || 0); + fieldSet("cfgHcrMaxSource", h.max_source_sessions || 0); + fieldSet("cfgHcrMaxFrame", h.max_download_frame || 0); + fieldSet("cfgHcrPollTimeout", h.download_poll_timeout || ""); + fieldSet("cfgHcrIdleTimeout", h.idle_session_timeout || ""); + fieldSet("cfgHcrAutoRestart", h.auto_restart_interval || ""); + fieldSet("cfgHcrRestartGrace", h.auto_restart_grace || ""); + fieldCheck("cfgHcrNoConsole", !!h.disable_console_log); + fieldCheck("cfgHcrLogConnections", !!h.log_connections); +} + +function readHcrConfig() { + if (!fieldBool("cfgHcrEnabled")) return null; + const listen = readListenLines("cfgHcrListen"); + const shared = fieldBool("cfgHcrSharedPorts"); + return { + // With shared ports on, a dedicated listener is optional. + listen: listen.length ? listen : (shared ? [] : ["0.0.0.0:8181"]), + shared_ports: shared, + max_sessions: fieldInt("cfgHcrMaxSessions"), + max_connections: fieldInt("cfgHcrMaxConnections"), + max_source_sessions: fieldInt("cfgHcrMaxSource"), + max_download_frame: fieldInt("cfgHcrMaxFrame"), + download_poll_timeout: fieldText("cfgHcrPollTimeout"), + idle_session_timeout: fieldText("cfgHcrIdleTimeout"), + auto_restart_interval: fieldText("cfgHcrAutoRestart"), + auto_restart_grace: fieldText("cfgHcrRestartGrace"), + disable_console_log: fieldBool("cfgHcrNoConsole"), + log_connections: fieldBool("cfgHcrLogConnections"), + }; +} + +async function loadHcrHealth() { + const summary = document.getElementById("hcrStatusSummary"); + if (!summary) return; + try { + const res = await api("/api/hcr"); + if (!res.ok) throw new Error(await res.text()); + const d = await res.json(); + setServiceChip("hcrStatusChip", d); + document.getElementById("hcrActiveSessions").textContent = fmtInt(d.activeSessions); + document.getElementById("hcrActiveConns").textContent = fmtInt(d.activeConnections); + document.getElementById("hcrUploadBytes").textContent = fmtBytes(d.uploadBytes || 0); + document.getElementById("hcrDownloadBytes").textContent = fmtBytes(d.downloadBytes || 0); + renderCounterRows("hcrHealthBody", [ + ["Sockets accepted", d.accepted], + ["Sockets rejected", d.connectionsRejected], + ["Sessions created", d.sessionsCreated], + ["Sessions rejected", d.sessionsRejected], + ["Protocol errors", d.protocolErrors], + ]); + if (d.enabled === false) { + summary.textContent = "HCR está desativado na configuração."; + } else if (!d.running) { + summary.textContent = "HCR 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.protocolErrors || 0); + summary.textContent = bad > 0 + ? `Rodando em ${d.listen || "?"} — atenção: ${fmtInt(bad)} rejeições/erros acumulados.` + : `Rodando em ${d.listen || "?"} — sem rejeições nem erros.`; + } + } catch (e) { + if (e.message === "auth") doAuthError(); + else summary.textContent = "Erro ao carregar status: " + e.message; + } +} + +async function loadHcrLogs() { + const box = document.getElementById("hcrLogs"); + if (!box) return; + box.textContent = "Carregando…"; + try { + const res = await api("/api/hcr/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; + } +} + +window.toggleHcrFields = toggleHcrFields; +window.loadHcrHealth = loadHcrHealth; +window.loadHcrLogs = loadHcrLogs; diff --git a/admin/index.html b/admin/index.html index b146955..6c98822 100644 --- a/admin/index.html +++ b/admin/index.html @@ -1231,17 +1231,18 @@
System studio

Configurações

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

-
@@ -1667,8 +1668,98 @@ +
+
06 · HCR

HCR (HTTP/Custom Relay)

Túnel de requisição/resposta do UDP-Custom. Cada sessão vai ao servidor SSH interno do painel e pode dividir as mesmas portas do BHTTP.

+
+
+
HCR Transport
+ live + +
+
+ +
+ Os listeners existentes distinguem HCR de BHTTP pelo cabeçalho de 62 bytes e pelo byte de versão 0x01, então SSH, injeção HTTP e BHTTP na mesma porta continuam funcionando. Com o compartilhamento ligado o campo Listen pode ficar vazio. +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
Cada sessão HCR conta como uma conexão SSH da conta: valem o limite de conexões, a banda e a cota de dados do usuário.
+ + +
+
+ +
+
+
Status HCR
+ — + +
+
+
Active Sessions
--
+
Active Sockets
--
+
Upload
--
+
Download
--
+
+
+ + + +
CounterValueCounterValue
+
+
Salve a configuração para iniciar o transporte.Rejeições e erros de protocolo devem normalmente ficar em 0.
+
+
Logs HCR
+ +
+
—
+
+
+
-
06 · Segurança

Encaminhadores TLS

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

+
07 · 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 index 3b405cb..aa20864 100644 --- a/bhttp_btun_integration_test.go +++ b/bhttp_btun_integration_test.go @@ -3,8 +3,10 @@ package main import ( "bufio" "bytes" + "context" "crypto/rand" "crypto/rsa" + "crypto/sha256" "encoding/binary" "io" "log" @@ -19,6 +21,7 @@ import ( "shell2/internal/bhttp" "shell2/internal/btun" + "shell2/internal/hcr" ) // ---------- Test scaffolding ---------- @@ -1367,3 +1370,209 @@ func readUDPGWFrame(t *testing.T, conn net.Conn) (uint16, uint16, []byte) { } return binary.BigEndian.Uint16(body[0:2]), binary.BigEndian.Uint16(body[7:9]), body[9:] } + +// ---------- HCR sharing the proxy and TLS ports ---------- + +// withSharedHCR starts an HCR instance owning no port of its own; it only +// serves connections handed over from the panel's listeners. +func withSharedHCR(t *testing.T) { + t.Helper() + server := hcr.NewServer(&hcr.Config{ + DialTarget: func() (net.Conn, error) { return dialInternalSSH("hcr") }, + Logger: nil, + MaxSessions: 100, + }) + ctx, cancel := context.WithCancel(context.Background()) + hcrMu.Lock() + hcrServer = server + hcrCtx = ctx + hcrCancel = cancel + hcrSharedPorts = true + hcrMu.Unlock() + t.Cleanup(func() { + hcrMu.Lock() + hcrServer = nil + hcrCtx = nil + hcrCancel = nil + hcrSharedPorts = false + hcrMu.Unlock() + cancel() + server.Close() + server.Wait() + }) + if !hcrShareEnabled() { + t.Fatal("shared-port handoff did not come up") + } +} + +// hcrMaskPayload mirrors the engine's payload cipher so the test can encode +// requests and decode responses. It is the same SHA-256 keystream XOR. +func sha256Sum(b []byte) [32]byte { return sha256.Sum256(b) } + +func hcrMaskPayload(payload []byte, sid [16]byte, code uint8, seq uint64, direction uint8) { + if len(payload) == 0 { + return + } + var seed [30]byte + copy(seed[0:16], sid[:]) + seed[16] = code + binary.BigEndian.PutUint64(seed[17:25], seq) + seed[25] = direction + for offset := 0; offset < len(payload); offset += 32 { + binary.BigEndian.PutUint32(seed[26:30], uint32(offset/32)) + block := sha256Sum(seed[:]) + for i := 0; i < 32 && offset+i < len(payload); i++ { + payload[offset+i] ^= block[i] + } + } +} + +// hcrConnectFrame builds a 62-byte Connect request. +func hcrConnectFrame(sid [16]byte) []byte { + b := make([]byte, hcr.RequestHeaderSize) + b[0] = 1 // ReqConnect + b[1] = 1 // ProtoVersion + copy(b[2:18], sid[:]) + return b +} + +// hcrPollFrame builds a Poll request for up to maxChunks records at seq. +func hcrPollFrame(sid [16]byte, seq uint64, maxChunks uint16) []byte { + payload := make([]byte, 2) + binary.BigEndian.PutUint16(payload, maxChunks) + hcrMaskPayload(payload, sid, 3, seq, 0) // ReqPoll, DirRequest + b := make([]byte, hcr.RequestHeaderSize+len(payload)) + b[0] = 3 // ReqPoll + b[1] = 1 + copy(b[2:18], sid[:]) + binary.BigEndian.PutUint64(b[50:58], seq) + binary.BigEndian.PutUint32(b[58:62], uint32(len(payload))) + copy(b[hcr.RequestHeaderSize:], payload) + return b +} + +// hcrReadResponse reads a 14-byte response header plus its payload. +func hcrReadResponse(t *testing.T, r *bufio.Reader) (status byte, seq uint64, payload []byte) { + t.Helper() + var hdr [14]byte + if _, err := io.ReadFull(r, hdr[:]); err != nil { + t.Fatalf("read HCR response header: %v", err) + } + status = hdr[0] + seq = binary.BigEndian.Uint64(hdr[2:10]) + n := binary.BigEndian.Uint32(hdr[10:14]) + if n > 0 { + payload = make([]byte, n) + if _, err := io.ReadFull(r, payload); err != nil { + t.Fatalf("read HCR response payload: %v", err) + } + } + return status, seq, payload +} + +// An HCR client on a port the HTTP+SSH proxy owns must reach the built-in SSH +// server: Connect succeeds, then a Poll returns the SSH banner. +func TestSharedProxyPortServesHCRClient(t *testing.T) { + withPanelUsers(t, &UserState{Cfg: UserConfig{Username: "tunnel", Password: "secret"}}) + withSharedHCR(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)) + reader := bufio.NewReader(conn) + + var sid [16]byte + copy(sid[:], "hcr-shared-sid01") + + if _, err := conn.Write(hcrConnectFrame(sid)); err != nil { + t.Fatalf("write connect: %v", err) + } + status, _, _ := hcrReadResponse(t, reader) + if status != 0 { // StatusOk + t.Fatalf("connect status = %d, want StatusOk — the proxy answered instead of HCR", status) + } + + // Poll for the SSH banner the target sends first. + if _, err := conn.Write(hcrPollFrame(sid, 0, 4)); err != nil { + t.Fatalf("write poll: %v", err) + } + status, seq, payload := hcrReadResponse(t, reader) + if status != 1 { // StatusPollData + t.Fatalf("poll status = %d, want StatusPollData(1)", status) + } + hcrMaskPayload(payload, sid, 3, seq, 1) // ReqPoll, DirResponse + if len(payload) < 4 { + t.Fatalf("poll payload too short: %d bytes", len(payload)) + } + chunkLen := binary.BigEndian.Uint32(payload[:4]) + banner := payload[4 : 4+chunkLen] + if !strings.HasPrefix(string(banner), "SSH-2.0-") { + t.Fatalf("first HCR download = %q, want the built-in SSH identification", banner) + } +} + +// The decisive coexistence test: HCR, BHTTP, BTUN and injected SSH all served +// on one listener at once, each answered correctly. +func TestSharedProxyPortServesHCRAlongsideBHTTP(t *testing.T) { + withPanelUsers(t, + &UserState{Cfg: UserConfig{Username: "tunnel", Password: "secret"}}, + &UserState{Cfg: UserConfig{Username: "vpn", Password: "letmein"}}, + ) + withSharedHCR(t) + withSharedBHTTP(t) + withSharedBTUN(t) + addr := serveProxyPort(t) + + t.Run("HCR", 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)) + reader := bufio.NewReader(conn) + var sid [16]byte + copy(sid[:], "coexist-hcr-sid1") + if _, err := conn.Write(hcrConnectFrame(sid)); err != nil { + t.Fatalf("write connect: %v", err) + } + if status, _, _ := hcrReadResponse(t, reader); status != 0 { + t.Fatalf("HCR was not served: connect status %d", status) + } + }) + + 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[:], "coexist-bhttp-s1") + if _, err := conn.Write(bhttpProbeFrame(sid)); err != nil { + t.Fatalf("write probe: %v", err) + } + client := &bhttpTestClient{t: t, conn: conn, sid: sid} + if status, body := client.readStatus(); status != bhttp.StatusOK { + t.Fatalf("BHTTP was not served: status %d (%q)", status, body) + } + }) + + 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) + } + }) +} diff --git a/config_safety.go b/config_safety.go index 7dc130c..cfa9a80 100644 --- a/config_safety.go +++ b/config_safety.go @@ -403,9 +403,70 @@ func normalizeRuntimePorts(cfg *Config) []string { normalizeAutoRestartFields(&cfg.BTUN.AutoRestartInterval, &cfg.BTUN.AutoRestartGrace, "BTUN", warn) } + if cfg.HCR != nil { + addrs := normalizeHCRListenList(cfg.HCR.Listen) + if len(addrs) == 0 && !cfg.HCR.SharedPorts { + addrs = []string{defaultHCRListen} + warn("HCR has no listen address and shared ports are off; using default %s", defaultHCRListen) + } + kept := make([]string, 0, len(addrs)) + for _, addr := range addrs { + if err := tcpAddrAvailableForHCR(addr); err != nil { + warn("HCR listener %s is unavailable (%v)", addr, err) + continue + } + kept = append(kept, addr) + } + if len(addrs) > 0 && len(kept) == 0 { + warn("no HCR listener could be opened; keeping the configured addresses so the panel reports the failure") + kept = addrs + } + cfg.HCR.Listen = kept + + normalizeDurationField(&cfg.HCR.DownloadPollTimeout, "HCR download_poll_timeout", time.Second, time.Minute, warn) + normalizeDurationField(&cfg.HCR.IdleSessionTimeout, "HCR idle_session_timeout", 10*time.Second, time.Hour, warn) + if cfg.HCR.MaxSessions < -1 { + warn("HCR max_sessions %d is invalid; using unlimited (-1)", cfg.HCR.MaxSessions) + cfg.HCR.MaxSessions = -1 + } + if cfg.HCR.MaxConnections < -1 { + warn("HCR max_connections %d is invalid; using unlimited (-1)", cfg.HCR.MaxConnections) + cfg.HCR.MaxConnections = -1 + } + if cfg.HCR.MaxSourceSessions < 0 { + warn("HCR max_source_sessions %d is invalid; using 0 (unlimited)", cfg.HCR.MaxSourceSessions) + cfg.HCR.MaxSourceSessions = 0 + } + if cfg.HCR.MaxDownloadFrame < 0 { + warn("HCR max_download_frame %d is invalid; using the default", cfg.HCR.MaxDownloadFrame) + cfg.HCR.MaxDownloadFrame = 0 + } + normalizeAutoRestartFields(&cfg.HCR.AutoRestartInterval, &cfg.HCR.AutoRestartGrace, "HCR", warn) + } + return warnings } +// tcpAddrAvailableForHCR reports whether an HCR listen address can be bound. An +// address this process already serves for HCR is treated as available. +func tcpAddrAvailableForHCR(addr string) error { + if addr == "" { + return nil + } + if hcrRunning() { + for _, current := range strings.Split(hcrListenList(), ", ") { + if strings.TrimSpace(current) == addr { + return nil + } + } + } + ln, err := net.Listen("tcp", addr) + if err != nil { + return err + } + return ln.Close() +} + // 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. diff --git a/hcr_integration.go b/hcr_integration.go new file mode 100644 index 0000000..0fdf5e5 --- /dev/null +++ b/hcr_integration.go @@ -0,0 +1,437 @@ +package main + +// This file embeds the HCR (HTTP/Custom Relay) transport into the panel. HCR is +// a request/response tunnel: the client sends 62-byte-header frames (connect, +// data, poll, ack, close, ping) and the server relays the stream to a target. +// +// Exactly like BHTTP, every HCR session is handed to this process's own SSH +// server through dialInternalSSH, so panel accounts, expiry, TOTP, per-user +// bandwidth limits, data quotas and connection counters all apply. There is no +// dependency on the system sshd, PAM or /etc/shadow. +// +// HCR is built to coexist with BHTTP on the same ports: see tunnel_share.go for +// how a shared listener tells an HCR frame (62-byte header, version byte 0x01) +// apart from a BHTTP frame (29-byte header) and from SSH/HTTP. + +import ( + "context" + "errors" + "fmt" + "io" + "log/slog" + "net" + "os" + "strings" + "sync" + "time" + + "shell2/internal/hcr" +) + +// HCRConfig defines the settings for the integrated HCR transport. A nil +// *HCRConfig in the main config disables it entirely. +type HCRConfig struct { + // Listen lists the TCP addresses to bind. IPv6 addresses must use bracket + // form, e.g. "[::]:8181". Empty with SharedPorts off uses the default. + Listen []string `json:"listen"` + + // SharedPorts also accepts HCR on the ports the panel already owns (the + // HTTP+SSH proxy listeners and every TLS forwarder), alongside BHTTP, SSH + // and HTTP-injection clients. See tunnel_share.go. + SharedPorts bool `json:"shared_ports,omitempty"` + + // MaxConnections caps concurrently accepted client sockets. Zero uses a + // safe default; negative disables the cap. + MaxConnections int `json:"max_connections,omitempty"` + + // MaxSessions caps concurrently tracked HCR sessions. Zero uses a safe + // default; negative disables the cap. + MaxSessions int `json:"max_sessions,omitempty"` + + // MaxSourceSessions caps sessions per client IP. Zero disables the per-IP + // cap. + MaxSourceSessions int `json:"max_source_sessions,omitempty"` + + // DownloadPollTimeout bounds a long-poll with no data. Empty defaults to + // "10s". + DownloadPollTimeout string `json:"download_poll_timeout,omitempty"` + + // MaxDownloadFrame is the largest record read from the target per frame, in + // bytes. Zero or out-of-range uses 16384. + MaxDownloadFrame int `json:"max_download_frame,omitempty"` + + // IdleSessionTimeout drops a session that sees no traffic for this long. + // Empty defaults to "5m". + IdleSessionTimeout string `json:"idle_session_timeout,omitempty"` + + // DisableConsoleLog keeps HCR log lines out of stderr. They are still + // captured in memory and served by /api/hcr/logs for the panel. + DisableConsoleLog bool `json:"disable_console_log,omitempty"` + + // LogConnections raises the engine to debug logging (per-frame events). + // Leave off on busy servers. + LogConnections bool `json:"log_connections,omitempty"` + + // AutoRestartInterval controls a watchdog that periodically hard-restarts + // only the HCR 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 ( + defaultHCRListen = "0.0.0.0:8181" + defaultHCRMaxConnections = 10000 + defaultHCRMaxSessions = 10000 + // hcrTargetLabel is only what shows up in logs; HCR never dials a real TCP + // target, it hands each session to the built-in SSH server. + hcrTargetLabel = "hcr" +) + +var ( + hcrMu sync.Mutex + hcrServer *hcr.Server + hcrListeners []net.Listener + hcrAddrs []string + hcrSharedPorts bool + hcrCtx context.Context + hcrCancel context.CancelFunc + + hcrAutoMu sync.Mutex + hcrAutoCancel context.CancelFunc + + hcrLogBuf *ringLogBuffer +) + +func getHCRLogLines() []string { return hcrLogBuf.GetLines() } + +// hcrLogger builds an slog logger that writes into the in-memory ring buffer +// (always) and to stderr (unless the console log is disabled), at debug level +// when connection logging is on. +func hcrLogger(cfg *HCRConfig) *slog.Logger { + level := slog.LevelInfo + if cfg.LogConnections { + level = slog.LevelDebug + } + var writer io.Writer = hcrLogBuf + if !cfg.DisableConsoleLog { + writer = io.MultiWriter(hcrLogBuf, os.Stderr) + } + return slog.New(slog.NewTextHandler(writer, &slog.HandlerOptions{Level: level})) +} + +// ---------- Lifecycle ---------- + +func stopHCR() { + stopHCRAutoRestart() + stopHCRInstance() +} + +func stopHCRInstance() { + hcrMu.Lock() + listeners := hcrListeners + server := hcrServer + cancel := hcrCancel + hcrListeners = nil + hcrAddrs = nil + hcrServer = nil + hcrSharedPorts = false + hcrCtx = nil + hcrCancel = nil + hcrMu.Unlock() + + if cancel != nil { + cancel() + } + for _, listener := range listeners { + if listener != nil { + _ = listener.Close() + } + } + if server != nil { + server.Close() + server.Wait() + } +} + +func stopHCRAutoRestart() { + hcrAutoMu.Lock() + defer hcrAutoMu.Unlock() + if hcrAutoCancel != nil { + hcrAutoCancel() + hcrAutoCancel = nil + } +} + +func hcrRunning() bool { + hcrMu.Lock() + defer hcrMu.Unlock() + return hcrServer != nil +} + +// hcrShareEnabled reports whether a running HCR server wants the shared proxy +// and TLS ports. +func hcrShareEnabled() bool { + hcrMu.Lock() + defer hcrMu.Unlock() + return hcrServer != nil && hcrSharedPorts +} + +func hcrListenList() string { + hcrMu.Lock() + addrs := append([]string(nil), hcrAddrs...) + shared := hcrSharedPorts + hcrMu.Unlock() + if shared { + addrs = append(addrs, "shared proxy/TLS ports") + } + return strings.Join(addrs, ", ") +} + +func hcrEnabledInCurrentConfig() bool { + globalCfgMu.RLock() + defer globalCfgMu.RUnlock() + return globalCfg != nil && globalCfg.HCR != nil +} + +// startHCR starts the integrated HCR transport if cfg is non-nil. +func startHCR(cfg *HCRConfig) error { + if cfg == nil { + return nil + } + stopHCRAutoRestart() + if err := startHCRInstance(cfg); err != nil { + return err + } + startHCRAutoRestart(cfg) + return nil +} + +func startHCRInstance(cfg *HCRConfig) error { + if cfg == nil { + return nil + } + if hcrLogBuf == nil { + hcrLogBuf = newRingLogBuffer(200) + } + logger := hcrLogger(cfg) + + addrs := normalizeHCRListenList(cfg.Listen) + if len(addrs) == 0 && !cfg.SharedPorts { + msg := errors.New("hcr: needs either a listen address or shared_ports") + logger.Error(msg.Error()) + return msg + } + cfg.Listen = addrs + + maxConnections := cfg.MaxConnections + if maxConnections == 0 { + maxConnections = defaultHCRMaxConnections + } else if maxConnections < 0 { + maxConnections = 0 + } + maxSessions := cfg.MaxSessions + if maxSessions == 0 { + maxSessions = defaultHCRMaxSessions + } else if maxSessions < 0 { + maxSessions = 0 + } + + server := hcr.NewServer(&hcr.Config{ + TargetAddr: hcrTargetLabel, + DialTarget: func() (net.Conn, error) { return dialInternalSSH(hcrTargetLabel) }, + Logger: logger, + MaxConnections: maxConnections, + MaxSessions: maxSessions, + MaxSourceSessions: cfg.MaxSourceSessions, + DownloadPollTimeout: hcrDurationOrDefault(cfg.DownloadPollTimeout, 10*time.Second, "download_poll_timeout", logger), + MaxDownloadFrame: cfg.MaxDownloadFrame, + IdleSessionTimeout: hcrDurationOrDefault(cfg.IdleSessionTimeout, 5*time.Minute, "idle_session_timeout", logger), + }) + + // Release the previous instance before rebinding the same addresses. + stopHCRInstance() + + 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("hcr: listen failed on %s: %w", addr, err) + logger.Error(msg.Error()) + return msg + } + listeners = append(listeners, listener) + bound = append(bound, addr) + } + + ctx, cancel := context.WithCancel(context.Background()) + hcrMu.Lock() + hcrServer = server + hcrListeners = listeners + hcrAddrs = bound + hcrSharedPorts = cfg.SharedPorts + hcrCtx = ctx + hcrCancel = cancel + hcrMu.Unlock() + + logger.Info("starting", + "listen", bound, "shared_ports", cfg.SharedPorts, + "max_connections", maxConnections, "max_sessions", maxSessions, + "log_connections", cfg.LogConnections) + + for _, listener := range listeners { + go func(current net.Listener) { + defer func() { + if r := recover(); r != nil { + logger.Error("recovered panic in accept loop", "err", r) + } + }() + if err := server.Serve(ctx, current); err != nil && !isListenerClosed(err) { + logger.Warn("listener stopped", "addr", current.Addr().String(), "err", err) + } + }(listener) + } + return nil +} + +func startHCRAutoRestart(cfg *HCRConfig) { + interval := hcrAutoRestartInterval(cfg) + if interval <= 0 { + return + } + grace := hcrAutoRestartGrace(cfg) + cfgCopy := *cfg + cfgCopy.Listen = append([]string(nil), cfg.Listen...) + ctx, cancel := context.WithCancel(context.Background()) + + hcrAutoMu.Lock() + if hcrAutoCancel != nil { + hcrAutoCancel() + } + hcrAutoCancel = cancel + hcrAutoMu.Unlock() + + go func() { + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + stopHCRInstance() + if !sleepOrContextDone(ctx, grace) { + return + } + for attempt := 1; ; attempt++ { + if err := startHCRInstance(&cfgCopy); err != nil { + if !sleepOrContextDone(ctx, 10*time.Second) { + return + } + continue + } + break + } + } + } + }() +} + +func hcrAutoRestartInterval(cfg *HCRConfig) 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 || d < time.Minute { + return 0 + } + return d +} + +func hcrAutoRestartGrace(cfg *HCRConfig) 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 { + return 2 * time.Second + } + if d > time.Minute { + return time.Minute + } + return d +} + +func hcrDurationOrDefault(raw string, fallback time.Duration, field string, logger *slog.Logger) time.Duration { + raw = strings.TrimSpace(raw) + if raw == "" { + return fallback + } + d, err := time.ParseDuration(raw) + if err != nil || d <= 0 { + logger.Warn("invalid duration; using default", "field", field, "value", raw, "default", fallback) + return fallback + } + return d +} + +func normalizeHCRListenList(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 +} + +// hcrConfiguredListen describes the addresses a config asks for, for status +// reports when the server failed to bind them. +func hcrConfiguredListen(cfg *HCRConfig) string { + if cfg == nil { + return "" + } + return strings.Join(normalizeHCRListenList(cfg.Listen), ", ") +} + +// ---------- Stats ---------- + +// HCRStatsSnapshot is what /api/hcr returns. +type HCRStatsSnapshot struct { + Enabled bool `json:"enabled"` + Running bool `json:"running"` + Listen string `json:"listen,omitempty"` + hcr.StatsSnapshot +} + +// GetHCRStatsSnapshot returns the current HCR counters. Safe for concurrent use. +func GetHCRStatsSnapshot() HCRStatsSnapshot { + snapshot := HCRStatsSnapshot{ + Enabled: hcrEnabledInCurrentConfig(), + Running: hcrRunning(), + Listen: hcrListenList(), + } + hcrMu.Lock() + server := hcrServer + hcrMu.Unlock() + if server != nil { + snapshot.StatsSnapshot = server.Stats() + } + return snapshot +} diff --git a/hotreload.go b/hotreload.go index d9ed9b1..94cef7e 100644 --- a/hotreload.go +++ b/hotreload.go @@ -477,6 +477,19 @@ func applyFullConfigReload(newCfg *Config) ConfigReloadReport { report.Services["btun"] = ServiceReloadStatus{Enabled: false, Running: false} } + // HCR — stop current instance (no-op if not running) then start new one. + stopHCR() + if newCfg.HCR != nil { + if err := startHCR(newCfg.HCR); err != nil { + report.warnf("HCR failed to start: %v", err) + report.Services["hcr"] = ServiceReloadStatus{Enabled: true, Running: false, Listen: hcrConfiguredListen(newCfg.HCR), Error: err.Error()} + } else { + report.Services["hcr"] = ServiceReloadStatus{Enabled: true, Running: hcrRunning(), Listen: hcrListenList()} + } + } else { + report.Services["hcr"] = 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/hcr/server.go b/internal/hcr/server.go new file mode 100644 index 0000000..2736030 --- /dev/null +++ b/internal/hcr/server.go @@ -0,0 +1,1182 @@ +package hcr + +import ( + "context" + "crypto/sha256" + "encoding/binary" + "encoding/hex" + "errors" + "fmt" + "io" + "log/slog" + "net" + "sync" + "sync/atomic" + "time" +) + +// ============================================================================ +// HCR SERVER (0.0.3 - Patch 1) - RECONSTRUÇÃO EM GOLANG +// +// O HCR (HTTP/Custom Relay) atua como servidor proxy/túnel de alta performance +// para o ecossistema UDP-Custom / HTTP Custom. O protocolo encapsula fluxos +// arbitrários de rede (tipicamente conexões SSH no alvo 127.0.0.1:22) em pacotes +// binários estruturados sobre TCP ou TLS (porta padrão :8880). +// +// ESTRUTURA DO PROTOCOLO BINÁRIO REVERSO: +// 1. Requisição do Cliente (Client Request Header) - 62 bytes fixos: +// - [0:1] Code (uint8): Código da operação (1..6) +// - [1:2] Version (uint8): Versão do protocolo (deve ser 0x01) +// - [2:18] SessionID ([16]byte): Identificador UUID da sessão +// - [18:50] AuthKey ([32]byte): Token de autenticação / PSK +// - [50:58] Sequence (uint64 BigEndian): Offset de sequência de stream +// - [58:62] PayloadLen (uint32 BigEndian): Tamanho do payload subsequente +// - [62:] Payload ([]byte): Dados da requisição +// +// 2. Resposta do Servidor (Server Response Header) - 14 bytes fixos: +// - [0:1] Status (uint8): 0=OK, 3=Closed, 4=Error +// - [1:2] Version (uint8): Versão do protocolo (0x01) +// - [2:10] Sequence (uint64 BigEndian): Offset de sequência confirmado +// - [10:14] PayloadLen (uint32 BigEndian): Tamanho do payload de resposta +// - [14:] Payload ([]byte): Dados da resposta +// ============================================================================ + +const ( + VersionString = "0.0.3 - Patch 1" + ProtoVersion = 1 + + // Tamanhos dos cabeçalhos binários + RequestHeaderSize = 62 // 1 + 1 + 16 + 32 + 8 + 4 + ResponseHeaderSize = 14 // 1 + 1 + 8 + 4 + + // Limite máximo de frame por payload (256 KB) deduzido de FUN_0065c580 (0x40000) + MaxPayloadLimit = 262144 +) + +// Códigos de Requisição (Request Codes) +const ( + ReqConnect uint8 = 1 // Inicia nova sessão e conecta ao alvo + ReqData uint8 = 2 // Envia dados do cliente para o alvo (Upload) + ReqPoll uint8 = 3 // Solicita dados recebidos do alvo (Download/Long-polling) + ReqAck uint8 = 4 // Confirmação de recebimento pelo cliente até Sequence + ReqClose uint8 = 5 // Encerra explicitamente a sessão + ReqPing uint8 = 6 // Keepalive / Checagem de status da sessão +) + +// Códigos de Resposta (Response Status Codes) +const ( + StatusOk uint8 = 0 // Operação bem-sucedida (ReqConnect, ReqData, ReqAck, ReqPing) + StatusPollData uint8 = 1 // Download com dados entregues (ReqPoll, FUN_00664300 linha 345282) + StatusPollTimeout uint8 = 2 // Long-poll expirado sem dados no intervalo (ReqPoll, FUN_00664300 linha 345408) + StatusClosed uint8 = 3 // Sessão ou conexão com o alvo encerrada (FUN_00664300 linha 345311) + StatusError uint8 = 4 // Erro / Requisição rejeitada +) + +// Erros do Protocolo +var ( + ErrInvalidRequest = errors.New("INVALID_REQUEST") + ErrAuthFailed = errors.New("AUTH_FAILED") + ErrTargetBroken = errors.New("TARGET_BROKEN") + ErrTargetUnavail = errors.New("target_unavailable") + ErrGlobalLimit = errors.New("global_session_limit") + ErrSourceLimit = errors.New("source_session_limit") + ErrAckInvalid = errors.New("ACK_INVALID") + ErrSessionCollision = errors.New("session_id_collision") +) + +// Direções do Fluxo para Cifra de Payload (de FUN_0065d160 em hcr.c) +const ( + DirRequest uint8 = 0 // Cliente -> Servidor (Request payload) + DirResponse uint8 = 1 // Servidor -> Cliente (Response payload) +) + +// maskPayload aplica a cifra de fluxo simétrica (CTR-mode com SHA-256) no payload +// conforme a implementação reversa da função FUN_0065d160 em hcr.c. +// Semente de 30 bytes: +// [0:16] SessionID (16 bytes) +// [16] Code (uint8) +// [17:25] Sequence (uint64 BigEndian) +// [25] Direction (uint8: 1=Req, 2=Resp) +// [26:30] BlockIndex (uint32 BigEndian) +func maskPayload(payload []byte, sessionID [16]byte, code uint8, seq uint64, direction uint8) { + pLen := len(payload) + if pLen == 0 { + return + } + var seed [30]byte + copy(seed[0:16], sessionID[:]) + seed[16] = code + binary.BigEndian.PutUint64(seed[17:25], seq) + seed[25] = direction + + for offset := 0; offset < pLen; offset += 32 { + blockIndex := uint32(offset / 32) + binary.BigEndian.PutUint32(seed[26:30], blockIndex) + block := sha256.Sum256(seed[:]) + chunkLen := 32 + if pLen-offset < 32 { + chunkLen = pLen - offset + } + p := payload[offset : offset+chunkLen] + b := block[:chunkLen] + rem := chunkLen + for rem >= 8 { + v1 := binary.LittleEndian.Uint64(p) + v2 := binary.LittleEndian.Uint64(b) + binary.LittleEndian.PutUint64(p, v1^v2) + p = p[8:] + b = b[8:] + rem -= 8 + } + for i := 0; i < rem; i++ { + p[i] ^= b[i] + } + } +} + +// Config holds the HCR engine settings. The panel owns the listeners and TLS, +// so this carries no listen address, transport or certificate: the integration +// hands the engine an already-accepted connection (ServeConn) or a plain +// listener (Serve). +type Config struct { + // TargetAddr is dialed for each session when DialTarget is nil. In the + // panel this stays empty and DialTarget points at the built-in SSH server. + TargetAddr string + // DialTarget, when set, supplies the per-session target connection. The + // panel uses it to hand every HCR session to its own in-process SSH server, + // so HCR logins are panel accounts with the usual limits — no system sshd. + DialTarget func() (net.Conn, error) + // Logger receives engine events. Nil uses a discard logger. + Logger *slog.Logger + + MaxConnections int + MaxSessions int + MaxSourceSessions int + DownloadPollTimeout time.Duration + MaxDownloadFrame int + IdleSessionTimeout time.Duration +} + +func minInt(a, b int) int { + if a < b { + return a + } + return b +} + +func shortID(id [16]byte) string { + return hex.EncodeToString(id[:4]) +} + +func reqCodeNameShort(c uint8) string { + switch c { + case ReqConnect: + return "Connect" + case ReqData: + return "Data" + case ReqPoll: + return "Poll" + case ReqAck: + return "Ack" + case ReqClose: + return "Close" + case ReqPing: + return "Ping" + default: + return fmt.Sprintf("Code(%d)", c) + } +} + +func statusCodeNameShort(s uint8) string { + switch s { + case StatusOk: + return "Ok(0)" + case StatusPollData: + return "PollData(1)" + case StatusPollTimeout: + return "PollTimeout(2)" + case StatusClosed: + return "Closed(3)" + case StatusError: + return "Error(4)" + default: + return fmt.Sprintf("Status(%d)", s) + } +} + +func reqCodeName(c uint8) string { + return reqCodeNameShort(c) +} + +func statusCodeName(s uint8) string { + return statusCodeNameShort(s) +} + +// RequestHeader representa o cabeçalho de 62 bytes enviado pelo cliente +type RequestHeader struct { + Code uint8 + Version uint8 + SessionID [16]byte + AuthKey [32]byte + Sequence uint64 + PayloadLen uint32 +} + +// ResponseHeader representa o cabeçalho de 14 bytes enviado pelo servidor +type ResponseHeader struct { + Status uint8 + Version uint8 + Sequence uint64 + PayloadLen uint32 +} + +// UnmarshalRequestHeader lê e decodifica os 62 bytes fixos da requisição +func UnmarshalRequestHeader(buf []byte) (*RequestHeader, error) { + if len(buf) < RequestHeaderSize { + return nil, io.ErrUnexpectedEOF + } + code := buf[0] + if code < 1 || code > 6 { + return nil, ErrInvalidRequest + } + version := buf[1] + if version != ProtoVersion { + return nil, ErrInvalidRequest + } + + h := &RequestHeader{ + Code: code, + Version: version, + Sequence: binary.BigEndian.Uint64(buf[50:58]), + PayloadLen: binary.BigEndian.Uint32(buf[58:62]), + } + copy(h.SessionID[:], buf[2:18]) + copy(h.AuthKey[:], buf[18:50]) + + if h.PayloadLen > MaxPayloadLimit { + return nil, ErrInvalidRequest + } + return h, nil +} + +// MarshalResponseHeader serializa o cabeçalho de 14 bytes do servidor +func MarshalResponseHeader(status uint8, seq uint64, payloadLen uint32) []byte { + buf := make([]byte, ResponseHeaderSize) + buf[0] = status + buf[1] = ProtoVersion + binary.BigEndian.PutUint64(buf[2:10], seq) + binary.BigEndian.PutUint32(buf[10:14], payloadLen) + return buf +} + +// DownloadFrame armazena um pedaço de dados vindo do alvo para entrega ao cliente +type DownloadFrame struct { + Seq uint64 + Data []byte +} + +// Session mantém o estado do túnel entre o cliente HCR e a conexão TCP com o alvo +type Session struct { + ID [16]byte + SourceIP string + Target net.Conn + CreatedAt time.Time + + mu sync.Mutex + + // Controle de escrita no alvo (Upload) + targetClosed bool + targetWriteCh chan []byte // Fila assíncrona FIFO para escrita contínua no alvo + writeSeq uint64 // Próximo pacote de upload esperado do cliente (0, 1, 2, ...) + upBuffer map[uint64][]byte // Buffer de upload para pacotes recebidos fora de ordem + + // Controle de leitura do alvo (Download/Poll) + cond *sync.Cond + dataNotify chan struct{} // Canal de broadcast (fechado para acordar todos os polls simultâneos) + downBuffer []*DownloadFrame + downSeq uint64 // Próximo offset a ser atribuído para dados lidos do alvo + ackSeq uint64 // Offset confirmado pelo cliente via REQ_ACK + hasAcked bool // Indica se o cliente já enviou ao menos um ACK + deliveredSeq uint64 // Maior offset entregue ao cliente + pendingBytes int // Total de bytes acumulados no buffer de download + maxFrame int // Tamanho máximo por frame lido do alvo + + lastActive atomic.Int64 // Unix nanoseconds +} + +// notifyDataLocked fecha o canal de notificação atual (acordando todos os workers de poll em broadcast) +// e cria um novo canal vazio. DEVE ser chamado com s.mu bloqueado. +func (s *Session) notifyDataLocked() { + if s.dataNotify != nil { + close(s.dataNotify) + s.dataNotify = make(chan struct{}) + } +} + +func (s *Session) touch() { + s.lastActive.Store(time.Now().UnixNano()) +} + +func (s *Session) isIdle(timeout time.Duration) bool { + last := s.lastActive.Load() + return time.Since(time.Unix(0, last)) > timeout +} + +func (s *Session) hasFramesFrom(seq uint64) bool { + if len(s.downBuffer) == 0 { + return false + } + firstSeq := s.downBuffer[0].Seq + lastSeq := s.downBuffer[len(s.downBuffer)-1].Seq + return seq >= firstSeq && seq <= lastSeq +} + +func (s *Session) getFramesFrom(startSeq uint64, maxChunks int, maxBytes int) []*DownloadFrame { + if len(s.downBuffer) == 0 { + return nil + } + firstSeq := s.downBuffer[0].Seq + if startSeq < firstSeq { + return nil + } + startIndex := int(startSeq - firstSeq) + if startIndex >= len(s.downBuffer) { + return nil + } + var result []*DownloadFrame + totalBytes := 0 + for i := startIndex; i < len(s.downBuffer) && len(result) < maxChunks; i++ { + f := s.downBuffer[i] + frameBytes := len(f.Data) + 4 + if len(result) > 0 && totalBytes+frameBytes > maxBytes { + break + } + result = append(result, f) + totalBytes += frameBytes + } + return result +} + +// SessionManager gerencia o ciclo de vida e limites das sessões ativas +type SessionManager struct { + mu sync.RWMutex + sessions map[[16]byte]*Session + sourceCount map[string]int + + cfg *Config + logger *slog.Logger +} + +func NewSessionManager(cfg *Config, logger *slog.Logger) *SessionManager { + return &SessionManager{ + sessions: make(map[[16]byte]*Session), + sourceCount: make(map[string]int), + cfg: cfg, + logger: logger, + } +} + +func (m *SessionManager) CreateSession(id [16]byte, sourceIP string) (*Session, error) { + m.mu.Lock() + defer m.mu.Unlock() + + // Validação de colisão de ID + if _, exists := m.sessions[id]; exists { + return nil, ErrSessionCollision + } + + // Validação de limite global de sessões + if m.cfg.MaxSessions > 0 && len(m.sessions) >= m.cfg.MaxSessions { + return nil, ErrGlobalLimit + } + + // Validação de limite de sessões por IP de origem + if m.cfg.MaxSourceSessions > 0 { + if count := m.sourceCount[sourceIP]; count >= m.cfg.MaxSourceSessions { + return nil, ErrSourceLimit + } + } + + // Open the per-session target. In the panel this is the built-in SSH server + // (DialTarget); standalone it dials TargetAddr over TCP. + var targetConn net.Conn + var err error + if m.cfg.DialTarget != nil { + targetConn, err = m.cfg.DialTarget() + } else { + targetConn, err = net.DialTimeout("tcp", m.cfg.TargetAddr, 5*time.Second) + } + if err != nil { + m.logger.Warn("target_unavailable", "target", m.cfg.TargetAddr, "err", err) + return nil, ErrTargetUnavail + } + + if tcpConn, ok := targetConn.(*net.TCPConn); ok { + _ = tcpConn.SetNoDelay(true) + _ = tcpConn.SetReadBuffer(1024 * 1024) + _ = tcpConn.SetWriteBuffer(1024 * 1024) + _ = tcpConn.SetKeepAlive(true) + _ = tcpConn.SetKeepAlivePeriod(30 * time.Second) + } + + maxFrame := m.cfg.MaxDownloadFrame + if maxFrame <= 0 || maxFrame > 16384 { + maxFrame = 16384 + } + + sess := &Session{ + ID: id, + SourceIP: sourceIP, + Target: targetConn, + CreatedAt: time.Now(), + dataNotify: make(chan struct{}), + targetWriteCh: make(chan []byte, 2048), + upBuffer: make(map[uint64][]byte), + maxFrame: maxFrame, + } + sess.cond = sync.NewCond(&sess.mu) + sess.touch() + + m.sessions[id] = sess + m.sourceCount[sourceIP]++ + + // Goroutines assíncronas para streaming com o alvo (Upload e Download desacoplados) + go m.writeTargetLoop(sess) + go m.readTargetLoop(sess) + + return sess, nil +} + +// writeTargetLoop consome continuamente a fila de upload e grava no alvo TCP de forma sequencial +func (m *SessionManager) writeTargetLoop(s *Session) { + for data := range s.targetWriteCh { + if len(data) == 0 { + continue + } + if _, err := s.Target.Write(data); err != nil { + s.mu.Lock() + if !s.targetClosed { + s.targetClosed = true + s.notifyDataLocked() + } + s.mu.Unlock() + break + } + } +} + +func (m *SessionManager) GetSession(id [16]byte) (*Session, bool) { + m.mu.RLock() + defer m.mu.RUnlock() + sess, ok := m.sessions[id] + return sess, ok +} + +// Len reports how many sessions are currently tracked. +func (m *SessionManager) Len() int64 { + m.mu.RLock() + defer m.mu.RUnlock() + return int64(len(m.sessions)) +} + +func (m *SessionManager) CloseSession(id [16]byte) { + m.mu.Lock() + sess, ok := m.sessions[id] + if !ok { + m.mu.Unlock() + return + } + delete(m.sessions, id) + if m.sourceCount[sess.SourceIP] > 0 { + m.sourceCount[sess.SourceIP]-- + if m.sourceCount[sess.SourceIP] == 0 { + delete(m.sourceCount, sess.SourceIP) + } + } + m.mu.Unlock() + + sess.mu.Lock() + if !sess.targetClosed { + sess.targetClosed = true + sess.Target.Close() + sess.notifyDataLocked() + } + sess.mu.Unlock() +} + +// CloseAll encerra todas as conexões de sessões ativas (durante o shutdown do servidor) +func (m *SessionManager) CloseAll() { + m.mu.Lock() + var toClose []*Session + for _, sess := range m.sessions { + toClose = append(toClose, sess) + } + m.sessions = make(map[[16]byte]*Session) + m.sourceCount = make(map[string]int) + m.mu.Unlock() + + for _, sess := range toClose { + sess.mu.Lock() + if !sess.targetClosed { + sess.targetClosed = true + sess.Target.Close() + sess.notifyDataLocked() + } + sess.mu.Unlock() + } +} + +// readTargetLoop lê os dados enviados pelo servidor alvo (ex: banner SSH) e enfileira no buffer de download +func (m *SessionManager) readTargetLoop(s *Session) { + buf := make([]byte, s.maxFrame) + for { + // Controle de fluxo de 4MB (FUN_0065e1a0 em hcr.c): + // Se pendingBytes >= 4MB, aguarda no broadcast do canal até que ACKs liberem espaço + s.mu.Lock() + for s.pendingBytes >= 4*1024*1024 && !s.targetClosed { + notifyCh := s.dataNotify + s.mu.Unlock() + <-notifyCh + s.mu.Lock() + } + if s.targetClosed { + s.mu.Unlock() + break + } + readSize := s.maxFrame + if remain := 4*1024*1024 - s.pendingBytes; remain < readSize { + readSize = remain + } + s.mu.Unlock() + + n, err := s.Target.Read(buf[:readSize]) + if n > 0 { + s.mu.Lock() + dataCopy := make([]byte, n) + copy(dataCopy, buf[:n]) + + frame := &DownloadFrame{ + Seq: s.downSeq, + Data: dataCopy, + } + s.downBuffer = append(s.downBuffer, frame) + s.downSeq++ + s.pendingBytes += n + s.touch() + s.notifyDataLocked() + s.mu.Unlock() + } + if err != nil { + s.mu.Lock() + s.targetClosed = true + s.notifyDataLocked() + s.mu.Unlock() + break + } + } +} + +// ReapIdleSessions limpa sessões inativas periodicamente +func (m *SessionManager) ReapIdleSessions() int { + var toClose [][16]byte + + m.mu.RLock() + for id, sess := range m.sessions { + if sess.isIdle(m.cfg.IdleSessionTimeout) { + toClose = append(toClose, id) + } + } + m.mu.RUnlock() + + for _, id := range toClose { + m.CloseSession(id) + } + return len(toClose) +} + +// ============================================================================ +// HCR Server Core +// ============================================================================ + +// ---------- Stats ---------- + +type counters struct { + accepted atomic.Uint64 + connectionsReject atomic.Uint64 + activeConns atomic.Int64 + sessionsCreated atomic.Uint64 + sessionsRejected atomic.Uint64 + uploadBytes atomic.Uint64 + downloadBytes atomic.Uint64 + protocolErrors atomic.Uint64 +} + +// StatsSnapshot is what 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"` + SessionsCreated uint64 `json:"sessionsCreated"` + SessionsRejected uint64 `json:"sessionsRejected"` + UploadBytes uint64 `json:"uploadBytes"` + DownloadBytes uint64 `json:"downloadBytes"` + ProtocolErrors uint64 `json:"protocolErrors"` +} + +// Server is the embeddable HCR engine. The panel owns listeners and TLS; the +// server only speaks the plaintext HCR frame protocol on a connection handed to +// Serve or ServeConn. +type Server struct { + cfg *Config + sessions *SessionManager + logger *slog.Logger + sem chan struct{} + started time.Time + stats counters + + closed chan struct{} + closeOnce sync.Once + wait sync.WaitGroup +} + +// NewServer builds an HCR engine. Logger defaults to a discard logger. +func NewServer(cfg *Config) *Server { + logger := cfg.Logger + if logger == nil { + logger = slog.New(slog.NewTextHandler(io.Discard, &slog.HandlerOptions{Level: slog.LevelInfo})) + } + if cfg.DownloadPollTimeout <= 0 { + cfg.DownloadPollTimeout = 10 * time.Second + } + if cfg.IdleSessionTimeout <= 0 { + cfg.IdleSessionTimeout = 5 * time.Minute + } + var sem chan struct{} + if cfg.MaxConnections > 0 { + sem = make(chan struct{}, cfg.MaxConnections) + } + return &Server{ + cfg: cfg, + sessions: NewSessionManager(cfg, logger), + logger: logger, + sem: sem, + started: time.Now(), + closed: make(chan struct{}), + } +} + +// Serve accepts plaintext HCR connections on a listener the panel owns. TLS, if +// any, is terminated by the panel's TLS forwarder before this point. +func (s *Server) Serve(ctx context.Context, listener net.Listener) error { + s.wait.Add(1) + defer s.wait.Done() + go s.idleReaperLoop(ctx) + for { + conn, err := listener.Accept() + if err != nil { + select { + case <-s.closed: + return nil + case <-ctx.Done(): + return nil + default: + } + if errors.Is(err, net.ErrClosed) { + return nil + } + return err + } + if !s.admit(conn) { + continue + } + s.wait.Add(1) + go func(c net.Conn) { + defer s.wait.Done() + defer s.release(c) + s.serve(ctx, c) + }(conn) + } +} + +// ServeConn serves one already-accepted, already-classified plaintext +// connection — the shared-port handoff path. It blocks until the connection +// ends and reports whether it was admitted. +func (s *Server) ServeConn(ctx context.Context, conn net.Conn) bool { + select { + case <-s.closed: + _ = conn.Close() + return false + default: + } + if !s.admit(conn) { + return false + } + s.wait.Add(1) + defer s.wait.Done() + defer s.release(conn) + s.serve(ctx, conn) + return true +} + +// admit charges a connection against the max-connections cap. +func (s *Server) admit(conn net.Conn) bool { + s.stats.accepted.Add(1) + if s.sem != nil { + select { + case s.sem <- struct{}{}: + default: + s.stats.connectionsReject.Add(1) + _ = conn.Close() + return false + } + } + s.stats.activeConns.Add(1) + return true +} + +func (s *Server) release(conn net.Conn) { + if s.sem != nil { + <-s.sem + } + s.stats.activeConns.Add(-1) + _ = conn.Close() +} + +// serve runs the HCR frame loop on one connection. +func (s *Server) serve(ctx context.Context, conn net.Conn) { + remote := conn.RemoteAddr().String() + if tcpConn, ok := conn.(*net.TCPConn); ok { + _ = tcpConn.SetNoDelay(true) + } + hdrBuf := make([]byte, RequestHeaderSize) + + for { + // Leitura dos 62 bytes fixos do cabeçalho da requisição + if _, err := io.ReadFull(conn, hdrBuf); err != nil { + if errors.Is(err, io.EOF) || errors.Is(err, net.ErrClosed) { + return + } + s.logger.Warn("read_header_failed", "remote", remote, "err", err) + return + } + + req, err := UnmarshalRequestHeader(hdrBuf) + if err != nil { + s.stats.protocolErrors.Add(1) + s.logger.Warn("unmarshal_header_failed", + "remote", remote, + "err", err, + "code", hdrBuf[0], + "version", hdrBuf[1], + ) + return + } + + // Leitura do payload da requisição (se houver) + var payload []byte + if req.PayloadLen > 0 { + payload = make([]byte, req.PayloadLen) + if _, err := io.ReadFull(conn, payload); err != nil { + s.logger.Warn("read_payload_failed", "remote", remote, "err", err) + return + } + // Desmascara o payload recebido do cliente (Client -> Server: direction = 0) + maskPayload(payload, req.SessionID, req.Code, req.Sequence, DirRequest) + } + + s.logger.Debug("REQ", + "code", reqCodeNameShort(req.Code), + "remote", remote, + "seq", req.Sequence, + "len", req.PayloadLen, + "sess", shortID(req.SessionID), + ) + + // Despacho da requisição pelo código + closeClient := s.dispatchRequest(ctx, conn, req, payload) + if closeClient { + return + } + } +} + +// Close stops the server: no new sessions, all existing ones dropped. +func (s *Server) Close() { + s.closeOnce.Do(func() { + close(s.closed) + s.sessions.CloseAll() + }) +} + +// Wait blocks until every serving goroutine has returned. +func (s *Server) Wait() { s.wait.Wait() } + +// Stats returns a counter snapshot for the admin panel. +func (s *Server) Stats() StatsSnapshot { + return StatsSnapshot{ + StartedAt: s.started, + ActiveConnections: s.stats.activeConns.Load(), + ActiveSessions: s.sessions.Len(), + Accepted: s.stats.accepted.Load(), + ConnectionsRejected: s.stats.connectionsReject.Load(), + SessionsCreated: s.stats.sessionsCreated.Load(), + SessionsRejected: s.stats.sessionsRejected.Load(), + UploadBytes: s.stats.uploadBytes.Load(), + DownloadBytes: s.stats.downloadBytes.Load(), + ProtocolErrors: s.stats.protocolErrors.Load(), + } +} + +// dispatchRequest processa os códigos de operação 1..6 +func (s *Server) dispatchRequest(ctx context.Context, conn net.Conn, req *RequestHeader, payload []byte) bool { + remoteIP, _, _ := net.SplitHostPort(conn.RemoteAddr().String()) + + switch req.Code { + case ReqConnect: // 1: Iniciar sessão + // Validações estritas do protocolo (de FUN_00663a00): + // - Sequence deve ser 0 + // - PayloadLen deve ser 0 + // - SessionID não pode ser nulo + var zeroID [16]byte + if req.Sequence != 0 || req.PayloadLen != 0 || req.SessionID == zeroID { + s.logger.Warn("connect_rejected_invalid", + "remote", remoteIP, + "seq", req.Sequence, + "payload_len", req.PayloadLen, + "is_zero_id", req.SessionID == zeroID, + ) + s.writeResponse(conn, req.SessionID, req.Code, StatusError, req.Sequence, []byte(ErrInvalidRequest.Error())) + return false + } + + sess, err := s.sessions.CreateSession(req.SessionID, remoteIP) + if err != nil { + s.stats.sessionsRejected.Add(1) + s.logger.Error("connect_target_failed", "remote", remoteIP, "sess", shortID(req.SessionID), "err", err) + s.writeResponse(conn, req.SessionID, req.Code, StatusError, req.Sequence, []byte(err.Error())) + return false + } + s.stats.sessionsCreated.Add(1) + + s.logger.Info("connect_session_created", "remote", remoteIP, "sess", shortID(req.SessionID), "target", s.cfg.TargetAddr) + // Confirmação de conexão com token de 32 bytes de volta (SessionID + 16 zeros) + token := make([]byte, 32) + copy(token[:16], req.SessionID[:]) + s.writeResponse(conn, req.SessionID, req.Code, StatusOk, 0, token) + sess.touch() + return false + + case ReqData: // 2: Upload de dados para o alvo + sess, ok := s.sessions.GetSession(req.SessionID) + if !ok { + s.logger.Warn("data_session_not_found", "session_id", hex.EncodeToString(req.SessionID[:])) + s.writeResponse(conn, req.SessionID, req.Code, StatusError, req.Sequence, []byte(ErrAuthFailed.Error())) + return true + } + + if len(payload) == 0 { + s.logger.Warn("data_empty_payload", "session_id", hex.EncodeToString(req.SessionID[:])) + s.writeResponse(conn, req.SessionID, req.Code, StatusError, req.Sequence, []byte(ErrInvalidRequest.Error())) + return false + } + + sess.mu.Lock() + if sess.targetClosed { + sess.mu.Unlock() + s.logger.Warn("data_target_already_closed", "session_id", hex.EncodeToString(req.SessionID[:])) + s.writeResponse(conn, req.SessionID, req.Code, StatusClosed, req.Sequence, []byte(ErrTargetBroken.Error())) + return false + } + + // Validação de sequence para upload (FUN_00661240 em hcr.c): + // Sequence de upload é o índice ordinal do pacote enviado pelo cliente (0, 1, 2...) + if req.Sequence < sess.writeSeq { + // Pacote duplicado já processado anteriormente (idempotente) + respSeq := sess.writeSeq + sess.touch() + sess.mu.Unlock() + s.logger.Debug("data_duplicate_packet_ignored", "session_id", hex.EncodeToString(req.SessionID[:]), "req_seq", req.Sequence, "write_seq", respSeq) + s.writeResponse(conn, req.SessionID, req.Code, StatusOk, respSeq, nil) + return false + } + + if req.Sequence > sess.writeSeq { + // Pacote fora de ordem + if req.Sequence-sess.writeSeq > 255 { + respSeq := sess.writeSeq + sess.mu.Unlock() + s.logger.Warn("data_seq_too_far_ahead", "session_id", hex.EncodeToString(req.SessionID[:]), "req_seq", req.Sequence, "write_seq", respSeq) + s.writeResponse(conn, req.SessionID, req.Code, StatusError, respSeq, []byte("SEQUENCE_INVALID")) + return false + } + if sess.upBuffer == nil { + sess.upBuffer = make(map[uint64][]byte) + } + bufCopy := make([]byte, len(payload)) + copy(bufCopy, payload) + sess.upBuffer[req.Sequence] = bufCopy + respSeq := sess.writeSeq + sess.touch() + sess.mu.Unlock() + s.logger.Debug("data_buffered_out_of_order", "session_id", hex.EncodeToString(req.SessionID[:]), "req_seq", req.Sequence, "waiting_for", respSeq) + s.writeResponse(conn, req.SessionID, req.Code, StatusOk, respSeq, nil) + return false + } + + // req.Sequence == sess.writeSeq: agrupa pacotes contíguos e despacha para escrita assíncrona + sess.writeSeq++ + toWrite := payload + + // Descarrega quaisquer pacotes subsequentes contíguos que já estavam no upBuffer + for { + nextPayload, exists := sess.upBuffer[sess.writeSeq] + if !exists { + break + } + delete(sess.upBuffer, sess.writeSeq) + sess.writeSeq++ + toWrite = append(toWrite, nextPayload...) + } + + if !sess.targetClosed && sess.targetWriteCh != nil { + select { + case sess.targetWriteCh <- toWrite: + default: + go func(ch chan []byte, data []byte) { + ch <- data + }(sess.targetWriteCh, toWrite) + } + } + + respSeq := sess.writeSeq + sess.touch() + sess.mu.Unlock() + + s.stats.uploadBytes.Add(uint64(len(payload))) + s.logger.Debug("DATA_OK", "sess", shortID(req.SessionID), "seq", req.Sequence, "bytes", len(payload), "newWriteSeq", respSeq) + s.writeResponse(conn, req.SessionID, req.Code, StatusOk, respSeq, nil) + return false + + case ReqPoll: // 3: Download / Polling de dados do alvo + sess, ok := s.sessions.GetSession(req.SessionID) + if !ok { + s.logger.Warn("poll_session_not_found", "sess", shortID(req.SessionID)) + s.writeResponse(conn, req.SessionID, req.Code, StatusError, req.Sequence, []byte(ErrAuthFailed.Error())) + return true + } + + maxChunks := 1 + if len(payload) == 2 { + maxChunks = int(binary.BigEndian.Uint16(payload[:2])) + } else if len(payload) != 0 { + s.logger.Warn("poll_invalid_payload_len", "len", len(payload)) + s.writeResponse(conn, req.SessionID, req.Code, StatusError, req.Sequence, []byte(ErrInvalidRequest.Error())) + return false + } + if maxChunks <= 0 { + maxChunks = 1 + } + if maxChunks > 32 { + maxChunks = 32 + } + + maxFrame := s.cfg.MaxDownloadFrame + if maxFrame <= 0 || maxFrame > 16384 { + maxFrame = 16384 + } + + sess.mu.Lock() + sess.touch() + + // Validação de ACK no hcr.c (FUN_0065d4c0 / linha 341072 e 345332): + // Se já houve ACK e req.Sequence <= ackSeq: não é erro fatal, retorna StatusPollTimeout (2) + if sess.hasAcked && req.Sequence <= sess.ackSeq { + sess.mu.Unlock() + s.logger.Debug("poll_already_acked", "sess", shortID(req.SessionID), "req_seq", req.Sequence, "ack_seq", sess.ackSeq) + s.writeResponse(conn, req.SessionID, req.Code, StatusPollTimeout, req.Sequence, nil) + return false + } + + // Se o worker está adiantado em relação à esteira contígua (> 255 frames à frente): + // Retorna StatusPollTimeout (2) para que o worker reconsulte sem abortar o túnel + if req.Sequence > sess.deliveredSeq && req.Sequence-sess.deliveredSeq > 255 { + sess.mu.Unlock() + s.logger.Debug("poll_seq_ahead_timeout", "sess", shortID(req.SessionID), "req_seq", req.Sequence, "delivered_seq", sess.deliveredSeq) + s.writeResponse(conn, req.SessionID, req.Code, StatusPollTimeout, req.Sequence, nil) + return false + } + + // Long-polling sequencial estrito (hcr.c linha 341103): + // Enquanto req.Sequence > deliveredSeq (worker adiantado em relação à esteira contígua) + // ou não há frames disponíveis a partir de req.Sequence, aguarda notificação em broadcast + pollTimer := time.NewTimer(s.cfg.DownloadPollTimeout) + defer pollTimer.Stop() + + for (req.Sequence > sess.deliveredSeq || !sess.hasFramesFrom(req.Sequence)) && !sess.targetClosed { + notifyCh := sess.dataNotify + sess.mu.Unlock() + select { + case <-pollTimer.C: + sess.mu.Lock() + goto finishPoll + case <-notifyCh: + sess.mu.Lock() + case <-ctx.Done(): + sess.mu.Lock() + goto finishPoll + } + } + + finishPoll: + var matching []*DownloadFrame + if req.Sequence <= sess.deliveredSeq { + matching = sess.getFramesFrom(req.Sequence, maxChunks, int(MaxPayloadLimit)) + } + + if len(matching) == 0 { + status := StatusPollTimeout // 2: Timeout / sem dados no intervalo (FUN_00664300 linha 345408) + if sess.targetClosed { + status = StatusClosed // 3: Conexão com o alvo encerrou + } + sess.mu.Unlock() + s.writeResponse(conn, req.SessionID, req.Code, status, req.Sequence, nil) + return false + } + + // Cada chunk no payload retornado deve ser precedido por seu tamanho uint32 BigEndian + var framed []byte + var highestSeq uint64 + for _, f := range matching { + chunkHdr := make([]byte, 4) + binary.BigEndian.PutUint32(chunkHdr, uint32(len(f.Data))) + framed = append(framed, chunkHdr...) + framed = append(framed, f.Data...) + highestSeq = f.Seq + } + if highestSeq+1 > sess.deliveredSeq { + sess.deliveredSeq = highestSeq + 1 + } + sess.notifyDataLocked() + sess.touch() + sess.mu.Unlock() + + s.logger.Debug("POLL_DATA", + "sess", shortID(req.SessionID), + "chunks", len(matching), + "bytes", len(framed), + "req_seq", req.Sequence, + "delivered_seq", sess.deliveredSeq, + ) + s.stats.downloadBytes.Add(uint64(len(framed))) + // Conforme FUN_00664300 em hcr.c (linha 345282), resposta com dados usa StatusPollData (1) + s.writeResponse(conn, req.SessionID, req.Code, StatusPollData, req.Sequence, framed) + return false + + case ReqAck: // 4: Confirmação de recebimento (ACK) + sess, ok := s.sessions.GetSession(req.SessionID) + if !ok { + s.logger.Warn("ack_session_not_found", "sess", shortID(req.SessionID)) + s.writeResponse(conn, req.SessionID, req.Code, StatusError, req.Sequence, []byte(ErrAuthFailed.Error())) + return true + } + + sess.mu.Lock() + var remaining []*DownloadFrame + var ackedBytes int + for _, f := range sess.downBuffer { + if f.Seq <= req.Sequence { + ackedBytes += len(f.Data) + } else { + remaining = append(remaining, f) + } + } + sess.downBuffer = remaining + sess.pendingBytes -= ackedBytes + if sess.pendingBytes < 0 { + sess.pendingBytes = 0 + } + sess.ackSeq = req.Sequence + sess.hasAcked = true + sess.notifyDataLocked() + sess.touch() + sess.mu.Unlock() + + s.logger.Debug("ACK_OK", "sess", shortID(req.SessionID), "seq", req.Sequence, "freed", ackedBytes, "pending", sess.pendingBytes) + s.writeResponse(conn, req.SessionID, req.Code, StatusOk, req.Sequence, nil) + return false + + case ReqClose: // 5: Fechar sessão + s.logger.Info("session_closed_by_request", "sess", shortID(req.SessionID)) + s.sessions.CloseSession(req.SessionID) + s.writeResponse(conn, req.SessionID, req.Code, StatusClosed, req.Sequence, nil) + return true + + case ReqPing: // 6: Keepalive / Ping + sess, ok := s.sessions.GetSession(req.SessionID) + if !ok { + s.logger.Warn("ping_session_not_found", "sess", shortID(req.SessionID)) + s.writeResponse(conn, req.SessionID, req.Code, StatusClosed, req.Sequence, nil) + return true + } + sess.mu.Lock() + closed := sess.targetClosed + sess.touch() + sess.mu.Unlock() + if closed { + s.writeResponse(conn, req.SessionID, req.Code, StatusClosed, req.Sequence, nil) + } else { + s.writeResponse(conn, req.SessionID, req.Code, StatusOk, req.Sequence, nil) + } + return false + + default: + s.logger.Warn("unknown_request_code", "code", req.Code, "sess", shortID(req.SessionID)) + s.writeResponse(conn, req.SessionID, req.Code, StatusError, req.Sequence, []byte(ErrInvalidRequest.Error())) + return true + } +} + +// writeResponse envia os 14 bytes do ResponseHeader seguidos do payload mascarado +func (s *Server) writeResponse(conn net.Conn, sessionID [16]byte, code uint8, status uint8, seq uint64, payload []byte) { + pLen := uint32(len(payload)) + hdr := MarshalResponseHeader(status, seq, pLen) + + s.logger.Debug("RESP", + "code", reqCodeNameShort(code), + "status", statusCodeNameShort(status), + "seq", seq, + "len", pLen, + ) + + if len(payload) == 0 { + conn.Write(hdr) + return + } + + // Mascara o payload de saída (Server -> Client: direction = 1) + outPayload := make([]byte, len(payload)) + copy(outPayload, payload) + maskPayload(outPayload, sessionID, code, seq, DirResponse) + + buf := append(hdr, outPayload...) + conn.Write(buf) +} + +func (s *Server) idleReaperLoop(ctx context.Context) { + ticker := time.NewTicker(30 * time.Second) + defer ticker.Stop() + + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + reaped := s.sessions.ReapIdleSessions() + if reaped > 0 { + s.logger.Info("idle_sessions_reaped", "count", reaped) + } + } + } +} diff --git a/internal/hcr/sniff.go b/internal/hcr/sniff.go new file mode 100644 index 0000000..f206f5b --- /dev/null +++ b/internal/hcr/sniff.go @@ -0,0 +1,84 @@ +package hcr + +import "encoding/binary" + +// Verdict is the result of inspecting the first bytes of a connection. +type Verdict int + +const ( + // VerdictNo means the bytes cannot begin an HCR request. + VerdictNo Verdict = iota + // VerdictMore means the bytes so far are consistent with HCR but more are + // needed to decide. The caller should peek further and ask again. + VerdictMore + // VerdictYes means the bytes begin a valid HCR request header. + VerdictYes +) + +// SniffLimit is the largest number of bytes SniffFrame ever needs: the full +// fixed request header. +const SniffLimit = RequestHeaderSize + +// IsHeader reports whether buf is a complete, valid 62-byte HCR request header. +// This is the strict check the coexistence design relies on: only a full header +// with the fixed protocol version and an in-range payload length counts. +func IsHeader(buf []byte) bool { + if len(buf) < RequestHeaderSize { + return false + } + code := buf[0] + if code < 1 || code > 6 { + return false + } + if buf[1] != ProtoVersion { + return false + } + if binary.BigEndian.Uint32(buf[58:62]) > MaxPayloadLimit { + return false + } + return true +} + +// SniffFrame reports whether data begins an HCR request, so a port shared with +// BHTTP (and SSH, HTTP injection) can route the connection without consuming +// anything. +// +// HCR and BHTTP deliberately overlap on the first byte (opcodes 1..4 mean +// upload/download/… in both). The discriminator is HCR's fixed protocol version +// at byte [1] (always 0x01) and its 62-byte header layout, checked in full: +// +// - byte 0 must be an HCR opcode (1..6); anything else (including BHTTP's +// probe 0x00) is not HCR. +// - byte 1 must be 0x01. A BHTTP frame's byte [1] is the first byte of its +// random session UUID, so it is 0x01 only by chance — and that is the only +// case where HCR waits for the full 62 bytes. A "clean" BHTTP frame is +// rejected here at two bytes, with no stall, and falls through to BHTTP. +// - the full 62-byte header must pass IsHeader. A BHTTP frame whose UUID +// happens to start 0x01 almost never has a valid HCR payload length at +// [58:62], so it is rejected and BHTTP still handles it. +// +// The caller must try HCR before BHTTP, exactly because a real HCR Connect +// (opcode 1) also looks like a BHTTP upload on the first byte. +func SniffFrame(data []byte) Verdict { + if len(data) == 0 { + return VerdictMore + } + if data[0] < 1 || data[0] > 6 { + return VerdictNo + } + if len(data) < 2 { + return VerdictMore + } + if data[1] != ProtoVersion { + // Not HCR: a BHTTP frame or junk. Reject now so BHTTP gets its fast + // 29-byte path with no wait for 62 bytes. + return VerdictNo + } + if len(data) < RequestHeaderSize { + return VerdictMore + } + if IsHeader(data[:RequestHeaderSize]) { + return VerdictYes + } + return VerdictNo +} diff --git a/internal/hcr/sniff_test.go b/internal/hcr/sniff_test.go new file mode 100644 index 0000000..63f77bc --- /dev/null +++ b/internal/hcr/sniff_test.go @@ -0,0 +1,83 @@ +package hcr + +import ( + "encoding/binary" + "testing" +) + +// hcrHeader builds a valid 62-byte request header. +func hcrHeader(code, version byte, payloadLen uint32) []byte { + b := make([]byte, RequestHeaderSize) + b[0] = code + b[1] = version + b[2] = 0xAB // session id byte + binary.BigEndian.PutUint32(b[58:62], payloadLen) + return b +} + +func TestSniffRejectsOtherProtocols(t *testing.T) { + cases := map[string]string{ + "SSH": "SSH-2.0-x\r\n", + "HTTP GET": "GET / HTTP/1.1\r\n", + "BTUN": "DTUNNEL/1.1 CLIENT_HELLO\r\n", + "BHTTP probe": "\x00\x11\x22\x33", + "TLS hello": "\x16\x03\x01\x00", + } + for name, in := range cases { + if got := SniffFrame([]byte(in)); got != VerdictNo { + t.Fatalf("%s: SniffFrame = %v, want VerdictNo", name, got) + } + } +} + +func TestSniffAcceptsValidHeaders(t *testing.T) { + for code := byte(1); code <= 6; code++ { + if got := SniffFrame(hcrHeader(code, ProtoVersion, 100)); got != VerdictYes { + t.Fatalf("code %d: SniffFrame = %v, want VerdictYes", code, got) + } + } +} + +// A BHTTP frame whose session UUID happens to start 0x01 must NOT be stolen: +// its bytes at [58:62] are not a valid HCR payload length. +func TestSniffRejectsBhttpLookalike(t *testing.T) { + b := make([]byte, RequestHeaderSize) + b[0] = 0x01 // BHTTP upload / HCR connect + b[1] = 0x01 // UUID happens to start 0x01 + binary.BigEndian.PutUint32(b[58:62], MaxPayloadLimit+1) // invalid HCR len + if got := SniffFrame(b); got != VerdictNo { + t.Fatalf("lookalike: SniffFrame = %v, want VerdictNo", got) + } +} + +// A clean BHTTP frame (byte1 != 0x01) is rejected at two bytes — no 62-byte wait. +func TestSniffFastRejectsCleanBhttp(t *testing.T) { + if got := SniffFrame([]byte{0x01, 0x7A}); got != VerdictNo { + t.Fatalf("clean BHTTP: SniffFrame(2B) = %v, want VerdictNo", got) + } +} + +func TestSniffProgressive(t *testing.T) { + full := hcrHeader(1, ProtoVersion, 10) + if got := SniffFrame(nil); got != VerdictMore { + t.Fatalf("empty = %v, want More", got) + } + if got := SniffFrame(full[:1]); got != VerdictMore { + t.Fatalf("1 byte = %v, want More", got) + } + if got := SniffFrame(full[:2]); got != VerdictMore { + t.Fatalf("2 bytes (ver=1) = %v, want More", got) + } + if got := SniffFrame(full[:RequestHeaderSize-1]); got != VerdictMore { + t.Fatalf("61 bytes = %v, want More", got) + } + if got := SniffFrame(full); got != VerdictYes { + t.Fatalf("full = %v, want Yes", got) + } +} + +func TestSniffRejectsWrongVersion(t *testing.T) { + if got := SniffFrame(hcrHeader(1, 0x02, 10)); got != VerdictNo { + t.Fatalf("version 2 = %v, want No", got) + } +} diff --git a/main.go b/main.go index 4b4b4e0..f01f9aa 100644 --- a/main.go +++ b/main.go @@ -163,6 +163,12 @@ type Config struct { // so it authenticates against the panel's own account database — never PAM // or /etc/shadow. See btun_integration.go. BTUN *BTUNConfig `json:"btun"` + + // HCR holds configuration for the integrated HCR (HTTP/Custom Relay) + // transport. If nil, it is disabled. Like BHTTP, each session is relayed to + // this process's own SSH server, and it can coexist with BHTTP on the same + // ports. See hcr_integration.go. + HCR *HCRConfig `json:"hcr"` } // DNSTTConfig defines the settings for the integrated dnstt server. See @@ -1729,6 +1735,8 @@ func startAdminAPI(store *Store, addr string, adminDir string) { 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))) + mux.Handle("/api/hcr", saSession(http.HandlerFunc(handleHCRStats))) + mux.Handle("/api/hcr/logs", saSession(http.HandlerFunc(handleHCRLogs))) // Superadmin-only: reseller management mux.Handle("/api/resellers", saSession(http.HandlerFunc(handleListResellers(store)))) @@ -2323,6 +2331,33 @@ func handleBHTTPLogs(w http.ResponseWriter, r *http.Request) { _ = json.NewEncoder(w).Encode(lines) } +// handleHCRStats returns the current HCR transport counters. +func handleHCRStats(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + if proxyManagedServerFromRequest(w, r, statsStore, "/api/hcr", nil, "") { + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(GetHCRStatsSnapshot()) +} + +// handleHCRLogs returns the recent HCR log lines as a JSON array. +func handleHCRLogs(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + lines := getHCRLogLines() + 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 { @@ -3633,6 +3668,9 @@ func main() { if err := startBTUN(cfg.BTUN); err != nil { log.Printf("btun auto-start failed: %v", err) } + if err := startHCR(cfg.HCR); err != nil { + log.Printf("hcr auto-start failed: %v", err) + } // Start public SSH listeners (listen + extra_listen). publicAddrs := append([]string{cfg.Listen}, cfg.ExtraListen...) diff --git a/server_config_api.go b/server_config_api.go index 788e041..e3f8971 100644 --- a/server_config_api.go +++ b/server_config_api.go @@ -96,6 +96,7 @@ func serverConfigPost(w http.ResponseWriter, r *http.Request) { PAMAuthEnabled *bool `json:"pam_auth_enabled"` BHTTP *json.RawMessage `json:"bhttp"` BTUN *json.RawMessage `json:"btun"` + HCR *json.RawMessage `json:"hcr"` } if err := json.Unmarshal(body, &fieldPresence); err != nil { http.Error(w, "invalid JSON: "+err.Error(), http.StatusBadRequest) @@ -128,6 +129,9 @@ func serverConfigPost(w http.ResponseWriter, r *http.Request) { if fieldPresence.BTUN == nil { newCfg.BTUN = globalCfg.BTUN } + if fieldPresence.HCR == nil { + newCfg.HCR = globalCfg.HCR + } } globalCfgMu.RUnlock() diff --git a/tunnel_share.go b/tunnel_share.go index 1bf062d..8e35ccf 100644 --- a/tunnel_share.go +++ b/tunnel_share.go @@ -23,6 +23,7 @@ import ( "shell2/internal/bhttp" "shell2/internal/btun" + "shell2/internal/hcr" ) // tunnelSniffTimeout bounds how long a shared listener waits for a client's @@ -37,7 +38,7 @@ 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() + return bhttpShareEnabled() || btunShareEnabled() || hcrShareEnabled() } // tunnelTakeSharedConn inspects the front of a connection that arrived on a @@ -53,7 +54,8 @@ func tunnelTakeSharedConn(conn net.Conn, reader *bufio.Reader) (*bufio.Reader, b } bhttpOn := bhttpShareEnabled() btunOn := btunShareEnabled() - if !bhttpOn && !btunOn { + hcrOn := hcrShareEnabled() + if !bhttpOn && !btunOn && !hcrOn { return reader, false } @@ -69,6 +71,9 @@ func tunnelTakeSharedConn(conn net.Conn, reader *bufio.Reader) (*bufio.Reader, b if btunOn && tunnelSniff(reader, btunSniffStep) { return reader, btunServeShared(conn, reader) } + if hcrOn && tunnelSniff(reader, hcrSniffStep) { + return reader, hcrServeShared(conn, reader) + } if bhttpOn && tunnelSniff(reader, bhttpSniffStep) { return reader, bhttpServeShared(conn, reader) } @@ -143,6 +148,36 @@ func bhttpSniffStep(peeked []byte) (int, int) { return sniffNo, 0 } +// hcrSniffStep matches an HCR request: its opcode, then its fixed version byte, +// then the full 62-byte header. A BHTTP frame whose session byte is not 0x01 is +// rejected at two bytes, so it never waits for 62 bytes. +func hcrSniffStep(peeked []byte) (int, int) { + switch hcr.SniffFrame(peeked) { + case hcr.VerdictYes: + return sniffYes, 0 + case hcr.VerdictMore: + if len(peeked) < 2 { + return sniffMore, 2 + } + return sniffMore, hcr.RequestHeaderSize + } + return sniffNo, 0 +} + +// hcrServeShared hands an identified connection to the running HCR server. +func hcrServeShared(conn net.Conn, reader *bufio.Reader) bool { + hcrMu.Lock() + server := hcrServer + ctx := hcrCtx + hcrMu.Unlock() + if server == nil || ctx == nil { + return false + } + // The engine's own debug log records the session; no extra line here. + server.ServeConn(ctx, &bufferedConn{Conn: conn, r: reader}) + return true +} + // bhttpServeShared hands an identified connection to the running BHTTP server. func bhttpServeShared(conn net.Conn, reader *bufio.Reader) bool { bhttpMu.Lock()