8000 auth: issuing a new recovery key requires the current password · Issue #315 · stratum-mining/sv2-ui · GitHub
[go: up one dir, main page]

Skip to content

auth: issuing a new recovery key requires the current password #315

Done

Description

@lucasbalieiro

Affected layers

  • Frontend (src/): affected. The Settings page's action for a new recovery key calls the regenerate mutation with no password, then reveals the key on screen. The change-password form next to it does ask for the current password.
  • Backend (server/): affected. POST /api/auth/recovery-key/regenerate is guarded only by the session middleware; it takes no body, verifies nothing, overwrites the stored recovery key and returns the new one in plaintext.
  • shared/: not affected.

Problem

Any valid session can mint a new recovery key without proving knowledge of the password. Because POST /api/auth/recover accepts a recovery key without a session to replace the password and revoke every session, a session alone is enough to obtain a durable way back in, and the owner's saved recovery key stops working at the same moment.

Impact

An attacker with a stolen but still valid session cookie, or a few seconds at an unlocked dashboard, can generate and copy a key, leave, and later reset the password to one of their choosing without ever knowing the original password or recovery key. The owner finds their password changed and their saved recovery key rejected.

Expected outcome

  • Issuing a replacement recovery key requires the current password, checked by the server regardless of what the UI sends.
  • A request without the correct password changes nothing and returns no key.
  • The UI asks for the password before revealing the new key, with the same handling as the change-password form.

Possible approach (non-binding)

Accept a currentPassword field in the regenerate request and verify it with the helper the change-password handler already uses before writing; have the Settings page collect it in a small confirmation form. server/src/auth-recovery.test.ts drives the handlers against the real server; a test can call regenerate with a session but no password, or a wrong one, and assert 401 and an unchanged recovery key.

Loupe findings

Related issues and PRs

Loupe export for #315 (finding #86)

