~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
347 lines · 16.0 KB Raw History
// The harness's own authenticator and client, as spec/webauthn/webauthn-3.md
// describes them, for checks/passkeys.mjs (spec/PASSKEYS.md): a P-256 key
// for each passkey (node:crypto), and the client data, authenticator data
// and `none` attestation objects written byte by byte, with a CBOR encoder
// of its own (spec/webauthn/rfc8949.txt), so that each can be made wrong in
// one way and in one way alone. Each ceremony answers what a browser's
// `toJSON()` gives (`RegistrationResponseJSON`, `AuthenticationResponseJSON`,
// §5.1), every byte string base64url without padding.
//
// What must only be fresh, keys and credential IDs, comes from node:crypto,
// as lib/oauth.mjs's keys do: an ECDSA signature is drawn afresh whatever
// the seed. What a check chooses comes from lib/random.mjs, in the check.

import { createECDH, createHash, createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes, sign as signWith } from 'node:crypto'

export const b64u = (bytes) => Buffer.from(bytes).toString('base64url')
export const sha256 = (bytes) => createHash('sha256').update(bytes).digest()

// ----------------------------------------------------------------- CBOR

/// Bytes written into CBOR as they are, not as an item.
export class Raw {
  constructor(bytes) {
    this.bytes = Buffer.from(bytes)
  }
}

/// A CBOR head: the major type and its argument, in the fewest bytes
/// (spec/webauthn/rfc8949.txt, §3, §4.2.1).
function head(major, n) {
  const m = major << 5
  if (typeof n === 'bigint' || n >= 2 ** 32) {
    const b = Buffer.alloc(9)
    b[0] = m | 27
    b.writeBigUInt64BE(BigInt(n), 1)
    return b
  }
  if (n < 24) return Buffer.from([m | n])
  if (n < 256) return Buffer.from([m | 24, n])
  if (n < 65536) {
    const b = Buffer.alloc(3)
    b[0] = m | 25
    b.writeUInt16BE(n, 1)
    return b
  }
  const b = Buffer.alloc(5)
  b[0] = m | 26
  b.writeUInt32BE(n, 1)
  return b
}

/// One CBOR item: an integer, a byte string (a Buffer or Uint8Array), a
/// text string, an array, a map (a `Map`, its keys of any of these, in its
/// order; or a plain object, its keys text, in theirs), `true`, `false`,
/// `null`, or `Raw` bytes as they are.
export function cbor(v) {
  if (v instanceof Raw) return v.bytes
  if (typeof v === 'number' || typeof v === 'bigint') {
    if (typeof v === 'number' && !Number.isInteger(v)) throw new Error(`no CBOR here for ${v}`)
    return v >= 0 ? head(0, v) : head(1, typeof v === 'bigint' ? -1n - v : -1 - v)
  }
  if (v instanceof Uint8Array) return Buffer.concat([head(2, v.length), Buffer.from(v)])
  if (typeof v === 'string') {
    const b = Buffer.from(v, 'utf8')
    return Buffer.concat([head(3, b.length), b])
  }
  if (Array.isArray(v)) return Buffer.concat([head(4, v.length), ...v.map(cbor)])
  if (v === false) return Buffer.from([0xf4])
  if (v === true) return Buffer.from([0xf5])
  if (v === null) return Buffer.from([0xf6])
  const entries = v instanceof Map ? [...v] : Object.entries(v)
  return Buffer.concat([head(5, entries.length), ...entries.flatMap(([k, x]) => [cbor(k), cbor(x)])])
}

// ---------------------------------------------------------------- P-256

/// The order of P-256's group, for an `s` in its upper half.
const N = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n
const P = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffffn
const B = 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604bn

const toBig = (b) => BigInt(`0x${Buffer.from(b).toString('hex') || '0'}`)
const toBytes = (n, len) => Buffer.from(n.toString(16).padStart(len * 2, '0'), 'hex')
const mod = (a, m) => ((a % m) + m) % m

/// Whether (x, y) is a point on P-256: y² = x³ − 3x + b (mod p).
export const onCurve = (x, y) => {
  const [X, Y] = [toBig(x), toBig(y)]
  return mod(Y * Y - (X * X * X - 3n * X + B), P) === 0n
}

