Security: fix ws-upgrade crash, per-user TOFU eviction, token log leaks; rebuild sshterm

Panel (index.js, client, views):
- upgrade handler: error guard on every upgraded socket (any path) plus a 3s
  zero-byte orphan reaper; engine.io destroyUpgrade disabled — closes the
  unauthenticated ECONNRESET crash of the whole panel and stops engine.io's
  1s timer from killing slow ssh-terminal handshakes
- /api/ssh-terminal/session: per-session token reuse cache in front of the
  rate limiter — floating-terminal auto-restore no longer burns the 10/min
  mint budget (tokens are re-served only to the same panel session + IP)
- global error middleware redacts credential-bearing query params via
  utils/url-sanitize.js — ssh-terminal ?token= values no longer reach logs
- floating-terminal restore consumes the persisted live flag: after the
  frame reported the SSH session dead, restore drops the stored session id
  and starts a clean connect; script cache busters bumped

sshterm (cmd/sshterm/main.go, rebuilt and deployed):
- TOFU store eviction is per-user and offender-pays (per-user caps: 64 pins
  and 256 contributed advisory hosts; total caps remain as backstops that
  evict the largest contributor first) — one user flooding first-use pins
  to hosts they control can no longer evict another user's pinned key or
  suppress their divergence warning
- the store file is reloaded on mtime/size change: admin edits to
  data/ssh_known_hosts.json now take effect on the next connection without
  a restart; corrupt files keep the last good state, deleted files clear
  the store, other read errors fail closed
- regression tests for flood/eviction/reload/healing + negative controls
- also lands the previously uncommitted IP-binding, trusted-proxy,
  allowed-hosts and metadata-blocking hardening; binary rebuilt through
  initialize.sh --repair-sshterm and verified live at
  /usr/local/bin/adpanel-sshterm (sha256 6bc0363479b91e6c49af9b153c8e552fd4ad8f9a5f787d73bbdc238ce0f7579e)
This commit is contained in:
antonn committed 2026-09-23 17:50:40 +00:00
1 parent a022f29e34
commit 78193254ad
14 files changed
+21400 -4827

No files matched your search