Finding

  • repo: stratum-mining/sv2-ui (https://github.com/stratum-mining/sv2-ui.git)
  • reviewed revision: 71de8607655467a0767b57702168a834fcb357f4
  • title: Require password verification before issuing a replacement recovery key
  • severity: medium
  • location: src/pages/Settings.tsx:39-41
  • cwe: CWE-620
  • scanner: llm-code-review
  • fingerprint: 03d2a2cbb01c8e77aee0648d0d1be0aadb4687ab427fb94bf7d51072984c92ab

Description

Settings.handleGenerateKey requests and reveals a replacement recovery key without obtaining the current password. useAuth sends an empty POST to /api/auth/recovery-key/regenerate, whose in-tree handler (server/src/index.ts:425–437) checks only the session middleware, overwrites the previous recovery key, and returns the new plaintext key. The public /api/auth/recover handler then accepts that key to replace the password and revoke all sessions. This bypasses the current-password verification enforced by the adjacent Change password flow and its backend handler.

An attacker with a stolen, still-valid administrator session, or temporary access to an unlocked dashboard, can generate and copy a key, end the session, and subsequently reset the password to an attacker-chosen value without knowing the original password or recovery key. The owner’s saved recovery key is also invalidated. The prerequisite is temporary authenticated access; the impact is persistent account takeover beyond that session.

The attached node:test regression executes the actual handlers, authorization middleware, session store and cryptography, substituting an in-memory storage adapter and listener. It ages the session by an hour, confirms direct password change is denied without the current password, then completes regeneration, logout, recovery and login with the attacker’s password. Executed against HEAD, it fails with 200 instead of 401 at the takeover assertion. validate_poc accepted the diff. Require fresh password proof server-side for regeneration and collect it in Settings.

Prior #25102 (concurrent stale credential writes), #25104 (sessions surviving a password change), and #25108 (cached secrets after logout) were inspected and are distinct: this sequence is serial and uses a deliberately revoked session only before logout.

Proof of Concept

diff --git a/server/src/auth-recovery-reauth.test.ts b/server/src/auth-recovery-reauth.test.ts
new file mode 100644
--- /dev/null
+++ b/server/src/auth-recovery-reauth.test.ts
@@ -0,0 +1,136 @@
+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';
+
+const SOURCE_ROOT = new URL('.', import.meta.url);
+
+// Exercise the actual route bodies, middleware, session checks and crypto.
+// Substitute only the listener and storage so this test needs neither Docker
+// nor a running server. No authentication decision is mocked.
+function evaluate(name, bindings, exportedNames) {
+  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 {' + exportedNames.join(',') + '};',
+  )(...Object.values(bindings));
+}
+
+function makeHarness() {
+  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 sessionHelpers = evaluate('sessions.ts', { randomBytes }, [
+    'SessionStore', 'SESSION_COOKIE_NAME', 'buildClearedSessionCookie',
+    'buildSessionCookie', 'parseCookies',
+  ]);
+  const originHelpers = evaluate('request-origin.ts', {}, ['isSameOriginRequest']);
+  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, ...auth, ...sessionHelpers, ...originHelpers,
+    process: { env: { CONFIG_DIR: '/memory-config', NODE_ENV: 'test' }, on() {} },
+    ActivePoolTracker: class {},
+    readContainerLogs() {},
+  }, []);
+
+  return async (route, body = {}, cookie = '', method = 'POST') => {
+    const headers = {
+      cookie, host: 'dashboard.example',
+      origin: 'http://dashboard.example', 'sec-fetch-site': 'same-origin',
+    };
+    const req = {
+      path: route, body, method, protocol: 'http',
+      get(name) { return headers[name.toLowerCase()]; },
+    };
+    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 handler of middleware) {
+      let continued = false;
+      await handler(req, res, () => { continued = true; });
+      if (!continued) return res;
+    }
+    await routes.get(method + ' ' + route)(req, res);
+    return res;
+  };
+}
+
+test('a session alone cannot mint a credential that bypasses current-password verification', async (t) => {
+  let now = Date.now();
+  t.mock.method(Date, 'now', () => now);
+  const request = makeHarness();
+  const setup = await request('/api/auth/setup-password', { password: 'owner-private-password' });
+  assert.equal(setup.statusCode, 200);
+  const stolenCookie = setup.headers['set-cookie'].split(';')[0];
+
+  // Model an existing session, not a recent password confirmation.
+  now += 60 * 60 * 1000;
+  assert.equal((await request('/api/auth/recovery-key/regenerate')).statusCode, 401);
+  const directChange = await request('/api/auth/change-password', {
+    newPassword: 'attacker-chosen-password',
+  }, stolenCookie);
+  assert.equal(directChange.statusCode, 401, 'Changing the password requires the current secret');
+
+  // This is exactly the password-free request made by Settings.handleGenerateKey.
+  const regenerated = await request('/api/auth/recovery-key/regenerate', {}, stolenCookie);
+  if ([400, 401, 403].includes(regenerated.statusCode)) {
+    assert.equal(regenerated.body?.recoveryKey, undefined);
+    return; // Fixed: fresh password proof is required before issuing a key.
+  }
+  assert.equal(regenerated.statusCode, 200);
+  assert.equal(typeof regenerated.body.recoveryKey, 'string');
+
+  assert.equal((await request('/api/auth/logout', {}, stolenCookie)).statusCode, 200);
+  const loggedOut = await request('/api/auth/state', {}, stolenCookie, 'GET');
+  assert.equal(loggedOut.body.authenticated, false);
+
+  // Use only the newly minted key after the temporary session is gone.
+  const recovered = await request('/api/auth/recover', {
+    recoveryKey: regenerated.body.recoveryKey,
+    newPassword: 'attacker-chosen-password',
+  });
+  assert.equal(recovered.statusCode, 200);
+  const takeover = await request('/api/auth/login', { password: 'attacker-chosen-password' });
+  assert.equal(
+    takeover.statusCode, 401,
+    'Recovery-key generation let a temporary session change the password without knowing it',
+  );
+});

This finding was discovered by Project Loupe.

Activity

  1. added
    area:auth
    and removed on Oct 14, 2026
  2. changed the title [-]Require password verification before issuing a replacement recovery key[/-] [+]auth: issuing a new recovery key requires the current password[/+] 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