/// A P-256 key: from its private scalar `d` (32 bytes) when given, else a
/// new one. Answers `{privateKey, x, y}`, `x` and `y` 32 bytes each.
export function p256(d) {
  if (!d) {
    const { privateKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' })
    const jwk = privateKey.export({ format: 'jwk' })
    return { privateKey, x: Buffer.from(jwk.x, 'base64url'), y: Buffer.from(jwk.y, 'base64url') }
  }
  const ecdh = createECDH('prime256v1')
  ecdh.setPrivateKey(Buffer.from(d))
  const pub = ecdh.getPublicKey()
  const [x, y] = [pub.subarray(1, 33), pub.subarray(33, 65)]
  const privateKey = createPrivateKey({ format: 'jwk', key: { kty: 'EC', crv: 'P-256', d: b64u(d), x: b64u(x), y: b64u(y) } })
  return { privateKey, x: Buffer.from(x), y: Buffer.from(y) }
}

/// A DER INTEGER of `n` (unsigned), with a 0 byte before a high bit.
const derInt = (n) => {
  const hex = n.toString(16)
  let b = Buffer.from(hex.length % 2 ? `0${hex}` : hex, 'hex')
  if (b[0] >= 0x80) b = Buffer.concat([Buffer.from([0]), b])
  return Buffer.concat([Buffer.from([0x02, b.length]), b])
}
const der = (r, s) => {
  const body = Buffer.concat([derInt(r), derInt(s)])
  return Buffer.concat([Buffer.from([0x30, body.length]), body])
}

/// `r` and `s` of a DER ECDSA signature.
export function rs(sig) {
  const b = Buffer.from(sig)
  let i = 2
  const read = () => {
    const len = b[i + 1]
    const v = toBig(b.subarray(i + 2, i + 2 + len))
    i += 2 + len
    return v
  }
  return { r: read(), s: read() }
}

/// An ES256 signature of `data` by `privateKey`, DER-encoded: with `s` in
/// the lower half of the group's order, or with `high`, in the upper; with
/// `p1363`, as `r ‖ s`, 64 bytes, which is not DER.
export function es256(privateKey, data, { high = false, p1363 = false } = {}) {
  const { r, s } = rs(signWith('sha256', data, { key: privateKey, dsaEncoding: 'der' }))
  const low = s > N / 2n ? N - s : s
  const S = high ? N - low : low
  return p1363 ? Buffer.concat([toBytes(r, 32), toBytes(S, 32)]) : der(r, S)
}

/// An RSA key of `bits` (spec/webauthn/rfc8230.txt, §6.1), its public
/// exponent 65537: `{privateKey, n, e}`, `n` and `e` big-endian bytes with
/// no leading zero.
export function rsa(bits = 2048) {
  const { privateKey } = generateKeyPairSync('rsa', { modulusLength: bits, publicExponent: 65537 })
  const jwk = privateKey.export({ format: 'jwk' })
  return { privateKey, n: Buffer.from(jwk.n, 'base64url'), e: Buffer.from(jwk.e, 'base64url') }
}

/// An RS256 signature of `data` by `privateKey`: RSASSA-PKCS1-v1_5 with
/// SHA-256 (spec/webauthn/rfc8017.txt, §8.2), as many bytes as the modulus.
const rs256 = (privateKey, data) => signWith('sha256', data, privateKey)

/// The passkey's public key as SubjectPublicKeyInfo, DER, as a browser's
/// `getPublicKey()` gives it.
const spki = (pk) => createPublicKey({ format: 'jwk', key: pk.alg === -257 ? { kty: 'RSA', n: b64u(pk.n), e: b64u(pk.e) } : { kty: 'EC', crv: 'P-256', x: b64u(pk.x), y: b64u(pk.y) } }).export({ format: 'der', type: 'spki' })

// ---------------------------------------------------------- the pieces

/// The authenticator data's flags (spec/webauthn/webauthn-3.md, §6.1).
export const FLAG = { UP: 0x01, UV: 0x04, BE: 0x08, BS: 0x10, AT: 0x40, ED: 0x80 }

/// A COSE_Key's bytes (spec/webauthn/rfc9052.txt, §7) from its members in
/// order; `over` sets a member, or with `undefined` takes it out; `extra`
/// adds members after them.
function coseOf(members, { over = {}, extra = [] }) {
  const m = new Map(members)
  for (const [k, v] of Object.entries(over)) {
    if (v === undefined) m.delete(Number(k))
    else m.set(Number(k), v)
  }
  for (const [k, v] of extra) m.set(k, v)
  return cbor(m)
}

/// A COSE_Key of an EC2 P-256 key for ES256 (rfc9053.txt, §2.1, §7.1), in
/// CTAP2's order: `1` kty, `3` alg, `-1` crv, `-2` x, `-3` y; `opts` as
/// `coseOf` takes them.
export const coseKey = (x, y, opts = {}) => coseOf([[1, 2], [3, -7], [-1, 1], [-2, x], [-3, y]], opts)

/// A COSE_Key of an RSA key for RS256 (rfc8230.txt, §4; rfc8812.txt, §2):
/// `1` kty `3`, `3` alg `-257`, `-1` n, `-2` e; `opts` as `coseOf` takes
/// them.
export const rsaKey = (n, e, opts = {}) => coseOf([[1, 3], [3, -257], [-1, n], [-2, e]], opts)

/// The passkey's own COSE_Key.
export const keyOf = (pk) => (pk.alg === -257 ? rsaKey(pk.n, pk.e) : coseKey(pk.x, pk.y))

/// A `clientDataJSON` (§5.8.1, §5.8.1.1's serialization): `type`,
/// `challenge` and `origin`, then `crossOrigin` unless it is `undefined`,
/// then `topOrigin` if given, then `extra`'s members; with `bom`, a UTF-8
/// byte order mark before it.
export function clientData({ type, challenge, origin, crossOrigin = false, topOrigin, extra = {}, bom = false }) {
  const o = { type, challenge, origin }
  if (crossOrigin !== undefined) o.crossOrigin = crossOrigin
  if (topOrigin !== undefined) o.topOrigin = topOrigin
  Object.assign(o, extra)
  const json = Buffer.from(JSON.stringify(o), 'utf8')
  return bom ? Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), json]) : json
}

