//! What the server checks of a WebAuthn credential (`spec/webauthn/`), as //! `spec/PASSKEYS.md` orders it: a registration's form, client data, //! attestation object and authenticator data (`registration`), and an //! assertion's form (`assertion`), then its client data, authenticator //! data, signature and count (`verify`). Each refusal says why, for the //! answer's `error_description`. use super::cbor::{self, Value}; use base64::Engine; use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64; use p256::ecdsa::signature::Verifier; use serde_json::{Map, Value as Json}; use sha2::{Digest, Sha256}; /// The relying party: its RP ID and origin (`spec/PASSKEYS.md`, "The relying party"). pub(crate) struct Party<'a> { pub id: &'a str, pub origin: &'a str, } /// The authenticator data's flags (`spec/webauthn/webauthn-3.md`, §6.1). const UP: u8 = 0x01; const UV: u8 = 0x04; const BE: u8 = 0x08; const BS: u8 = 0x10; const AT: u8 = 0x40; const ED: u8 = 0x80; /// The transports a passkey keeps, of those a credential names. const TRANSPORTS: [&str; 6] = ["usb", "nfc", "ble", "smart-card", "hybrid", "internal"]; /// The longest credential ID (§6.5.1). const MAX_ID: usize = 1023; /// A refusal, and why. type Refused = String; fn refused(why: &str) -> Result { Err(why.to_string()) } /// A passkey's public key, of one of the relying party's algorithms. #[derive(Clone, Debug, PartialEq, Eq)] pub(crate) enum Key { /// ES256: an uncompressed SEC1 point on P-256. Es256(Vec), /// RS256: an RSA modulus and public exponent, big-endian. Rs256 { n: Vec, e: Vec }, } /// What a registration makes: a passkey's credential ID, its public key, /// its signature count, BE and BS, and transports. #[derive(Debug, PartialEq, Eq)] pub(crate) struct Made { pub id: Vec, pub key: Key, pub count: u32, pub be: bool, pub bs: bool, pub transports: Vec, } /// Bytes a JSON member holds as base64url without padding, if it does. fn bytes(m: &Map, k: &str) -> Option> { B64.decode(m.get(k)?.as_str()?).ok() } /// A credential's form, as `PublicKeyCredential.toJSON()` gives it: an /// object with `id` and `rawId` the same string, base64url; `type` /// `public-key`; and a `response` object. Answers its credential ID and /// `response`. fn form(credential: &Json) -> Result<(Vec, &Map), Refused> { let Json::Object(c) = credential else { return refused("The credential must be an object"); }; let (Some(Json::String(id)), Some(Json::String(raw))) = (c.get("id"), c.get("rawId")) else { return refused("The credential's id and rawId must be strings"); }; if id != raw { return refused("The credential's id and rawId differ"); } let Some(raw) = bytes(c, "rawId") else { return refused("The credential's rawId is not base64url"); }; if c.get("type").and_then(Json::as_str) != Some("public-key") { return refused("The credential's type must be public-key"); } let Some(Json::Object(response)) = c.get("response") else { return refused("The credential's response must be an object"); }; Ok((raw, response)) } /// Check client data (§7.1 steps 5 to 11, §7.2 steps 8 to 14): UTF-8, a /// leading byte order mark dropped, a JSON object of `kind`, `challenge` /// (base64url) and the party's origin, not cross-origin and with no top /// origin. fn client_data(party: &Party, data: &[u8], kind: &str, challenge: &str) -> Result<(), Refused> { let Ok(text) = std::str::from_utf8(data) else { return refused("The client data is not UTF-8"); }; let text = text.strip_prefix('\u{feff}').unwrap_or(text); let Ok(Json::Object(c)) = serde_json::from_str::(text) else { return refused("The client data is not a JSON object"); }; if c.get("type").and_then(Json::as_str) != Some(kind) { return refused("The client data is of another type"); } if c.get("challenge").and_then(Json::as_str) != Some(challenge) { return refused("The client data has another challenge"); } if c.get("origin").and_then(Json::as_str) != Some(party.origin) { return refused("The client data has another origin"); } if c.get("crossOrigin") .is_some_and(|v| *v != Json::Bool(false)) { return refused("The client data is cross-origin"); } if c.contains_key("topOrigin") { return refused("The client data has a topOrigin"); } Ok(()) } /// The authenticator data's first 37 bytes (§6.1): `rpIdHash` the party's, /// UP set, UV set, BS set only with BE. Answers its flags, its count, and /// what follows them. fn auth_head<'a>(party: &Party, data: &'a [u8]) -> Result<(u8, u32, &'a [u8]), Refused> { if data.len() < 37 { return refused("The authenticator data is too short"); } if data[..32] != Sha256::digest(party.id.as_bytes())[..] { return refused("The authenticator data is of another RP ID"); } let flags = data[32]; if flags & UP == 0 { return refused("The user was not present"); } if flags & UV == 0 { return refused("The user was not verified"); } if flags & BS != 0 && flags & BE == 0 { return refused("The authenticator data is backed up but not eligible to be"); } let count = u32::from_be_bytes([data[33], data[34], data[35], data[36]]); Ok((flags, count, &data[37..])) } /// What follows in the authenticator data once its other parts are read: /// with ED, one CBOR map, the extensions, ignored; without, nothing. fn extensions(flags: u8, rest: &[u8]) -> Result<(), Refused> { if flags & ED == 0 { return if rest.is_empty() { Ok(()) } else { refused("The authenticator data has more than it says") }; } match cbor::one(rest) { Ok(Value::Map(_)) => Ok(()), _ => refused("The authenticator data's extensions are not one CBOR map"), } } /// A COSE_Key (`spec/webauthn/rfc9052.txt`, §7) of ES256 or RS256. /// ES256's (`rfc9053.txt`, §2.1, §7.1): a map of exactly kty EC2, alg -7, /// crv P-256, and x and y of 32 bytes each, a point on the curve. RS256's /// (`rfc8230.txt`, §4; `rfc8812.txt`, §2): a map of exactly kty RSA, alg /// -257, n of 256 to 512 bytes whose first is not zero, and e of 1 to 8 /// bytes whose first is not zero, odd and at least 3. fn cose_key(v: &Value) -> Option { let (kty, alg) = (Value::Uint(1), Value::Uint(3)); let bytes = |k: &Value| match v.get(k) { Some(Value::Bytes(b)) => Some(b.clone()), _ => None, }; match (v.get(&kty), v.get(&alg)) { (Some(Value::Uint(2)), Some(Value::Neg(6))) => { let (crv, x, y) = (Value::Neg(0), Value::Neg(1), Value::Neg(2)); if !v.keyed_exactly(&[kty, alg, crv.clone(), x.clone(), y.clone()]) || v.get(&crv) != Some(&Value::Uint(1)) { return None; } let (x, y) = (bytes(&x)?, bytes(&y)?); if x.len() != 32 || y.len() != 32 { return None; } let point = [&[4u8][..], &x, &y].concat(); p256::PublicKey::from_sec1_bytes(&point).ok()?; Some(Key::Es256(point)) } (Some(Value::Uint(3)), Some(Value::Neg(256))) => { let (n_key, e_key) = (Value::Neg(0), Value::Neg(1)); if !v.keyed_exactly(&[kty, alg, n_key.clone(), e_key.clone()]) { return None; } let (n, e) = (bytes(&n_key)?, bytes(&e_key)?); let n_ok = (256..=512).contains(&n.len()) && n[0] != 0; let e_value = e.iter().fold(0u64, |a, &b| (a << 8) | u64::from(b)); let e_ok = (1..=8).contains(&e.len()) && e[0] != 0 && e_value % 2 == 1 && e_value >= 3; (n_ok && e_ok).then_some(Key::Rs256 { n, e }) } _ => None, } } /// A registration's `credential` (`spec/PASSKEYS.md`, "passkey-register", /// checks 3 to 6), for `challenge`, base64url. pub(crate) fn registration( party: &Party, challenge: &str, credential: &Json, ) -> Result { // 3. Its form. let (raw, response) = form(credential)?; let (Some(data), Some(attestation)) = ( bytes(response, "clientDataJSON"), bytes(response, "attestationObject"), ) else { return refused("The response's clientDataJSON and attestationObject must be base64url"); }; let transports = match response.get("transports") { None => vec![], Some(Json::Array(ts)) => { let mut kept: Vec = Vec::new(); for t in ts { let Some(t) = t.as_str() else { return refused("The response's transports must be strings"); }; if TRANSPORTS.contains(&t) && !kept.iter().any(|k| k == t) { kept.push(t.to_string()); } } kept } Some(_) => return refused("The response's transports must be an array"), }; // 4. The client data. client_data(party, &data, "webauthn.create", challenge)?; // 5. The attestation object. let Ok(object) = cbor::one(&attestation) else { return refused("The attestation object is not one CBOR item"); }; let (fmt, statement, auth) = ( Value::Text("fmt".into()), Value::Text("attStmt".into()), Value::Text("authData".into()), ); if !object.keyed_exactly(&[fmt.clone(), statement.clone(), auth.clone()]) { return refused("The attestation object must have fmt, attStmt and authData alone"); } if object.get(&fmt) != Some(&Value::Text("none".into())) { return refused("The attestation must be none"); } if object.get(&statement) != Some(&Value::Map(vec![])) { return refused("The attestation statement must be empty"); } let Some(Value::Bytes(auth)) = object.get(&auth) else { return refused("The authenticator data must be a byte string"); }; // 6. The authenticator data, and the attested credential data. let (flags, count, rest) = auth_head(party, auth)?; if flags & AT == 0 { return refused("The authenticator data has no attested credential data"); } if rest.len() < 18 { return refused("The attested credential data is too short"); } let n = usize::from(u16::from_be_bytes([rest[16], rest[17]])); if n > MAX_ID { return refused("The credential ID is too long"); } let Some(id) = rest.get(18..18 + n) else { return refused("The attested credential data is too short"); }; if id != raw { return refused("The credential ID is not rawId"); } let rest = &rest[18 + n..]; let Ok((key, used)) = cbor::item(rest) else { return refused("The credential public key is not CBOR"); }; let Some(key) = cose_key(&key) else { return refused("The credential public key is no ES256 or RS256 key"); }; extensions(flags, &rest[used..])?; Ok(Made { id: raw, key, count, be: flags & BE != 0, bs: flags & BS != 0, transports, }) } /// An assertion's parts, as `credential` gives them, base64url decoded. pub(crate) struct Assertion { /// Its credential ID. pub id: Vec, pub user_handle: Vec, client_data: Vec, auth_data: Vec, signature: Vec, } /// An assertion's `credential` (`spec/PASSKEYS.md`, "passkey-sign-in", /// check 2): its form. pub(crate) fn assertion(credential: &Json) -> Result { let (id, response) = form(credential)?; let (Some(client_data), Some(auth_data), Some(signature), Some(user_handle)) = ( bytes(response, "clientDataJSON"), bytes(response, "authenticatorData"), bytes(response, "signature"), bytes(response, "userHandle"), ) else { return refused( "The response's clientDataJSON, authenticatorData, signature and userHandle must be base64url", ); }; Ok(Assertion { id, user_handle, client_data, auth_data, signature, }) } /// What a passkey keeps that an assertion is checked against. pub(crate) struct Kept<'a> { pub key: &'a Key, pub count: u32, pub be: bool, } /// What an assertion that passed gives the passkey: its signature count and BS. #[derive(Debug, PartialEq, Eq)] pub(crate) struct Used { pub count: u32, pub bs: bool, } /// An assertion of passkey `kept` (`spec/PASSKEYS.md`, "passkey-sign-in", /// checks 4 to 7), for `challenge`, base64url. pub(crate) fn verify( party: &Party, challenge: &str, a: &Assertion, kept: &Kept, ) -> Result { // 4. The client data. client_data(party, &a.client_data, "webauthn.get", challenge)?; // 5. The authenticator data. let (flags, count, rest) = auth_head(party, &a.auth_data)?; if (flags & BE != 0) != kept.be { return refused("The authenticator data's BE is not the passkey's"); } if flags & AT != 0 { return refused("The authenticator data has attested credential data"); } extensions(flags, rest)?; // 6. The signature. if !signed(kept.key, &a.auth_data, &a.client_data, &a.signature) { return refused("The signature is not the passkey's"); } // 7. The signature count. if (count != 0 || kept.count != 0) && count <= kept.count { return refused("The signature count did not grow"); } Ok(Used { count, bs: flags & BS != 0, }) } /// Whether `signature` is `key`'s signature of the authenticator data and /// the SHA-256 of the client data (§7.2 steps 20 and 21): for ES256, DER, /// an `s` in the upper half of the curve's order taken as in the lower; for /// RS256, RSASSA-PKCS1-v1_5 with SHA-256 (`rfc8017.txt`, §8.2.2), of as /// many bytes as the modulus. fn signed(key: &Key, auth_data: &[u8], client_data: &[u8], signature: &[u8]) -> bool { let mut message = auth_data.to_vec(); message.extend_from_slice(&Sha256::digest(client_data)); match key { Key::Es256(point) => { let (Ok(key), Ok(sig)) = ( p256::ecdsa::VerifyingKey::from_sec1_bytes(point), p256::ecdsa::Signature::from_der(signature), ) else { return false; }; key.verify(&message, &sig.normalize_s()).is_ok() } Key::Rs256 { n, e } => { // The exponent was checked when the key was registered; one // past the crate's own bound is taken as the spec takes it. let key = rsa::PublicKey::new_unchecked( rsa::BoxedUint::from_be_slice_vartime(n), rsa::BoxedUint::from_be_slice_vartime(e), ); signature.len() == n.len() && key .verify( rsa::Pkcs1v15Sign::new::(), &Sha256::digest(&message), signature, ) .is_ok() } } } /// A software authenticator, as `spec/webauthn/webauthn-3.md` describes /// one, for the tests: a P-256 key, a credential ID, a signature count, and /// the flags it sets, writing what it gives byte by byte. #[cfg(test)] pub(crate) mod testing { use super::*; use p256::ecdsa::SigningKey; use p256::ecdsa::signature::Signer; use serde_json::json; pub(crate) struct Authenticator { pub key: SigningKey, pub id: Vec, pub count: u32, pub flags: u8, pub rp_id: String, pub origin: String, } /// A CBOR head of major type `major` and argument `n`. pub(crate) fn head(major: u8, n: usize) -> Vec { let m = major << 5; match n { 0..=23 => vec![m | n as u8], 24..=0xff => vec![m | 24, n as u8], _ => { let n = u16::try_from(n).unwrap(); vec![m | 25, (n >> 8) as u8, n as u8] } } } pub(crate) fn text(s: &str) -> Vec { let mut out = head(3, s.len()); out.extend_from_slice(s.as_bytes()); out } pub(crate) fn byte_string(b: &[u8]) -> Vec { let mut out = head(2, b.len()); out.extend_from_slice(b); out } impl Authenticator { /// One of party `rp_id` at `origin`, its key and ID from `seed`, with UP, UV, BE and BS. pub fn new(rp_id: &str, origin: &str, seed: u8) -> Authenticator { Authenticator { key: SigningKey::from_slice(&[seed.max(1); 32]).unwrap(), id: vec![seed; 16], count: 0, flags: UP | UV | BE | BS, rp_id: rp_id.into(), origin: origin.into(), } } /// Its public key, as a COSE_Key. pub fn cose(&self) -> Vec { let p = self.key.verifying_key().to_sec1_point(false); let mut k = vec![0xa5, 0x01, 0x02, 0x03, 0x26, 0x20, 0x01, 0x21]; k.extend(byte_string(p.x().unwrap())); k.push(0x22); k.extend(byte_string(p.y().unwrap())); k } pub fn client_data(&self, kind: &str, challenge: &str) -> Vec { json!({ "type": kind, "challenge": challenge, "origin": self.origin, "crossOrigin": false }) .to_string() .into_bytes() } /// The first 37 bytes of its authenticator data, with `flags`. pub fn auth_head(&self, flags: u8) -> Vec { let mut d = Sha256::digest(self.rp_id.as_bytes()).to_vec(); d.push(flags); d.extend(self.count.to_be_bytes()); d } /// Its authenticator data for a registration: with AT, its attested credential data. pub fn registration_data(&self) -> Vec { let mut d = self.auth_head(self.flags | AT); d.extend([0u8; 16]); d.extend(u16::try_from(self.id.len()).unwrap().to_be_bytes()); d.extend(&self.id); d.extend(self.cose()); d } pub fn attestation(auth_data: &[u8]) -> Vec { let mut o = vec![0xa3]; o.extend(text("fmt")); o.extend(text("none")); o.extend(text("attStmt")); o.push(0xa0); o.extend(text("authData")); o.extend(byte_string(auth_data)); o } /// A registration's credential, as `toJSON()` gives it, of these parts. pub fn credential(id: &[u8], client_data: &[u8], attestation: &[u8]) -> Json { json!({ "id": B64.encode(id), "rawId": B64.encode(id), "type": "public-key", "response": { "clientDataJSON": B64.encode(client_data), "attestationObject": B64.encode(attestation), "transports": ["internal", "hybrid"] }, "clientExtensionResults": {}, "authenticatorAttachment": "platform", }) } /// Its registration for `challenge`. pub fn register(&self, challenge: &str) -> Json { Self::credential( &self.id, &self.client_data("webauthn.create", challenge), &Self::attestation(&self.registration_data()), ) } /// An assertion's credential of these parts, signed by its key. pub fn signed(&self, client_data: &[u8], auth_data: &[u8], user_handle: &[u8]) -> Json { let mut message = auth_data.to_vec(); message.extend_from_slice(&Sha256::digest(client_data)); let sig: p256::ecdsa::Signature = self.key.sign(&message); json!({ "id": B64.encode(&self.id), "rawId": B64.encode(&self.id), "type": "public-key", "response": { "clientDataJSON": B64.encode(client_data), "authenticatorData": B64.encode(auth_data), "signature": B64.encode(sig.to_der().as_bytes()), "userHandle": B64.encode(user_handle), }, "clientExtensionResults": {}, }) } /// Its assertion for `challenge`, its count one more, past its /// greatest back to zero. pub fn assert(&mut self, challenge: &str, user_handle: &[u8]) -> Json { self.count = self.count.wrapping_add(1); self.signed( &self.client_data("webauthn.get", challenge), &self.auth_head(self.flags), user_handle, ) } } } #[cfg(test)] mod tests { use super::testing::*; use super::*; use serde_json::json; fn hex(s: &str) -> Vec { ::hex::decode(s).unwrap() } const PARTY: Party = Party { id: "example.org", origin: "https://example.org", }; /// `spec/webauthn/webauthn-3.md`, §16.2: ES256 with no attestation. #[test] fn the_es256_test_vector() { let challenge = B64.encode(hex( "00c30fb78531c464d2b6771dab8d7b603c01162f2fa486bea70f283ae556e130", )); let id = hex("f91f391db4c9b2fde0ea70189cba3fb63f579ba6122b33ad94ff3ec330084be4"); let data = hex( "7b2274797065223a22776562617574686e2e637265617465222c226368616c6c656e6765223a22414d4d507434557878475453746e63647134313759447742466938767049612d7077386f4f755657345441222c226f726967696e223a2268747470733a2f2f6578616d706c652e6f7267222c2263726f73734f726967696e223a66616c73652c22657874726144617461223a22636c69656e74446174614a534f4e206d617920626520657874656e6465642077697468206164646974696f6e616c206669656c647320696e20746865206675747572652c207375636820617320746869733a20426b5165446a646354427258426941774a544c453551227d", ); let mut attestation = hex( "a363666d74646e6f6e656761747453746d74a068617574684461746158a4bfabc37432958b063360d3ad6461c9c4735ae7f8edd46592a5e0f01452b2e4b559000000008446ccb9ab1db374750b2367ff6f3a1f0020f91f391db4c9b2fde0ea70189cba3fb63f579ba6122b33ad94ff3ec330084be4a5010203262001215820afefa16f97ca9b2d23eb86ccb64098d20db90856062eb249c33a9b672f26df61225820930a56b87a2fca66334b03458abf879717c12cc68ed73290af2e2664796b9220", ); // Its flags (0x59: UP, BE, BS, AT) have UV clear, which the // server requires: as given it is refused, with UV set it is taken. // The authenticator data is its last 0xa4 bytes; its flags follow the RP ID hash. let flags_at = attestation.len() - 0xa4 + 32; assert_eq!(attestation[flags_at], 0x59); let refused = registration( &PARTY, &challenge, &Authenticator::credential(&id, &data, &attestation), ); assert_eq!(refused, Err("The user was not verified".into())); attestation[flags_at] |= UV; let made = registration( &PARTY, &challenge, &Authenticator::credential(&id, &data, &attestation), ) .unwrap(); let key = Key::Es256(hex( "04afefa16f97ca9b2d23eb86ccb64098d20db90856062eb249c33a9b672f26df61930a56b87a2fca66334b03458abf879717c12cc68ed73290af2e2664796b9220", )); assert_eq!( made, Made { id: id.clone(), key: key.clone(), count: 0, be: true, bs: true, transports: vec!["internal".into(), "hybrid".into()], } ); // The assertion: its signature verifies; its flags (0x19: UP, BE, // BS) have UV clear, so the whole assertion is refused for that. let auth_data = hex("bfabc37432958b063360d3ad6461c9c4735ae7f8edd46592a5e0f01452b2e4b51900000000"); let data = hex( "7b2274797065223a22776562617574686e2e676574222c226368616c6c656e6765223a224f63446e55685158756c5455506f334a5558543049393770767a7a59425039745a63685879617630314167222c226f726967696e223a2268747470733a2f2f6578616d706c652e6f7267222c2263726f73734f726967696e223a66616c73657d", ); let signature = hex( "3046022100f50a4e2e4409249c4a853ba361282f09841df4dd4547a13a87780218deffcd380221008480ac0f0b93538174f575bf11a1dd5d78c6e486013f937295ea13653e331e87", ); assert!(signed(&key, &auth_data, &data, &signature)); assert!(!signed(&key, &auth_data, b"{}", &signature)); let challenge = B64.encode(hex( "39c0e7521417ba54d43e8dc95174f423dee9bf3cd804ff6d65c857c9abf4d408", )); let credential = json!({ "id": B64.encode(&id), "rawId": B64.encode(&id), "type": "public-key", "response": { "clientDataJSON": B64.encode(&data), "authenticatorData": B64.encode(&auth_data), "signature": B64.encode(&signature), "userHandle": "" }, }); let a = assertion(&credential).unwrap(); let kept = Kept { key: &key, count: 0, be: true, }; assert_eq!( verify(&PARTY, &challenge, &a, &kept), Err("The user was not verified".into()) ); } fn party(a: &Authenticator) -> Party<'_> { Party { id: &a.rp_id, origin: &a.origin, } } /// Registrations each wrong in one way, refused; the extensions after /// the key with ED, taken. #[test] fn registrations_refused() { let a = Authenticator::new("pds.test", "https://pds.test", 7); let p = party(&a); let c = "Y2hhbGxlbmdl"; assert!(registration(&p, c, &a.register(c)).is_ok()); let data = a.client_data("webauthn.create", c); let reg = |auth: Vec| { Authenticator::credential(&a.id, &data, &Authenticator::attestation(&auth)) }; // A byte after the attestation object. let mut object = Authenticator::attestation(&a.registration_data()); object.push(0); assert!(registration(&p, c, &Authenticator::credential(&a.id, &data, &object)).is_err()); // A byte after the key, and extensions with ED clear; none with ED set. let mut auth = a.registration_data(); auth.push(0xa0); assert!(registration(&p, c, ®(auth.clone())).is_err()); auth[32] |= ED; assert!(registration(&p, c, ®(auth.clone())).is_ok()); auth.pop(); assert!(registration(&p, c, ®(auth)).is_err()); // BS without BE. let mut auth = a.registration_data(); auth[32] &= !BE; assert_eq!( registration(&p, c, ®(auth.clone())), Err("The authenticator data is backed up but not eligible to be".into()) ); auth[32] &= !BS; assert!(registration(&p, c, ®(auth)).is_ok()); // A sixth member of the key. let mut auth = a.registration_data(); let at = auth.len() - a.cose().len(); auth[at] = 0xa6; auth.extend([0x04, 0x00]); assert_eq!( registration(&p, c, ®(auth)), Err("The credential public key is no ES256 or RS256 key".into()) ); // A key off the curve. let mut auth = a.registration_data(); let last = auth.len() - 1; auth[last] ^= 1; assert!(registration(&p, c, ®(auth)).is_err()); // Another challenge, origin and type; and a byte order mark, taken. assert!(registration(&p, "b3RoZXI", &a.register(c)).is_err()); let other = Party { id: "pds.test", origin: "https://pds.test:8443", }; assert!(registration(&other, c, &a.register(c)).is_err()); let mut bom = vec![0xef, 0xbb, 0xbf]; bom.extend(&data); assert!( registration( &p, c, &Authenticator::credential( &a.id, &bom, &Authenticator::attestation(&a.registration_data()) ) ) .is_ok() ); // A rawId other than the id, and padding. let mut cred = a.register(c); cred["rawId"] = json!(B64.encode([1u8; 16])); assert!(registration(&p, c, &cred).is_err()); let mut cred = a.register(c); let padded = format!("{}==", cred["id"].as_str().unwrap()); (cred["id"], cred["rawId"]) = (json!(padded), json!(padded)); assert!(registration(&p, c, &cred).is_err()); } /// Assertions: taken, then refused for a count that did not grow, a /// BE not the passkey's, AT set, or another key; a high `s` taken. #[test] fn assertions() { let mut a = Authenticator::new("pds.test", "https://pds.test", 9); let made = registration(&party(&a), "Yw", &a.register("Yw")).unwrap(); let mut kept_count = made.count; let kept = |count| Kept { key: &made.key, count, be: true, }; let cred = a.assert("Yw", b"handle"); let used = verify( &party(&a), "Yw", &assertion(&cred).unwrap(), &kept(kept_count), ) .unwrap(); assert_eq!(used, Used { count: 1, bs: true }); kept_count = used.count; // The same count again, and a count of zero after one that was not. assert!( verify( &party(&a), "Yw", &assertion(&cred).unwrap(), &kept(kept_count) ) .is_err() ); a.count = u32::MAX; let zero = a.assert("Yw", b"handle"); assert_eq!( verify( &party(&a), "Yw", &assertion(&zero).unwrap(), &kept(kept_count) ), Err("The signature count did not grow".into()) ); // A count of zero, twice, taken. assert!(verify(&party(&a), "Yw", &assertion(&zero).unwrap(), &kept(0)).is_ok()); // BE other than the passkey's. let p = Party { id: "pds.test", origin: "https://pds.test", }; let data = a.client_data("webauthn.get", "Yw"); a.count = 5; let no_be = a.signed(&data, &a.auth_head(UP | UV), b"h"); assert!(verify(&p, "Yw", &assertion(&no_be).unwrap(), &kept(1)).is_err()); let with_at = a.signed(&data, &a.auth_head(a.flags | AT), b"h"); assert!(verify(&p, "Yw", &assertion(&with_at).unwrap(), &kept(1)).is_err()); // Signed by another key. let b = Authenticator::new("pds.test", "https://pds.test", 10); let forged = b.signed(&data, &a.auth_head(a.flags), b"h"); let mut forged = forged; forged["id"] = json!(B64.encode(&a.id)); forged["rawId"] = json!(B64.encode(&a.id)); assert!(verify(&p, "Yw", &assertion(&forged).unwrap(), &kept(1)).is_err()); // The same signature with `s` in the upper half. let good = a.signed(&data, &a.auth_head(a.flags), b"h"); let der = B64 .decode(good["response"]["signature"].as_str().unwrap()) .unwrap(); let low = p256::ecdsa::Signature::from_der(&der) .unwrap() .normalize_s(); let order = hex("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"); let s = low.s().to_bytes(); let mut high = [0u8; 32]; let mut borrow = 0i16; for i in (0..32).rev() { let d = i16::from(order[i]) - i16::from(s[i]) - borrow; (high[i], borrow) = if d < 0 { ((d + 256) as u8, 1) } else { (d as u8, 0) }; } let high = p256::ecdsa::Signature::from_scalars(low.r().to_bytes(), high).unwrap(); let mut upper = good.clone(); upper["response"]["signature"] = json!(B64.encode(high.to_der().as_bytes())); assert!(verify(&p, "Yw", &assertion(&upper).unwrap(), &kept(1)).is_ok()); // A signature that is not DER. let mut raw = good; raw["response"]["signature"] = json!(B64.encode(low.to_bytes())); assert!(verify(&p, "Yw", &assertion(&raw).unwrap(), &kept(1)).is_err()); } /// An RS256 COSE_Key of `n` and `e`. fn rsa_cose(n: &[u8], e: &[u8]) -> Vec { let mut k = vec![0xa4, 0x01, 0x03, 0x03, 0x39, 0x01, 0x00, 0x20]; k.extend(byte_string(n)); k.push(0x21); k.extend(byte_string(e)); k } /// An RSA passkey registers and signs in; keys of the wrong size, /// exponent or type, and a signature a byte short or by another key, are refused. #[test] fn rs256() { use rsa::Generate; use rsa::traits::PublicKeyParts; let a = Authenticator::new("pds.test", "https://pds.test", 11); let p = party(&a); let private = rsa::PrivateKey::generate(); // Its modulus, of the crate's default size, between 2048 and 4096 // bits; its exponent, 65537. let (n, e) = (private.n().as_ref().to_be_bytes().to_vec(), vec![1, 0, 1]); assert!((256..=512).contains(&n.len()) && n[0] != 0); let data = a.client_data("webauthn.create", "Yw"); let with_key = |cose: Vec| { let mut d = a.auth_head(a.flags | AT); d.extend([0u8; 16]); d.extend(u16::try_from(a.id.len()).unwrap().to_be_bytes()); d.extend(&a.id); d.extend(cose); Authenticator::credential(&a.id, &data, &Authenticator::attestation(&d)) }; let made = registration(&p, "Yw", &with_key(rsa_cose(&n, &e))).unwrap(); assert_eq!( made.key, Key::Rs256 { n: n.clone(), e: e.clone() } ); // Refused: n of 255 and 513 bytes, and with a first byte of zero; // e even, and 1; kty EC2 with RS256, and RSA with ES256. let mut zero = n.clone(); zero[0] = 0; let long = vec![1u8; 513]; for (n, e) in [ (vec![1u8; 255], e.clone()), (long, e.clone()), (zero, e.clone()), (n.clone(), vec![1, 0, 0]), (n.clone(), vec![1]), ] { assert!(registration(&p, "Yw", &with_key(rsa_cose(&n, &e))).is_err()); } let mut ec2 = rsa_cose(&n, &e); ec2[2] = 0x02; assert!(registration(&p, "Yw", &with_key(ec2)).is_err()); let mut rsa_es256 = a.cose(); rsa_es256[2] = 0x03; assert!(registration(&p, "Yw", &with_key(rsa_es256)).is_err()); // Its assertions. let sign = |key: &rsa::PrivateKey, client: &[u8], auth: &[u8]| { let mut message = auth.to_vec(); message.extend_from_slice(&Sha256::digest(client)); key.sign( rsa::Pkcs1v15Sign::new::(), &Sha256::digest(&message), ) .unwrap() }; let client = a.client_data("webauthn.get", "Yw"); let auth = a.auth_head(a.flags); let with_sig = |sig: &[u8]| { json!({ "id": B64.encode(&a.id), "rawId": B64.encode(&a.id), "type": "public-key", "response": { "clientDataJSON": B64.encode(&client), "authenticatorData": B64.encode(&auth), "signature": B64.encode(sig), "userHandle": "aA" }, }) }; let kept = Kept { key: &made.key, count: 0, be: true, }; let good = sign(&private, &client, &auth); assert_eq!(good.len(), n.len()); assert!(verify(&p, "Yw", &assertion(&with_sig(&good)).unwrap(), &kept).is_ok()); assert!(verify(&p, "Yw", &assertion(&with_sig(&good[1..])).unwrap(), &kept).is_err()); let other = rsa::PrivateKey::generate(); let forged = sign(&other, &client, &auth); assert!(verify(&p, "Yw", &assertion(&with_sig(&forged)).unwrap(), &kept).is_err()); } }