Repository navigation
Description
Affected layers
- Backend (
server/): affected.POST /api/auth/change-passwordverifies the current password, writes the new hash and returns success. It never destroys any session, unlikePOST /api/auth/recover, which clears them all. The middleware accepts any token whose expiry has not passed. - Frontend (
src/): not affected. After a successful change the UI refetches the auth state, which still reports the caller as authenticated; the defect is server-side. shared/: not affected.
Problem
Changing the password leaves every existing session valid for the rest of its 12-hour lifetime. Nothing on later requests checks the credential a session was issued under.
Impact
An attacker who logged in with a compromised password, or who obtained a session cookie, keeps configuration access and mining control after the owner changes the password. From that session they can also regenerate the recovery key and, with it, reset the password later. Changing the password is the operator's natural reaction to a suspected compromise, and today it does not remove the access that prompted it.
Expected outcome
- After a successful password change, every session other than the one that performed the change is rejected by the protected routes.
- The session that performed the change stays valid, so the operator is not logged out by their own change.
Possible approach (non-binding)
Destroy all sessions after the write and issue a fresh cookie to the caller, or add a credential generation to sessions as #317 suggests and reject older generations in the middleware. server/src/sessions.test.ts unit-tests the store and server/src/auth-recovery.test.ts drives the handlers against the real server; a test can open two sessions, change the password from one, and assert the other receives 401.
Loupe findings
- project-loupe/audit-sv2-ui#82: a password change leaves other sessions valid (reported as auth: changing the password ends every other session #319)
Related issues and PRs
- Lands together with auth: a login verified against a replaced credential issues no session #317 and auth: credential writes never restore a replaced password #321: one credential version, checked by sessions and by credential writes, solves all three.
- auth: issuing a new recovery key requires the current password #315: a surviving session can use recovery-key regeneration to keep access after the change.
- Tracker: [Tracker] Authentication and sessions #368.
Loupe export for #319 (finding #82)
Finding
- repo:
stratum-mining/sv2-ui(https://github.com/stratum-mining/sv2-ui.git) - reviewed revision:
71de8607655467a0767b57702168a834fcb357f4 - title: Invalidate other administrator sessions after a password change
- severity:
medium - location:
server/src/index.ts:477-483 - cwe: CWE-613
- scanner:
llm-code-review - fingerprint:
80a6226f8e16ecc88407748cab8f0e2535318b75e935606ea77901ad7b4dbec3
Description
The change-password handler replaces the stored password and reports success without invalidating any existing sessions. SessionStore entries contain only an expiration timestamp, so protected-route middleware continues to accept cookies issued under the old credential for their remaining lifetime (up to 12 hours). Nothing on the subsequent request checks the current password or a credential generation.
An attacker who previously logged in with a compromised password, or obtained an administrator cookie, retains configuration access and mining control after the owner changes the password. The surviving session can also call recovery-key/regenerate, then use that key to reset the password and establish persistent access. Changing the password therefore does not remove access obtained with the compromised credential.
The node:test regression creates separate owner and attacker sessions, changes the password using the owner's session, and accesses /api/env with the attacker cookie. HEAD returns 200 instead of the required 401. It uses the actual handlers, middleware, password hashing and SessionStore, with the listener and atomic storage replaced for isolation. The test passes when password changes revoke existing sessions. Invalidate other sessions, optionally rotate and retain the requesting owner's session, or bind sessions to a credential generation. Searches for password session and credential found no matching prior finding.
Proof of Concept
diff --git a/server/src/auth-password-session-revocation.test.ts b/server/src/auth-password-session-revocation.test.ts
new file mode 100644
--- /dev/null
+++ b/server/src/auth-password-session-revocation.test.ts
@@ -0,0 +1,100 @@
+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)
8000
{ return res.headers['set-cookie']?.split(';')[0] || ''; }
+function deferred() {
+ let resolve;
+ const promise = new Promise(r => { resolve = r; });
+ return { promise, resolve };
+}
+test('password change revokes another browser session', async () => {
+ const h = makeHarness();
+ const owner = await h.request('/api/auth/setup-password', { password: 'old-password' });
+ const attacker = await h.request('/api/auth/login', { password: 'old-password' });
+ assert.equal(attacker.statusCode, 200);
+ const change = await h.request('/api/auth/change-password',
+ { currentPassword: 'old-password', newPassword: 'new-password' }, cookie(owner));
+ assert.equal(change.statusCode, 200);
+ const protectedResponse = await h.request('/api/env', {}, cookie(attacker), 'GET');
+ assert.equal(protectedResponse.statusCode, 401);
+});
Suggested Fix
diff --git a/server/src/index.ts b/server/src/index.ts
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -479,7 +479,10 @@
...updatedCredential,
recoveryKey: credential.recoveryKey,
});
+ sessions.destroyAll();
+ const token = sessions.create();
+ res.setHeader('Set-Cookie', buildSessionCookie(token, isSecureRequest(req)));
res.json({ success: true });
} catch (error) {
if (error instanceof CredentialError) {
This finding was discovered by Project Loupe.
Activity
[-]Invalidate other administrator sessions after a password change[/-][+]auth: changing the password ends every other session[/+]fix(auth): end every other session when the password changes