/// Authenticator data (§6.1): `rpIdHash`, flags, the signature count, then
/// the attested credential data (§6.5.1) if `attested` is given (`{aaguid,
/// credentialId, publicKey, idLength}`, `idLength` the length field as
/// written, the credential ID's own by default), then `extensions`' bytes,
/// then `after`.
export function authData({ rpIdHash, flags, count, attested, extensions, after }) {
  const c = Buffer.alloc(4)
  c.writeUInt32BE(count >>> 0)
  const parts = [Buffer.from(rpIdHash), Buffer.from([flags]), c]
  if (attested) {
    const len = Buffer.alloc(2)
    len.writeUInt16BE(attested.idLength ?? attested.credentialId.length)
    parts.push(Buffer.from(attested.aaguid), len, Buffer.from(attested.credentialId), Buffer.from(attested.publicKey))
  }
  if (extensions) parts.push(Buffer.from(extensions))
  if (after) parts.push(Buffer.from(after))
  return Buffer.concat(parts)
}

/// A `none` attestation object (§6.5.4, §8.7): the map of `fmt`, `attStmt`
/// and `authData`, in that order, then `extra`'s members; then `after`'s
/// bytes.
export function attestationObject({ fmt = 'none', attStmt = {}, authData: data, extra = [], after }) {
  const m = new Map([['fmt', fmt], ['attStmt', attStmt], ['authData', data]])
  for (const [k, v] of extra) m.set(k, v)
  const out = cbor(m)
  return after ? Buffer.concat([out, Buffer.from(after)]) : out
}

// ------------------------------------------------------------- passkeys

/// A passkey, as an authenticator keeps it: its credential ID (`idLength`
/// random bytes), its key, ES256 (`alg` -7) or RS256 (-257, of `bits`),
/// the RP ID it is for, the user handle the registration gave it, whether
/// it is backup eligible (`be`) and backed up (`bs`), and its signature
/// counter: one that counts (`counting`) gives each signature one more than
/// the last, from `count`; one that does not always gives 0. `stored` is
/// the count the server is to hold of it, as the harness knows.
export function newPasskey({ rpId, alg = -7, bits = 2048, idLength = 32, be = true, bs = be, counting = true, count = counting ? 1 : 0, aaguid = Buffer.alloc(16) } = {}) {
  const key = alg === -257 ? { ...rsa(bits), bits } : p256()
  return { id: randomBytes(idLength), alg, ...key, rpId, userHandle: null, be, bs, counting, count, aaguid, stored: null }
}

/// What `registration` takes, each one thing made wrong (or set) while
/// everything else is as a browser makes it:
/// - the client data's `type`, `challenge`, `origin`, `crossOrigin`,
///   `topOrigin`, `bom` (§7.1, steps 5 to 11);
/// - the authenticator data's `rpIdHash`, its flags by name (`UP`, `UV`,
///   `BE`, `BS`, `AT`, `ED`: true or false), `count`, `aaguid`,
///   `credentialId` (the one in it, where `rawId` stays the passkey's),
///   `idLength` (the length field), `key` (a COSE_Key's bytes),
///   `extensions` (a CBOR map's bytes after the key), `after` (bytes after
///   all that) (§6.1, §6.5.1);
/// - the attestation object's `fmt`, `attStmt`, `extraMember` (`[key,
///   value]`, a fourth), `trailing` (bytes after it) (§6.5.4, §8.7);
/// - `transports`, as the browser gives them; and `form`, a function of the
///   JSON that answers what is sent instead.

