feat(crypto): PBKDF2 iterations 100k → 600k with transparent re-encryption

Bumps the PBKDF2-SHA256 iteration count from 100,000 (OWASP 2017) to
600,000 (OWASP 2023). 6x slowdown on every brute-force attempt against
either the server-stored auth hash OR the AES-GCM ciphertext of the
entries — both currently use the same PBKDF2 output (see KNOWN ISSUE
below for why that's another problem to fix later).

Schema
======
users.kdf_iterations INTEGER DEFAULT 100000
  Per-user iteration count. Legacy rows predating the column default
  to 100k via the DEFAULT clause. New accounts insert 600k explicitly.

Migration flow
==============
Atomic from the user's perspective. No partial state ever persisted.

  1. /login (or /reauth):
     server reads users.kdf_iterations and verifies the master pw at
     that count. Login succeeds at the legacy strength. Response now
     includes kdfIterations (current) and optionally kdfMigration =
     { target: 600000 } when an upgrade is recommended.

  2. Client:
     derives the AES key at the OLD count to decrypt current entries
     (state.cryptoKey). enterApp() loads the vault normally.

  3. runKdfMigration() (background, after enterApp):
     - derives the NEW key at target iterations
     - decrypts every entry with the old key
     - re-encrypts every entry with the new key + fresh random IVs
     - POSTs { masterPassword, entries: [...] } to /migrate-kdf

  4. /migrate-kdf (new endpoint):
     - verifies the master pw against the OLD hash
     - in a single transaction:
        UPDATE users  SET password_hash = pbkdf2(pw, salt, 600k),
                          kdf_iterations = 600000
        UPDATE vault_entries SET encrypted_password, iv (per entry)
     - on any failure: ROLLBACK. User stays at legacy config, retries
       at next login. No half-migrated state possible.

  5. Client (post-commit):
     swaps state.cryptoKey to the new key, persists it, updates the
     cached ciphertext in state.entries, shows a "Vault security
     upgraded" toast.

Idempotency: server's /migrate-kdf short-circuits with "Already at
target" if users.kdf_iterations >= PBKDF2_ITERATIONS_TARGET.

Race conditions: two concurrent migrations from two tabs both
recompute the SAME new key (deterministic PBKDF2). The losing
transaction's entries get re-encrypted with the winning one's IVs,
but both clients can decrypt because the keys are identical.

KNOWN ISSUE (not fixed by this commit)
======================================
The server's password_hash IS the client's AES key, in hex form —
both sides compute PBKDF2(pw, salt, iters) and store/use the same
32 bytes. This means a stolen vault.db gives the attacker the
encryption key directly, without needing to brute-force anything.
The 100k → 600k bump still helps because the AES-GCM ciphertext
itself is also a brute-force target, but the architectural fix
(server stores SHA256(aes_key) instead of aes_key in hex) is a
separate concern that needs its own migration.

Other changes
=============
 - HandleRegister: new accounts insert kdf_iterations=600000.
 - HandleReauth: response upgraded to JSON with kdfIterations
   + optional kdfMigration. Unlock path now also triggers migration.
 - SendAuthSuccess: extended signature, all callers updated.
 - deriveKey(pwd, saltHex, iterations) in app.js: iterations param
   required, defaults to 100000 for back-compat with any legacy caller.
This commit is contained in:
2026-05-23 04:54:05 +01:00
parent bff9bdf9f2
commit e0e452306e
3 changed files with 345 additions and 24 deletions
+110 -6
View File
@@ -88,13 +88,18 @@ const state = {
// CRYPTO (preserved from legacy app.js — DO NOT TOUCH)
// ============================================================
async function deriveKey(pwd, saltHex) {
async function deriveKey(pwd, saltHex, iterations) {
// Iterations parameter is the per-user value returned by the server in
// the /login response (legacy users = 100000, modern = 600000). Falling
// back to 100000 keeps backwards compatibility with old code paths that
// didn't pass the value, but every new caller should pass it explicitly.
iterations = iterations || 100000;
const enc = new TextEncoder();
const km = await crypto.subtle.importKey('raw', enc.encode(pwd), 'PBKDF2', false, ['deriveKey']);
// saltHex is the same string that PHP/Delphi passed to PBKDF2 — use its bytes.
const sb = enc.encode(saltHex);
return crypto.subtle.deriveKey(
{ name: 'PBKDF2', salt: sb, iterations: 100000, hash: 'SHA-256' },
{ name: 'PBKDF2', salt: sb, iterations: iterations, hash: 'SHA-256' },
km,
{ name: 'AES-GCM', length: 256 },
true, ['encrypt', 'decrypt']
@@ -169,6 +174,92 @@ async function api(path, opts) {
return body;
}
// ============================================================
// KDF MIGRATION (PBKDF2 100k → 600k re-encryption)
// ============================================================
//
// When the server signals kdfMigration in /login or /reauth, we transparently
// re-encrypt every entry with a stronger key (600k PBKDF2 iterations) and
// commit the new ciphertext + the new server-side hash in one atomic
// /migrate-kdf request. If anything fails, the user stays on the legacy
// config and the migration retries at next login. The entries currently
// loaded in state.entries are encrypted with the OLD key (state.cryptoKey).
//
// Threading: runs in the background after enterApp completes. Locking the
// vault during migration is safe — we just lose the in-flight transition
// and the server's atomic rollback means nothing persisted.
let kdfMigrationInProgress = false;
async function runKdfMigration(masterPwd, fromIters, toIters) {
if (kdfMigrationInProgress) return; // dedupe concurrent calls
if (!state.entries || !state.cryptoKey) return;
kdfMigrationInProgress = true;
try {
// Derive the new key. The old key is already in state.cryptoKey
// (used to decrypt the entries we just loaded).
const newKey = await deriveKey(masterPwd, state.salt, toIters);
// Re-encrypt every entry. Each entry gets a fresh random IV under
// the new key — never reuse the old IV with the new key (would be
// pointless but also a small information leak via IV reuse patterns).
const newCiphertexts = [];
for (const entry of state.entries) {
const plain = await decryptPwd(entry.encrypted_password, entry.iv);
if (plain === '[ERROR]') {
// One decrypt failure aborts the whole migration — better to
// stay on the legacy config than to commit partial state.
throw new Error('Could not decrypt entry id=' + entry.id);
}
const tmpKey = state.cryptoKey;
try {
state.cryptoKey = newKey;
const re = await encryptPwd(plain);
newCiphertexts.push({
id: entry.id,
encrypted_password: re.encrypted,
iv: re.iv,
});
} finally {
state.cryptoKey = tmpKey; // restore for any concurrent read
}
}
// Send the atomic migrate request. Server verifies the master pw
// against the OLD hash, then updates hash + iterations + every
// entry in a single transaction.
await api('/migrate-kdf', {
method: 'POST',
headers: authHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify({
masterPassword: masterPwd,
entries: newCiphertexts,
}),
});
// Server committed → switch our in-memory crypto key and update
// the cached ciphertexts in state.entries so subsequent reads use
// the new key transparently.
state.cryptoKey = newKey;
await persistCryptoKey();
for (let i = 0; i < state.entries.length; i++) {
const nc = newCiphertexts[i];
state.entries[i].encrypted_password = nc.encrypted_password;
state.entries[i].iv = nc.iv;
}
toast('Vault security upgraded (' + fromIters.toLocaleString() +
' → ' + toIters.toLocaleString() + ' KDF iterations)');
} catch (err) {
// Silent retry on next login — the migration is idempotent and
// safe to abandon (server rolled back).
console.warn('KDF migration aborted:', err);
} finally {
kdfMigrationInProgress = false;
}
}
// ============================================================
// ACCOUNT LOCKOUT UI
// ============================================================
@@ -277,10 +368,17 @@ async function doLogin(e) {
sessionStorage.setItem('csrfToken', state.csrf);
sessionStorage.setItem('salt', state.salt);
sessionStorage.setItem('username', state.username);
state.cryptoKey = await deriveKey(p, state.salt);
// Derive with the server-specified iteration count — legacy users
// receive 100k, modern users 600k. The cryptoKey is what currently
// decrypts the entries on this server.
state.cryptoKey = await deriveKey(p, state.salt, r.kdfIterations);
await persistCryptoKey();
toast('Welcome back, ' + u);
await enterApp();
// Trigger KDF migration AFTER entries are loaded into state.
if (r.kdfMigration && r.kdfMigration.target) {
runKdfMigration(p, r.kdfIterations, r.kdfMigration.target);
}
} catch (err) {
// 429 with retry_after = account lockout. Show countdown in the
// auth hint instead of a generic error toast, and keep the login
@@ -317,7 +415,9 @@ async function doRegister(e) {
sessionStorage.setItem('csrfToken', state.csrf);
sessionStorage.setItem('salt', state.salt);
sessionStorage.setItem('username', state.username);
state.cryptoKey = await deriveKey(p, state.salt);
// Fresh account → server returns kdfIterations = current target.
// No migration ever needed for a brand-new vault.
state.cryptoKey = await deriveKey(p, state.salt, r.kdfIterations);
await persistCryptoKey();
toast('Vault created');
await enterApp();
@@ -375,18 +475,22 @@ function lockVault() {
// then re-derive the crypto key locally without rotating session/csrf.
async function doUnlock(p) {
try {
await api('/reauth', {
const r = await api('/reauth', {
method: 'POST',
headers: authHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify({ masterPassword: p }),
});
state.cryptoKey = await deriveKey(p, state.salt);
// r now carries kdfIterations + optional kdfMigration, same as /login.
state.cryptoKey = await deriveKey(p, state.salt, r.kdfIterations);
await persistCryptoKey();
state.locked = false;
$('#loginUsername').readOnly = false;
$('#authHint').textContent = '';
toast('Unlocked');
await enterApp();
if (r.kdfMigration && r.kdfMigration.target) {
runKdfMigration(p, r.kdfIterations, r.kdfMigration.target);
}
return true;
} catch (err) {
// Account lockout (too many wrong master pw attempts): show