use std::sync::Mutex;
use std::time::{SystemTime, UNIX_EPOCH};
use p256::ecdsa::signature::Verifier;
use p256::ecdsa::{Signature, VerifyingKey};
use serde::Deserialize;
use sha2::{Digest, Sha256};
use subtle::ConstantTimeEq;
use crate::auth::factors::AuthFactors;
use crate::auth::second_factor::SecondFactor;
const CHALLENGE_LEN: usize = 32;
const AUTHENTICATOR_DATA_MIN_LEN: usize = 37;
const FLAG_USER_PRESENT: u8 = 0b0000_0001;
const FLAG_USER_VERIFIED: u8 = 0b0000_0100;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum CoseAlgorithm {
Es256,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum UserVerification {
#[default]
Required,
Preferred,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum PasskeyError {
#[error("a passkey assertion is required")]
NotPresented,
#[error("the passkey assertion is malformed")]
Malformed,
#[error("the assertion names an unknown credential")]
UnknownCredential,
#[error("the assertion is not a webauthn.get ceremony")]
WrongCeremonyType,
#[error("the assertion answers no outstanding challenge")]
ChallengeNotOutstanding,
#[error("the assertion came from an origin this account does not accept")]
UntrustedOrigin,
#[error("the assertion was made for a different relying party")]
WrongRelyingParty,
#[error("the authenticator did not report user presence")]
UserNotPresent,
#[error("the authenticator did not verify the user")]
UserNotVerified,
#[error("the signature counter did not advance; the credential may be cloned")]
ClonedCredential,
#[error("the assertion signature is invalid")]
BadSignature,
#[error("the enrolled credential public key is not a valid P-256 point")]
BadPublicKey,
#[error("the system clock is unreadable, so no challenge expiry can be judged")]
ClockUnreadable,
#[error("the passkey factor state is unusable")]
GuardPoisoned,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Challenge {
bytes: [u8; CHALLENGE_LEN],
}
impl Challenge {
pub fn as_bytes(&self) -> &[u8; CHALLENGE_LEN] {
&self.bytes
}
pub fn to_base64url(&self) -> String {
data_encoding::BASE64URL_NOPAD.encode(&self.bytes)
}
}
pub struct ChallengeIssuer {
ttl_secs: u64,
outstanding: Mutex<Option<(Challenge, u64)>>,
}
impl ChallengeIssuer {
pub fn new(ttl_secs: u64) -> Self {
Self {
ttl_secs,
outstanding: Mutex::new(None),
}
}
pub fn issue(&self, now: u64) -> Result<Challenge, PasskeyError> {
use rand_core::RngCore;
let mut bytes = [0u8; CHALLENGE_LEN];
rand_core::OsRng.fill_bytes(&mut bytes);
let challenge = Challenge { bytes };
let mut slot = self
.outstanding
.lock()
.map_err(|_| PasskeyError::GuardPoisoned)?;
*slot = Some((challenge.clone(), now.saturating_add(self.ttl_secs)));
Ok(challenge)
}
fn consume(&self, presented: &[u8], now: u64) -> Result<(), PasskeyError> {
let mut slot = self
.outstanding
.lock()
.map_err(|_| PasskeyError::GuardPoisoned)?;
let Some((challenge, expires_at)) = slot.as_ref() else {
return Err(PasskeyError::ChallengeNotOutstanding);
};
if now >= *expires_at {
return Err(PasskeyError::ChallengeNotOutstanding);
}
if !bool::from(challenge.bytes.as_slice().ct_eq(presented)) {
return Err(PasskeyError::ChallengeNotOutstanding);
}
*slot = None;
Ok(())
}
}
pub struct PasskeyCredential {
id: Vec<u8>,
public_key: VerifyingKey,
rp_id: String,
sign_count: Mutex<u32>,
}
impl PasskeyCredential {
pub fn new(
id: Vec<u8>,
public_key_sec1: &[u8],
algorithm: CoseAlgorithm,
rp_id: impl Into<String>,
initial_sign_count: u32,
) -> Result<Self, PasskeyError> {
let CoseAlgorithm::Es256 = algorithm;
let public_key = VerifyingKey::from_sec1_bytes(public_key_sec1)
.map_err(|_| PasskeyError::BadPublicKey)?;
Ok(Self {
id,
public_key,
rp_id: rp_id.into(),
sign_count: Mutex::new(initial_sign_count),
})
}
pub fn id(&self) -> &[u8] {
&self.id
}
}
#[derive(Debug, Deserialize)]
struct AssertionEnvelope {
credential_id: String,
authenticator_data: String,
client_data_json: String,
signature: String,
}
#[derive(Debug, Deserialize)]
struct ClientData {
#[serde(rename = "type")]
ceremony_type: String,
challenge: String,
origin: String,
}
pub struct PasskeyFactor {
credential: PasskeyCredential,
challenges: ChallengeIssuer,
accepted_origins: Vec<String>,
user_verification: UserVerification,
clock: Box<dyn PasskeyClock>,
}
impl PasskeyFactor {
pub fn new(
credential: PasskeyCredential,
challenges: ChallengeIssuer,
accepted_origins: Vec<String>,
user_verification: UserVerification,
) -> Self {
Self::with_clock(
credential,
challenges,
accepted_origins,
user_verification,
Box::new(SystemPasskeyClock),
)
}
pub fn with_clock(
credential: PasskeyCredential,
challenges: ChallengeIssuer,
accepted_origins: Vec<String>,
user_verification: UserVerification,
clock: Box<dyn PasskeyClock>,
) -> Self {
Self {
credential,
challenges,
accepted_origins,
user_verification,
clock,
}
}
pub fn issue_challenge(&self) -> Result<Challenge, PasskeyError> {
self.challenges.issue(self.clock.unix_seconds()?)
}
pub fn check(&self, envelope_json: &[u8]) -> Result<(), PasskeyError> {
let envelope: AssertionEnvelope =
serde_json::from_slice(envelope_json).map_err(|_| PasskeyError::Malformed)?;
let credential_id = b64url(&envelope.credential_id)?;
let authenticator_data = b64url(&envelope.authenticator_data)?;
let client_data_json = b64url(&envelope.client_data_json)?;
let signature_der = b64url(&envelope.signature)?;
if !bool::from(self.credential.id.as_slice().ct_eq(&credential_id)) {
return Err(PasskeyError::UnknownCredential);
}
let client_data: ClientData =
serde_json::from_slice(&client_data_json).map_err(|_| PasskeyError::Malformed)?;
if client_data.ceremony_type != "webauthn.get" {
return Err(PasskeyError::WrongCeremonyType);
}
if !self.accepted_origins.contains(&client_data.origin) {
return Err(PasskeyError::UntrustedOrigin);
}
let presented_challenge = b64url(&client_data.challenge)?;
if authenticator_data.len() < AUTHENTICATOR_DATA_MIN_LEN {
return Err(PasskeyError::Malformed);
}
let expected_rp_hash = Sha256::digest(self.credential.rp_id.as_bytes());
if !bool::from(authenticator_data[..32].ct_eq(&expected_rp_hash)) {
return Err(PasskeyError::WrongRelyingParty);
}
let flags = authenticator_data[32];
if flags & FLAG_USER_PRESENT == 0 {
return Err(PasskeyError::UserNotPresent);
}
if self.user_verification == UserVerification::Required && flags & FLAG_USER_VERIFIED == 0 {
return Err(PasskeyError::UserNotVerified);
}
let signature =
Signature::from_der(&signature_der).map_err(|_| PasskeyError::BadSignature)?;
let mut signed = authenticator_data.clone();
signed.extend_from_slice(&Sha256::digest(&client_data_json));
self.credential
.public_key
.verify(&signed, &signature)
.map_err(|_| PasskeyError::BadSignature)?;
self.challenges
.consume(&presented_challenge, self.clock.unix_seconds()?)?;
let presented_count = u32::from_be_bytes(
authenticator_data[33..37]
.try_into()
.expect("a 4-byte slice of a >=37-byte buffer"),
);
let mut stored = self
.credential
.sign_count
.lock()
.map_err(|_| PasskeyError::GuardPoisoned)?;
if !(presented_count == 0 && *stored == 0) && presented_count <= *stored {
return Err(PasskeyError::ClonedCredential);
}
*stored = presented_count;
Ok(())
}
}
impl SecondFactor for PasskeyFactor {
fn name(&self) -> &str {
"passkey"
}
fn verify(&self, factors: &AuthFactors) -> Result<(), String> {
let Some(envelope) = factors.passkey.as_deref() else {
return Err(PasskeyError::NotPresented.to_string());
};
self.check(envelope).map_err(|e| e.to_string())
}
}
fn b64url(s: &str) -> Result<Vec<u8>, PasskeyError> {
data_encoding::BASE64URL_NOPAD
.decode(s.trim_end_matches('=').as_bytes())
.map_err(|_| PasskeyError::Malformed)
}
pub trait PasskeyClock: Send + Sync {
fn unix_seconds(&self) -> Result<u64, PasskeyError>;
}
#[derive(Debug, Clone, Copy, Default)]
pub struct SystemPasskeyClock;
impl PasskeyClock for SystemPasskeyClock {
fn unix_seconds(&self) -> Result<u64, PasskeyError> {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.map_err(|_| PasskeyError::ClockUnreadable)
}
}