Files
Kelx/utils/totp-secret-crypto.js
2026-11-30 16:32:37 +00:00

120 lines
5.4 KiB
JavaScript

"use strict";
// TOTP seed protection at rest (audit finding M1).
//
// users.secret previously held the base32 TOTP seed in plaintext, so any DB
// read path that leaked rows (backup, db-proxy surface, SQLi elsewhere) also
// leaked live 2FA seeds for every account — defeating the second factor and
// every destructive-action step-up that depends on it. Seeds are now stored
// as AES-256-GCM ciphertext in the same envelope discipline as node tokens
// (utils/node-token-crypto.js, audit finding C2) and the MongoDB admin
// credential (utils/mongo-admin-credentials.js, finding H2):
//
// enc:v1:<iv_b64>:<tag_b64>:<ciphertext_b64>
//
// The AES key is derived from SESSION_SECRET via scrypt with a TOTP-specific
// fixed salt, so no extra key material needs provisioning and one master
// secret never yields the same AES key for two subsystems. When the
// TOTP_SEALING_KEY override is set (see getKey below), it replaces the KDF
// INPUT only — same scrypt, same salt, same 32-byte output — so rotating
// SESSION_SECRET no longer re-keys TOTP sealing.
//
// Decryption is transparent for readers: legacy plaintext rows pass through
// unchanged (the startup migration seals them), and a value that fails GCM
// verification decrypts to null so no caller can mistake a corrupted row for
// a working seed. Null is DISTINCT from "no 2FA" — verifyTotpForUser must
// treat a sealed-but-unopenable secret as a failed verification (fail closed),
// never as "2FA disabled".
const crypto = require("crypto");
const ENC_PREFIX = "enc:v1:";
const SALT = "adpanel-totp-secret-v1";
let _keyCache = null;
function getKey() {
if (_keyCache) return _keyCache;
// adpanel:totp-sealing-key-override — the KDF INPUT is the ONLY change the
// override makes: same scryptSync, same TOTP-specific SALT, same 32-byte
// output; every parameter and the cache discipline stay exactly as before.
// With the override unset or empty ("" is falsy in this ||-fallback and is
// treated as unset by the boot check's `override !== ""` guard, so the two
// agree) the input is process.env.SESSION_SECRET — byte-identical to the
// pre-override algorithm, so every existing seal stays decryptable. With it
// set, SESSION_SECRET rotation stops being a 2FA re-enrollment event.
// There is deliberately NO derivation fallback beyond this one lookup: a
// seal that fails GCM verification under the effective key fails CLOSED
// (decryptTotpSecret returns null) — never a silent re-derivation under
// some other input, which would convert key rotation/tampering into a 2FA
// bypass. Introducing the override AFTER users have enrolled bricks their
// existing seals by design (fail-closed): seals minted under the previously
// derived key can no longer be decrypted and require re-enrollment —
// index.js says so once at boot (TOTP_SEALING_KEY advisory), so set the
// override once and keep it stable.
const secret = String(process.env.TOTP_SEALING_KEY || process.env.SESSION_SECRET || "");
if (!secret) {
throw new Error("totp-secret-crypto: SESSION_SECRET is not set; cannot seal TOTP secrets");
}
_keyCache = crypto.scryptSync(secret, SALT, 32);
return _keyCache;
}
function isTotpSecretEnvelope(value) {
return typeof value === "string" && value.startsWith(ENC_PREFIX);
}
// Seals a base32 TOTP seed. Returns "" for empty input (nothing to store) and
// the sealed envelope otherwise; returns null on any sealing failure so a
// caller can never accidentally persist plaintext — a null result must abort
// the write with an error, not downgrade to plaintext.
function encryptTotpSecret(plaintext) {
const value = String(plaintext || "").trim();
if (!value) return "";
if (isTotpSecretEnvelope(value)) return value;
try {
const iv = crypto.randomBytes(12);
// authTagLength: 16 on both sides rejects truncated auth tags at
// setAuthTag time instead of decrypting under a partial MAC.
const cipher = crypto.createCipheriv("aes-256-gcm", getKey(), iv, { authTagLength: 16 });
const ct = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
const tag = cipher.getAuthTag();
return `${ENC_PREFIX}${iv.toString("base64")}:${tag.toString("base64")}:${ct.toString("base64")}`;
} catch (err) {
return null;
}
}
// Opens a stored value:
// "" — nothing stored (2FA disabled)
// plaintext — legacy pre-migration row passed through unchanged
// seed — envelope that decrypted and verified cleanly
// null — envelope that failed GCM verification (SESSION_SECRET rotated
// since storage, truncated, or tampered row). Callers MUST treat
// null as "2FA configured but unverifiable" and fail closed.
function decryptTotpSecret(stored) {
const value = String(stored || "").trim();
if (!value) return "";
if (!isTotpSecretEnvelope(value)) return value;
try {
const parts = value.slice(ENC_PREFIX.length).split(":");
if (parts.length !== 3) return null;
const iv = Buffer.from(parts[0], "base64");
const tag = Buffer.from(parts[1], "base64");
const ct = Buffer.from(parts[2], "base64");
const decipher = crypto.createDecipheriv("aes-256-gcm", getKey(), iv, { authTagLength: 16 });
decipher.setAuthTag(tag);
return Buffer.concat([decipher.update(ct), decipher.final()]).toString("utf8");
} catch (err) {
return null;
}
}
module.exports = {
ENC_PREFIX,
SALT,
isTotpSecretEnvelope,
encryptTotpSecret,
decryptTotpSecret,
};