Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Use constant-time comparisons for PIN hashes and PIN auth verification.
- Don’t decrement the PIN retry counter for invalid pinAuth data in `credential_management`.
- Also enforce the `credProtect` extension over U2F/CTAP1.
- Add initial and max usage timer for PIN tokens.

## [v0.4.0-rc.3](https://github.com/trussed-dev/fido-authenticator/releases/tag/v0.4.0-rc.3) (2026-06-01)

Expand Down
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ rand = "0.8.4"
rand_chacha = "0.3"
sha2 = "0.10"
serde_test = "1.0.176"
trussed = { version = "0.2", features = ["aes256-gcm", "virt"] }
trussed = { version = "0.2.1", features = ["aes256-gcm", "virt"] }
trussed-staging = { version = "0.5", features = ["chunked", "hkdf", "virt", "fs-info"] }
trussed-usbip = { version = "0.4", features = ["ctaphid"] }
x509-parser = "0.16"
Expand Down
116 changes: 100 additions & 16 deletions src/ctap2/pin.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use core::time::Duration;

use cosey::EcdhEsHkdf256PublicKey;
use ctap_types::{ctap2::client_pin::Permissions, Error, Result};
use heapless::String;
Expand All @@ -8,13 +10,19 @@ use trussed_core::{
types::{
Bytes, KeyId, KeySerialization, Location, Mechanism, Message, ShortData, StorageAttributes,
},
CryptoClient,
CryptoClient, ManagementClient,
};
use trussed_hkdf::{HkdfClient, KeyOrData, OkmId};

// PIN protocol 1 supports 16 or 32 bytes, PIN protocol 2 requires 32 bytes.
const PIN_TOKEN_LENGTH: usize = 32;

// See § 6.5.2.1 of the spec for a description of the timeouts.
// The spec recommends 30 s for USB and 19.8 s for NFC and smart-card but allows smaller values.
// We use 19 s for simplicity.
const INITIAL_USAGE_TIME_LIMIT: Duration = Duration::from_secs(19);
const MAX_USAGE_TIME_PERIOD: Duration = Duration::from_secs(10 * 60);

#[derive(Clone, Copy, Debug)]
pub enum PinProtocolVersion {
V1,
Expand Down Expand Up @@ -98,7 +106,29 @@ pub struct PinTokenMut<'a, T: CryptoClient> {
trussed: &'a mut T,
}

impl<T: CryptoClient> PinTokenMut<'_, T> {
impl<'a, T: CryptoClient + ManagementClient> PinTokenMut<'a, T> {
pub fn is_in_use(&self) -> bool {
self.pin_token.state.is_in_use()
}

pub fn key_id(&self) -> KeyId {
self.pin_token.key_id
}

pub fn update(&mut self) {
self.pin_token.state.update(self.trussed)
}

pub fn clear_initial_usage_timeout(&mut self) {
if let Some(usage_timeouts) = &mut self.pin_token.state.usage_timeouts {
usage_timeouts.initial_usage_timeout = None;
}
}

pub fn into_inner(self) -> &'a mut PinToken {
self.pin_token
}

pub fn restrict(&mut self, permissions: Permissions, rp_id: Option<String<256>>) {
self.pin_token.state.permissions = permissions;
self.pin_token.state.rp = rp_id.map(|id| Rp::new(self.trussed, id));
Expand Down Expand Up @@ -135,7 +165,55 @@ struct PinTokenState {
rp: Option<Rp>,
is_user_present: bool,
is_user_verified: bool,
is_in_use: bool,
usage_timeouts: Option<PinTokenTimeouts>,
}

impl PinTokenState {
// in spec: pinUvAuthTokenUsageTimerObserver
fn update<T: ManagementClient>(&mut self, trussed: &mut T) {
let Some(usage_timeouts) = &self.usage_timeouts else {
return;
};
let now = syscall!(trussed.uptime()).uptime;

let mut timed_out = false;
if now > usage_timeouts.max_usage_timeout {
timed_out = true;
} else if let Some(initial_usage_timeout) = usage_timeouts.initial_usage_timeout {
if now > initial_usage_timeout {
timed_out = true;
}
}

if timed_out {
self.reset();
}
}

// in spec: stopUsingPinUvAuthToken
fn reset(&mut self) {
*self = Self::default();
}

fn is_in_use(&self) -> bool {
self.usage_timeouts.is_some()
}
}

#[derive(Debug)]
struct PinTokenTimeouts {
initial_usage_timeout: Option<Duration>,
max_usage_timeout: Duration,
}

impl PinTokenTimeouts {
fn new<T: ManagementClient>(trussed: &mut T) -> Self {
let now = syscall!(trussed.uptime()).uptime;
Self {
initial_usage_timeout: Some(now + INITIAL_USAGE_TIME_LIMIT),
max_usage_timeout: now + MAX_USAGE_TIME_PERIOD,
}
}
}

#[derive(Debug)]
Expand Down Expand Up @@ -183,7 +261,7 @@ pub struct PinProtocol<'a, T> {
version: PinProtocolVersion,
}

