Commit Graph

6 Commits

Author SHA1 Message Date
Zaki d13e5bc89f feat(zero-knowledge): client computes verifier, master pw never leaves the browser
THE GAP THIS CLOSES
===================
Before this commit, every auth endpoint accepted the master password
in plaintext. The server ran PBKDF2 + SHA-256 server-side to verify.
That means:
 - master pw traveled over HTTP (loopback, but still observable by
   any process that can intercept localhost)
 - master pw sat in the server's process memory (a local string
   variable) for the ~500 ms PBKDF2 took to run
 - a memory dump of PMServer.exe during /login would expose it

This commit moves the PBKDF2 step to the CLIENT and sends only the
hex result (the "verifier") to the server. The master pw never
leaves the browser — server is now zero-knowledge in the everyday
sense (the stored hash and the hash-format remain the same; SRP-
style proper zero-knowledge would be another refactor).

NEW ENDPOINT
============
POST /login/challenge  body { username }
                       -> { salt, kdfIterations, hashAlgo }

First leg of login: client posts username, server returns the params
needed for the client to compute PBKDF2 locally. Per-IP rate-limited.
Returns 404 for unknown user — client masks this as a generic
"Invalid credentials" toast to preserve user-existence opacity
(consistent with the existing /login timing leak).

UPDATED ENDPOINTS
=================
All auth endpoints now accept EITHER plaintext masterPassword OR a
precomputed verifier. New helpers in PM.Handler.Auth:

  function IsValidVerifier(s): 64 hex chars sanity check
  function VerifierToStoredHash(v, algo): SHA-256 wrap (CURRENT) or
                                          identity (LEGACY)
  function CheckVerifier(v, stored, algo): constant-time compare

Endpoint matrix:
  /register        :: salt, kdfIterations, verifier (all client-gen)
                      OR masterPassword (legacy)
  /login           :: verifier OR masterPassword
  /reauth          :: verifier OR masterPassword
  /migrate-kdf     :: oldVerifier + newVerifier OR masterPassword
                      (oldVerifier = under current iters, newVerifier
                      = under target iters)
  /change-master-pw:: currentVerifier + newVerifier + newSalt
                      OR currentMasterPassword + newMasterPassword
  /recovery-key/setup :: verifier OR masterPassword
                         (via VerifyMasterPassword helper updated to
                         accept either input)

When a verifier is present, the server simply applies the SHA-256
wrap (for HASH_ALGO_CURRENT) or compares directly (LEGACY) — no
PBKDF2 work, no plaintext pw in memory.

CLIENT
======
New helpers in app.js:

  bytesToHex(arr) : matches the server's PBKDF2_SHA256_Hex output
                    format (lowercase hex, no separators)
  deriveKeyAndVerifier(pwd, saltHex, iters)
                  : single PBKDF2 → returns BOTH the AES-GCM CryptoKey
                    AND the hex verifier. No double-PBKDF2 cost.
  computeVerifier(pwd, salt, iters)
                  : verifier-only variant for places that don't need
                    the CryptoKey (reauth, recovery setup, ...).

state.kdfIterations is now tracked + persisted to sessionStorage so
verifier computation works without a fresh /login/challenge round
trip on every reauth / change-pw / recovery setup.

Flows updated:
  doLogin           : POST /login/challenge → derive locally → POST
                      /login with verifier. CryptoKey reused from
                      the same PBKDF2 run.
  doRegister        : client-side randomHexSalt + derive → POST with
                      {salt, kdfIterations, verifier}.
  doUnlock          : verifier from cached salt+iters → POST /reauth.
  runKdfMigration   : compute oldVerifier + newVerifier from same
                      salt at different iters → POST.
  doChangeMasterPassword:
                    : currentVerifier (old salt+iters) + newVerifier
                      (fresh salt, target iters) + newSalt. New key
                      ready in memory by the time we POST.
  doGenerateRecoveryKey:
                    : verifier → /recovery-key/setup.
  enableQuickUnlock,
  doExport          : both /reauth callers switched to verifier.

Persistence
===========
The DPAPI quick-unlock blob (when enabled) now includes kdfIterations
so cold-start restores can correctly re-derive verifiers if reauth
is needed later. Recovery redeem similarly stashes kdfIterations
from the server response.