+103
View File
@@ -0,0 +1,103 @@
"use strict";
// Redacts credential-bearing query parameters before a URL is written to any
// log sink. Query strings are a documented token-exposure channel in this
// panel's threat model: the SSH-terminal ticket travels as
// `/ssh-terminal/?token=...`, is replayable for its full 20-minute TTL, and
// Express's req.originalUrl (used by the global error middleware) includes the
// query string verbatim — so an unredacted URL would put a live credential
// into persistent logs (console, journald, containers) on every store or
// handler error. The sanitizer keeps the path and the query's original order
// and encoding intact, and replaces only the VALUE of any parameter whose name
// decodes to a denylist entry with the literal "[REDACTED]".
//
// Fragments are dropped before parsing: req.originalUrl never carries one, but
// the helper must also be safe if ever handed a client-side URL — credentials
// do live in fragments (this panel's #sid=..., OAuth implicit-flow tokens),
// and a "?token=..." buried after a "#" would otherwise slip past the query
// parsing below into a log line.
//
// "code" is deliberately NOT on the denylist: it is a common benign parameter
// (color=, sort=, country_code=, ...) and redacting it would corrupt ordinary
// log lines without protecting a credential.
const REDACTED = "[REDACTED]";
// Exact lowercase matches against the decoded parameter name.
const SENSITIVE_QUERY_KEYS = Object.freeze(new Set([
"token",
"access_token",
"refresh_token",
"auth",
"authorization",
"key",
"apikey",
"api_key",
"secret",
"password",
"passwd",
"pwd",
"session",
"sessionid",
"session_id",
"sid",
"sig",
"signature",
"jwt",
"otp",
]));
// decodeURIComponent throws on malformed UTF-8 percent-escapes; callers must
// not crash (and must not lose the whole line) over a hostile name.
function decodeName(rawName) {
try {
return decodeURIComponent(rawName);
} catch (_) {
return null;
}
}
function isSensitiveName(rawName) {
const decoded = decodeName(rawName);
if (decoded !== null && SENSITIVE_QUERY_KEYS.has(decoded.toLowerCase())) {
return true;
}
// Fallback: a malformed escape defeats decoding, so also compare the raw
// lowercased name — an attacker should not be able to smuggle a credential
// parameter past the filter by corrupting their own escape sequence.
return SENSITIVE_QUERY_KEYS.has(String(rawName).toLowerCase());
}
function sanitizeUrlForLogging(raw) {
if (typeof raw !== "string" || raw.length === 0) return raw;
// Drop any fragment first: nothing after "#" is ever sent to a server, and
// leaving it in the output could leak a fragment-borne credential verbatim.
const fragmentStart = raw.indexOf("#");
const withoutFragment = fragmentStart === -1 ? raw : raw.slice(0, fragmentStart);
const queryStart = withoutFragment.indexOf("?");
if (queryStart === -1) return withoutFragment;
const base = withoutFragment.slice(0, queryStart);
const query = withoutFragment.slice(queryStart + 1);
const parts = query.split("&");
const sanitized = new Array(parts.length);
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
if (part.length === 0) {
sanitized[i] = part;
continue;
}
// Split on the FIRST "=" only: values may legitimately contain "=".
const eq = part.indexOf("=");
if (eq === -1) {
// Bare valueless flag (e.g. "?token") — redact it whole when sensitive.
sanitized[i] = isSensitiveName(part) ? REDACTED : part;
} else {
const name = part.slice(0, eq);
sanitized[i] = isSensitiveName(name) ? `${name}=${REDACTED}` : part;
}
}
return `${base}?${sanitized.join("&")}`;
}
module.exports = { sanitizeUrlForLogging, SENSITIVE_QUERY_KEYS };
+144
View File
@@ -0,0 +1,144 @@
"use strict";
// Tests for the URL log-sanitizer. Contract under test:
// - credential-bearing query parameters (the ssh-terminal ?token= is the
// concrete case) never survive into a URL destined for persistent logs;
// - everything else — path, parameter order, encoding, non-sensitive
// values — is preserved byte-for-byte;
// - hostile input (non-strings, malformed escapes, "=" inside values) can
// never crash a logging path.
const test = require("node:test");
const assert = require("node:assert");
const { sanitizeUrlForLogging, SENSITIVE_QUERY_KEYS } = require("./url-sanitize");
test("redacts the ssh-terminal token in place", () => {
assert.strictEqual(
sanitizeUrlForLogging("/ssh-terminal/?token=ABC.123.def"),
"/ssh-terminal/?token=[REDACTED]"
);
});
test("redacts only sensitive parameters, preserving order and neighbors", () => {
assert.strictEqual(
sanitizeUrlForLogging("/x?a=1&token=s&b=2"),
"/x?a=1&token=[REDACTED]&b=2"
);
});
test("redacts every occurrence of a repeated sensitive parameter", () => {
assert.strictEqual(
sanitizeUrlForLogging("/x?token=a&token=b"),
"/x?token=[REDACTED]&token=[REDACTED]"
);
});
test("matching is case-insensitive on the parameter name", () => {
assert.strictEqual(sanitizeUrlForLogging("/x?Token=x"), "/x?Token=[REDACTED]");
assert.strictEqual(sanitizeUrlForLogging("/x?PASSWORD=hunter2"), "/x?PASSWORD=[REDACTED]");
});
test("covers the whole denylist, not just token", () => {
for (const key of SENSITIVE_QUERY_KEYS) {
assert.strictEqual(
sanitizeUrlForLogging(`/x?${key}=v`),
`/x?${key}=[REDACTED]`,
`expected "${key}" to be redacted`
);
}
});
test("a URL with no query string is returned as-is", () => {
assert.strictEqual(sanitizeUrlForLogging("/ssh-terminal/"), "/ssh-terminal/");
assert.strictEqual(sanitizeUrlForLogging("/a/b/c"), "/a/b/c");
});
test("empty and non-string input passes through unchanged", () => {
assert.strictEqual(sanitizeUrlForLogging(""), "");
assert.strictEqual(sanitizeUrlForLogging(123), 123);
assert.strictEqual(sanitizeUrlForLogging(null), null);
assert.strictEqual(sanitizeUrlForLogging(undefined), undefined);
});
test("percent-encoded sensitive names are still recognized", () => {
// %74oken === "token"
assert.strictEqual(sanitizeUrlForLogging("/x?%74oken=x"), "/x?%74oken=[REDACTED]");
});
test("values containing '=' are split on the first '=' only", () => {
assert.strictEqual(
sanitizeUrlForLogging("/x?token=abc=def"),
"/x?token=[REDACTED]"
);
// Non-sensitive value with '=' inside passes through untouched.
assert.strictEqual(sanitizeUrlForLogging("/x?a=b=c"), "/x?a=b=c");
});
test("malformed percent-escapes in a name do not throw", () => {
// %C3%28 is an invalid UTF-8 sequence; decodeURIComponent throws on it.
const url = "/x?token%C3%28=x&a=1";
assert.doesNotThrow(() => sanitizeUrlForLogging(url));
assert.strictEqual(sanitizeUrlForLogging(url), "/x?token%C3%28=x&a=1");
// The raw-name fallback can only fire when the raw lowercase name itself is
// a denylist entry — impossible for a "%"-bearing name, since no denylist
// key contains "%". So a malformed escape that defeats decoding passes the
// pair through untouched (which matches what the query parser on the
// server sees: the same undecoded name).
assert.strictEqual(sanitizeUrlForLogging("/x?token%ZZ=x"), "/x?token%ZZ=x");
});
test("benign parameters are never redacted", () => {
assert.strictEqual(sanitizeUrlForLogging("/x?code=abc&state=def"), "/x?code=abc&state=def");
assert.strictEqual(sanitizeUrlForLogging("/x?page=2&sort=country_code"), "/x?page=2&sort=country_code");
});
test("encoding of untouched parts is preserved byte-for-byte", () => {
const url = "/x?a%20b=1%2F2&c=3";
assert.strictEqual(sanitizeUrlForLogging(url), url);
});
test("a bare valueless sensitive flag is redacted whole", () => {
assert.strictEqual(sanitizeUrlForLogging("/x?token"), "/x?[REDACTED]");
assert.strictEqual(sanitizeUrlForLogging("/x?debug&token&b=2"), "/x?debug&[REDACTED]&b=2");
assert.strictEqual(sanitizeUrlForLogging("/x?debug"), "/x?debug");
});
test("mixed-case escapes and letters in a name are still recognized", () => {
// %54 === "T"; decodeURIComponent accepts both hex cases.
assert.strictEqual(sanitizeUrlForLogging("/x?%54oKeN=x"), "/x?%54oKeN=[REDACTED]");
assert.strictEqual(sanitizeUrlForLogging("/x?SeSsIoNiD=x"), "/x?SeSsIoNiD=[REDACTED]");
});
test("a raw '?' inside a value does not hide a later sensitive name", () => {
assert.strictEqual(
sanitizeUrlForLogging("/x?next=/y?a=b&token=s"),
"/x?next=/y?a=b&token=[REDACTED]"
);
});
test("an encoded '&' stays inside the value and does not split the pair", () => {
assert.strictEqual(
sanitizeUrlForLogging("/x?token=a%26b&x=1"),
"/x?token=[REDACTED]&x=1"
);
});
test("fragments are dropped, never logged", () => {
// A fragment after a sensitive value is swallowed by the redaction anyway.
assert.strictEqual(sanitizeUrlForLogging("/x?token=s#frag"), "/x?token=[REDACTED]");
// A sensitive name buried after a "#" must not slip past query parsing.
assert.strictEqual(sanitizeUrlForLogging("/x?a=1#b?token=s"), "/x?a=1");
// Client-side URLs put credentials in the fragment (this panel's #sid=...,
// OAuth implicit-flow tokens) — they must not survive into a log line.
assert.strictEqual(sanitizeUrlForLogging("/x#access_token=abc"), "/x");
assert.strictEqual(sanitizeUrlForLogging("/x?a=1#keep"), "/x?a=1");
});
test("regression: a full-length ssh-terminal token leaves no trace in the output", () => {
const secret = "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08";
assert.strictEqual(secret.length, 64);
const out = sanitizeUrlForLogging(`/ssh-terminal/?token=${secret}`);
assert.strictEqual(out, "/ssh-terminal/?token=[REDACTED]");
assert.ok(!out.includes(secret), "sanitized URL must not contain the token value");
});