taper / server /webauthn.js
abr00kx's picture
Round 2 security fixes (part 4)
cce9364 verified
Raw History Blame Contribute Delete
14.6 kB
// WebAuthn (FIDO2) verification for security keys such as a YubiKey.
//
// Pure functions: no server state. The server keeps the flows (challenges)
// and the stored credentials; this file only checks what an authenticator
// sent. It uses Node's own crypto, so there is no new dependency.
//
// Privacy: attestation says what model of key someone owns, which is a
// fingerprint. `verifyRegistration` reads it, decides a level
// ("attested" or "unattested") and returns nothing else about it: no
// certificate, no AAGUID, no serial number.
import { createHash, createPublicKey, verify as cryptoVerify, X509Certificate } from 'node:crypto';
import { readdirSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
export class WebAuthnError extends Error {}
const bad = (msg) => { throw new WebAuthnError(msg); };
const sha256 = (data) => createHash('sha256').update(data).digest();
const b64u = (buf) => Buffer.from(buf).toString('base64url');
// ---------------------------------------------------------------------------
// CBOR (RFC 8949): only what WebAuthn uses. No tags, no floats, no
// indefinite lengths; bounded depth and size.
// ---------------------------------------------------------------------------
export function cborDecode(buf, { maxDepth = 8 } = {}) {
let pos = 0;
const need = (n) => { if (n < 0 || pos + n > buf.length) bad('CBOR is truncated'); };
const head = () => {
need(1);
const b = buf[pos++];
const major = b >> 5;
const info = b & 31;
let arg;
if (info < 24) arg = info;
else if (info === 24) { need(1); arg = buf[pos++]; }
else if (info === 25) { need(2); arg = buf.readUInt16BE(pos); pos += 2; }
else if (info === 26) { need(4); arg = buf.readUInt32BE(pos); pos += 4; }
else if (info === 27) {
need(8);
const v = buf.readBigUInt64BE(pos);
pos += 8;
if (v > BigInt(Number.MAX_SAFE_INTEGER)) bad('CBOR integer is too large');
arg = Number(v);
} else bad('CBOR uses an unsupported encoding');
return { major, arg, info };
};
const item = (depth) => {
if (depth > maxDepth) bad('CBOR is nested too deeply');
const { major, arg, info } = head();
switch (major) {
case 0: return arg;
case 1: return -1 - arg;
case 2: { need(arg); const v = buf.subarray(pos, pos + arg); pos += arg; return Buffer.from(v); }
case 3: { need(arg); const v = buf.subarray(pos, pos + arg).toString('utf8'); pos += arg; return v; }
case 4: {
if (arg > 1024) bad('CBOR array is too long');
const out = [];
for (let i = 0; i < arg; i++) out.push(item(depth + 1));
return out;
}
case 5: {
if (arg > 1024) bad('CBOR map is too large');
const out = new Map();
for (let i = 0; i < arg; i++) {
const k = item(depth + 1);
if (typeof k !== 'string' && typeof k !== 'number') bad('CBOR map key must be text or an integer');
if (out.has(k)) bad('CBOR map repeats a key');
out.set(k, item(depth + 1));
}
return out;
}
case 7:
if (info === 20) return false;
if (info === 21) return true;
if (info === 22) return null;
return bad('CBOR uses an unsupported simple value');
default: return bad('CBOR uses an unsupported type');
}
};
const value = item(0);
return { value, length: pos };
}
function decodeOne(buf) {
const { value, length } = cborDecode(buf);
if (length !== buf.length) bad('CBOR has trailing bytes');
return value;
}
// ---------------------------------------------------------------------------
// COSE keys and signatures
// ---------------------------------------------------------------------------
export const ALGORITHMS = { ES256: -7, EdDSA: -8, RS256: -257 };
export function coseToKey(coseBytes) {
const m = decodeOne(coseBytes);
if (!(m instanceof Map)) bad('Public key is not a COSE map');
const kty = m.get(1);
const alg = m.get(3);
let jwk;
if (kty === 2 && alg === ALGORITHMS.ES256 && m.get(-1) === 1) {
const x = m.get(-2);
const y = m.get(-3);
if (!Buffer.isBuffer(x) || !Buffer.isBuffer(y) || x.length !== 32 || y.length !== 32) bad('Bad P-256 key');
jwk = { kty: 'EC', crv: 'P-256', x: b64u(x), y: b64u(y) };
} else if (kty === 1 && alg === ALGORITHMS.EdDSA && m.get(-1) === 6) {
const x = m.get(-2);
if (!Buffer.isBuffer(x) || x.length !== 32) bad('Bad Ed25519 key');
jwk = { kty: 'OKP', crv: 'Ed25519', x: b64u(x) };
} else if (kty === 3 && alg === ALGORITHMS.RS256) {
const n = m.get(-1);
const e = m.get(-2);
if (!Buffer.isBuffer(n) || !Buffer.isBuffer(e) || n.length < 256 || n.length > 512) bad('Bad RSA key');
jwk = { kty: 'RSA', n: b64u(n), e: b64u(e) };
} else {
bad('Unsupported public key algorithm (use ES256, EdDSA or RS256)');
}
try {
return { key: createPublicKey({ key: jwk, format: 'jwk' }), alg };
} catch {
return bad('Public key is not valid');
}
}
function verifySig(alg, key, data, sig) {
try {
if (alg === ALGORITHMS.ES256) return cryptoVerify('sha256', data, { key, dsaEncoding: 'der' }, sig);
if (alg === ALGORITHMS.EdDSA) return cryptoVerify(null, data, key, sig);
if (alg === ALGORITHMS.RS256) return cryptoVerify('sha256', data, key, sig);
} catch { /* falls through */ }
return false;
}
// ---------------------------------------------------------------------------
// Authenticator data and client data
// ---------------------------------------------------------------------------
const FLAG_UP = 0x01;
const FLAG_BE = 0x08; // backup eligible: a passkey that can sync, not one device
const FLAG_AT = 0x40;
const FLAG_ED = 0x80;
function parseAuthData(buf, { expectCredential }) {
if (buf.length < 37) bad('Authenticator data is too short');
const out = {
rpIdHash: buf.subarray(0, 32), flags: buf[32], signCount: buf.readUInt32BE(33),
};
let pos = 37;
if (expectCredential) {
if (!(out.flags & FLAG_AT)) bad('No credential in authenticator data');
if (buf.length < pos + 18) bad('Authenticator data is too short');
pos += 16; // AAGUID: read past it and never keep it
const idLen = buf.readUInt16BE(pos);
pos += 2;
if (idLen < 16 || idLen > 1023 || buf.length < pos + idLen) bad('Bad credential id length');
out.credentialId = Buffer.from(buf.subarray(pos, pos + idLen));
pos += idLen;
const { length } = cborDecode(buf.subarray(pos));
out.publicKey = Buffer.from(buf.subarray(pos, pos + length));
pos += length;
} else if (out.flags & FLAG_AT) {
bad('Unexpected credential in an assertion');
}
if (out.flags & FLAG_ED) pos += cborDecode(buf.subarray(pos)).length; // extensions: parsed, ignored
if (pos !== buf.length) bad('Trailing bytes in authenticator data');
return out;
}
function parseClientData(json, { type, challenge, origin }) {
let cd;
try { cd = JSON.parse(Buffer.from(json).toString('utf8')); } catch { return bad('clientDataJSON is not JSON'); }
if (!cd || cd.type !== type) bad(`clientData type must be ${type}`);
if (cd.challenge !== challenge) bad('Wrong challenge');
if (cd.origin !== origin) bad('Wrong origin');
if (cd.crossOrigin === true) bad('Cross-origin requests are refused');
return cd;
}
const bytes = (v, name, max = 8192) => {
if (typeof v !== 'string' || v.length > max * 2) bad(`${name} must be base64url text`);
const buf = Buffer.from(v, 'base64url');
if (buf.toString('base64url') !== v) bad(`${name} is not base64url`);
return buf;
};
// ---------------------------------------------------------------------------
// Attestation: trust roots and chains
// ---------------------------------------------------------------------------
/** Load PEM certificates (*.pem, *.crt) from a directory the operator trusts. */
export function loadRoots(dir) {
if (!dir) return [];
const roots = [];
for (const name of readdirSync(dir)) {
if (!/\.(pem|crt)$/.test(name)) continue;
const text = readFileSync(join(dir, name), 'utf8');
for (const block of text.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g) ?? []) {
roots.push(new X509Certificate(block));
}
}
return roots;
}
function chainsToRoot(x5c, roots, atMs) {
if (!roots.length || !Array.isArray(x5c) || !x5c.length || x5c.length > 5) return false;
let certs;
try { certs = x5c.map((der) => new X509Certificate(der)); } catch { return false; }
const when = new Date(atMs);
const current = (c) => when >= new Date(c.validFrom) && when <= new Date(c.validTo);
if (!certs.every(current) || certs[0].ca) return false; // the attestation certificate itself must not be a CA
for (let i = 0; i + 1 < certs.length; i++) {
if (!certs[i].checkIssued(certs[i + 1]) || !certs[i].verify(certs[i + 1].publicKey)) return false;
if (certs[i + 1].ca !== true) return false; // an issuer in the chain must be a CA
}
const last = certs.at(-1);
return roots.some((r) => current(r) && (r.fingerprint256 === last.fingerprint256 || (last.checkIssued(r) && last.verify(r.publicKey))));
}
// ---------------------------------------------------------------------------
// Registration
// ---------------------------------------------------------------------------
/**
* Check a `navigator.credentials.create()` result.
*
* @param credential {id, rawId, type, response: {clientDataJSON, attestationObject}}, base64url
* @param expect {challenge, origin, rpId, roots, now}
* @returns {credentialId, publicKey, alg, signCount, level}, `publicKey` being the COSE key in base64url
*/
export function verifyRegistration(credential, { challenge, origin, rpId, roots = [], now = Date.now() }) {
if (!credential || credential.type !== 'public-key' || typeof credential.response !== 'object' || credential.response === null) bad('Not a public-key credential');
const clientDataJSON = bytes(credential.response.clientDataJSON, 'clientDataJSON');
parseClientData(clientDataJSON, { type: 'webauthn.create', challenge, origin });
const clientDataHash = sha256(clientDataJSON);
const att = decodeOne(bytes(credential.response.attestationObject, 'attestationObject', 16_384));
if (!(att instanceof Map)) bad('attestationObject is not a map');
const authData = att.get('authData');
if (!Buffer.isBuffer(authData)) bad('No authData');
const ad = parseAuthData(authData, { expectCredential: true });
if (!ad.rpIdHash.equals(sha256(rpId))) bad('Wrong relying party');
if (!(ad.flags & FLAG_UP)) bad('The key was not touched');
if (credential.id !== b64u(ad.credentialId)) bad('Credential id mismatch');
const { key, alg } = coseToKey(ad.publicKey);
const fmt = att.get('fmt');
const stmt = att.get('attStmt');
let level = 'unattested';
const signedData = Buffer.concat([authData, clientDataHash]);
if (fmt === 'packed' && stmt instanceof Map) {
const sig = stmt.get('sig');
if (!Buffer.isBuffer(sig)) bad('Attestation has no signature');
const x5c = stmt.get('x5c');
if (x5c === undefined) {
// Self attestation: signed by the credential's own key. Proves nothing about the device.
if (stmt.get('alg') !== alg || !verifySig(alg, key, signedData, sig)) bad('Bad self-attestation signature');
} else {
if (!Array.isArray(x5c) || !x5c.every(Buffer.isBuffer)) bad('Bad attestation certificates');
let leaf;
try { leaf = new X509Certificate(x5c[0]); } catch { return bad('Bad attestation certificate'); }
if (!verifySig(stmt.get('alg'), leaf.publicKey, signedData, sig)) bad('Bad attestation signature');
if (chainsToRoot(x5c, roots, now) && !(ad.flags & FLAG_BE)) level = 'attested';
}
} else if (fmt === 'fido-u2f' && stmt instanceof Map) {
const sig = stmt.get('sig');
const x5c = stmt.get('x5c');
if (!Buffer.isBuffer(sig) || !Array.isArray(x5c) || x5c.length < 1 || !x5c.every(Buffer.isBuffer)) bad('Bad U2F attestation');
const m = decodeOne(ad.publicKey);
const x = m.get(-2);
const y = m.get(-3);
if (m.get(3) !== ALGORITHMS.ES256 || !Buffer.isBuffer(x) || !Buffer.isBuffer(y)) bad('U2F credentials must use ES256');
const data = Buffer.concat([Buffer.from([0]), ad.rpIdHash, clientDataHash, ad.credentialId, Buffer.from([4]), x, y]);
let leaf;
try { leaf = new X509Certificate(x5c[0]); } catch { return bad('Bad attestation certificate'); }
if (!verifySig(ALGORITHMS.ES256, leaf.publicKey, data, sig)) bad('Bad U2F attestation signature');
if (chainsToRoot(x5c, roots, now)) level = 'attested';
} else if (fmt !== 'none') {
// Formats we don't verify (TPM, Android, Apple…): the key is real, the
// claim about its hardware isn't checked, so it is not "attested".
level = 'unattested';
}
// Nothing about the attestation is returned beyond `level`.
return { credentialId: b64u(ad.credentialId), publicKey: b64u(ad.publicKey), alg, signCount: ad.signCount, level };
}
// ---------------------------------------------------------------------------
// Assertion
// ---------------------------------------------------------------------------
/**
* Check a `navigator.credentials.get()` result against a stored credential.
* Returns the new signature counter. Throws when the proof is wrong, or when
* the counter went backwards (a cloned key).
*
* @param stored {public_key, sign_count}
*/
export function verifyAssertion(credential, { challenge, origin, rpId, stored }) {
if (!credential || credential.type !== 'public-key' || typeof credential.response !== 'object' || credential.response === null) bad('Not a public-key credential');
const clientDataJSON = bytes(credential.response.clientDataJSON, 'clientDataJSON');
parseClientData(clientDataJSON, { type: 'webauthn.get', challenge, origin });
const authData = bytes(credential.response.authenticatorData, 'authenticatorData');
const sig = bytes(credential.response.signature, 'signature');
const ad = parseAuthData(authData, { expectCredential: false });
if (!ad.rpIdHash.equals(sha256(rpId))) bad('Wrong relying party');
if (!(ad.flags & FLAG_UP)) bad('The key was not touched');
const { key, alg } = coseToKey(Buffer.from(stored.public_key, 'base64url'));
if (!verifySig(alg, key, Buffer.concat([authData, sha256(clientDataJSON)]), sig)) bad('Bad signature');
// Many keys always report 0. Otherwise the counter must go up.
if ((ad.signCount !== 0 || stored.sign_count !== 0) && ad.signCount <= stored.sign_count) bad('The key\'s counter went backwards: it may have been cloned');
return ad.signCount;
}