Backward compat
===============
Server endpoints still accept the legacy masterPassword path so
older client builds keep working through the next deploy. Future
cleanup: drop the plaintext branches once everyone has rolled
forward.

What this does NOT achieve
==========================
This is not SRP / OPAQUE. The stored value on the server IS the
final hash, and a stolen vault.db gives the attacker something they
can directly verify candidate guesses against (offline brute force).
Closing that requires asymmetric proofs (client and server holding
different things), which is a much larger refactor. The realistic
win here is "master pw never transits the network or sits in server
memory" — that's a meaningful reduction in attack surface, not a
cryptographic miracle.
2026-05-23 12:03:41 +01:00
Zaki cca8184b81 feat(auth): change master password with full vault re-encryption
Adds the canonical PM feature: let the user pick a new master password
and have every entry transparently re-encrypted under the new key,
without ever exposing plaintext to the server.

Backend endpoint: POST /change-master-password
==============================================
Body:
  {
    currentMasterPassword,   verified against current stored hash
    newMasterPassword,       basis for the new hash + new client key
    newSalt,                 64-char hex, client-generated
    entries: [{ id, encrypted_password, iv,
                totp_secret?, totp_iv? }, ...]
  }

Flow:
  1. Authenticate + RequireCSRF (caller already logged in).
  2. RejectIfAccountLocked — pw change is brute-forceable through a
     hijacked session, so it respects the same per-account lockout as
     /login.
  3. Verify currentMasterPassword against the stored hash. Branches on
     hash_algo to handle both legacy 'pbkdf2' and current 'pbkdf2-sha256'.
     Wrong pw → RecordFailedAccountAttempt + audit + 401.
  4. Compute new auth hash = SHA256(PBKDF2(new_pw, new_salt, 600k)),
     always using the current scheme (migration baked in).
  5. ATOMIC transaction:
       UPDATE users SET password_hash, salt, kdf_iterations, hash_algo
       UPDATE vault_entries SET encrypted_password, iv, totp_secret, totp_iv
       (per entry)
     Any failure → rollback, user stays on the old config.
  6. DeleteAllUserSessions — every OTHER session is invalidated so a
     leaked old token can't keep working past the rotation. The current
     caller's session stays valid.
  7. ClearAccountLockout + audit_log entry.
  8. Returns { message, salt, kdfIterations }.