/// The flags `f` makes of the passkey's own.
function flagsOf(pk, f, attested) {
  const on = { UP: true, UV: true, BE: pk.be, BS: pk.be && pk.bs, AT: attested, ED: false }
  for (const k of Object.keys(FLAG)) if (f[k] !== undefined) on[k] = f[k]
  return Object.entries(on).reduce((n, [k, v]) => (v ? n | FLAG[k] : n), 0)
}

/// The registration a browser gives for `pk` with these options
/// (`{challenge, origin}`, `challenge` base64url); `f` as above. Answers
/// `{json, authData, clientDataJSON}`.
export function registration(pk, { challenge, origin }, f = {}) {
  const cd = clientData({ type: f.type ?? 'webauthn.create', challenge: f.challenge ?? challenge, origin: f.origin ?? origin, crossOrigin: 'crossOrigin' in f ? f.crossOrigin : false, topOrigin: f.topOrigin, bom: f.bom })
  const ed = f.ED ?? false
  const data = authData({
    rpIdHash: f.rpIdHash ?? sha256(pk.rpId),
    flags: flagsOf(pk, { ...f, ED: ed }, f.AT ?? true),
    count: f.count ?? pk.count,
    attested: { aaguid: f.aaguid ?? pk.aaguid, credentialId: f.credentialId ?? pk.id, idLength: f.idLength, publicKey: f.key ?? keyOf(pk) },
    extensions: f.extensions,
    after: f.after,
  })
  const att = attestationObject({ fmt: f.fmt, attStmt: f.attStmt, authData: data, extra: f.extraMember ? [f.extraMember] : [], after: f.trailing })
  const id = b64u(pk.id)
  let json = {
    id,
    rawId: id,
    type: 'public-key',
    response: {
      clientDataJSON: b64u(cd),
      attestationObject: b64u(att),
      authenticatorData: b64u(data),
      transports: f.transports ?? ['internal', 'hybrid'],
      publicKeyAlgorithm: pk.alg,
      publicKey: b64u(spki(pk)),
    },
    authenticatorAttachment: 'platform',
    clientExtensionResults: {},
  }
  if (f.form) json = f.form(json)
  return { json, authData: data, clientDataJSON: cd }
}

/// What `assertion` takes, each one thing made wrong (or set):
/// - the client data's, as `registration`'s, its `type` `webauthn.get`;
/// - the authenticator data's `rpIdHash`, flags by name, `count` (else the
///   counter's next), `extensions` (bytes after the 37), `after`;
/// - `userHandle` (base64url, or `null` for none), `credentialId` (the
///   bytes `id` and `rawId` name);
/// - the signature: by `otherKey`, over `signed` (other bytes, or a
///   function of the authenticator data and the client data that answers
///   them); for ES256, `high` (`s` in the upper half), `p1363` (not DER);
///   for RS256, `short` (its last byte taken off);
/// - `form`, a function of the JSON that answers what is sent instead.

/// The assertion a browser gives for `pk` (`{challenge, origin}`), its
/// counter moved on; `f` as above. Answers `{json, count}`, the count it
/// signed.
export function assertion(pk, { challenge, origin }, f = {}) {
  const cd = clientData({ type: f.type ?? 'webauthn.get', challenge: f.challenge ?? challenge, origin: f.origin ?? origin, crossOrigin: 'crossOrigin' in f ? f.crossOrigin : false, topOrigin: f.topOrigin, bom: f.bom })
  let count = f.count
  if (count === undefined) {
    count = pk.counting ? pk.count + 1 : 0
    if (pk.counting) pk.count = count
  }
  const data = authData({ rpIdHash: f.rpIdHash ?? sha256(pk.rpId), flags: flagsOf(pk, f, false), count, extensions: f.extensions, after: f.after })
  const signed = typeof f.signed === 'function' ? f.signed(data, cd) : (f.signed ?? Buffer.concat([data, sha256(cd)]))
  const by = f.otherKey ?? pk.privateKey
  const whole = pk.alg === -257 ? rs256(by, signed) : es256(by, signed, { high: f.high, p1363: f.p1363 })
  const sig = f.short ? whole.subarray(0, -1) : whole
  const id = b64u(f.credentialId ?? pk.id)
  const userHandle = f.userHandle === undefined ? pk.userHandle : f.userHandle
  let json = {
    id,
    rawId: id,
    type: 'public-key',
    response: { clientDataJSON: b64u(cd), authenticatorData: b64u(data), signature: b64u(sig), ...(userHandle === null ? {} : { userHandle }) },
    authenticatorAttachment: 'platform',
    clientExtensionResults: {},
  }
  if (f.form) json = f.form(json)
  return { json, count }
}

/// A key of no passkey, of `pk`'s algorithm and size, to sign with in its
/// place.
export const otherKey = (pk) => (pk.alg === -257 ? rsa(pk.bits).privateKey : p256().privateKey)