Hash the web password and revoke sessions server-side
Store a scrypt hash (migrating a plaintext password without changing it), sign sessions with a generation that ./password and --revoke-all rotate, make logout a same-origin POST that revokes the token, add sign out everywhere, and close proxied websockets whose session ends. Enforce a strength rule for new passwords, back off logins per client and server-wide, check Origin on login, tighten next, add security headers and a __Host- cookie over https.
This commit is contained in:
@@ -0,0 +1,233 @@
|
||||
// The web sign-in credential and its sessions.
|
||||
//
|
||||
// web-auth.json (0600, outside the repository) holds:
|
||||
// password_hash "scrypt$N$r$p$<salt>$<key>" (unpadded base64url); the same
|
||||
// hash scripts/password.py writes and the Go server verifies
|
||||
// for step-up re-authentication
|
||||
// password_weak true when the stored password predates the strength rule
|
||||
// secret the cookie HMAC key
|
||||
// generation bumped (with a new secret) by every password change and by
|
||||
// `./password --revoke-all`
|
||||
// A file still holding a plaintext "password" is migrated to a hash the first
|
||||
// time it is loaded; the password itself does not change.
|
||||
//
|
||||
// Sessions are signed tokens "v2.<generation>.<issued ms>.<expires s>.<id>.<mac>".
|
||||
// <auth file>.sessions.json (0600, written only by this proxy) records signed
|
||||
// out token ids until they expire and a "not_before" time for "sign out
|
||||
// everywhere" from Settings.
|
||||
import { createHmac, randomBytes, scrypt, scryptSync, timingSafeEqual } from "node:crypto";
|
||||
import { closeSync, fsyncSync, lstatSync, openSync, readFileSync, renameSync, unlinkSync, writeSync } from "node:fs";
|
||||
import { basename, dirname, join } from "node:path";
|
||||
import { passwordProblem } from "./passwordPolicy.js";
|
||||
|
||||
export const SCRYPT = { N: 1 << 15, r: 8, p: 1, keyLength: 32 };
|
||||
const MAXMEM = 64 * 1024 * 1024;
|
||||
/** Signed-out token ids kept until they expire; the soonest to expire go first. */
|
||||
export const REVOKED_LIMIT = 10000;
|
||||
|
||||
const b64 = (buffer) => Buffer.from(buffer).toString("base64url");
|
||||
|
||||
export function hashPassword(password, { N, r, p, keyLength } = SCRYPT) {
|
||||
const salt = randomBytes(16);
|
||||
const key = scryptSync(String(password), salt, keyLength, { N, r, p, maxmem: MAXMEM });
|
||||
return `scrypt$${N}$${r}$${p}$${b64(salt)}$${b64(key)}`;
|
||||
}
|
||||
|
||||
export function parseHash(value) {
|
||||
const parts = String(value ?? "").split("$");
|
||||
if (parts.length !== 6 || parts[0] !== "scrypt") return null;
|
||||
const [N, r, p] = parts.slice(1, 4).map((part) => (/^\d{1,7}$/.test(part) ? Number(part) : 0));
|
||||
const salt = Buffer.from(parts[4], "base64url");
|
||||
const key = Buffer.from(parts[5], "base64url");
|
||||
if (N < 2 || N > 1 << 20 || (N & (N - 1)) !== 0 || r < 1 || r > 32 || p < 1 || p > 16) return null;
|
||||
if (salt.length < 8 || key.length < 16 || key.length > 64) return null;
|
||||
return { N, r, p, salt, key };
|
||||
}
|
||||
|
||||
/** Constant-time check of candidate against a stored hash. */
|
||||
export function verifyPassword(stored, candidate) {
|
||||
const parsed = parseHash(stored);
|
||||
if (!parsed) return Promise.resolve(false);
|
||||
const { N, r, p, salt, key } = parsed;
|
||||
return new Promise((done) => {
|
||||
scrypt(String(candidate ?? ""), salt, key.length, { N, r, p, maxmem: MAXMEM }, (error, derived) => {
|
||||
done(!error && derived.length === key.length && timingSafeEqual(derived, key));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** Writes data to path through a private temporary file and a rename. */
|
||||
function writePrivateAtomic(path, text, unchanged) {
|
||||
const temporary = join(dirname(path), `.${basename(path)}.${randomBytes(6).toString("hex")}`);
|
||||
const fd = openSync(temporary, "wx", 0o600);
|
||||
try {
|
||||
writeSync(fd, text);
|
||||
fsyncSync(fd);
|
||||
} finally {
|
||||
closeSync(fd);
|
||||
}
|
||||
try {
|
||||
if (unchanged && !unchanged()) throw new Error("file changed during the update");
|
||||
renameSync(temporary, path);
|
||||
} catch (error) {
|
||||
try {
|
||||
unlinkSync(temporary);
|
||||
} catch {}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
const signature = (info) => `${info.dev}:${info.ino}:${info.mtimeMs}:${info.size}`;
|
||||
|
||||
export class AuthStore {
|
||||
constructor(file, { now = Date.now, log = (line) => console.error(line) } = {}) {
|
||||
this.file = file;
|
||||
this.sessionsFile = `${file}.sessions.json`;
|
||||
this.now = now;
|
||||
this.log = log;
|
||||
this.state = null;
|
||||
this.stamp = "";
|
||||
this.notBefore = 0;
|
||||
this.revoked = new Map(); // id -> expires (seconds)
|
||||
this.revokedGeneration = null;
|
||||
this.loadSessions();
|
||||
}
|
||||
|
||||
/** The current credential; throws when the file is missing or invalid. */
|
||||
load() {
|
||||
const info = lstatSync(this.file);
|
||||
if (!info.isFile()) throw new Error("web auth file is not a regular file");
|
||||
if (this.state && signature(info) === this.stamp) return this.state;
|
||||
const parsed = JSON.parse(readFileSync(this.file, "utf8"));
|
||||
if (!parsed || typeof parsed !== "object" || typeof parsed.secret !== "string" || parsed.secret.length < 32)
|
||||
throw new Error("web auth file has no valid secret");
|
||||
let hash = parsed.password_hash;
|
||||
let weak = parsed.password_weak === true;
|
||||
if (typeof hash !== "string" && typeof parsed.password === "string" && parsed.password.length >= 8) {
|
||||
({ hash, weak } = this.migrate(parsed, info));
|
||||
}
|
||||
if (!parseHash(hash)) throw new Error("web auth file has no valid password hash");
|
||||
const generation = Number.isSafeInteger(parsed.generation) && parsed.generation >= 0 ? parsed.generation : 0;
|
||||
this.state = { hash, weak, secret: parsed.secret, generation };
|
||||
// Re-stat: a successful migration replaced the file.
|
||||
try {
|
||||
this.stamp = signature(lstatSync(this.file));
|
||||
} catch {
|
||||
this.stamp = "";
|
||||
}
|
||||
if (this.revokedGeneration !== generation) {
|
||||
// A new generation already invalidates every older token.
|
||||
this.revoked.clear();
|
||||
this.notBefore = 0;
|
||||
this.revokedGeneration = generation;
|
||||
}
|
||||
return this.state;
|
||||
}
|
||||
|
||||
/** Replaces a plaintext password by its hash, keeping the password itself. */
|
||||
migrate(parsed, info) {
|
||||
const hash = hashPassword(parsed.password);
|
||||
const weak = passwordProblem(parsed.password) !== null;
|
||||
const next = { ...parsed, password_hash: hash, password_weak: weak };
|
||||
delete next.password;
|
||||
if (this.state) {
|
||||
// A plaintext password written over a running proxy's file is a password
|
||||
// change: like ./password, it signs every session out.
|
||||
const generation = Number.isSafeInteger(parsed.generation) && parsed.generation >= 0 ? parsed.generation : 0;
|
||||
next.generation = generation + 1;
|
||||
next.secret = randomBytes(48).toString("base64url");
|
||||
parsed.generation = next.generation;
|
||||
parsed.secret = next.secret;
|
||||
}
|
||||
try {
|
||||
writePrivateAtomic(this.file, `${JSON.stringify(next, null, 2)}\n`, () => {
|
||||
const current = lstatSync(this.file);
|
||||
return signature(current) === signature(info);
|
||||
});
|
||||
this.log(`web auth: stored the sign-in password as a scrypt hash${weak ? "; it is weak, choose a stronger one with ./password" : ""}`);
|
||||
} catch (error) {
|
||||
// Signing in keeps working from the in-memory hash until the file changes.
|
||||
this.log(`web auth: could not migrate the password file to a hash (${error.message})`);
|
||||
}
|
||||
return { hash, weak };
|
||||
}
|
||||
|
||||
loadSessions() {
|
||||
try {
|
||||
const parsed = JSON.parse(readFileSync(this.sessionsFile, "utf8"));
|
||||
this.revokedGeneration = Number.isSafeInteger(parsed.generation) ? parsed.generation : null;
|
||||
this.notBefore = Number.isFinite(parsed.not_before) ? parsed.not_before : 0;
|
||||
for (const [id, expires] of Object.entries(parsed.revoked ?? {}))
|
||||
if (/^[A-Za-z0-9_-]{8,64}$/.test(id) && Number.isFinite(expires)) this.revoked.set(id, expires);
|
||||
} catch {
|
||||
// No list yet (or unreadable): nothing has been signed out.
|
||||
}
|
||||
}
|
||||
|
||||
saveSessions() {
|
||||
const nowSeconds = Math.floor(this.now() / 1000);
|
||||
for (const [id, expires] of this.revoked) if (expires <= nowSeconds) this.revoked.delete(id);
|
||||
if (this.revoked.size > REVOKED_LIMIT) {
|
||||
const sorted = [...this.revoked].sort((a, b) => a[1] - b[1]);
|
||||
this.revoked = new Map(sorted.slice(sorted.length - REVOKED_LIMIT));
|
||||
}
|
||||
const body = {
|
||||
generation: this.revokedGeneration,
|
||||
not_before: this.notBefore,
|
||||
revoked: Object.fromEntries(this.revoked),
|
||||
};
|
||||
try {
|
||||
writePrivateAtomic(this.sessionsFile, `${JSON.stringify(body)}\n`);
|
||||
} catch (error) {
|
||||
// The revocation still holds in memory until the proxy restarts.
|
||||
this.log(`web auth: could not record signed-out sessions (${error.message})`);
|
||||
}
|
||||
}
|
||||
|
||||
mac(payload) {
|
||||
return createHmac("sha256", this.load().secret).update(payload).digest();
|
||||
}
|
||||
|
||||
/** A new signed session token valid for ttlSeconds. */
|
||||
issue(ttlSeconds) {
|
||||
const { generation } = this.load();
|
||||
const now = this.now();
|
||||
const expires = Math.floor(now / 1000) + ttlSeconds;
|
||||
const payload = `v2.${generation}.${now}.${expires}.${randomBytes(18).toString("base64url")}`;
|
||||
return { token: `${payload}.${b64(this.mac(payload))}`, expires };
|
||||
}
|
||||
|
||||
/** The session a token names, or null when it is forged, old or revoked. */
|
||||
check(token) {
|
||||
if (typeof token !== "string" || token.length > 256) return null;
|
||||
const parts = token.split(".");
|
||||
if (parts.length !== 6 || parts[0] !== "v2") return null;
|
||||
const [, generation, issued, expires, id, mac] = parts;
|
||||
if (![generation, issued, expires].every((part) => /^\d{1,16}$/.test(part))) return null;
|
||||
const state = this.load();
|
||||
const expected = this.mac(parts.slice(0, 5).join("."));
|
||||
const given = Buffer.from(mac, "base64url");
|
||||
if (given.length !== expected.length || !timingSafeEqual(given, expected)) return null;
|
||||
if (Number(generation) !== state.generation) return null;
|
||||
if (Number(expires) <= Math.floor(this.now() / 1000)) return null;
|
||||
if (Number(issued) <= this.notBefore || this.revoked.has(id)) return null;
|
||||
return { id, expires: Number(expires), issued: Number(issued) };
|
||||
}
|
||||
|
||||
/** Signs one token out (server-side logout). */
|
||||
revoke(token) {
|
||||
const session = this.check(token);
|
||||
if (!session) return false;
|
||||
this.revoked.set(session.id, session.expires);
|
||||
this.saveSessions();
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Signs every token issued so far out ("Sign out everywhere"). */
|
||||
revokeAll() {
|
||||
this.load();
|
||||
this.notBefore = Math.max(this.now(), this.notBefore + 1);
|
||||
this.revoked.clear();
|
||||
this.saveSessions();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user