Client
======
New modal in index.html (#changeMasterModal) with three password
fields (current / new / confirm) + inline error display. Added a
"Change master password" button in the Settings panel → Account
section. Escape-key handler routes through it like the other modals.

doChangeMasterPassword():
  1. Local validation: all fields filled, new ≥ 8 chars, new == confirm,
     new ≠ current. Fast failure beats a round trip.
  2. randomHexSalt() → 32 secure random bytes, hex-encoded.
  3. Derive newKey = PBKDF2(new_pw, new_salt, 600k).
  4. Walk state.entries: decrypt password + (optional) TOTP under the
     current key, re-encrypt under newKey with fresh random IVs.
     One decrypt failure aborts the whole change — better than partial
     commit.
  5. POST to /change-master-password.
  6. On success: swap state.salt + state.cryptoKey, persistCryptoKey,
     update sessionStorage, refresh cached ciphertexts in state.entries,
     close modal, toast.
  7. On 401 / 429 / generic error: show inline error in the modal so
     the user can fix and retry without re-typing everything.

Threat model notes
==================
 - The current session token stays valid because the new server hash
   only invalidates OTHER sessions. Self-logout would be needlessly
   disruptive (user already proved knowledge of both pws).
 - Server still sees the old + new master pws transiently in /change-
   master-password. Same trade-off as /login — eliminating it requires
   redesigning to send pre-computed verifiers (SRP-style), tracked
   separately.
 - The salt rotates with the password — best-practice against any
   precomputed dictionary attack tied to the previous salt.
2026-05-23 11:11:38 +01:00
Zaki 60aa106a30 fix(crypto): SHA-256 wrap auth hash so vault.db at rest no longer = AES key
THE PROBLEM
===========
Before this commit, users.password_hash stored on the server contained
PBKDF2(pw, salt, iters) in hex — the exact same 32 bytes the client
uses as the AES-GCM key to encrypt every entry. Anyone who got hold of
vault.db (filesystem access, backup leak, etc.) had the encryption key
in their hand, no brute force needed. The increased PBKDF2 iteration
count from the previous commit helped against the cipher-text path,
but the easier path was right there in the user row.

THE FIX
=======
Wrap the PBKDF2 output in SHA-256 before storing:

  password_hash = SHA256(PBKDF2(pw, salt, iters))

SHA-256 is one-way. The stored hash can still be verified at login
(server recomputes PBKDF2 from the posted master pw, then SHA-256s it,
compares to stored), but the AES key can no longer be recovered from
it. At rest, vault.db only contains an irreversible derivative.

The server still sees pw transiently during /login while computing
the comparison — eliminating that requires a redesigned auth
protocol where the client sends a pre-computed verifier (SRP, OPAQUE,
or simply SHA-256(PBKDF2(pw, salt, iters)) sent from the client).
That's a separate, larger refactor. This commit closes the at-rest
hole, which is the realistic attack surface for vault file leaks.

SCHEMA / MARKER
===============
users.hash_algo distinguishes the two schemes:
  'pbkdf2'        — LEGACY (raw hex, = AES key)
  'pbkdf2-sha256' — CURRENT (SHA-256-wrapped, one-way)

A constant HASH_ALGO_CURRENT replaces the string literal everywhere
to avoid silent drift between the writer and the reader sides.

MIGRATION
=========
Folded into the existing /migrate-kdf endpoint introduced for the
100k→600k iteration bump. Login response now signals migration on
EITHER:
  - kdf_iterations < PBKDF2_ITERATIONS_TARGET, OR
  - hash_algo != 'pbkdf2-sha256'

The endpoint handles both transitions in one atomic transaction:
  UPDATE users SET password_hash = SHA256(PBKDF2(pw, salt, 600k)),
                   kdf_iterations = 600000,
                   hash_algo = 'pbkdf2-sha256'
  UPDATE vault_entries SET encrypted_password, iv (per entry, if KDF changed)

Idempotency tightened: the "already at target" short-circuit now
requires BOTH conditions, not just the iteration count. Without this,
users who migrated KDF before this commit landed would have been
stuck on the legacy hash format.

CLIENT
======
runKdfMigration() branches on whether the KDF actually changed:
  - kdfChange (fromIters !== toIters): re-encrypt all entries with the
    new key, send them in the entries array, swap state.cryptoKey on
    success. Shows "Vault security upgraded" toast.
  - !kdfChange (hash format only): skip the entry re-encryption loop
    entirely, send entries: []. Silent — the user didn't perceive a
    weakness change worth toasting about.

LOGIN / REAUTH
==============
Both now branch on hash_algo to pick the right verifier:
  HASH_ALGO_LEGACY  → ConstantTimeEquals(stored, PBKDF2(pw, salt, iters))
  HASH_ALGO_CURRENT → ConstantTimeEquals(stored, SHA256(PBKDF2(pw, salt, iters)))

Same constant-time comparison helper as before. Same legacy bcrypt
fallback (still 501-not-implemented).

ALL THREE SCENARIOS AFTER THIS COMMIT
=====================================
1. New register: starts at HASH_ALGO_CURRENT + 600k. No migration ever.
2. Legacy 100k + 'pbkdf2': full migration on next login (hash format
   + iter count + entry re-encryption) in one transaction.
3. Mid-state (already-migrated KDF + still-'pbkdf2'): hash format
   upgrade only on next login, no entry re-encryption.
2026-05-23 05:19:39 +01:00
Zaki e0e452306e 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.
2026-05-23 04:54:05 +01:00
Zaki 9f6636defc feat(auth): per-account brute-force lockout with exponential backoff
Existing protection was per-IP only (login_attempts table). On a loopback
deployment everyone hits 127.0.0.1, so the per-IP counter is mostly
ornamental — the real attacker is on the same machine. Adds a second
defense layer that tracks failures per username with an exponential
backoff schedule.

Schema:
  account_lockouts (username TEXT PK, failed_count INT,
                    locked_until DATETIME, last_attempt_at, last_attempt_ip)

Backoff after threshold (4+ failures):
  1, 2, 3 failures → no lockout (grace window for typos)
  4th             → 60 s
  5th             → 5 min
  6th             → 15 min
  7th             → 1 h
  8th             → 6 h
  9th and beyond  → 24 h (capped)

Counter resets to 0 on successful login or reauth. Old non-locked rows
older than 30 days are pruned by CleanupExpired alongside the existing
sessions / audit_log / login_attempts cleanups.

Wiring:
 - HandleLogin / HandleReauth both check RejectIfAccountLocked() before
   touching the users table. Lockout responses are 429 with JSON body
   { error, retry_after } and a Retry-After header.
 - Failed attempts are recorded against the username even when the user
   doesn't exist, preventing account enumeration via differential
   "is this account locked?" probes.
 - PBKDF2 hash comparison was already constant-time (ConstantTimeEquals);
   no change there.

Client (js/app.js):
 - api() now preserves response status + body on Error so callers can
   distinguish 429-lockout from other errors.
 - New showLockoutCountdown(seconds) renders a live "Account locked —
   try again in Xm Ys" message in #authHint, disables #loginBtn until
   the countdown reaches 0, then re-enables it.
 - doLogin / doUnlock both branch on err.status === 429 + retry_after
   to call showLockoutCountdown instead of a generic error toast.

Known limitation: an attacker can DoS-lock arbitrary usernames by
spamming /login with that name. This is intentional — the alternative
(per-(username,IP) tracking) would let attackers enumerate accounts.
DoS-lock is acceptable; auth bypass is not.
2026-05-23 00:14:44 +01:00
Zaki 506aee7e6f feat: Delphi backend + JS↔Delphi bridge (clipboard, tray, auto-lock)
Introduces the Delphi 12 FMX backend (PMServer) that hosts the embedded
WebView2 vault on 127.0.0.1, and a native bridge between JS and Delphi
that wires three privacy-focused features:

1. Secure clipboard
   Copying a password registers the Win32 "ExcludeClipboardContentFromMonitorProcessing"
   format alongside CF_UNICODETEXT, so Win+V clipboard history never sees
   the value. Auto-clears after 30s via TTimer. Bridge.copySecure() in
   app.js routes all password/username/secret copy paths through the
   native layer when running inside the Delphi WebView2 (falls back to
   navigator.clipboard for the PHP standalone).

2. Tray icon (X-to-tray when server running)
   Closing the dev panel hides both the form HWND and the TFMAppClass
   per-process proxy window that owns the FMX taskbar entry — the form's
   HWND alone is not the taskbar-visible one in FMX (took some iteration
   to discover). Tray menu: Open, Lock vault, Quit. Clipboard is force-
   cleared on minimize as extra safety. First-time minimize fires a
   balloon notification so the user knows the app is still running.

3. Auto-lock on Windows session lock (Win+L)
   wtsapi32.dll!WTSRegisterSessionNotification on a dedicated message-only
   window. On WM_WTSSESSION_CHANGE / WTS_SESSION_LOCK, the bridge calls
   ExecuteJavaScript('lockVault()'). Same path used by the tray "Lock vault"
   menu item.

Bridge architecture:
 - JS → Delphi via cmd:// URLs intercepted in OnBeforeNavigate
   (pattern lifted from DeskInsight Monaco). Currently exposes
   cmd://clipboard/copy?text=...&clear=... and cmd://clipboard/clear.
 - Delphi → JS via TTMSFNCWebBrowser.ExecuteJavaScript with guarded
   calls (typeof check) so the bridge degrades cleanly if app.js isn't
   loaded yet.

Files:
 - Source/PM.Bridge.pas (new) — TSecureClipboard + TPMBridge
 - UMainForm.pas/.fmx — bridge wiring, FormCloseQuery intercept, tray
   callbacks (BridgeTrayRestore / BridgeLockRequest / BridgeQuit)
 - js/app.js — Bridge object, 5 navigator.clipboard sites migrated to
   Bridge.copySecure with PHP-compatible fallback, Bridge.onTrayRestore
   handler that resets the auto-lock timer

.gitignore extended with Delphi build artifacts (*.dcu, Win32/, Win64/,
__history/, __recovery/, *.identcache, *.dsk, *.local, etc.) so source
checkouts stay clean.
2026-05-22 23:47:57 +01:00