Cotton code
620 lines · 22.4 KB · RustRaw
//! A passkey — a WebAuthn credential Cotton Keys holds as a `passkey` row.//!//! ```text//! make    (rp_id, user_handle, ES256)            → Passkey        a P-256 pair, credential id, COSE key//! attest  (passkey, rp_id, client_data_hash)     → Attestation    registration: authData + a `none` statement//! assert  (passkey, rp_id, client_data_hash, n)  → Assertion      sign-in: authData + DER ECDSA signature//! ```//!//! One implementation for every caller: the iOS credential provider (over FFI,//! later), the Mac importer signing WhatsApp's assertion from the row, and the//! tests. Nobody writes WebAuthn twice.//!//! **Pure**, as the rest of [`crate::keys`]: no clock, no counter store, no//! database. The counter is the caller's; [`make`] reaches for the OS random//! source and [`make_from`] is its sibling taking the bytes.//!//! **The private half** is a P-256 scalar. It leaves this type only by//! [`Passkey::private_scalar`] (for the caller to seal into `private_key_enc`),//! by a signature, and by the drop that wipes it. Not `Clone`, not//! `Serialize`; `Debug` prints the credential id only. Sealing is not here://! this module writes no sealing scheme of its own.//!//! Only ES256 is made. The row's `algorithm` column also names RS256 and EdDSA;//! asking for either is refused with words until somebody needs one.use std::fmt;use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine as _;use p256::ecdsa::signature::Signer as _;use p256::ecdsa::{Signature, SigningKey, VerifyingKey};use p256::elliptic_curve::sec1::FromEncodedPoint as _;use p256::{EncodedPoint, FieldBytes, PublicKey};use rand::RngCore;use sha2::{Digest, Sha256};use zeroize::Zeroizing;/// How many random bytes a credential id is.pub const CREDENTIAL_ID_LEN: usize = 16;/// A WebAuthn user handle is 1 to 64 bytes.pub const USER_HANDLE_MAX: usize = 64;/// A client data hash is SHA-256: 32 bytes.pub const CLIENT_DATA_HASH_LEN: usize = 32;/// authenticatorData flag: the user was present.pub const FLAG_UP: u8 = 0x01;/// authenticatorData flag: the user was verified.pub const FLAG_UV: u8 = 0x04;/// authenticatorData flag: attested credential data follows.pub const FLAG_AT: u8 = 0x40;/// COSE algorithm id of ES256 (ECDSA P-256 with SHA-256).pub const COSE_ALG_ES256: i64 = -7;/// The AAGUID a provider without its own reports: sixteen zero bytes.pub const AAGUID: [u8; 16] = [0; 16];/// The algorithms the row's `algorithm` column names.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Algorithm {    Es256,    Rs256,    EdDsa,}impl Algorithm {    /// The column's spelling.    pub fn as_str(self) -> &'static str {        match self {            Algorithm::Es256 => "ES256",            Algorithm::Rs256 => "RS256",            Algorithm::EdDsa => "EdDSA",        }    }    /// The column's spelling read back; anything else is refused.    pub fn parse(value: &str) -> Result<Algorithm, PasskeyError> {        match value {            "ES256" => Ok(Algorithm::Es256),            "RS256" => Ok(Algorithm::Rs256),            "EdDSA" => Ok(Algorithm::EdDsa),            other => Err(PasskeyError::UnknownAlgorithm(other.to_string())),        }    }}/// Why a passkey call was refused, in words.#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]pub enum PasskeyError {    #[error("{0} passkeys are not made yet: Cotton Vault makes ES256 (P-256) only")]    AlgorithmNotMade(&'static str),    #[error("\"{0}\" is not a passkey algorithm: the column holds ES256, RS256 or EdDSA")]    UnknownAlgorithm(String),    #[error("a passkey needs a site (rp_id)")]    EmptyRpId,    #[error("this passkey is for {held}, not {asked}")]    WrongRpId { held: String, asked: String },    #[error("the account id (user_handle) must be base64url of 1 to 64 bytes")]    BadUserHandle,    #[error("the client data hash must be 32 bytes, not {0}")]    BadClientDataHash(usize),    #[error("the credential id must be base64url bytes")]    BadCredentialId,    #[error("the private key is not a P-256 scalar")]    BadPrivateKey,    #[error("the public key is not an ES256 COSE key: {0}")]    BadPublicKey(&'static str),    #[error("the private key does not belong to this row's public key")]    KeyMismatch,    #[error("the private key could not be sealed")]    NotSealed,    #[error("this passkey's private key does not open with this vault key")]    DoesNotOpen,    #[error("this passkey row has no {0}")]    MissingColumn(&'static str),    #[error("the private key is not PKCS#8 DER: {0}")]    NotPkcs8(String),    #[error("the private key is on {0}, not P-256: Cotton Vault holds ES256 (P-256) only")]    CurveNotP256(String),    #[error("the private key's algorithm {0} is not a passkey algorithm: Cotton Vault holds ES256 (P-256) only")]    UnknownKeyAlgorithm(String),    #[error("the public key {0} is not the one the private key makes")]    PublicKeyMismatch(&'static str),    #[error("a credential id is 1 to 1023 bytes, not {0}")]    BadCredentialIdLength(usize),}/// A passkey with its private half in memory: what a `passkey` row becomes/// once its `private_key_enc` is opened.pub struct Passkey {    /// `rp_id`: the site the key is for, e.g. `whatsapp.com`.    pub rp_id: String,    /// `user_handle`: the site's account id, base64url, echoed on assertion.    pub user_handle: String,    /// `credential_id`: base64url, no padding.    pub credential_id: String,    /// `algorithm`.    pub algorithm: Algorithm,    /// `public_key`: the COSE_Key, base64url.    pub public_key: String,    /// `sign_count` when made: 0.    pub sign_count: u32,    key: SigningKey,}impl fmt::Debug for Passkey {    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {        f.debug_struct("Passkey")            .field("rp_id", &self.rp_id)            .field("credential_id", &self.credential_id)            .finish_non_exhaustive()    }}/// What a provider hands the platform back at registration.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Attestation {    /// The raw credential id.    pub credential_id: Vec<u8>,    /// rpIdHash || flags (UP|UV|AT) || counter || AAGUID || id length || id || COSE key.    pub authenticator_data: Vec<u8>,    /// CBOR `{ "fmt": "none", "attStmt": {}, "authData": authenticator_data }`.    pub attestation_object: Vec<u8>,    /// The client data hash it was asked over, echoed.    pub client_data_hash: [u8; 32],}/// What a provider hands the platform back at sign-in.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Assertion {    /// The raw credential id.    pub credential_id: Vec<u8>,    /// rpIdHash || flags (UP|UV) || counter.    pub authenticator_data: Vec<u8>,    /// DER ECDSA over authenticator_data || client_data_hash.    pub signature: Vec<u8>,    /// The row's `user_handle`, as stored (base64url).    pub user_handle: String,    /// The counter signed.    pub counter: u32,}/// A fresh passkey for `rp_id` and the site's account id, from the OS.pub fn make(rp_id: &str, user_handle: &str, algorithm: Algorithm) -> Result<Passkey, PasskeyError> {    refuse_unmade(algorithm)?;    let mut credential_id = [0u8; CREDENTIAL_ID_LEN];    rand::rngs::OsRng.fill_bytes(&mut credential_id);    let key = SigningKey::random(&mut rand::rngs::OsRng);    build(rp_id, user_handle, algorithm, &credential_id, key)}/// The passkey these bytes make: [`make`]'s sibling for vectors.pub fn make_from(    rp_id: &str,    user_handle: &str,    algorithm: Algorithm,    credential_id: [u8; CREDENTIAL_ID_LEN],    scalar: Zeroizing<[u8; 32]>,) -> Result<Passkey, PasskeyError> {    refuse_unmade(algorithm)?;    let key = signing_key(&scalar)?;    build(rp_id, user_handle, algorithm, &credential_id, key)}/// A row's passkey, its private half the bytes `private_key_enc` opened to./// The scalar must make the row's own public key.pub fn from_row(    rp_id: &str,    user_handle: &str,    credential_id: &str,    algorithm: &str,    public_key: &str,    sign_count: u32,    opened: &[u8],) -> Result<Passkey, PasskeyError> {    let algorithm = Algorithm::parse(algorithm)?;    refuse_unmade(algorithm)?;    check_rp_id(rp_id)?;    check_user_handle(user_handle)?;    decode(credential_id).ok_or(PasskeyError::BadCredentialId)?;    let scalar: [u8; 32] = opened.try_into().map_err(|_| PasskeyError::BadPrivateKey)?;    let key = signing_key(&Zeroizing::new(scalar))?;    if cose_public_key(public_key)? != *key.verifying_key() {        return Err(PasskeyError::KeyMismatch);    }    Ok(Passkey {        rp_id: rp_id.to_string(),        user_handle: user_handle.to_string(),        credential_id: credential_id.to_string(),        algorithm,        public_key: public_key.to_string(),        sign_count,        key,    })}/// The largest credential id WebAuthn allows (§5.1 `rawId`, §6.5.1: at most 1023 bytes).pub const CREDENTIAL_ID_MAX: usize = 1023;/// id-ecPublicKey (RFC 5480 §2.1.1).const OID_EC_PUBLIC_KEY: &str = "1.2.840.10045.2.1";/// rsaEncryption (RFC 8017 Appendix C).const OID_RSA: &str = "1.2.840.113549.1.1.1";/// id-Ed25519 and id-Ed448 (RFC 8410 §3).const OID_ED25519: &str = "1.3.101.112";const OID_ED448: &str = "1.3.101.113";/// A passkey another provider handed over: its private key as PKCS#8 DER/// (RFC 5208 v1, or RFC 5958 v2 `OneAsymmetricKey` with its public key), as/// the Credential Exchange Format carries it (CXF 1.0 §3.3.12 `key`).////// Only a P-256 key is held: any other curve is refused naming the curve, an/// RSA or Ed25519/Ed448 key naming RS256 or EdDSA, and malformed DER in words./// Every public key the DER embeds — the SEC1 `ECPrivateKey`'s `publicKey`/// (RFC 5915 §3) and the v2 `publicKey` (RFC 5958 §2) — must be the one the/// scalar makes. The passkey comes back at sign count 0: CXF §3.3.12 says an/// importer MUST set a zero counter.pub fn from_pkcs8(    rp_id: &str,    user_handle: &[u8],    credential_id: &[u8],    der: &[u8],) -> Result<Passkey, PasskeyError> {    check_rp_id(rp_id)?;    if !(1..=USER_HANDLE_MAX).contains(&user_handle.len()) {        return Err(PasskeyError::BadUserHandle);    }    let id_len = credential_id.len();    if !(1..=CREDENTIAL_ID_MAX).contains(&id_len) {        return Err(PasskeyError::BadCredentialIdLength(id_len));    }    let key = pkcs8_signing_key(der)?;    build(        rp_id,        &URL_SAFE_NO_PAD.encode(user_handle),        Algorithm::Es256,        credential_id,        key,    )}/// The P-256 signing key a PKCS#8 DER holds, its embedded public keys checked.fn pkcs8_signing_key(der: &[u8]) -> Result<SigningKey, PasskeyError> {    use p256::pkcs8::der::Decode as _;    use p256::pkcs8::{AssociatedOid as _, PrivateKeyInfo};    let info = PrivateKeyInfo::try_from(der)        .map_err(|err| PasskeyError::NotPkcs8(format!("not a PrivateKeyInfo ({err})")))?;    let oid = info.algorithm.oid.to_string();    match oid.as_str() {        OID_EC_PUBLIC_KEY => {}        OID_RSA => return Err(PasskeyError::AlgorithmNotMade(Algorithm::Rs256.as_str())),        OID_ED25519 | OID_ED448 => {            return Err(PasskeyError::AlgorithmNotMade(Algorithm::EdDsa.as_str()))        }        _ => return Err(PasskeyError::UnknownKeyAlgorithm(oid)),    }    let curve = info        .algorithm        .parameters_oid()        .map_err(|_| PasskeyError::NotPkcs8("an EC key that does not name its curve".into()))?;    if curve != p256::NistP256::OID {        return Err(PasskeyError::CurveNotP256(curve_name(&curve.to_string())));    }    let ec = sec1::EcPrivateKey::from_der(info.private_key).map_err(|err| {        PasskeyError::NotPkcs8(format!("the EC key inside is not a SEC1 ECPrivateKey ({err})"))    })?;    if let Some(parameters) = ec.parameters {        let inner = parameters            .named_curve()            .ok_or_else(|| PasskeyError::NotPkcs8("the EC key's own curve is not named".into()))?;        if inner != p256::NistP256::OID {            return Err(PasskeyError::CurveNotP256(curve_name(&inner.to_string())));        }    }    let scalar: [u8; 32] = ec        .private_key        .try_into()        .map_err(|_| PasskeyError::BadPrivateKey)?;    let key = signing_key(&Zeroizing::new(scalar))?;    let made = key.verifying_key();    for (embedded, place) in [        (ec.public_key, "inside the EC key"),        (info.public_key, "in the PKCS#8 v2 envelope"),    ] {        if let Some(bytes) = embedded {            match VerifyingKey::from_sec1_bytes(bytes) {                Ok(public) if public == *made => {}                _ => return Err(PasskeyError::PublicKeyMismatch(place)),            }        }    }    Ok(key)}/// A curve OID by the name a person reads (SEC 2 §2, RFC 5480 §2.1.1.1).fn curve_name(oid: &str) -> String {    match oid {        "1.3.132.0.34" => "P-384".into(),        "1.3.132.0.35" => "P-521".into(),        "1.3.132.0.10" => "secp256k1".into(),        other => format!("the curve {other}"),    }}impl Passkey {    /// The private scalar, for the caller to seal into `private_key_enc`.    pub fn private_scalar(&self) -> Zeroizing<Vec<u8>> {        Zeroizing::new(self.key.to_bytes().to_vec())    }    /// The public half the row's `public_key` encodes.    pub fn verifying_key(&self) -> VerifyingKey {        *self.key.verifying_key()    }}/// Registration: the authenticatorData with the attested credential and a/// `none` attestation, at the passkey's own `sign_count`.pub fn attest(    passkey: &Passkey,    rp_id: &str,    client_data_hash: &[u8],) -> Result<Attestation, PasskeyError> {    check_same_rp(passkey, rp_id)?;    let client_data_hash = client_hash(client_data_hash)?;    let credential_id = decode(&passkey.credential_id).ok_or(PasskeyError::BadCredentialId)?;    let cose = decode(&passkey.public_key).ok_or(PasskeyError::BadPublicKey("not base64url"))?;    let id_len = u16::try_from(credential_id.len()).map_err(|_| PasskeyError::BadCredentialId)?;    let mut auth = rp_head(rp_id, FLAG_UP | FLAG_UV | FLAG_AT, passkey.sign_count);    auth.extend_from_slice(&AAGUID);    auth.extend_from_slice(&id_len.to_be_bytes());    auth.extend_from_slice(&credential_id);    auth.extend_from_slice(&cose);    // CTAP2 canonical CBOR: keys ordered shortest first.    let mut object = vec![0xa3];    cbor_text(&mut object, "fmt");    cbor_text(&mut object, "none");    cbor_text(&mut object, "attStmt");    object.push(0xa0);    cbor_text(&mut object, "authData");    cbor_bytes(&mut object, &auth);    Ok(Attestation {        credential_id,        authenticator_data: auth,        attestation_object: object,        client_data_hash,    })}/// Sign-in: authenticatorData at `counter` and its DER ECDSA signature over/// authenticatorData || clientDataHash. Every Cotton caller passes 0, as/// iCloud Keychain does: several devices sign for one row and never count.pub fn assert(    passkey: &Passkey,    rp_id: &str,    client_data_hash: &[u8],    counter: u32,) -> Result<Assertion, PasskeyError> {    check_same_rp(passkey, rp_id)?;    let client_data_hash = client_hash(client_data_hash)?;    let credential_id = decode(&passkey.credential_id).ok_or(PasskeyError::BadCredentialId)?;    let auth = rp_head(rp_id, FLAG_UP | FLAG_UV, counter);    let mut signed = auth.clone();    signed.extend_from_slice(&client_data_hash);    let signature: Signature = passkey.key.sign(&signed);    Ok(Assertion {        credential_id,        authenticator_data: auth,        signature: signature.to_der().as_bytes().to_vec(),        user_handle: passkey.user_handle.clone(),        counter,    })}/// The COSE_Key of an ES256 public key: `{1: 2, 3: -7, -1: 1, -2: x, -3: y}`,/// in CTAP2 canonical order.pub fn cose_key(key: &VerifyingKey) -> Vec<u8> {    let point = key.to_encoded_point(false);    let (x, y) = (point.x().expect("uncompressed"), point.y().expect("uncompressed"));    let mut out = Vec::with_capacity(77);    out.extend_from_slice(&[0xa5, 0x01, 0x02, 0x03, 0x26, 0x20, 0x01]);    out.push(0x21);    cbor_bytes(&mut out, x);    out.push(0x22);    cbor_bytes(&mut out, y);    out}/// A row's `public_key` read back into the key it names. Strict: exactly the/// ES256 COSE_Key [`cose_key`] writes, any key order.pub fn cose_public_key(public_key: &str) -> Result<VerifyingKey, PasskeyError> {    let bytes = decode(public_key).ok_or(PasskeyError::BadPublicKey("not base64url"))?;    let mut at = 0;    let head = *bytes.first().ok_or(PasskeyError::BadPublicKey("empty"))?;    if head != 0xa5 {        return Err(PasskeyError::BadPublicKey("not a five-entry map"));    }    at += 1;    let (mut kty, mut alg, mut crv, mut x, mut y) = (None, None, None, None, None);    for _ in 0..5 {        let label = cbor_small_int(&bytes, &mut at)?;        match label {            1 => kty = Some(cbor_small_int(&bytes, &mut at)?),            3 => alg = Some(cbor_small_int(&bytes, &mut at)?),            -1 => crv = Some(cbor_small_int(&bytes, &mut at)?),            -2 => x = Some(cbor_bstr32(&bytes, &mut at)?),            -3 => y = Some(cbor_bstr32(&bytes, &mut at)?),            _ => return Err(PasskeyError::BadPublicKey("an unknown label")),        }    }    if at != bytes.len() {        return Err(PasskeyError::BadPublicKey("bytes after the map"));    }    if kty != Some(2) {        return Err(PasskeyError::BadPublicKey("kty is not EC2"));    }    if alg != Some(COSE_ALG_ES256) {        return Err(PasskeyError::BadPublicKey("alg is not ES256"));    }    if crv != Some(1) {        return Err(PasskeyError::BadPublicKey("crv is not P-256"));    }    let (x, y) = match (x, y) {        (Some(x), Some(y)) => (x, y),        _ => return Err(PasskeyError::BadPublicKey("x or y missing")),    };    let point = EncodedPoint::from_affine_coordinates(        FieldBytes::from_slice(&x),        FieldBytes::from_slice(&y),        false,    );    let public = Option::<PublicKey>::from(PublicKey::from_encoded_point(&point))        .ok_or(PasskeyError::BadPublicKey("not a point on P-256"))?;    Ok(VerifyingKey::from(public))}fn refuse_unmade(algorithm: Algorithm) -> Result<(), PasskeyError> {    match algorithm {        Algorithm::Es256 => Ok(()),        other => Err(PasskeyError::AlgorithmNotMade(other.as_str())),    }}fn build(    rp_id: &str,    user_handle: &str,    algorithm: Algorithm,    credential_id: &[u8],    key: SigningKey,) -> Result<Passkey, PasskeyError> {    check_rp_id(rp_id)?;    check_user_handle(user_handle)?;    Ok(Passkey {        rp_id: rp_id.to_string(),        user_handle: user_handle.to_string(),        credential_id: URL_SAFE_NO_PAD.encode(credential_id),        algorithm,        public_key: URL_SAFE_NO_PAD.encode(cose_key(key.verifying_key())),        sign_count: 0,        key,    })}fn signing_key(scalar: &Zeroizing<[u8; 32]>) -> Result<SigningKey, PasskeyError> {    SigningKey::from_bytes(FieldBytes::from_slice(scalar.as_ref()))        .map_err(|_| PasskeyError::BadPrivateKey)}fn check_rp_id(rp_id: &str) -> Result<(), PasskeyError> {    if rp_id.trim().is_empty() {        return Err(PasskeyError::EmptyRpId);    }    Ok(())}fn check_user_handle(user_handle: &str) -> Result<(), PasskeyError> {    match decode(user_handle) {        Some(bytes) if (1..=USER_HANDLE_MAX).contains(&bytes.len()) => Ok(()),        _ => Err(PasskeyError::BadUserHandle),    }}fn check_same_rp(passkey: &Passkey, rp_id: &str) -> Result<(), PasskeyError> {    if passkey.rp_id != rp_id {        return Err(PasskeyError::WrongRpId {            held: passkey.rp_id.clone(),            asked: rp_id.to_string(),        });    }    Ok(())}fn client_hash(bytes: &[u8]) -> Result<[u8; 32], PasskeyError> {    bytes.try_into().map_err(|_| PasskeyError::BadClientDataHash(bytes.len()))}fn rp_head(rp_id: &str, flags: u8, counter: u32) -> Vec<u8> {    let mut out = Vec::with_capacity(37);    out.extend_from_slice(&Sha256::digest(rp_id.as_bytes()));    out.push(flags);    out.extend_from_slice(&counter.to_be_bytes());    out}fn decode(value: &str) -> Option<Vec<u8>> {    URL_SAFE_NO_PAD.decode(value).ok()}fn cbor_head(out: &mut Vec<u8>, major: u8, len: usize) {    let major = major << 5;    match len {        0..=23 => out.push(major | len as u8),        24..=0xff => out.extend_from_slice(&[major | 24, len as u8]),        0x100..=0xffff => {            out.push(major | 25);            out.extend_from_slice(&(len as u16).to_be_bytes());        }        _ => {            out.push(major | 26);            out.extend_from_slice(&(len as u32).to_be_bytes());        }    }}fn cbor_bytes(out: &mut Vec<u8>, bytes: &[u8]) {    cbor_head(out, 2, bytes.len());    out.extend_from_slice(bytes);}fn cbor_text(out: &mut Vec<u8>, text: &str) {    cbor_head(out, 3, text.len());    out.extend_from_slice(text.as_bytes());}/// An integer in -24..=23, the only kind a COSE_Key's labels and small values use.fn cbor_small_int(bytes: &[u8], at: &mut usize) -> Result<i64, PasskeyError> {    let byte = *bytes.get(*at).ok_or(PasskeyError::BadPublicKey("cut short"))?;    *at += 1;    let (major, info) = (byte >> 5, i64::from(byte & 0x1f));    match (major, info) {        (0, 0..=23) => Ok(info),        (1, 0..=23) => Ok(-1 - info),        _ => Err(PasskeyError::BadPublicKey("an integer out of shape")),    }}fn cbor_bstr32(bytes: &[u8], at: &mut usize) -> Result<[u8; 32], PasskeyError> {    if bytes.get(*at..*at + 2) != Some(&[0x58, 0x20]) {        return Err(PasskeyError::BadPublicKey("a coordinate is not 32 bytes"));    }    *at += 2;    let coordinate = bytes        .get(*at..*at + 32)        .ok_or(PasskeyError::BadPublicKey("cut short"))?;    *at += 32;    Ok(coordinate.try_into().expect("32 bytes"))}/// Whether a kept passkey is offered at a sign-in: its site is the one the/// request names (`rpId`, a domain, any case), and when the site lists the/// credentials it takes (`allowCredentials`, base64url with or without/// padding) it is one of them. An empty list takes any of the site's. The/// rule the Android provider asks of the core (`passkey.identities {rpId,/// allow}`) and the iPhone's credential identity store applies by site.pub fn offered(kept_rp_id: &str, kept_credential_id: &str, asked_rp_id: &str, allow: &[String]) -> bool {    let asked = asked_rp_id.trim();    if asked.is_empty() || !kept_rp_id.trim().eq_ignore_ascii_case(asked) {        return false;    }    let kept = kept_credential_id.trim_end_matches('=');    allow.is_empty() || allow.iter().any(|id| id.trim().trim_end_matches('=') == kept)}#[cfg(test)]#[path = "passkey_tests.rs"]mod tests;