impl<'a, T: CryptoClient + HkdfClient + HmacSha256 + P256> PinProtocol<'a, T> {
impl<'a, T: CryptoClient + HkdfClient + HmacSha256 + ManagementClient + P256> PinProtocol<'a, T> {
pub fn new(
trussed: &'a mut T,
state: &'a mut PinProtocolState,
Expand All @@ -196,11 +274,15 @@ impl<'a, T: CryptoClient + HkdfClient + HmacSha256 + P256> PinProtocol<'a, T> {
}
}

fn pin_token(&self) -> Option<&PinToken> {
match self.version {
PinProtocolVersion::V1 => self.state.pin_token_v1.as_ref(),
PinProtocolVersion::V2 => self.state.pin_token_v2.as_ref(),
}
fn pin_token_mut(&mut self) -> Option<PinTokenMut<'_, T>> {
let pin_token = match self.version {
PinProtocolVersion::V1 => self.state.pin_token_v1.as_mut(),
PinProtocolVersion::V2 => self.state.pin_token_v2.as_mut(),
};
pin_token.map(|pin_token| PinTokenMut {
pin_token,
trussed: self.trussed,
})
}

pub fn regenerate(&mut self) {
Expand All @@ -227,9 +309,7 @@ impl<'a, T: CryptoClient + HkdfClient + HmacSha256 + P256> PinProtocol<'a, T> {
let mut pin_token = PinToken::generate(self.trussed);
pin_token.state.is_user_present = is_user_present;
pin_token.state.is_user_verified = true;
// TODO: set initial usage time limit
// TODO: start and observe usage timer
pin_token.state.is_in_use = true;
pin_token.state.usage_timeouts = Some(PinTokenTimeouts::new(self.trussed));
let pin_token_field = match self.version {
PinProtocolVersion::V1 => &mut self.state.pin_token_v1,
PinProtocolVersion::V2 => &mut self.state.pin_token_v2,
Expand Down Expand Up @@ -276,12 +356,16 @@ impl<'a, T: CryptoClient + HkdfClient + HmacSha256 + P256> PinProtocol<'a, T> {

// in spec: verify(pinUvAuthToken, ...)
pub fn verify_pin_token(&mut self, data: &[u8], signature: &[u8]) -> Result<&PinToken> {
let pin_token = self.pin_token().ok_or(Error::PinAuthInvalid)?;
if pin_token.state.is_in_use && self.verify(pin_token.key_id, data, signature) {
// We previously checked that `pin_token()` is not None in the first line of this
let mut pin_token = self.pin_token_mut().ok_or(Error::PinAuthInvalid)?;
pin_token.update();
let key_id = pin_token.key_id();
if pin_token.is_in_use() && self.verify(key_id, data, signature) {
// We previously checked that `pin_token_mut()` is not None in the first line of this
// function so this cannot panic, but we cannot return the `pin_token` variable here
// because of the `verify` call after it.
Ok(self.pin_token().unwrap())
let mut pin_token = self.pin_token_mut().unwrap();
pin_token.clear_initial_usage_timeout();
Ok(pin_token.into_inner())
} else {
Err(Error::PinAuthInvalid)
}
Expand Down
135 changes: 124 additions & 11 deletions tests/basic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ pub mod webauthn;
use std::{
collections::{BTreeMap, BTreeSet},
fmt::Debug,
time::Duration,
};

use ciborium::Value;
Expand Down Expand Up @@ -70,9 +71,11 @@ macro_rules! run_tests {
}}
}

const ERR_PIN_AUTH_INVALID: Ctap2Error = Ctap2Error(0x33);

#[test]
fn test_ping() {
virt::run_ctaphid(|device| {
virt::run_ctaphid(|device, _| {
device.ping(&[0xf1, 0xd0]).unwrap();
});
}
Expand Down Expand Up @@ -485,6 +488,123 @@ fn test_get_pin_token_no_pin() {
})
}

fn test_pin_token_timeout(timeout1: Duration, err1: bool, timeout2: Duration, err2: bool) {
let client_data_hash = b"";
let key_agreement_key = KeyAgreementKey::generate();
let rp = Rp::new("example.com");
let user = User::new(b"test");
let pub_key_cred_params = vec![PubKeyCredParam::new("public-key", -7)];
let pin = b"123456";

virt::run_ctap2(|device| {
let shared_secret = get_shared_secret(&device, &key_agreement_key);
set_pin(&device, &key_agreement_key, &shared_secret, pin).unwrap();

let pin_token =
get_pin_token(&device, &key_agreement_key, &shared_secret, pin, 0x01, None).unwrap();
let pin_auth = pin_token.authenticate(client_data_hash);

device.uptime_offset().add(timeout1);

let mut request = MakeCredential::new(
client_data_hash,
rp.clone(),
user.clone(),
pub_key_cred_params.clone(),
);
request.pin_auth = Some(pin_auth);
request.pin_protocol = Some(2);
if err1 {
assert_eq!(device.exec(request), Err(ERR_PIN_AUTH_INVALID));
} else {
device.exec(request).unwrap();
}

device.uptime_offset().add(timeout2);

let mut request =
MakeCredential::new(client_data_hash, rp, user, pub_key_cred_params.clone());
request.pin_auth = Some(pin_auth);
request.pin_protocol = Some(2);
if err2 {
assert_eq!(device.exec(request), Err(ERR_PIN_AUTH_INVALID));
} else {
device.exec(request).unwrap();
}
});
}

#[test]
fn test_pin_token_timeout_ok() {
test_pin_token_timeout(
Duration::from_secs(10),
false,
Duration::from_secs(5 * 60),
false,
);
}

#[test]
fn test_pin_token_timeout_initial() {
test_pin_token_timeout(
Duration::from_secs(60),
true,
Duration::from_secs(5 * 60),
true,
);
}

#[test]
fn test_pin_token_timeout_max() {
test_pin_token_timeout(
Duration::from_secs(10),
false,
Duration::from_secs(10 * 60),
true,
);
}

// This test ensures that an invalid pinAuth value does not count as a usage with regard to the
// initial usage timer.
#[test]
fn test_pin_token_timeout_invalid_pin_auth() {
let client_data_hash = b"";
let key_agreement_key = KeyAgreementKey::generate();
let rp = Rp::new("example.com");
let user = User::new(b"test");
let pub_key_cred_params = vec![PubKeyCredParam::new("public-key", -7)];
let pin = b"123456";

virt::run_ctap2(|device| {
let shared_secret = get_shared_secret(&device, &key_agreement_key);
set_pin(&device, &key_agreement_key, &shared_secret, pin).unwrap();

let pin_token =
get_pin_token(&device, &key_agreement_key, &shared_secret, pin, 0x01, None).unwrap();
let pin_auth = pin_token.authenticate(client_data_hash);

device.uptime_offset().add(Duration::from_secs(10));

let mut request = MakeCredential::new(
client_data_hash,
rp.clone(),
user.clone(),
pub_key_cred_params.clone(),
);
request.pin_auth = Some([0; 32]);
request.pin_protocol = Some(2);
assert_eq!(device.exec(request), Err(ERR_PIN_AUTH_INVALID));

device.uptime_offset().add(Duration::from_secs(30));

let mut request =
MakeCredential::new(client_data_hash, rp, user, pub_key_cred_params.clone());
request.pin_auth = Some(pin_auth);
request.pin_protocol = Some(2);
assert_eq!(device.exec(request), Err(ERR_PIN_AUTH_INVALID));
});
}

#[derive(Clone, Copy, Debug)]
enum RequestPinToken {
InvalidPermissions,
Expand Down Expand Up @@ -3705,7 +3825,6 @@ fn test_get_assertion_empty_rp_id_rejected() {
// Verify that calling commands with a bad PIN auth does not decrement the PIN retry counter.
#[test]
fn test_bad_pin_auth_retries() {
const ERR_PIN_AUTH_INVALID: u8 = 0x33;
let client_data_hash = &[0; 32];
let key_agreement_key = KeyAgreementKey::generate();
let pin = b"123456";
Expand All @@ -3725,7 +3844,7 @@ fn test_bad_pin_auth_retries() {
);
request.pin_auth = Some(pin_auth);
request.pin_protocol = Some(2);
assert_eq!(device.exec(request), Err(Ctap2Error(ERR_PIN_AUTH_INVALID)));
assert_eq!(device.exec(request), Err(ERR_PIN_AUTH_INVALID));

assert_eq!(get_pin_retries(&device), 8);

Expand All @@ -3734,20 +3853,14 @@ fn test_bad_pin_auth_retries() {
request.pin_hash_enc = Some(Vec::new());
request.new_pin_enc = Some(Vec::new());
request.pin_auth = Some(pin_auth);
assert_eq!(
device.exec(request).err(),
Some(Ctap2Error(ERR_PIN_AUTH_INVALID))
);
assert_eq!(device.exec(request).err(), Some(ERR_PIN_AUTH_INVALID));

assert_eq!(get_pin_retries(&device), 8);

let mut request = CredentialManagement::new(0x01);
request.pin_protocol = Some(2);
request.pin_auth = Some(pin_auth);
assert_eq!(
device.exec(request).err(),
Some(Ctap2Error(ERR_PIN_AUTH_INVALID))
);
assert_eq!(device.exec(request).err(), Some(ERR_PIN_AUTH_INVALID));

assert_eq!(get_pin_retries(&device), 8);
});
Expand Down
Loading
Loading