8000 auth: a login verified against a replaced credential issues no session · Issue #317 · stratum-mining/sv2-ui · GitHub
[go: up one dir, main page]

Skip to content

auth: a login verified against a replaced credential issues no session #317

Open

Description

@lucasbalieiro

Affected layers

  • Backend (server/): affected. POST /api/auth/login reads the credential file, awaits scrypt verification and then creates a session. Nothing compares the credential at session creation with the one that was verified, and sessions in server/src/sessions.ts hold only an expiry, so a session created after destroyAll() cannot be told from a legitimate one.
  • Frontend (src/): not affected. Session creation is decided by the server.
  • shared/: not affected.

Problem

Account recovery writes a new credential and then destroys every session. A login that loaded the old credential before that write, and finishes verifying after the sessions were destroyed, still creates a session: the old password was correct against the snapshot it read. That session is valid for its full 12 hours, although the password it was obtained with has just been replaced and every other session has been revoked.

Impact

An attacker who knows the old password and sees the owner recovering can overlap login requests with the recovery and keep a valid administrator session after the reset, with configuration access, mining control and the ability to regenerate the recovery key. It needs the old password and timing, but logins can be retried freely while the owner recovers, and the window exists on every recovery. A password change has the same race once #319 makes it revoke sessions.

Expected outcome

  • A login whose verification started against a credential that has since been replaced does not issue a session, whatever the ordering of the two requests.
  • After recovery or a password change completes, only sessions created from the new credential are valid.

Possible approach (non-binding)

Give the stored credential a generation and have login check that it is unchanged after verification and before the session is created. Stamping each session with the generation it was issued under, and rejecting older generations in the middleware, solves #319 at the same time and gives #321 a version to check writes against. server/src/auth-recovery.test.ts runs recovery against the real server; a test can start a login with the old password, let recovery finish while the login is still verifying, and assert the login's cookie is rejected.

Loupe findings

Related issues and PRs

Loupe export for #317 (finding #84)

