Files
Kelx/utils/url-sanitize.js
antonn 78193254ad 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)
2026-09-23 17:50:40 +00:00

104 lines
3.7 KiB
JavaScript

"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 };