Repository navigation
Description
Affected layers
- Backend (
server/): affected.POST /api/auth/recovery-key/regenerateloads the credential, awaits the scrypt hash of a new key, then writes the loaded credential back with only the recovery-key field replaced. No version check protects that read, modify and write sequence, andsaveCredentialreplaces the file unconditionally. - Frontend (
src/): not affected. The UI sends one request; the race is between requests. shared/: not affected.
Problem
If recovery or a password change replaces the credential between regeneration's read and its write, regeneration writes the old password hash back together with its new recovery key. The password the owner just set stops working, the replaced one works again, and the only valid recovery key is the one the regeneration caller received.
Impact
An attacker holding an administrator session can start a regeneration while the owner is recovering the account. The request passes the session middleware before recovery revokes sessions; if recovery commits first, the regeneration still completes and silently undoes it. The same overlap with a password change restores the previous password.
Expected outcome
- A credential write never restores a password hash or recovery key that another request has replaced since the write's input was read.
- A regeneration that loses such a race fails, and its caller receives no key that is stored.
- The guarantee holds for every writer of the credential file: setup, recovery, password change and regeneration.
Possible approach (non-binding)
Store a generation number in the credential and make every write conditional on the generation it read, failing on mismatch; the same generation serves #317 and #319. A process-wide lock serialising credential writes closes the race for one process more simply. server/src/auth-store.test.ts tests the store and server/src/auth-recovery.test.ts drives recovery against the real server; a test can interleave a regeneration with a recovery and assert the recovered password still works afterwards.
Loupe findings
- project-loupe/audit-sv2-ui#80: recovery-key regeneration writes back a stale password hash (reported as auth: credential writes never restore a replaced password #321)
Related issues and PRs
- Lands together with auth: a login verified against a replaced credential issues no session #317 and auth: changing the password ends every other session #319: one credential version, checked by sessions and by credential writes, solves all three.
- auth: issuing a new recovery key requires the current password #315 covers the same handler's missing password check.
- Tracker: [Tracker] Authentication and sessions #368.
Loupe export for #321 (finding #80)
Finding
- repo:
stratum-mining/sv2-ui(https://github.com/stratum-mining/sv2-ui.git) - reviewed revision:
71de8607655467a0767b57702168a834fcb357f4 - title: Reject stale credential writes when regenerating recovery keys
- severity:
medium - location:
server/src/index.ts:425-436 - cwe: CWE-362
- scanner:
llm-code-review - fingerprint:
ec5918871128e0efa782d6184a93631cb1186955d630e0b950c0d39f19ba1ddd
Description
Recovery-key regeneration loads the complete credential, awaits a new key's scrypt hash, then writes the original password hash back with the new recovery-key hash. No version check or shared transaction protects that read/modify/write sequence. A concurrent password recovery or password change can replace the password in between, after which regeneration silently restores the old password and installs its caller's recovery key.
An attacker holding an administrator session can start regeneration while the owner recovers the account. The regeneration request passes session middleware before recovery revokes sessions. If recovery commits first, its success response and sessions.destroyAll() do not prevent the already admitted regeneration from subsequently replacing the recovered credential. The revoked password becomes valid again, the owner's new password stops working, and the attacker receives a valid recovery key that permits another password reset. A stolen session suffices to obtain the attacker-controlled recovery key; knowledge of the old password is unnecessary for that follow-up takeover.
The regression executes the real handlers and auth/session helpers, delaying only regeneration's asynchronous hash completion. HEAD accepts the old password after recovery successfully committed, failing the test. The harness models atomic file replacement in memory. Serialize credential updates and revalidate authorization, or reject writes whose credential version has changed. Prior searches for recover race, credential, and race found no matching report.
Proof of Concept
diff --git a/server/src/auth-credential-update-race.test.ts b/server/src/auth-credential-update-race.test.ts
new file mode 100644
--- /dev/null
+++ b/server/src/auth-credential-update-race.test.ts
@@ -0,0 +1,143 @@
+const SOURCE_ROOT = new URL('.', import.meta.url);
+import assert from 'node:assert/strict';
+import { test } from 'node:test';
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { stripTypeScriptTypes } from 'node:module';
+import { randomBytes, scrypt as scryptCallback, timingSafeEqual } from 'node:crypto';
+import { promisify } from 'node:util';
+
+// Evaluate the repository's actual handlers and credential/session helpers.
+// Only the HTTP listener and disk storage are replaced; no Docker is needed.
+function evaluate(name, bindings, exports) {
+ const url = new URL(name, SOURCE_ROOT);
+ const source = stripTypeScriptTypes(readFileSync(url, 'utf8'), { mode: 'transform' })
+ .replace(/^import\s[\s\S]*?from\s+['"][^'"]+['"];?\s*$/gm, '')
+ .replace(/^export\s/gm, '')
+ .replace(/import\.meta\.url/g, JSON.stringify(url.href));
+ return new Function(...Object.keys(bindings), source + '\nreturn {' + exports.join(',') + '};')(...Object.values(bindings));
+}
+const sessionHelpers = evaluate('sessions.ts', { randomBytes }, [
+ 'SessionStore', 'SESSION_COOKIE_NAME', 'buildClearedSessionCookie', 'buildSessionCookie', 'parseCookies',
+]);
+const originHelpers = evaluate('request-origin.ts', {}, ['isSameOriginRequest']);
+
+function makeHarness(wrapAuth = auth => auth) {
+ const files = new Map();
+ const fs = {
+ async mkdir() {}, async chmod() {},
+ async readFile(file) {
+ if (!files.has(file)) throw Object.assign(new Error('missing'), { code: 'ENOENT' });
+ return files.get(file);
+ },
+ };
+ const auth = evaluate('auth-store.ts', {
+ fs, randomBytes, scryptCallback, timingSafeEqual, promisify,
+ async writeFileAtomically(file, contents) { files.set(file, contents); },
+ }, [
+ 'CredentialError', 'generateRecoveryKey', 'getPasswordValidationError', 'hashPassword',
+ 'loadCredential', 'saveCredential', 'verifyPassword', 'verifyRecoveryKey',
+ ]);
+ const routes = new Map();
+ const middleware = [];
+ const app = {
+ set() {}, listen() {},
+ use(...args) { if (args.length === 1) middleware.push(args[0]); },
+ get(route, handler) { routes.set('GET ' + route, handler); },
+ post(route, handler) { routes.set('POST ' + route, handler); },
+ put(route, handler) { routes.set('PUT ' + route, handler); },
+ };
+ const express = Object.assign(() => app, {
+ json: () => (_req, _res, next) => next(),
+ static: () => (_req, _res, next) => next(),
+ });
+ evaluate('index.ts', {
+ express, path, fs, fileURLToPath, ...wrapAuth(auth), ...sessionHelpers, ...originHelpers,
+ process: { env: { CONFIG_DIR: '/memory-config', NODE_ENV: 'test' }, on() {} },
+ ActivePoolTracker: class {}, readContainerLogs() {},
+ }, []);
+ return {
+ auth,
+ credential: () => auth.loadCredential('/memory-config/credential.json'),
+ async request(route, body = {}, cookie = '', method = 'POST') {
+ const req = {
+ path: route, body, method, protocol: 'http',
+ get(name) { return name.toLowerCase() === 'cookie' ? cookie : undefined; },
+ };
+ const res = {
+ statusCode: 200, headers: {}, body: undefined,
+ status(code) { this.statusCode = code; return this; },
+ setHeader(name, value) { this.headers[name.toLowerCase()] = value; return this; },
+ json(value) { this.body = value; return this; },
+ };
+ for (const fn of middleware) {
+ let continued = false;
+ await fn(req, res, () => { continued = true; });
+ if (!continued) return res;
+ }
+ await routes.get(method + ' ' + route)(req, res);
+ return res;
+ },
+ };
+}
+function cookie(res) { return res.headers['set-cookie']?.split(';')[0] || ''; }
+function deferred() {
+ let resolve;
+ const promise = new Promise(r => { resolve = r; });
+ return { promise, resolve };
+}
+test('an old credential snapshot cannot undo completed account recovery', async () => {
+ const entered = deferred();
+ const release = deferred();
+ let pauseNextHash = false;
+ const h = makeHarness(auth => ({
+ ...auth,
+ async hashPassword(password) {
+ const hash = await auth.hashPassword(password);
+ if (pauseNextHash) {
+ pauseNextHash = false;
+ entered.resolve();
+ await release.promise;
+ }
+ return hash;
+ },
+ }));
+ const setup = await h.request('/api/auth/setup-password', { password: 'old-password' });
+ assert.equal(setup.statusCode, 200);
+ pauseNextHash = true;
+ const staleUpdate = h.request('/api/auth/recovery-key/regenerate', {}, cookie(setup));
+ await entered.promise;
+
+ // Let HEAD commit recovery while regeneration is suspended. Also release
+ // after a deadline so a fix that serializes the writers does not deadlock.
+ const timer = setTimeout(() => release.resolve(), 1000);
+ let recovered;
+ let regenerated;
+ try {
+ recovered = await h.request('/api/auth/recover', {
+ recoveryKey: setup.body.recoveryKey, newPassword: 'new-owner-password',
+ });
+ } finally {
+ release.resolve();
+ regenerated = await staleUpdate;
+ clearTimeout(timer);
+ }
+
+ if (recovered.statusCode === 401 || recovered.statusCode === 409) {
+ // With serialized updates the regeneration can win, invalidating the
+ // submitted recovery key. The server must not falsely report a reset.
+ return;
+ }
+ assert.equal(recovered.statusCode, 200);
+ const oldLogin = await h.request('/api/auth/login', { password: 'old-password' });
+ assert.equal(oldLogin.statusCode, 401,
+ 'the in-flight regeneration restored the revoked password');
+ const newLogin = await h.request('/api/auth/login', { password: 'new-owner-password' });
+ assert.equal(newLogin.statusCode, 200);
+ if (regenerated.statusCode === 200) {
+ assert.equal(await h.auth.verifyRecoveryKey(
+ regenerated.body.recoveryKey, await h.credential()), false,
+ 'a revoked session must not leave an attacker-controlled recovery key');
+ }
+});
This finding was discovered by Project Loupe.
Activity
[-]Reject stale credential writes when regenerating recovery keys[/-][+]auth: credential writes never restore a replaced password[/+]fix(auth): change the credential one request at a time