/** * A fresh second factor from a panel session: a code from the account's * CloudPanel authenticator or one of its passkeys, against a single-use * challenge bound to that session. The root terminal and step-up share it, * and with it each account's guess budget and its last used code. * See docs/decisions/terminal.md#verification-when-opening-root. */ import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto"; import { lstatSync, mkdirSync, readFileSync, rmSync } from "node:fs"; import { join } from "node:path"; import { ActionFailure, failAction } from "../../lib/action"; import { writeFileAtomic } from "../../lib/atomic-write"; import { errorMessage } from "../../lib/errors"; import { withFileLockSync } from "../../lib/file-lock"; import { openPanelDatabase } from "../../lib/panel-db"; import { addonConfigFile, LOCK_DIR, STATE_DIR } from "../../lib/paths"; import { isTrustedDirectory, isTrustedFile, OWNER_ONLY } from "../../lib/trusted-file"; import { DEFAULT_SECURITY_KEYS_PATHS, verifyAccountKey } from "./action"; import { WebAuthnError } from "./webauthn"; /** `securityKeys` is the addon's enabled marker: passkeys count only while it exists, as at sign-in. */ export interface FactorStorage { dir: string; lock: string; securityKeys: string } export const DEFAULT_FACTOR_STORAGE: FactorStorage = { dir: `${STATE_DIR}/second-factor`, lock: `${LOCK_DIR}/second-factor.lock`, securityKeys: addonConfigFile("security-keys"), }; export type FactorPurpose = "terminal" | "step-up"; export interface FactorState { attempts: number[]; usedStep?: number; challenges: Record; /** When each session's first prompt opened, kept while it keeps opening them, so a retry never restarts the wait. */ openings?: Record; tickets: Record; /** Panel sessions, by binding, that passed step-up, and until when it holds. */ stepUp?: Record; } const digest = (value: string) => createHash("sha256").update(value).digest("hex"); const factorFile = (dir: string, user: string) => join(dir, `${digest(user)}.json`); /** A code or signature that was checked and is wrong: the only failure that spends the budget. */ class WrongProof extends ActionFailure {} /** RFC 6238, SHA-1, six digits; CloudPanel's authenticator configuration. */ export function totp(secret: string, step: number): string { let bits = ""; for (const char of secret.toUpperCase().replace(/=+$/, "")) { const n = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".indexOf(char); if (n < 0) failAction("Invalid authenticator configuration."); bits += n.toString(2).padStart(5, "0"); } const key = Buffer.from((bits.match(/.{8}/g) ?? []).map(byte => parseInt(byte, 2))); if (!key.length) failAction("Invalid authenticator configuration."); const counter = Buffer.alloc(8); counter.writeBigUInt64BE(BigInt(step)); const mac = createHmac("sha1", key).update(counter).digest(); const offset = mac[19]! & 15; return String((mac.readUInt32BE(offset) & 0x7fffffff) % 1000000).padStart(6, "0"); } /** * Root deciding again starts the account's verification afresh: a budget * spent by someone holding its session no longer keeps it out. */ export function clearFactorState(user: string, storage: Pick = DEFAULT_FACTOR_STORAGE): void { withFileLockSync(storage.lock, 15, "a verification is still running", () => rmSync(factorFile(storage.dir, user), { force: true })); } /** One account's attempt budget and replay protection, shared by every worker. */ export function withFactorState(user: string, uid: number, now: number, storage: FactorStorage, use: (state: FactorState, save: () => void) => T): T { mkdirSync(storage.dir, { recursive: true, mode: 0o700 }); if (!isTrustedDirectory(lstatSync(storage.dir), uid, 0o077)) failAction("Verification state is not root-only."); return withFileLockSync(storage.lock, 15, "Another verification is running.", () => { const file = factorFile(storage.dir, user); let state: FactorState; try { state = JSON.parse(readFileSync(file, "utf8")); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; state = { attempts: [], challenges: {}, tickets: {} }; } const live = (entries: Record | undefined) => Object.fromEntries(Object.entries(entries ?? {}).filter(([, value]) => value.expires > now)); state.attempts = state.attempts.filter(at => at > now - 86_400_000); state.challenges = live(state.challenges); state.openings = live(state.openings); state.tickets = live(state.tickets); state.stepUp = Object.fromEntries(Object.entries(state.stepUp ?? {}).filter(([, until]) => until > now)); const save = () => writeFileAtomic(file, JSON.stringify(state), { mode: 0o600 }); return use(state, save); }); } /** * Whether this panel session passed step-up and it still holds. Read without * the lock, so the gateway never waits on a verification: every write * replaces the file in one rename. */ export function stepUpHolds(user: string, binding: string, uid: number, now: number, storage: FactorStorage): boolean { try { if (!isTrustedDirectory(lstatSync(storage.dir), uid, OWNER_ONLY)) return false; const file = factorFile(storage.dir, user); if (!isTrustedFile(lstatSync(file), uid, OWNER_ONLY)) return false; const state = JSON.parse(readFileSync(file, "utf8")) as FactorState; const until = state.stepUp?.[binding]; return typeof until === "number" && until > now; } catch { return false; } } /** Five in five minutes, and twenty a day, so guessing never runs on unattended. */ function checkBudget(state: FactorState, now: number): void { if (state.attempts.filter(at => at > now - 300_000).length >= 5 || state.attempts.length >= 20) failAction("Too many failed verifications. Try again later."); } /** A new prompt for this session and purpose, replacing any it left open, so cancelling and retrying never fills the cap. */ export function openChallenge(state: FactorState, binding: string, purpose: FactorPurpose, now: number): string { checkBudget(state, now); state.challenges = Object.fromEntries(Object.entries(state.challenges) .filter(([, value]) => value.session !== binding || (value.purpose ?? "terminal") !== purpose)); if (Object.keys(state.challenges).length >= 20) failAction("Too many pending prompts. Try again in five minutes."); const challenge = randomBytes(32).toString("base64url"); // A retry after a wrong code opens a fresh prompt, which must not restart the wait for a later code. const opened = state.openings![binding]?.at ?? now; state.openings![binding] = { at: opened, expires: now + 300_000 }; state.challenges[challenge] = { session: binding, expires: now + 300_000, opened, purpose }; return challenge; } /** * CloudPanel keeps no record of the code it took at sign-in, so a phishing * proxy holding the session holds that code too. CloudPanel takes a code up * to two steps either side of its clock, so every code the session could have * signed in with is from no later than two steps after the one `signedIn` * falls in, and only a later one counts here. A code that matches one of those steps, or * one at or before `used`, the last step that succeeded, is not a guess, and * spends nothing. `accept` may refuse the secret itself before any code is compared. */ function verifyCode(panelDb: string, user: string, code: string, used: number, signedIn: number, now: number, accept?: (secret: string) => void): number { if (!/^\d{6}$/.test(code)) failAction("Enter a six-digit authenticator code."); const db = openPanelDatabase(panelDb, true); try { const secret = db.query<{ mfa_secret: string }, [string]>("SELECT mfa_secret FROM user WHERE user_name = ?").get(user)?.mfa_secret; if (!secret) failAction("Authenticator configuration is unavailable."); accept?.(secret); const step = Math.floor(now / 30_000); const matched = [step - 1, step, step + 1].find(n => n >= 0 && timingSafeEqual(Buffer.from(totp(secret, n)), Buffer.from(code))); if (matched === undefined) throw new WrongProof("Invalid code. Try the next code."); if (matched <= used) failAction("This code was used already. Wait for the next code your app shows."); if (matched <= Math.floor(signedIn / 30_000) + 2) failAction("This code could be the one you signed in with. Wait for the next code your app shows."); return matched; } finally { db.close(); } } export interface ProofRequest { user: string; binding: string; purpose: FactorPurpose; input: Record; /** When the gateway first saw the session signed in, if it said. */ seen: number | null; panelDb: string; /** Security Keys' state directory, and who must own it. */ securityKeys: string; uid: number; /** The passkeys this check accepts. */ keys: () => string[]; /** Refuses the account's authenticator secret, such as one set up too recently to trust. */ acceptSecret?: (secret: string) => void; /** What the journal calls a failure, such as "root verification". */ what: string; } /** Answers the session's open challenge with a code or a passkey; returns how. The caller saves after. */ export function checkProof(state: FactorState, save: () => void, request: ProofRequest, now: number): string { const { user, binding, purpose, input } = request; checkBudget(state, now); const challenge = typeof input.challenge === "string" ? input.challenge : ""; const pending = state.challenges[challenge]; if (!pending || pending.session !== binding || (pending.purpose ?? "terminal") !== purpose) failAction("The verification prompt expired. Try again."); delete state.challenges[challenge]; let method = "an authenticator code"; try { if (typeof input.code === "string") { // The gateway's sighting is of this sign-in; the challenge is bound only // to the session id, which a later sign-in can keep, so the prompt's // opening (five minutes before its challenge expires) stands in only // without a sighting. const opened = pending.opened ?? pending.expires - 300_000; state.usedStep = verifyCode(request.panelDb, user, input.code, state.usedStep ?? -1, request.seen ?? opened, now, request.acceptSecret); } else { verifyAccountKey({ ...DEFAULT_SECURITY_KEYS_PATHS, stateDir: request.securityKeys, panelDb: request.panelDb, stateUid: request.uid }, user, request.keys(), challenge, input, now); method = `passkey ${String(input.id)}`; } } catch (error) { const wrong = error instanceof WrongProof || error instanceof WebAuthnError; if (wrong) state.attempts.push(now); save(); process.stderr.write(`[${purpose}] ${user} failed ${request.what}: ${errorMessage(error).replace(/\s+/g, " ")}\n`); if (wrong || error instanceof ActionFailure) throw error; failAction("Verification is unavailable right now. Try again."); } delete state.openings![binding]; return method; }