|
| 1 | +import crypto from 'node:crypto' |
| 2 | + |
| 3 | +const DEFAULT_ITERATIONS = 220000 |
| 4 | +const LEGACY_ITERATIONS = 5000 |
| 5 | +const SELF_DESCRIBING_RE = /^(\d+)\$([0-9a-f]{64})$/ |
| 6 | +const LEGACY_PBKDF2_RE = /^[0-9a-f]{64}$/ |
| 7 | +const LEGACY_SHA1_RE = /^[0-9a-f]{40}$/ |
| 8 | + |
| 9 | +// PBKDF2-SHA512 costs ~40ms at the 220k default. This ceiling bounds both a |
| 10 | +// misconfigured env var and a tampered DB row: a stored count is untrusted |
| 11 | +// input to a CPU bound function, so cap the amplification at roughly 4x. |
| 12 | +const MAX_ITERATIONS = 1_000_000 |
| 13 | + |
| 14 | +function validIterations(n) { |
| 15 | + return Number.isSafeInteger(n) && n >= 1 && n <= MAX_ITERATIONS |
| 16 | +} |
| 17 | + |
| 18 | +const PBKDF2_ITERATIONS = (() => { |
| 19 | + const raw = process.env.PBKDF2_ITERATIONS |
| 20 | + if (raw === undefined) return DEFAULT_ITERATIONS |
| 21 | + |
| 22 | + // Number() rather than parseInt(), which would read "220000zzz" as 220000 |
| 23 | + const parsed = Number(raw) |
| 24 | + if (!validIterations(parsed)) { |
| 25 | + console.warn( |
| 26 | + `PBKDF2_ITERATIONS="${raw}" is not an integer in 1..${MAX_ITERATIONS}, using ${DEFAULT_ITERATIONS}`, |
| 27 | + ) |
| 28 | + return DEFAULT_ITERATIONS |
| 29 | + } |
| 30 | + return parsed |
| 31 | +})() |
| 32 | + |
| 33 | +function equalsConstantTime(a, b) { |
| 34 | + const bufA = Buffer.from(a, 'hex') |
| 35 | + const bufB = Buffer.from(b, 'hex') |
| 36 | + if (bufA.length !== bufB.length) return false |
| 37 | + return crypto.timingSafeEqual(bufA, bufB) |
| 38 | +} |
| 39 | + |
| 40 | +/** |
| 41 | + * Password hashing and verification, independent of how users are stored. |
| 42 | + * |
| 43 | + * Hashes are stored self-describing as `iterations$hexHash`, so verification |
| 44 | + * never has to guess a format and a wrong password costs exactly one PBKDF2 |
| 45 | + * computation no matter how many legacy formats have existed. |
| 46 | + */ |
| 47 | +class Credentials { |
| 48 | + constructor(args = {}) { |
| 49 | + this.debug = args?.debug ?? false |
| 50 | + } |
| 51 | + |
| 52 | + generateSalt(length = 16) { |
| 53 | + const chars = Array.from({ length: 87 }, (_, i) => String.fromCharCode(i + 40)) // ASCII 40–126 |
| 54 | + let salt = '' |
| 55 | + for (let i = 0; i < length; i++) { |
| 56 | + salt += chars[Math.floor(Math.random() * 87)] |
| 57 | + } |
| 58 | + return salt |
| 59 | + } |
| 60 | + |
| 61 | + async hashAuthPbkdf2(pass, salt, iterations = PBKDF2_ITERATIONS) { |
| 62 | + return new Promise((resolve, reject) => { |
| 63 | + crypto.pbkdf2(pass, salt, iterations, 32, 'sha512', (err, derivedKey) => { |
| 64 | + if (err) return reject(err) |
| 65 | + resolve(derivedKey.toString('hex')) |
| 66 | + }) |
| 67 | + }) |
| 68 | + } |
| 69 | + |
| 70 | + async hashForStorage(pass, salt, iterations = PBKDF2_ITERATIONS) { |
| 71 | + const hex = await this.hashAuthPbkdf2(pass, salt, iterations) |
| 72 | + return `${iterations}$${hex}` |
| 73 | + } |
| 74 | + |
| 75 | + /** |
| 76 | + * The password/pass_salt pair to persist for a plain text password. |
| 77 | + * |
| 78 | + * Omit `salt` to get a fresh one, which is what a password change and a |
| 79 | + * hash upgrade both want. Pass an existing salt only to preserve a caller |
| 80 | + * supplied one, as create() does for fixtures and imports. |
| 81 | + */ |
| 82 | + async forStorage(pass, salt = this.generateSalt()) { |
| 83 | + return { password: await this.hashForStorage(pass, salt), pass_salt: salt } |
| 84 | + } |
| 85 | + |
| 86 | + async validPassword(passTry, passDb, username, salt) { |
| 87 | + const invalid = { valid: false, needsUpgrade: false } |
| 88 | + |
| 89 | + if (!salt && passTry === passDb) { |
| 90 | + return { valid: true, needsUpgrade: true } |
| 91 | + } |
| 92 | + |
| 93 | + if (salt) { |
| 94 | + // Self-describing format: "iterations$hexHash" — single hash, no fallback |
| 95 | + const m = SELF_DESCRIBING_RE.exec(passDb) |
| 96 | + if (m) { |
| 97 | + const storedIters = parseInt(m[1], 10) |
| 98 | + const storedHashHex = m[2] |
| 99 | + if (!validIterations(storedIters)) { |
| 100 | + console.warn(`refusing stored PBKDF2 iteration count ${storedIters} for user ${username}`) |
| 101 | + return invalid |
| 102 | + } |
| 103 | + |
| 104 | + let hashed |
| 105 | + try { |
| 106 | + hashed = await this.hashAuthPbkdf2(passTry, salt, storedIters) |
| 107 | + } catch (err) { |
| 108 | + console.error(`PBKDF2 failed for user ${username}`, err) |
| 109 | + return invalid |
| 110 | + } |
| 111 | + |
| 112 | + if (this.debug) console.log(`self-describing: ${hashed}`) |
| 113 | + if (equalsConstantTime(hashed, storedHashHex)) { |
| 114 | + return { valid: true, needsUpgrade: storedIters < PBKDF2_ITERATIONS } |
| 115 | + } |
| 116 | + return invalid |
| 117 | + } |
| 118 | + |
| 119 | + // Raw hex (legacy NicTool 2 format, implicitly 5000 iterations). Reject |
| 120 | + // on shape before hashing, so an unrecognized stored value still costs |
| 121 | + // an attempt exactly zero PBKDF2 computations. |
| 122 | + if (!LEGACY_PBKDF2_RE.test(passDb)) return invalid |
| 123 | + |
| 124 | + const legacy = await this.hashAuthPbkdf2(passTry, salt, LEGACY_ITERATIONS) |
| 125 | + if (this.debug) console.log(`legacy: ${legacy}`) |
| 126 | + if (equalsConstantTime(legacy, passDb)) { |
| 127 | + return { valid: true, needsUpgrade: true } |
| 128 | + } |
| 129 | + return invalid |
| 130 | + } |
| 131 | + |
| 132 | + // HMAC SHA-1 (NicTool 2). Verified, never written: a successful match |
| 133 | + // returns needsUpgrade so the caller rewrites it as PBKDF2 immediately. |
| 134 | + // CodeQL js/insufficient-password-hash flags this; dismissed as won't fix. |
| 135 | + if (LEGACY_SHA1_RE.test(passDb)) { |
| 136 | + const digest = crypto.createHmac('sha1', username.toLowerCase()).update(passTry).digest('hex') |
| 137 | + if (this.debug) console.log(`digest: ${digest}`) |
| 138 | + if (equalsConstantTime(digest, passDb)) { |
| 139 | + return { valid: true, needsUpgrade: true } |
| 140 | + } |
| 141 | + } |
| 142 | + |
| 143 | + return invalid |
| 144 | + } |
| 145 | +} |
| 146 | + |
| 147 | +export default new Credentials() |
| 148 | +export { Credentials } |
0 commit comments