361 lines
11 KiB
Rust
361 lines
11 KiB
Rust
//! Passkey assertions produce private, single-use proofs for exact host-owned bindings.
|
|
//! Bootstrap proofs remain valid only while the decision transaction finds no passkeys.
|
|
//! The caller serializes access to this manager and supplies the credentials database.
|
|
use super::{requests::Overrides, types::FieldType};
|
|
use anyhow::{Result, bail};
|
|
use rusqlite::{Connection, params};
|
|
use serde::{Deserialize, Serialize};
|
|
use std::{
|
|
collections::HashMap,
|
|
time::{Duration, Instant},
|
|
};
|
|
use webauthn_rs::prelude::*;
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(rename_all = "snake_case")]
|
|
pub enum Decision {
|
|
Approve,
|
|
Deny,
|
|
}
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(rename_all = "snake_case")]
|
|
pub enum Mutation {
|
|
CreateItem,
|
|
GrantCreate,
|
|
RevokeSubjects,
|
|
ResolveStale,
|
|
}
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
#[serde(tag = "type", deny_unknown_fields)]
|
|
pub enum Binding {
|
|
Decision {
|
|
request_id: String,
|
|
decision: Decision,
|
|
overrides: Overrides,
|
|
payload_sha256: String,
|
|
},
|
|
SecretEntry {
|
|
item: String,
|
|
field: String,
|
|
ciphertext_sha256: String,
|
|
field_type: Option<FieldType>,
|
|
key_type: Option<String>,
|
|
},
|
|
Mutation {
|
|
action: Mutation,
|
|
parameters_sha256: String,
|
|
},
|
|
Enrollment {
|
|
label: String,
|
|
},
|
|
}
|
|
impl Binding {
|
|
pub fn mutation(action: Mutation, parameters: &impl Serialize) -> super::Result<Self> {
|
|
Ok(Self::Mutation {
|
|
action,
|
|
parameters_sha256: digest(&serde_json::to_vec(parameters)?),
|
|
})
|
|
}
|
|
}
|
|
pub(crate) fn digest(bytes: &[u8]) -> String {
|
|
use sha2::{Digest, Sha256};
|
|
hex::encode(Sha256::digest(bytes))
|
|
}
|
|
/// Only successful WebAuthn verification constructs this value. It cannot be cloned.
|
|
pub struct Verified {
|
|
credential: CredentialID,
|
|
binding: Binding,
|
|
}
|
|
impl Verified {
|
|
pub fn credential(&self) -> &CredentialID {
|
|
&self.credential
|
|
}
|
|
pub fn binding(&self) -> &Binding {
|
|
&self.binding
|
|
}
|
|
}
|
|
/// The constructor checks the registry. Every mutation checks it again in its transaction.
|
|
#[derive(Clone, Copy)]
|
|
pub struct Unlocked(());
|
|
pub enum Proof {
|
|
Verified(Verified),
|
|
Unlocked(Unlocked),
|
|
}
|
|
impl From<Verified> for Proof {
|
|
fn from(v: Verified) -> Self {
|
|
Self::Verified(v)
|
|
}
|
|
}
|
|
impl From<Unlocked> for Proof {
|
|
fn from(v: Unlocked) -> Self {
|
|
Self::Unlocked(v)
|
|
}
|
|
}
|
|
impl Proof {
|
|
pub(crate) fn check(
|
|
self,
|
|
db: &Connection,
|
|
expected: &Binding,
|
|
) -> super::Result<Option<String>> {
|
|
match self {
|
|
Self::Unlocked(_) => {
|
|
let unlocked: bool = db.query_row(
|
|
"SELECT NOT EXISTS(SELECT 1 FROM passkey_credentials)",
|
|
[],
|
|
|r| r.get(0),
|
|
)?;
|
|
if !unlocked {
|
|
return Err(super::Error("assertion_required"));
|
|
}
|
|
Ok(None)
|
|
}
|
|
Self::Verified(v) => {
|
|
if &v.binding != expected {
|
|
return Err(super::Error("binding_mismatch"));
|
|
}
|
|
let id = serde_json::to_string(&v.credential)?;
|
|
let registered: bool = db.query_row(
|
|
"SELECT EXISTS(SELECT 1 FROM passkey_credentials WHERE id=?)",
|
|
[&id],
|
|
|r| r.get(0),
|
|
)?;
|
|
if !registered {
|
|
return Err(super::Error("assertion_required"));
|
|
}
|
|
Ok(Some(id))
|
|
}
|
|
}
|
|
}
|
|
}
|
|
impl super::Cred {
|
|
pub fn unlocked(&self) -> super::Result<Unlocked> {
|
|
let s = self.access()?;
|
|
let unlocked: bool = s.db.query_row(
|
|
"SELECT NOT EXISTS(SELECT 1 FROM passkey_credentials)",
|
|
[],
|
|
|r| r.get(0),
|
|
)?;
|
|
if !unlocked {
|
|
return Err(super::Error("assertion_required"));
|
|
}
|
|
Ok(Unlocked(()))
|
|
}
|
|
}
|
|
#[derive(Serialize, Deserialize)]
|
|
pub struct Gate {
|
|
pub id: String,
|
|
pub response: PublicKeyCredential,
|
|
}
|
|
#[derive(Serialize, Deserialize)]
|
|
pub struct Challenge<T> {
|
|
pub id: String,
|
|
pub options: T,
|
|
}
|
|
struct Pending<T> {
|
|
deadline: Instant,
|
|
value: T,
|
|
}
|
|
pub struct Passkeys<'a> {
|
|
db: &'a Connection,
|
|
webauthn: Webauthn,
|
|
registrations: HashMap<String, Pending<(String, bool, PasskeyRegistration)>>,
|
|
assertions: HashMap<String, Pending<(Binding, PasskeyAuthentication)>>,
|
|
}
|
|
impl<'a> Passkeys<'a> {
|
|
pub fn new(db: &'a Connection, rp_id: &str, origin: &str) -> Result<Self> {
|
|
let origin = Url::parse(origin)?;
|
|
let webauthn = WebauthnBuilder::new(rp_id, &origin)?.build()?;
|
|
db.execute_batch("CREATE TABLE IF NOT EXISTS passkey_credentials(id TEXT PRIMARY KEY,label TEXT NOT NULL,credential TEXT NOT NULL)")?;
|
|
Ok(Self {
|
|
db,
|
|
webauthn,
|
|
registrations: HashMap::new(),
|
|
assertions: HashMap::new(),
|
|
})
|
|
}
|
|
/// Database errors leave the manager locked.
|
|
pub fn is_unlocked(&self) -> bool {
|
|
self.db
|
|
.query_row(
|
|
"SELECT NOT EXISTS(SELECT 1 FROM passkey_credentials)",
|
|
[],
|
|
|r| r.get(0),
|
|
)
|
|
.unwrap_or(false)
|
|
}
|
|
fn credentials(&self) -> Result<Vec<Passkey>> {
|
|
let mut q = self
|
|
.db
|
|
.prepare("SELECT credential FROM passkey_credentials")?;
|
|
q.query_map([], |r| r.get::<_, String>(0))?
|
|
.map(|r| Ok(serde_json::from_str(&r?)?))
|
|
.collect()
|
|
}
|
|
pub fn start_registration(
|
|
&mut self,
|
|
label: String,
|
|
gate: Option<Gate>,
|
|
) -> Result<Challenge<CreationChallengeResponse>> {
|
|
let gated = gate.is_some();
|
|
match gate {
|
|
None if !self.is_unlocked() => bail!("enrollment assertion required"),
|
|
None => {}
|
|
Some(Gate { id, response }) => {
|
|
let proof = self.finish_assertion(&id, response)?;
|
|
if proof.binding
|
|
!= (Binding::Enrollment {
|
|
label: label.clone(),
|
|
})
|
|
{
|
|
bail!("invalid enrollment gate");
|
|
}
|
|
}
|
|
}
|
|
let exclude = self
|
|
.credentials()?
|
|
.iter()
|
|
.map(|p| p.cred_id().clone())
|
|
.collect();
|
|
let (options, state) = self.webauthn.start_passkey_registration(
|
|
Uuid::new_v4(),
|
|
&label,
|
|
&label,
|
|
Some(exclude),
|
|
)?;
|
|
trim(&mut self.registrations);
|
|
let id = Uuid::new_v4().to_string();
|
|
self.registrations.insert(
|
|
id.clone(),
|
|
Pending {
|
|
deadline: Instant::now() + Duration::from_secs(300),
|
|
value: (label, gated, state),
|
|
},
|
|
);
|
|
Ok(Challenge { id, options })
|
|
}
|
|
pub fn finish_registration(
|
|
&mut self,
|
|
id: &str,
|
|
response: RegisterPublicKeyCredential,
|
|
) -> Result<Passkey> {
|
|
let unlocked = self.is_unlocked();
|
|
let (label, gated, state) = pending(&mut self.registrations, id)?;
|
|
if !*gated && !unlocked {
|
|
bail!("enrollment assertion required");
|
|
}
|
|
let credential = self
|
|
.webauthn
|
|
.finish_passkey_registration(&response, state)?;
|
|
self.db.execute(
|
|
"INSERT INTO passkey_credentials(id,label,credential) VALUES(?1,?2,?3)",
|
|
params![
|
|
serde_json::to_string(credential.cred_id())?,
|
|
label,
|
|
serde_json::to_string(&credential)?
|
|
],
|
|
)?;
|
|
self.registrations.remove(id);
|
|
Ok(credential)
|
|
}
|
|
pub fn start_assertion(
|
|
&mut self,
|
|
binding: Binding,
|
|
) -> Result<Challenge<RequestChallengeResponse>> {
|
|
let (options, state) = self
|
|
.webauthn
|
|
.start_passkey_authentication(&self.credentials()?)?;
|
|
trim(&mut self.assertions);
|
|
let id = Uuid::new_v4().to_string();
|
|
self.assertions.insert(
|
|
id.clone(),
|
|
Pending {
|
|
deadline: Instant::now() + Duration::from_secs(300),
|
|
value: (binding, state),
|
|
},
|
|
);
|
|
Ok(Challenge { id, options })
|
|
}
|
|
pub fn finish_assertion(
|
|
&mut self,
|
|
id: &str,
|
|
response: PublicKeyCredential,
|
|
) -> Result<Verified> {
|
|
let (binding, state) = pending(&mut self.assertions, id)?;
|
|
let binding = binding.clone();
|
|
let result = self
|
|
.webauthn
|
|
.finish_passkey_authentication(&response, state)?;
|
|
let mut credentials = self.credentials()?;
|
|
let credential = credentials
|
|
.iter_mut()
|
|
.find(|p| p.cred_id() == result.cred_id())
|
|
.ok_or_else(|| anyhow::anyhow!("unregistered passkey"))?;
|
|
let stored = serde_json::to_value(&*credential)?;
|
|
let counter = stored["cred"]["counter"]
|
|
.as_u64()
|
|
.ok_or_else(|| anyhow::anyhow!("invalid stored passkey counter"))?;
|
|
if (counter > 0 || result.counter() > 0) && u64::from(result.counter()) <= counter {
|
|
bail!("passkey counter did not increase");
|
|
}
|
|
credential.update_credential(&result);
|
|
self.db.execute(
|
|
"UPDATE passkey_credentials SET credential=?1 WHERE id=?2",
|
|
params![
|
|
serde_json::to_string(credential)?,
|
|
serde_json::to_string(result.cred_id())?
|
|
],
|
|
)?;
|
|
self.assertions.remove(id);
|
|
Ok(Verified {
|
|
credential: result.cred_id().clone(),
|
|
binding,
|
|
})
|
|
}
|
|
}
|
|
fn pending<'a, T>(map: &'a mut HashMap<String, Pending<T>>, id: &str) -> Result<&'a T> {
|
|
let expired = map
|
|
.get(id)
|
|
.ok_or_else(|| anyhow::anyhow!("unknown or consumed challenge"))?
|
|
.deadline
|
|
<= Instant::now();
|
|
if expired {
|
|
map.remove(id);
|
|
bail!("expired challenge");
|
|
}
|
|
Ok(&map.get(id).expect("checked challenge").value)
|
|
}
|
|
fn trim<T>(map: &mut HashMap<String, Pending<T>>) {
|
|
map.retain(|_, p| p.deadline > Instant::now());
|
|
if map.len() >= 32 {
|
|
let id = map
|
|
.iter()
|
|
.min_by_key(|(_, p)| p.deadline)
|
|
.map(|(id, _)| id.clone())
|
|
.expect("full challenge map");
|
|
map.remove(&id);
|
|
}
|
|
}
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
#[test]
|
|
fn expired_assertion() -> Result<()> {
|
|
use webauthn_authenticator_rs::{WebauthnAuthenticator, softpasskey::SoftPasskey};
|
|
let db = Connection::open_in_memory()?;
|
|
let mut host = Passkeys::new(&db, "localhost", "http://localhost:8000")?;
|
|
let start = host.start_registration("test".into(), None)?;
|
|
let mut auth = WebauthnAuthenticator::new(SoftPasskey::new(true));
|
|
let origin = Url::parse("http://localhost:8000")?;
|
|
let response = auth.do_registration(origin.clone(), start.options)?;
|
|
host.finish_registration(&start.id, response)?;
|
|
let start = host.start_assertion(Binding::Enrollment {
|
|
label: "next".into(),
|
|
})?;
|
|
let response = auth.do_authentication(origin, start.options)?;
|
|
host.assertions.get_mut(&start.id).unwrap().deadline = Instant::now();
|
|
assert!(host.finish_assertion(&start.id, response).is_err());
|
|
assert!(!host.assertions.contains_key(&start.id));
|
|
Ok(())
|
|
}
|
|
}
|