HCR SUPPORT

This commit is contained in:
2026-09-13 22:31:36 -03:00
parent ede2e9eb89
commit 2b5a8c4452
13 changed files with 2393 additions and 5 deletions
+43
View File
@@ -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)
+108
View File
@@ -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;
+94 -3
View File
@@ -1231,17 +1231,18 @@
<section class="page-hero" data-tone="blue"><div class="page-hero-copy"><span class="page-kicker">System studio</span><h2>Configurações</h2><p>Rede, SSH, túneis e TLS organizados em blocos visuais e aplicados ao vivo.</p></div></section>
<div class="workspace-nav-shell" data-tone="blue">
<nav class="workspace-section-nav" id="configSectionNav" aria-label="Áreas de configuração" style="--workspace-nav-columns:7">
<nav class="workspace-section-nav" id="configSectionNav" aria-label="Áreas de configuração" style="--workspace-nav-columns:8">
<button class="active" type="button" data-workspace="config" data-workspace-section="general"><span>⌁</span> Rede e SSH</button>
<button type="button" data-workspace="config" data-workspace-section="slowdns"><span>DNS</span> SlowDNS</button>
<button type="button" data-workspace="config" data-workspace-section="udp"><span>⇅</span> UDP Gateway</button>
<button type="button" data-workspace="config" data-workspace-section="bhttp"><span>BH</span> BHTTP</button>
<button type="button" data-workspace="config" data-workspace-section="btun"><span>BT</span> BTUN</button>
<button type="button" data-workspace="config" data-workspace-section="hcr"><span>HC</span> HCR</button>
<button type="button" data-workspace="config" data-workspace-section="tls"><span>◇</span> TLS</button>
<button type="button" data-workspace="config" data-workspace-section="xray"><span>◆</span> Xray</button>
</nav>
<select id="configSection" class="workspace-section-select" data-workspace-select="config" aria-label="Área de configuração">
<option value="general">Rede e SSH</option><option value="slowdns">SlowDNS</option><option value="udp">UDP Gateway</option><option value="bhttp">BHTTP</option><option value="btun">BTUN</option><option value="tls">TLS</option><option value="xray">Xray</option>
<option value="general">Rede e SSH</option><option value="slowdns">SlowDNS</option><option value="udp">UDP Gateway</option><option value="bhttp">BHTTP</option><option value="btun">BTUN</option><option value="hcr">HCR</option><option value="tls">TLS</option><option value="xray">Xray</option>
</select>
</div>
@@ -1667,8 +1668,98 @@
</div>
</section>
<section class="workspace-section" data-workspace-panel="config" data-workspace-section-panel="hcr">
<div class="workspace-section-heading"><div><span>06 · HCR</span><h3>HCR (HTTP/Custom Relay)</h3><p>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.</p></div></div>
<div class="card" style="margin-top:12px">
<div class="card-hdr">
<div class="card-title">HCR Transport</div>
<span class="chip green">live</span>
<label style="font-size:.73rem;display:flex;align-items:center;gap:5px;cursor:pointer;margin-left:auto;">
<input type="checkbox" id="cfgHcrEnabled" onchange="toggleHcrFields(this.checked)"/> Enabled
</label>
</div>
<div id="hcrFields" class="form-grid" style="opacity:.4;pointer-events:none;">
<label style="font-size:.73rem;display:flex;align-items:center;gap:5px;cursor:pointer;grid-column:1/-1">
<input type="checkbox" id="cfgHcrSharedPorts"/> Compartilhar as portas do painel <span class="hint">80/8080 (proxy) e 443 (TLS), junto com BHTTP</span>
</label>
<div class="hint" style="grid-column:1/-1;margin-top:-4px;">
Os listeners existentes distinguem HCR de BHTTP pelo cabeçalho de 62 bytes e pelo byte de versão <code>0x01</code>, então SSH, injeção HTTP e BHTTP na mesma porta continuam funcionando. Com o compartilhamento ligado o campo Listen pode ficar vazio.
</div>
<div class="field" style="grid-column:1/-1">
<label>Listen <span class="hint">um endereço por linha; opcional com portas compartilhadas</span></label>
<textarea id="cfgHcrListen" rows="2" placeholder="0.0.0.0:8181"></textarea>
</div>
<div class="field">
<label>Max Sessions <span class="hint">0 = padrão (10000), -1 = ilimitado</span></label>
<input type="number" id="cfgHcrMaxSessions" placeholder="10000"/>
</div>
<div class="field">
<label>Max Connections <span class="hint">0 = padrão (10000), -1 = ilimitado</span></label>
<input type="number" id="cfgHcrMaxConnections" placeholder="10000"/>
</div>
<div class="field">
<label>Max Sessions Per IP <span class="hint">0 = ilimitado</span></label>
<input type="number" id="cfgHcrMaxSource" min="0" placeholder="0"/>
</div>
<div class="field">
<label>Max Download Frame <span class="hint">bytes; 0 = 16384</span></label>
<input type="number" id="cfgHcrMaxFrame" min="0" placeholder="16384"/>
</div>
<div class="field">
<label>Download Poll Timeout <span class="hint">1s..1m</span></label>
<input type="text" id="cfgHcrPollTimeout" placeholder="10s"/>
</div>
<div class="field">
<label>Idle Session Timeout <span class="hint">10s..1h</span></label>
<input type="text" id="cfgHcrIdleTimeout" placeholder="5m"/>
</div>
<div class="field">
<label>Auto Restart Interval <span class="hint">0s/off desativa</span></label>
<input type="text" id="cfgHcrAutoRestart" placeholder="24h"/>
</div>
<div class="field">
<label>Restart Grace Delay</label>
<input type="text" id="cfgHcrRestartGrace" placeholder="2s"/>
</div>
<div class="hint" style="grid-column:1/-1;margin-top:-4px;">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.</div>
<label style="font-size:.73rem;display:flex;align-items:center;gap:5px;cursor:pointer;grid-column:1/-1">
<input type="checkbox" id="cfgHcrNoConsole"/> Disable Console Log
</label>
<label style="font-size:.73rem;display:flex;align-items:center;gap:5px;cursor:pointer;grid-column:1/-1">
<input type="checkbox" id="cfgHcrLogConnections"/> Verbose Connection Logs
</label>
</div>
</div>
<div class="card" style="margin-top:12px">
<div class="card-hdr">
<div class="card-title">Status HCR</div>
<span class="chip" id="hcrStatusChip">—</span>
<button class="btn btn-ghost btn-sm" type="button" onclick="loadHcrHealth()">Atualizar</button>
</div>
<div class="metrics">
<div class="metric"><div class="m-label">Active Sessions</div><div class="m-val" id="hcrActiveSessions">--</div></div>
<div class="metric"><div class="m-label">Active Sockets</div><div class="m-val" id="hcrActiveConns">--</div></div>
<div class="metric"><div class="m-label">Upload</div><div class="m-val" id="hcrUploadBytes">--</div></div>
<div class="metric"><div class="m-label">Download</div><div class="m-val" id="hcrDownloadBytes">--</div></div>
</div>
<div class="tbl-wrap" style="margin-top:10px;">
<table>
<thead><tr><th>Counter</th><th>Value</th><th>Counter</th><th>Value</th></tr></thead>
<tbody id="hcrHealthBody"></tbody>
</table>
</div>
<div class="statusbar"><span id="hcrStatusSummary">Salve a configuração para iniciar o transporte.</span><span class="hint">Rejeições e erros de protocolo devem normalmente ficar em 0.</span></div>
<div class="card-hdr" style="margin-top:12px">
<div class="card-title">Logs HCR</div>
<button class="btn btn-ghost btn-sm" type="button" onclick="loadHcrLogs()">Carregar logs</button>
</div>
<pre id="hcrLogs" class="log-box">—</pre>
</div>
</section>
<section class="workspace-section" data-workspace-panel="config" data-workspace-section-panel="tls">
<div class="workspace-section-heading"><div><span>06 · Segurança</span><h3>Encaminhadores TLS</h3><p>Gerencie os certificados do servidor e crie listeners TLS com certificado automático, colado ou armazenado em arquivo.</p></div></div>
<div class="workspace-section-heading"><div><span>07 · Segurança</span><h3>Encaminhadores TLS</h3><p>Gerencie os certificados do servidor e crie listeners TLS com certificado automático, colado ou armazenado em arquivo.</p></div></div>
<!-- TLS Certificates -->
<div class="card" style="margin-top:12px">
+209
View File
@@ -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)
}
})
}
+61
View File
@@ -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.
+437
View File
@@ -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
}
+13
View File
@@ -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()
File diff suppressed because it is too large Load Diff
+84
View File
@@ -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
}
+83
View File
@@ -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)
}
}
+38
View File
@@ -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...)
+4
View File
@@ -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()
+37 -2
View File
@@ -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()