Finding

  • repo: stratum-mining/sv2-ui (https://github.com/stratum-mining/sv2-ui.git)
  • reviewed revision: 71de8607655467a0767b57702168a834fcb357f4
  • title: Check credential freshness before issuing a login session
  • severity: medium
  • location: server/src/index.ts:337-350
  • cwe: CWE-367
  • scanner: llm-code-review
  • fingerprint: 43b532f6384e5f1135ab5ff4ec868585d7a93c31091658ca3ba0ec05ac90de99

Description

Login reads a credential snapshot, awaits scrypt verification, and creates a session without checking whether the credential changed during verification. Account recovery writes a replacement credential and calls sessions.destroyAll(), but that only removes sessions which already exist. A login that is still verifying the old snapshot can issue a new, fully valid administrator session after recovery has completed its revocation.

An attacker who knows the old password can overlap login requests with the owner's recovery. For example, login reads the old file while recovery has finished hashing its replacement and is about to write it; recovery's file replacement and session clearing then finish before the login scrypt operation completes. The late session remains valid despite the successful password reset, allowing configuration access, mining control, and recovery-key regeneration. Repeated correct-password logins are not failure-rate-limited.

The regression pauses recovery immediately before its credential write, starts a login with the old password, then completes recovery before releasing login verification. It executes the repository's actual handlers and crypto/session helpers against an in-memory atomic storage adapter. HEAD subsequently returns 200 for /api/env using the late cookie, instead of 401. Capture a credential generation and compare it synchronously before session creation, updating that generation on reset/recovery. Searches for recover race and password session found no matching prior report.

Proof of Concept

diff --git a/server/src/auth-recovery-login-race.test.ts b/server/src/auth-recovery-login-race.test.ts
new file mode 100644
--- /dev/null
+++ b/server/src/auth-recovery-login-race.test.ts
@@ -0,0 +1,138 @@
+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('login using a credential replaced during verification cannot create a session', async () => {
+  const saveEntered = deferred();
+  const releaseSave = deferred();
+  const recoveryFinished = deferred();
+  let pauseNextSave = false;
+  let holdLogin = false;
+  const h = makeHarness(auth => ({
+    ...auth,
+    async saveCredential(file, credential) {
+      if (pauseNextSave) {
+        pauseNextSave = false;
+        saveEntered.resolve();
+        await releaseSave.promise;
+      }
+      return auth.saveCredential(file, credential);
+    },
+    async verifyPassword(password, credential) {
+      const valid = await auth.verifyPassword(password, credential);
+      if (holdLogin) await recoveryFinished.promise;
+      return valid;
+    },
+  }));
+  const setup = await h.request('/api/auth/setup-password', { password: 'old-password' });
+  assert.equal(setup.statusCode, 200);
+
+  // Begin recovery first, pausing just before its atomic credential write.
+  // A simultaneous login can still read the old credential at this point.
+  pauseNextSave = true;
+  const recovering = h.request('/api/auth/recover', {
+    recoveryKey: setup.body.recoveryKey, newPassword: 'new-owner-password',
+  });
+  await saveEntered.promise;
+  holdLogin = true;
+  const pendingLogin = h.request('/api/auth/login', { password: 'old-password' });
+  await new Promise(resolve => setImmediate(resolve));
+  releaseSave.resolve();
+  let recovered;
+  try {
+    recovered = await recovering;
+  } finally {
+    recoveryFinished.resolve();
+  }
+  assert.equal(recovered.statusCode, 200);
+  const staleLogin = await pendingLogin;
+  const protectedResponse = await h.request('/api/env', {}, cookie(staleLogin), 'GET');
+  assert.equal(protectedResponse.statusCode, 401,
+    'a late login minted an admin session after recovery cleared all sessions');
+});

Suggested Fix

diff --git a/server/src/index.ts b/server/src/index.ts
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -76,6 +76,7 @@
 const STATE_FILE = path.join(CONFIG_DIR, 'state.json');
 const CREDENTIAL_FILE = path.join(CONFIG_DIR, 'credential.json');
 const sessions = new SessionStore();
+let sessionGeneration = 0;
 
 const AUTO_START_RETRY_INTERVAL_MS = 30_000;
 const AUTO_START_MIN_BACKOFF_MS = 60_000;
@@ -334,6 +335,7 @@
   }
 
   try {
+    const loginGeneration = sessionGeneration;
     const credential = await loadCredential(CREDENTIAL_FILE);
     if (!credential) {
       return res.status(409).json({ error: 'No password has been set yet.' });
@@ -345,6 +347,11 @@
       return res.status(401).json({ error: 'Incorrect password.' });
     }
 
+    // Recovery or reset may have revoked sessions during verification.
+    if (loginGeneration !== sessionGeneration) {
+      return res.status(401).json({ error: 'Incorrect password.' });
+    }
+
     const token = sessions.create();
     res.setHeader('Set-Cookie', buildSessionCookie(token, isSecureRequest(req)));
     res.json({ success: true });
@@ -409,6 +416,7 @@
       ...(await hashPassword(newPassword as string)),
       recoveryKey: await hashPassword(newRecoveryKey),
     });
+    sessionGeneration += 1;
     sessions.destroyAll();
     recoverAttempts.count = 0;
     res.json({ success: true, recoveryKey: newRecoveryKey });
@@ -917,6 +925,7 @@
     ]);
 
     // The credential is gone, so every existing session is now unbacked.
+    sessionGeneration += 1;
     sessions.destroyAll();
 
     res.json({ success: true });

This finding was discovered by Project Loupe.

Activity

  1. added
    area:auth
    and removed on Oct 14, 2026
  2. changed the title [-]Check credential freshness before issuing a login session[/-] [+]auth: a login verified against a replaced credential issues no session[/+] on Oct 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:auth

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      0