Use Store instead of Storage in Env

This commit is contained in:
Julien Cretin
2022-03-04 17:14:23 +01:00
parent 2e3034193e
commit 732523d380
12 changed files with 1202 additions and 1492 deletions

View File

@@ -19,8 +19,8 @@ use super::data_formats::{
use super::pin_protocol::{verify_pin_uv_auth_token, PinProtocol, SharedSecret}; use super::pin_protocol::{verify_pin_uv_auth_token, PinProtocol, SharedSecret};
use super::response::{AuthenticatorClientPinResponse, ResponseData}; use super::response::{AuthenticatorClientPinResponse, ResponseData};
use super::status_code::Ctap2StatusCode; use super::status_code::Ctap2StatusCode;
use super::storage::PersistentStore;
use super::token_state::PinUvAuthTokenState; use super::token_state::PinUvAuthTokenState;
use crate::ctap::storage;
use crate::env::Env; use crate::env::Env;
use alloc::boxed::Box; use alloc::boxed::Box;
use alloc::str; use alloc::str;
@@ -76,13 +76,13 @@ fn decrypt_pin(
/// The new PIN is passed encrypted, so it is first decrypted and stripped from /// The new PIN is passed encrypted, so it is first decrypted and stripped from
/// padding. Next, it is checked against the PIN policy. Last, it is hashed and /// padding. Next, it is checked against the PIN policy. Last, it is hashed and
/// truncated for persistent storage. /// truncated for persistent storage.
fn check_and_store_new_pin<E: Env>( fn check_and_store_new_pin(
persistent_store: &mut PersistentStore<E>, env: &mut impl Env,
shared_secret: &dyn SharedSecret, shared_secret: &dyn SharedSecret,
new_pin_enc: Vec<u8>, new_pin_enc: Vec<u8>,
) -> Result<(), Ctap2StatusCode> { ) -> Result<(), Ctap2StatusCode> {
let pin = decrypt_pin(shared_secret, new_pin_enc)?; let pin = decrypt_pin(shared_secret, new_pin_enc)?;
let min_pin_length = persistent_store.min_pin_length()? as usize; let min_pin_length = storage::min_pin_length(env)? as usize;
let pin_length = str::from_utf8(&pin).unwrap_or("").chars().count(); let pin_length = str::from_utf8(&pin).unwrap_or("").chars().count();
if pin_length < min_pin_length || pin.len() == PIN_PADDED_LENGTH { if pin_length < min_pin_length || pin.len() == PIN_PADDED_LENGTH {
return Err(Ctap2StatusCode::CTAP2_ERR_PIN_POLICY_VIOLATION); return Err(Ctap2StatusCode::CTAP2_ERR_PIN_POLICY_VIOLATION);
@@ -90,7 +90,7 @@ fn check_and_store_new_pin<E: Env>(
let mut pin_hash = [0u8; PIN_AUTH_LENGTH]; let mut pin_hash = [0u8; PIN_AUTH_LENGTH];
pin_hash.copy_from_slice(&Sha256::hash(&pin[..])[..PIN_AUTH_LENGTH]); pin_hash.copy_from_slice(&Sha256::hash(&pin[..])[..PIN_AUTH_LENGTH]);
// The PIN length is always < PIN_PADDED_LENGTH < 256. // The PIN length is always < PIN_PADDED_LENGTH < 256.
persistent_store.set_pin(&pin_hash, pin_length as u8)?; storage::set_pin(env, &pin_hash, pin_length as u8)?;
Ok(()) Ok(())
} }
@@ -156,28 +156,27 @@ impl ClientPin {
/// Decrypts the encrypted pin_hash and compares it to the stored pin_hash. /// Decrypts the encrypted pin_hash and compares it to the stored pin_hash.
/// Resets or decreases the PIN retries, depending on success or failure. /// Resets or decreases the PIN retries, depending on success or failure.
/// Also, in case of failure, the key agreement key is randomly reset. /// Also, in case of failure, the key agreement key is randomly reset.
fn verify_pin_hash_enc<E: Env>( fn verify_pin_hash_enc(
&mut self, &mut self,
rng: &mut impl Rng256, env: &mut impl Env,
persistent_store: &mut PersistentStore<E>,
pin_uv_auth_protocol: PinUvAuthProtocol, pin_uv_auth_protocol: PinUvAuthProtocol,
shared_secret: &dyn SharedSecret, shared_secret: &dyn SharedSecret,
pin_hash_enc: Vec<u8>, pin_hash_enc: Vec<u8>,
) -> Result<(), Ctap2StatusCode> { ) -> Result<(), Ctap2StatusCode> {
match persistent_store.pin_hash()? { match storage::pin_hash(env)? {
Some(pin_hash) => { Some(pin_hash) => {
if self.consecutive_pin_mismatches >= 3 { if self.consecutive_pin_mismatches >= 3 {
return Err(Ctap2StatusCode::CTAP2_ERR_PIN_AUTH_BLOCKED); return Err(Ctap2StatusCode::CTAP2_ERR_PIN_AUTH_BLOCKED);
} }
persistent_store.decr_pin_retries()?; storage::decr_pin_retries(env)?;
let pin_hash_dec = shared_secret let pin_hash_dec = shared_secret
.decrypt(&pin_hash_enc) .decrypt(&pin_hash_enc)
.map_err(|_| Ctap2StatusCode::CTAP2_ERR_PIN_INVALID)?; .map_err(|_| Ctap2StatusCode::CTAP2_ERR_PIN_INVALID)?;
if !bool::from(pin_hash.ct_eq(&pin_hash_dec)) { if !bool::from(pin_hash.ct_eq(&pin_hash_dec)) {
self.get_mut_pin_protocol(pin_uv_auth_protocol) self.get_mut_pin_protocol(pin_uv_auth_protocol)
.regenerate(rng); .regenerate(env.rng());
if persistent_store.pin_retries()? == 0 { if storage::pin_retries(env)? == 0 {
return Err(Ctap2StatusCode::CTAP2_ERR_PIN_BLOCKED); return Err(Ctap2StatusCode::CTAP2_ERR_PIN_BLOCKED);
} }
self.consecutive_pin_mismatches += 1; self.consecutive_pin_mismatches += 1;
@@ -190,19 +189,19 @@ impl ClientPin {
// This status code is not explicitly mentioned in the specification. // This status code is not explicitly mentioned in the specification.
None => return Err(Ctap2StatusCode::CTAP2_ERR_PUAT_REQUIRED), None => return Err(Ctap2StatusCode::CTAP2_ERR_PUAT_REQUIRED),
} }
persistent_store.reset_pin_retries()?; storage::reset_pin_retries(env)?;
self.consecutive_pin_mismatches = 0; self.consecutive_pin_mismatches = 0;
Ok(()) Ok(())
} }
fn process_get_pin_retries<E: Env>( fn process_get_pin_retries(
&self, &self,
persistent_store: &PersistentStore<E>, env: &mut impl Env,
) -> Result<AuthenticatorClientPinResponse, Ctap2StatusCode> { ) -> Result<AuthenticatorClientPinResponse, Ctap2StatusCode> {
Ok(AuthenticatorClientPinResponse { Ok(AuthenticatorClientPinResponse {
key_agreement: None, key_agreement: None,
pin_uv_auth_token: None, pin_uv_auth_token: None,
retries: Some(persistent_store.pin_retries()? as u64), retries: Some(storage::pin_retries(env)? as u64),
power_cycle_state: Some(self.consecutive_pin_mismatches >= 3), power_cycle_state: Some(self.consecutive_pin_mismatches >= 3),
}) })
} }
@@ -223,9 +222,9 @@ impl ClientPin {
}) })
} }
fn process_set_pin<E: Env>( fn process_set_pin(
&mut self, &mut self,
persistent_store: &mut PersistentStore<E>, env: &mut impl Env,
client_pin_params: AuthenticatorClientPinParameters, client_pin_params: AuthenticatorClientPinParameters,
) -> Result<(), Ctap2StatusCode> { ) -> Result<(), Ctap2StatusCode> {
let AuthenticatorClientPinParameters { let AuthenticatorClientPinParameters {
@@ -239,21 +238,20 @@ impl ClientPin {
let pin_uv_auth_param = ok_or_missing(pin_uv_auth_param)?; let pin_uv_auth_param = ok_or_missing(pin_uv_auth_param)?;
let new_pin_enc = ok_or_missing(new_pin_enc)?; let new_pin_enc = ok_or_missing(new_pin_enc)?;
if persistent_store.pin_hash()?.is_some() { if storage::pin_hash(env)?.is_some() {
return Err(Ctap2StatusCode::CTAP2_ERR_PIN_AUTH_INVALID); return Err(Ctap2StatusCode::CTAP2_ERR_PIN_AUTH_INVALID);
} }
let shared_secret = self.get_shared_secret(pin_uv_auth_protocol, key_agreement)?; let shared_secret = self.get_shared_secret(pin_uv_auth_protocol, key_agreement)?;
shared_secret.verify(&new_pin_enc, &pin_uv_auth_param)?; shared_secret.verify(&new_pin_enc, &pin_uv_auth_param)?;
check_and_store_new_pin(persistent_store, shared_secret.as_ref(), new_pin_enc)?; check_and_store_new_pin(env, shared_secret.as_ref(), new_pin_enc)?;
persistent_store.reset_pin_retries()?; storage::reset_pin_retries(env)?;
Ok(()) Ok(())
} }
fn process_change_pin<E: Env>( fn process_change_pin(
&mut self, &mut self,
rng: &mut impl Rng256, env: &mut impl Env,
persistent_store: &mut PersistentStore<E>,
client_pin_params: AuthenticatorClientPinParameters, client_pin_params: AuthenticatorClientPinParameters,
) -> Result<(), Ctap2StatusCode> { ) -> Result<(), Ctap2StatusCode> {
let AuthenticatorClientPinParameters { let AuthenticatorClientPinParameters {
@@ -269,7 +267,7 @@ impl ClientPin {
let new_pin_enc = ok_or_missing(new_pin_enc)?; let new_pin_enc = ok_or_missing(new_pin_enc)?;
let pin_hash_enc = ok_or_missing(pin_hash_enc)?; let pin_hash_enc = ok_or_missing(pin_hash_enc)?;
if persistent_store.pin_retries()? == 0 { if storage::pin_retries(env)? == 0 {
return Err(Ctap2StatusCode::CTAP2_ERR_PIN_BLOCKED); return Err(Ctap2StatusCode::CTAP2_ERR_PIN_BLOCKED);
} }
let shared_secret = self.get_shared_secret(pin_uv_auth_protocol, key_agreement)?; let shared_secret = self.get_shared_secret(pin_uv_auth_protocol, key_agreement)?;
@@ -277,23 +275,21 @@ impl ClientPin {
auth_param_data.extend(&pin_hash_enc); auth_param_data.extend(&pin_hash_enc);
shared_secret.verify(&auth_param_data, &pin_uv_auth_param)?; shared_secret.verify(&auth_param_data, &pin_uv_auth_param)?;
self.verify_pin_hash_enc( self.verify_pin_hash_enc(
rng, env,
persistent_store,
pin_uv_auth_protocol, pin_uv_auth_protocol,
shared_secret.as_ref(), shared_secret.as_ref(),
pin_hash_enc, pin_hash_enc,
)?; )?;
check_and_store_new_pin(persistent_store, shared_secret.as_ref(), new_pin_enc)?; check_and_store_new_pin(env, shared_secret.as_ref(), new_pin_enc)?;
self.pin_protocol_v1.reset_pin_uv_auth_token(rng); self.pin_protocol_v1.reset_pin_uv_auth_token(env.rng());
self.pin_protocol_v2.reset_pin_uv_auth_token(rng); self.pin_protocol_v2.reset_pin_uv_auth_token(env.rng());
Ok(()) Ok(())
} }
fn process_get_pin_token<E: Env>( fn process_get_pin_token(
&mut self, &mut self,
rng: &mut impl Rng256, env: &mut impl Env,
persistent_store: &mut PersistentStore<E>,
client_pin_params: AuthenticatorClientPinParameters, client_pin_params: AuthenticatorClientPinParameters,
now: ClockValue, now: ClockValue,
) -> Result<AuthenticatorClientPinResponse, Ctap2StatusCode> { ) -> Result<AuthenticatorClientPinResponse, Ctap2StatusCode> {
@@ -311,28 +307,27 @@ impl ClientPin {
return Err(Ctap2StatusCode::CTAP1_ERR_INVALID_PARAMETER); return Err(Ctap2StatusCode::CTAP1_ERR_INVALID_PARAMETER);
} }
if persistent_store.pin_retries()? == 0 { if storage::pin_retries(env)? == 0 {
return Err(Ctap2StatusCode::CTAP2_ERR_PIN_BLOCKED); return Err(Ctap2StatusCode::CTAP2_ERR_PIN_BLOCKED);
} }
let shared_secret = self.get_shared_secret(pin_uv_auth_protocol, key_agreement)?; let shared_secret = self.get_shared_secret(pin_uv_auth_protocol, key_agreement)?;
self.verify_pin_hash_enc( self.verify_pin_hash_enc(
rng, env,
persistent_store,
pin_uv_auth_protocol, pin_uv_auth_protocol,
shared_secret.as_ref(), shared_secret.as_ref(),
pin_hash_enc, pin_hash_enc,
)?; )?;
if persistent_store.has_force_pin_change()? { if storage::has_force_pin_change(env)? {
return Err(Ctap2StatusCode::CTAP2_ERR_PIN_INVALID); return Err(Ctap2StatusCode::CTAP2_ERR_PIN_INVALID);
} }
self.pin_protocol_v1.reset_pin_uv_auth_token(rng); self.pin_protocol_v1.reset_pin_uv_auth_token(env.rng());
self.pin_protocol_v2.reset_pin_uv_auth_token(rng); self.pin_protocol_v2.reset_pin_uv_auth_token(env.rng());
self.pin_uv_auth_token_state self.pin_uv_auth_token_state
.begin_using_pin_uv_auth_token(now); .begin_using_pin_uv_auth_token(now);
self.pin_uv_auth_token_state.set_default_permissions(); self.pin_uv_auth_token_state.set_default_permissions();
let pin_uv_auth_token = shared_secret.encrypt( let pin_uv_auth_token = shared_secret.encrypt(
rng, env.rng(),
self.get_pin_protocol(pin_uv_auth_protocol) self.get_pin_protocol(pin_uv_auth_protocol)
.get_pin_uv_auth_token(), .get_pin_uv_auth_token(),
)?; )?;
@@ -360,10 +355,9 @@ impl ClientPin {
Err(Ctap2StatusCode::CTAP2_ERR_INVALID_SUBCOMMAND) Err(Ctap2StatusCode::CTAP2_ERR_INVALID_SUBCOMMAND)
} }
fn process_get_pin_uv_auth_token_using_pin_with_permissions<E: Env>( fn process_get_pin_uv_auth_token_using_pin_with_permissions(
&mut self, &mut self,
rng: &mut impl Rng256, env: &mut impl Env,
persistent_store: &mut PersistentStore<E>,
mut client_pin_params: AuthenticatorClientPinParameters, mut client_pin_params: AuthenticatorClientPinParameters,
now: ClockValue, now: ClockValue,
) -> Result<AuthenticatorClientPinResponse, Ctap2StatusCode> { ) -> Result<AuthenticatorClientPinResponse, Ctap2StatusCode> {
@@ -381,7 +375,7 @@ impl ClientPin {
return Err(Ctap2StatusCode::CTAP1_ERR_INVALID_PARAMETER); return Err(Ctap2StatusCode::CTAP1_ERR_INVALID_PARAMETER);
} }
let response = self.process_get_pin_token(rng, persistent_store, client_pin_params, now)?; let response = self.process_get_pin_token(env, client_pin_params, now)?;
self.pin_uv_auth_token_state.set_permissions(permissions); self.pin_uv_auth_token_state.set_permissions(permissions);
self.pin_uv_auth_token_state self.pin_uv_auth_token_state
.set_permissions_rp_id(permissions_rp_id); .set_permissions_rp_id(permissions_rp_id);
@@ -390,30 +384,27 @@ impl ClientPin {
} }
/// Processes the authenticatorClientPin command. /// Processes the authenticatorClientPin command.
pub fn process_command<E: Env>( pub fn process_command(
&mut self, &mut self,
rng: &mut impl Rng256, env: &mut impl Env,
persistent_store: &mut PersistentStore<E>,
client_pin_params: AuthenticatorClientPinParameters, client_pin_params: AuthenticatorClientPinParameters,
now: ClockValue, now: ClockValue,
) -> Result<ResponseData, Ctap2StatusCode> { ) -> Result<ResponseData, Ctap2StatusCode> {
let response = match client_pin_params.sub_command { let response = match client_pin_params.sub_command {
ClientPinSubCommand::GetPinRetries => { ClientPinSubCommand::GetPinRetries => Some(self.process_get_pin_retries(env)?),
Some(self.process_get_pin_retries(persistent_store)?)
}
ClientPinSubCommand::GetKeyAgreement => { ClientPinSubCommand::GetKeyAgreement => {
Some(self.process_get_key_agreement(client_pin_params)?) Some(self.process_get_key_agreement(client_pin_params)?)
} }
ClientPinSubCommand::SetPin => { ClientPinSubCommand::SetPin => {
self.process_set_pin(persistent_store, client_pin_params)?; self.process_set_pin(env, client_pin_params)?;
None None
} }
ClientPinSubCommand::ChangePin => { ClientPinSubCommand::ChangePin => {
self.process_change_pin(rng, persistent_store, client_pin_params)?; self.process_change_pin(env, client_pin_params)?;
None None
} }
ClientPinSubCommand::GetPinToken => { ClientPinSubCommand::GetPinToken => {
Some(self.process_get_pin_token(rng, persistent_store, client_pin_params, now)?) Some(self.process_get_pin_token(env, client_pin_params, now)?)
} }
ClientPinSubCommand::GetPinUvAuthTokenUsingUvWithPermissions => Some( ClientPinSubCommand::GetPinUvAuthTokenUsingUvWithPermissions => Some(
self.process_get_pin_uv_auth_token_using_uv_with_permissions(client_pin_params)?, self.process_get_pin_uv_auth_token_using_uv_with_permissions(client_pin_params)?,
@@ -421,8 +412,7 @@ impl ClientPin {
ClientPinSubCommand::GetUvRetries => Some(self.process_get_uv_retries()?), ClientPinSubCommand::GetUvRetries => Some(self.process_get_uv_retries()?),
ClientPinSubCommand::GetPinUvAuthTokenUsingPinWithPermissions => Some( ClientPinSubCommand::GetPinUvAuthTokenUsingPinWithPermissions => Some(
self.process_get_pin_uv_auth_token_using_pin_with_permissions( self.process_get_pin_uv_auth_token_using_pin_with_permissions(
rng, env,
persistent_store,
client_pin_params, client_pin_params,
now, now,
)?, )?,
@@ -602,12 +592,12 @@ mod test {
const DUMMY_CLOCK_VALUE: ClockValue = ClockValue::new(0, CLOCK_FREQUENCY_HZ); const DUMMY_CLOCK_VALUE: ClockValue = ClockValue::new(0, CLOCK_FREQUENCY_HZ);
/// Stores a PIN hash corresponding to the dummy PIN "1234". /// Stores a PIN hash corresponding to the dummy PIN "1234".
fn set_standard_pin<E: Env>(persistent_store: &mut PersistentStore<E>) { fn set_standard_pin(env: &mut TestEnv) {
let mut pin = [0u8; 64]; let mut pin = [0u8; 64];
pin[..4].copy_from_slice(b"1234"); pin[..4].copy_from_slice(b"1234");
let mut pin_hash = [0u8; 16]; let mut pin_hash = [0u8; 16];
pin_hash.copy_from_slice(&Sha256::hash(&pin[..])[..16]); pin_hash.copy_from_slice(&Sha256::hash(&pin[..])[..16]);
persistent_store.set_pin(&pin_hash, 4).unwrap(); storage::set_pin(env, &pin_hash, 4).unwrap();
} }
/// Fails on PINs bigger than 64 bytes. /// Fails on PINs bigger than 64 bytes.
@@ -733,7 +723,6 @@ mod test {
fn test_helper_verify_pin_hash_enc(pin_uv_auth_protocol: PinUvAuthProtocol) { fn test_helper_verify_pin_hash_enc(pin_uv_auth_protocol: PinUvAuthProtocol) {
let mut env = TestEnv::new(); let mut env = TestEnv::new();
let mut persistent_store = PersistentStore::new(&mut env);
let mut client_pin = ClientPin::new(env.rng()); let mut client_pin = ClientPin::new(env.rng());
let pin_protocol = client_pin.get_pin_protocol(pin_uv_auth_protocol); let pin_protocol = client_pin.get_pin_protocol(pin_uv_auth_protocol);
let shared_secret = pin_protocol let shared_secret = pin_protocol
@@ -744,7 +733,7 @@ mod test {
0x01, 0xD9, 0x88, 0x40, 0x50, 0xBB, 0xD0, 0x7A, 0x23, 0x1A, 0xEB, 0x69, 0xD8, 0x36, 0x01, 0xD9, 0x88, 0x40, 0x50, 0xBB, 0xD0, 0x7A, 0x23, 0x1A, 0xEB, 0x69, 0xD8, 0x36,
0xC4, 0x12, 0xC4, 0x12,
]; ];
persistent_store.set_pin(&pin_hash, 4).unwrap(); storage::set_pin(&mut env, &pin_hash, 4).unwrap();
let pin_hash_enc = shared_secret let pin_hash_enc = shared_secret
.as_ref() .as_ref()
@@ -752,8 +741,7 @@ mod test {
.unwrap(); .unwrap();
assert_eq!( assert_eq!(
client_pin.verify_pin_hash_enc( client_pin.verify_pin_hash_enc(
env.rng(), &mut env,
&mut persistent_store,
pin_uv_auth_protocol, pin_uv_auth_protocol,
shared_secret.as_ref(), shared_secret.as_ref(),
pin_hash_enc pin_hash_enc
@@ -764,8 +752,7 @@ mod test {
let pin_hash_enc = vec![0xEE; 16]; let pin_hash_enc = vec![0xEE; 16];
assert_eq!( assert_eq!(
client_pin.verify_pin_hash_enc( client_pin.verify_pin_hash_enc(
env.rng(), &mut env,
&mut persistent_store,
pin_uv_auth_protocol, pin_uv_auth_protocol,
shared_secret.as_ref(), shared_secret.as_ref(),
pin_hash_enc pin_hash_enc
@@ -780,8 +767,7 @@ mod test {
client_pin.consecutive_pin_mismatches = 3; client_pin.consecutive_pin_mismatches = 3;
assert_eq!( assert_eq!(
client_pin.verify_pin_hash_enc( client_pin.verify_pin_hash_enc(
env.rng(), &mut env,
&mut persistent_store,
pin_uv_auth_protocol, pin_uv_auth_protocol,
shared_secret.as_ref(), shared_secret.as_ref(),
pin_hash_enc pin_hash_enc
@@ -793,8 +779,7 @@ mod test {
let pin_hash_enc = vec![0x77; PIN_AUTH_LENGTH - 1]; let pin_hash_enc = vec![0x77; PIN_AUTH_LENGTH - 1];
assert_eq!( assert_eq!(
client_pin.verify_pin_hash_enc( client_pin.verify_pin_hash_enc(
env.rng(), &mut env,
&mut persistent_store,
pin_uv_auth_protocol, pin_uv_auth_protocol,
shared_secret.as_ref(), shared_secret.as_ref(),
pin_hash_enc pin_hash_enc
@@ -805,8 +790,7 @@ mod test {
let pin_hash_enc = vec![0x77; PIN_AUTH_LENGTH + 1]; let pin_hash_enc = vec![0x77; PIN_AUTH_LENGTH + 1];
assert_eq!( assert_eq!(
client_pin.verify_pin_hash_enc( client_pin.verify_pin_hash_enc(
env.rng(), &mut env,
&mut persistent_store,
pin_uv_auth_protocol, pin_uv_auth_protocol,
shared_secret.as_ref(), shared_secret.as_ref(),
pin_hash_enc pin_hash_enc
@@ -831,20 +815,14 @@ mod test {
ClientPinSubCommand::GetPinRetries, ClientPinSubCommand::GetPinRetries,
); );
let mut env = TestEnv::new(); let mut env = TestEnv::new();
let mut persistent_store = PersistentStore::new(&mut env);
let expected_response = Some(AuthenticatorClientPinResponse { let expected_response = Some(AuthenticatorClientPinResponse {
key_agreement: None, key_agreement: None,
pin_uv_auth_token: None, pin_uv_auth_token: None,
retries: Some(persistent_store.pin_retries().unwrap() as u64), retries: Some(storage::pin_retries(&mut env).unwrap() as u64),
power_cycle_state: Some(false), power_cycle_state: Some(false),
}); });
assert_eq!( assert_eq!(
client_pin.process_command( client_pin.process_command(&mut env, params.clone(), DUMMY_CLOCK_VALUE),
env.rng(),
&mut persistent_store,
params.clone(),
DUMMY_CLOCK_VALUE
),
Ok(ResponseData::AuthenticatorClientPin(expected_response)) Ok(ResponseData::AuthenticatorClientPin(expected_response))
); );
@@ -852,11 +830,11 @@ mod test {
let expected_response = Some(AuthenticatorClientPinResponse { let expected_response = Some(AuthenticatorClientPinResponse {
key_agreement: None, key_agreement: None,
pin_uv_auth_token: None, pin_uv_auth_token: None,
retries: Some(persistent_store.pin_retries().unwrap() as u64), retries: Some(storage::pin_retries(&mut env).unwrap() as u64),
power_cycle_state: Some(true), power_cycle_state: Some(true),
}); });
assert_eq!( assert_eq!(
client_pin.process_command(env.rng(), &mut persistent_store, params, DUMMY_CLOCK_VALUE), client_pin.process_command(&mut env, params, DUMMY_CLOCK_VALUE),
Ok(ResponseData::AuthenticatorClientPin(expected_response)) Ok(ResponseData::AuthenticatorClientPin(expected_response))
); );
} }
@@ -877,7 +855,6 @@ mod test {
ClientPinSubCommand::GetKeyAgreement, ClientPinSubCommand::GetKeyAgreement,
); );
let mut env = TestEnv::new(); let mut env = TestEnv::new();
let mut persistent_store = PersistentStore::new(&mut env);
let expected_response = Some(AuthenticatorClientPinResponse { let expected_response = Some(AuthenticatorClientPinResponse {
key_agreement: params.key_agreement.clone(), key_agreement: params.key_agreement.clone(),
pin_uv_auth_token: None, pin_uv_auth_token: None,
@@ -885,7 +862,7 @@ mod test {
power_cycle_state: None, power_cycle_state: None,
}); });
assert_eq!( assert_eq!(
client_pin.process_command(env.rng(), &mut persistent_store, params, DUMMY_CLOCK_VALUE), client_pin.process_command(&mut env, params, DUMMY_CLOCK_VALUE),
Ok(ResponseData::AuthenticatorClientPin(expected_response)) Ok(ResponseData::AuthenticatorClientPin(expected_response))
); );
} }
@@ -904,9 +881,8 @@ mod test {
let (mut client_pin, params) = let (mut client_pin, params) =
create_client_pin_and_parameters(pin_uv_auth_protocol, ClientPinSubCommand::SetPin); create_client_pin_and_parameters(pin_uv_auth_protocol, ClientPinSubCommand::SetPin);
let mut env = TestEnv::new(); let mut env = TestEnv::new();
let mut persistent_store = PersistentStore::new(&mut env);
assert_eq!( assert_eq!(
client_pin.process_command(env.rng(), &mut persistent_store, params, DUMMY_CLOCK_VALUE), client_pin.process_command(&mut env, params, DUMMY_CLOCK_VALUE),
Ok(ResponseData::AuthenticatorClientPin(None)) Ok(ResponseData::AuthenticatorClientPin(None))
); );
} }
@@ -932,40 +908,29 @@ mod test {
) )
.unwrap(); .unwrap();
let mut env = TestEnv::new(); let mut env = TestEnv::new();
let mut persistent_store = PersistentStore::new(&mut env); set_standard_pin(&mut env);
set_standard_pin(&mut persistent_store);
let mut auth_param_data = params.new_pin_enc.clone().unwrap(); let mut auth_param_data = params.new_pin_enc.clone().unwrap();
auth_param_data.extend(params.pin_hash_enc.as_ref().unwrap()); auth_param_data.extend(params.pin_hash_enc.as_ref().unwrap());
let pin_uv_auth_param = shared_secret.authenticate(&auth_param_data); let pin_uv_auth_param = shared_secret.authenticate(&auth_param_data);
params.pin_uv_auth_param = Some(pin_uv_auth_param); params.pin_uv_auth_param = Some(pin_uv_auth_param);
assert_eq!( assert_eq!(
client_pin.process_command( client_pin.process_command(&mut env, params.clone(), DUMMY_CLOCK_VALUE),
env.rng(),
&mut persistent_store,
params.clone(),
DUMMY_CLOCK_VALUE
),
Ok(ResponseData::AuthenticatorClientPin(None)) Ok(ResponseData::AuthenticatorClientPin(None))
); );
let mut bad_params = params.clone(); let mut bad_params = params.clone();
bad_params.pin_hash_enc = Some(vec![0xEE; 16]); bad_params.pin_hash_enc = Some(vec![0xEE; 16]);
assert_eq!( assert_eq!(
client_pin.process_command( client_pin.process_command(&mut env, bad_params, DUMMY_CLOCK_VALUE),
env.rng(),
&mut persistent_store,
bad_params,
DUMMY_CLOCK_VALUE
),
Err(Ctap2StatusCode::CTAP2_ERR_PIN_AUTH_INVALID) Err(Ctap2StatusCode::CTAP2_ERR_PIN_AUTH_INVALID)
); );
while persistent_store.pin_retries().unwrap() > 0 { while storage::pin_retries(&mut env).unwrap() > 0 {
persistent_store.decr_pin_retries().unwrap(); storage::decr_pin_retries(&mut env).unwrap();
} }
assert_eq!( assert_eq!(
client_pin.process_command(env.rng(), &mut persistent_store, params, DUMMY_CLOCK_VALUE), client_pin.process_command(&mut env, params, DUMMY_CLOCK_VALUE),
Err(Ctap2StatusCode::CTAP2_ERR_PIN_BLOCKED) Err(Ctap2StatusCode::CTAP2_ERR_PIN_BLOCKED)
); );
} }
@@ -993,16 +958,10 @@ mod test {
) )
.unwrap(); .unwrap();
let mut env = TestEnv::new(); let mut env = TestEnv::new();
let mut persistent_store = PersistentStore::new(&mut env); set_standard_pin(&mut env);
set_standard_pin(&mut persistent_store);
let response = client_pin let response = client_pin
.process_command( .process_command(&mut env, params.clone(), DUMMY_CLOCK_VALUE)
env.rng(),
&mut persistent_store,
params.clone(),
DUMMY_CLOCK_VALUE,
)
.unwrap(); .unwrap();
let encrypted_token = match response { let encrypted_token = match response {
ResponseData::AuthenticatorClientPin(Some(response)) => { ResponseData::AuthenticatorClientPin(Some(response)) => {
@@ -1038,12 +997,7 @@ mod test {
let mut bad_params = params; let mut bad_params = params;
bad_params.pin_hash_enc = Some(vec![0xEE; 16]); bad_params.pin_hash_enc = Some(vec![0xEE; 16]);
assert_eq!( assert_eq!(
client_pin.process_command( client_pin.process_command(&mut env, bad_params, DUMMY_CLOCK_VALUE),
env.rng(),
&mut persistent_store,
bad_params,
DUMMY_CLOCK_VALUE
),
Err(Ctap2StatusCode::CTAP2_ERR_PIN_INVALID) Err(Ctap2StatusCode::CTAP2_ERR_PIN_INVALID)
); );
} }
@@ -1064,12 +1018,11 @@ mod test {
ClientPinSubCommand::GetPinToken, ClientPinSubCommand::GetPinToken,
); );
let mut env = TestEnv::new(); let mut env = TestEnv::new();
let mut persistent_store = PersistentStore::new(&mut env); set_standard_pin(&mut env);
set_standard_pin(&mut persistent_store);
assert_eq!(persistent_store.force_pin_change(), Ok(())); assert_eq!(storage::force_pin_change(&mut env), Ok(()));
assert_eq!( assert_eq!(
client_pin.process_command(env.rng(), &mut persistent_store, params, DUMMY_CLOCK_VALUE), client_pin.process_command(&mut env, params, DUMMY_CLOCK_VALUE),
Err(Ctap2StatusCode::CTAP2_ERR_PIN_INVALID), Err(Ctap2StatusCode::CTAP2_ERR_PIN_INVALID),
); );
} }
@@ -1099,16 +1052,10 @@ mod test {
) )
.unwrap(); .unwrap();
let mut env = TestEnv::new(); let mut env = TestEnv::new();
let mut persistent_store = PersistentStore::new(&mut env); set_standard_pin(&mut env);
set_standard_pin(&mut persistent_store);
let response = client_pin let response = client_pin
.process_command( .process_command(&mut env, params.clone(), DUMMY_CLOCK_VALUE)
env.rng(),
&mut persistent_store,
params.clone(),
DUMMY_CLOCK_VALUE,
)
.unwrap(); .unwrap();
let encrypted_token = match response { let encrypted_token = match response {
ResponseData::AuthenticatorClientPin(Some(response)) => { ResponseData::AuthenticatorClientPin(Some(response)) => {
@@ -1144,36 +1091,21 @@ mod test {
let mut bad_params = params.clone(); let mut bad_params = params.clone();
bad_params.permissions = Some(0x00); bad_params.permissions = Some(0x00);
assert_eq!( assert_eq!(
client_pin.process_command( client_pin.process_command(&mut env, bad_params, DUMMY_CLOCK_VALUE),
env.rng(),
&mut persistent_store,
bad_params,
DUMMY_CLOCK_VALUE
),
Err(Ctap2StatusCode::CTAP1_ERR_INVALID_PARAMETER) Err(Ctap2StatusCode::CTAP1_ERR_INVALID_PARAMETER)
); );
let mut bad_params = params.clone(); let mut bad_params = params.clone();
bad_params.permissions_rp_id = None; bad_params.permissions_rp_id = None;
assert_eq!( assert_eq!(
client_pin.process_command( client_pin.process_command(&mut env, bad_params, DUMMY_CLOCK_VALUE),
env.rng(),
&mut persistent_store,
bad_params,
DUMMY_CLOCK_VALUE
),
Err(Ctap2StatusCode::CTAP1_ERR_INVALID_PARAMETER) Err(Ctap2StatusCode::CTAP1_ERR_INVALID_PARAMETER)
); );
let mut bad_params = params; let mut bad_params = params;
bad_params.pin_hash_enc = Some(vec![0xEE; 16]); bad_params.pin_hash_enc = Some(vec![0xEE; 16]);
assert_eq!( assert_eq!(
client_pin.process_command( client_pin.process_command(&mut env, bad_params, DUMMY_CLOCK_VALUE),
env.rng(),
&mut persistent_store,
bad_params,
DUMMY_CLOCK_VALUE
),
Err(Ctap2StatusCode::CTAP2_ERR_PIN_INVALID) Err(Ctap2StatusCode::CTAP2_ERR_PIN_INVALID)
); );
} }
@@ -1196,12 +1128,11 @@ mod test {
ClientPinSubCommand::GetPinUvAuthTokenUsingPinWithPermissions, ClientPinSubCommand::GetPinUvAuthTokenUsingPinWithPermissions,
); );
let mut env = TestEnv::new(); let mut env = TestEnv::new();
let mut persistent_store = PersistentStore::new(&mut env); set_standard_pin(&mut env);
set_standard_pin(&mut persistent_store);
assert_eq!(persistent_store.force_pin_change(), Ok(())); assert_eq!(storage::force_pin_change(&mut env), Ok(()));
assert_eq!( assert_eq!(
client_pin.process_command(env.rng(), &mut persistent_store, params, DUMMY_CLOCK_VALUE), client_pin.process_command(&mut env, params, DUMMY_CLOCK_VALUE),
Err(Ctap2StatusCode::CTAP2_ERR_PIN_INVALID) Err(Ctap2StatusCode::CTAP2_ERR_PIN_INVALID)
); );
} }
@@ -1266,7 +1197,6 @@ mod test {
fn test_helper_check_and_store_new_pin(pin_uv_auth_protocol: PinUvAuthProtocol) { fn test_helper_check_and_store_new_pin(pin_uv_auth_protocol: PinUvAuthProtocol) {
let mut env = TestEnv::new(); let mut env = TestEnv::new();
let mut persistent_store = PersistentStore::new(&mut env);
let pin_protocol = PinProtocol::new(env.rng()); let pin_protocol = PinProtocol::new(env.rng());
let shared_secret = pin_protocol let shared_secret = pin_protocol
.decapsulate(pin_protocol.get_public_key(), pin_uv_auth_protocol) .decapsulate(pin_protocol.get_public_key(), pin_uv_auth_protocol)
@@ -1292,17 +1222,17 @@ mod test {
), ),
]; ];
for (pin, result) in test_cases { for (pin, result) in test_cases {
let old_pin_hash = persistent_store.pin_hash().unwrap(); let old_pin_hash = storage::pin_hash(&mut env).unwrap();
let new_pin_enc = encrypt_pin(shared_secret.as_ref(), pin); let new_pin_enc = encrypt_pin(shared_secret.as_ref(), pin);
assert_eq!( assert_eq!(
check_and_store_new_pin(&mut persistent_store, shared_secret.as_ref(), new_pin_enc), check_and_store_new_pin(&mut env, shared_secret.as_ref(), new_pin_enc),
result result
); );
if result.is_ok() { if result.is_ok() {
assert_ne!(old_pin_hash, persistent_store.pin_hash().unwrap()); assert_ne!(old_pin_hash, storage::pin_hash(&mut env).unwrap());
} else { } else {
assert_eq!(old_pin_hash, persistent_store.pin_hash().unwrap()); assert_eq!(old_pin_hash, storage::pin_hash(&mut env).unwrap());
} }
} }
} }
@@ -1683,12 +1613,11 @@ mod test {
ClientPinSubCommand::GetPinUvAuthTokenUsingPinWithPermissions, ClientPinSubCommand::GetPinUvAuthTokenUsingPinWithPermissions,
); );
let mut env = TestEnv::new(); let mut env = TestEnv::new();
let mut persistent_store = PersistentStore::new(&mut env); set_standard_pin(&mut env);
set_standard_pin(&mut persistent_store);
params.permissions = Some(0xFF); params.permissions = Some(0xFF);
assert!(client_pin assert!(client_pin
.process_command(env.rng(), &mut persistent_store, params, DUMMY_CLOCK_VALUE) .process_command(&mut env, params, DUMMY_CLOCK_VALUE)
.is_ok()); .is_ok());
for permission in PinPermission::into_enum_iter() { for permission in PinPermission::into_enum_iter() {
assert_eq!( assert_eq!(
@@ -1730,12 +1659,11 @@ mod test {
ClientPinSubCommand::GetPinUvAuthTokenUsingPinWithPermissions, ClientPinSubCommand::GetPinUvAuthTokenUsingPinWithPermissions,
); );
let mut env = TestEnv::new(); let mut env = TestEnv::new();
let mut persistent_store = PersistentStore::new(&mut env); set_standard_pin(&mut env);
set_standard_pin(&mut persistent_store);
params.permissions = Some(0xFF); params.permissions = Some(0xFF);
assert!(client_pin assert!(client_pin
.process_command(env.rng(), &mut persistent_store, params, DUMMY_CLOCK_VALUE) .process_command(&mut env, params, DUMMY_CLOCK_VALUE)
.is_ok()); .is_ok());
for permission in PinPermission::into_enum_iter() { for permission in PinPermission::into_enum_iter() {
assert_eq!( assert_eq!(

View File

@@ -18,16 +18,16 @@ use super::customization::ENTERPRISE_ATTESTATION_MODE;
use super::data_formats::{ConfigSubCommand, ConfigSubCommandParams, SetMinPinLengthParams}; use super::data_formats::{ConfigSubCommand, ConfigSubCommandParams, SetMinPinLengthParams};
use super::response::ResponseData; use super::response::ResponseData;
use super::status_code::Ctap2StatusCode; use super::status_code::Ctap2StatusCode;
use super::storage::PersistentStore; use crate::ctap::storage;
use crate::env::Env; use crate::env::Env;
use alloc::vec; use alloc::vec;
/// Processes the subcommand enableEnterpriseAttestation for AuthenticatorConfig. /// Processes the subcommand enableEnterpriseAttestation for AuthenticatorConfig.
fn process_enable_enterprise_attestation<E: Env>( fn process_enable_enterprise_attestation(
persistent_store: &mut PersistentStore<E>, env: &mut impl Env,
) -> Result<ResponseData, Ctap2StatusCode> { ) -> Result<ResponseData, Ctap2StatusCode> {
if ENTERPRISE_ATTESTATION_MODE.is_some() { if ENTERPRISE_ATTESTATION_MODE.is_some() {
persistent_store.enable_enterprise_attestation()?; storage::enable_enterprise_attestation(env)?;
Ok(ResponseData::AuthenticatorConfig) Ok(ResponseData::AuthenticatorConfig)
} else { } else {
Err(Ctap2StatusCode::CTAP1_ERR_INVALID_PARAMETER) Err(Ctap2StatusCode::CTAP1_ERR_INVALID_PARAMETER)
@@ -35,16 +35,14 @@ fn process_enable_enterprise_attestation<E: Env>(
} }
/// Processes the subcommand toggleAlwaysUv for AuthenticatorConfig. /// Processes the subcommand toggleAlwaysUv for AuthenticatorConfig.
fn process_toggle_always_uv<E: Env>( fn process_toggle_always_uv(env: &mut impl Env) -> Result<ResponseData, Ctap2StatusCode> {
persistent_store: &mut PersistentStore<E>, storage::toggle_always_uv(env)?;
) -> Result<ResponseData, Ctap2StatusCode> {
persistent_store.toggle_always_uv()?;
Ok(ResponseData::AuthenticatorConfig) Ok(ResponseData::AuthenticatorConfig)
} }
/// Processes the subcommand setMinPINLength for AuthenticatorConfig. /// Processes the subcommand setMinPINLength for AuthenticatorConfig.
fn process_set_min_pin_length<E: Env>( fn process_set_min_pin_length(
persistent_store: &mut PersistentStore<E>, env: &mut impl Env,
params: SetMinPinLengthParams, params: SetMinPinLengthParams,
) -> Result<ResponseData, Ctap2StatusCode> { ) -> Result<ResponseData, Ctap2StatusCode> {
let SetMinPinLengthParams { let SetMinPinLengthParams {
@@ -52,31 +50,31 @@ fn process_set_min_pin_length<E: Env>(
min_pin_length_rp_ids, min_pin_length_rp_ids,
force_change_pin, force_change_pin,
} = params; } = params;
let store_min_pin_length = persistent_store.min_pin_length()?; let store_min_pin_length = storage::min_pin_length(env)?;
let new_min_pin_length = new_min_pin_length.unwrap_or(store_min_pin_length); let new_min_pin_length = new_min_pin_length.unwrap_or(store_min_pin_length);
if new_min_pin_length < store_min_pin_length { if new_min_pin_length < store_min_pin_length {
return Err(Ctap2StatusCode::CTAP2_ERR_PIN_POLICY_VIOLATION); return Err(Ctap2StatusCode::CTAP2_ERR_PIN_POLICY_VIOLATION);
} }
let mut force_change_pin = force_change_pin.unwrap_or(false); let mut force_change_pin = force_change_pin.unwrap_or(false);
if force_change_pin && persistent_store.pin_hash()?.is_none() { if force_change_pin && storage::pin_hash(env)?.is_none() {
return Err(Ctap2StatusCode::CTAP2_ERR_PIN_NOT_SET); return Err(Ctap2StatusCode::CTAP2_ERR_PIN_NOT_SET);
} }
if let Some(old_length) = persistent_store.pin_code_point_length()? { if let Some(old_length) = storage::pin_code_point_length(env)? {
force_change_pin |= new_min_pin_length > old_length; force_change_pin |= new_min_pin_length > old_length;
} }
if force_change_pin { if force_change_pin {
persistent_store.force_pin_change()?; storage::force_pin_change(env)?;
} }
persistent_store.set_min_pin_length(new_min_pin_length)?; storage::set_min_pin_length(env, new_min_pin_length)?;
if let Some(min_pin_length_rp_ids) = min_pin_length_rp_ids { if let Some(min_pin_length_rp_ids) = min_pin_length_rp_ids {
persistent_store.set_min_pin_length_rp_ids(min_pin_length_rp_ids)?; storage::set_min_pin_length_rp_ids(env, min_pin_length_rp_ids)?;
} }
Ok(ResponseData::AuthenticatorConfig) Ok(ResponseData::AuthenticatorConfig)
} }
/// Processes the AuthenticatorConfig command. /// Processes the AuthenticatorConfig command.
pub fn process_config<E: Env>( pub fn process_config(
persistent_store: &mut PersistentStore<E>, env: &mut impl Env,
client_pin: &mut ClientPin, client_pin: &mut ClientPin,
params: AuthenticatorConfigParameters, params: AuthenticatorConfigParameters,
) -> Result<ResponseData, Ctap2StatusCode> { ) -> Result<ResponseData, Ctap2StatusCode> {
@@ -87,9 +85,9 @@ pub fn process_config<E: Env>(
pin_uv_auth_protocol, pin_uv_auth_protocol,
} = params; } = params;
let enforce_uv = !matches!(sub_command, ConfigSubCommand::ToggleAlwaysUv) let enforce_uv =
&& persistent_store.has_always_uv()?; !matches!(sub_command, ConfigSubCommand::ToggleAlwaysUv) && storage::has_always_uv(env)?;
if persistent_store.pin_hash()?.is_some() || enforce_uv { if storage::pin_hash(env)?.is_some() || enforce_uv {
let pin_uv_auth_param = let pin_uv_auth_param =
pin_uv_auth_param.ok_or(Ctap2StatusCode::CTAP2_ERR_PUAT_REQUIRED)?; pin_uv_auth_param.ok_or(Ctap2StatusCode::CTAP2_ERR_PUAT_REQUIRED)?;
let pin_uv_auth_protocol = let pin_uv_auth_protocol =
@@ -109,13 +107,11 @@ pub fn process_config<E: Env>(
} }
match sub_command { match sub_command {
ConfigSubCommand::EnableEnterpriseAttestation => { ConfigSubCommand::EnableEnterpriseAttestation => process_enable_enterprise_attestation(env),
process_enable_enterprise_attestation(persistent_store) ConfigSubCommand::ToggleAlwaysUv => process_toggle_always_uv(env),
}
ConfigSubCommand::ToggleAlwaysUv => process_toggle_always_uv(persistent_store),
ConfigSubCommand::SetMinPinLength => { ConfigSubCommand::SetMinPinLength => {
if let Some(ConfigSubCommandParams::SetMinPinLength(params)) = sub_command_params { if let Some(ConfigSubCommandParams::SetMinPinLength(params)) = sub_command_params {
process_set_min_pin_length(persistent_store, params) process_set_min_pin_length(env, params)
} else { } else {
Err(Ctap2StatusCode::CTAP2_ERR_MISSING_PARAMETER) Err(Ctap2StatusCode::CTAP2_ERR_MISSING_PARAMETER)
} }
@@ -135,7 +131,6 @@ mod test {
#[test] #[test]
fn test_process_enable_enterprise_attestation() { fn test_process_enable_enterprise_attestation() {
let mut env = TestEnv::new(); let mut env = TestEnv::new();
let mut persistent_store = PersistentStore::new(&mut env);
let key_agreement_key = crypto::ecdh::SecKey::gensk(env.rng()); let key_agreement_key = crypto::ecdh::SecKey::gensk(env.rng());
let pin_uv_auth_token = [0x55; 32]; let pin_uv_auth_token = [0x55; 32];
let mut client_pin = let mut client_pin =
@@ -147,11 +142,11 @@ mod test {
pin_uv_auth_param: None, pin_uv_auth_param: None,
pin_uv_auth_protocol: None, pin_uv_auth_protocol: None,
}; };
let config_response = process_config(&mut persistent_store, &mut client_pin, config_params); let config_response = process_config(&mut env, &mut client_pin, config_params);
if ENTERPRISE_ATTESTATION_MODE.is_some() { if ENTERPRISE_ATTESTATION_MODE.is_some() {
assert_eq!(config_response, Ok(ResponseData::AuthenticatorConfig)); assert_eq!(config_response, Ok(ResponseData::AuthenticatorConfig));
assert_eq!(persistent_store.enterprise_attestation(), Ok(true)); assert_eq!(storage::enterprise_attestation(&mut env), Ok(true));
} else { } else {
assert_eq!( assert_eq!(
config_response, config_response,
@@ -163,7 +158,6 @@ mod test {
#[test] #[test]
fn test_process_toggle_always_uv() { fn test_process_toggle_always_uv() {
let mut env = TestEnv::new(); let mut env = TestEnv::new();
let mut persistent_store = PersistentStore::new(&mut env);
let key_agreement_key = crypto::ecdh::SecKey::gensk(env.rng()); let key_agreement_key = crypto::ecdh::SecKey::gensk(env.rng());
let pin_uv_auth_token = [0x55; 32]; let pin_uv_auth_token = [0x55; 32];
let mut client_pin = let mut client_pin =
@@ -175,9 +169,9 @@ mod test {
pin_uv_auth_param: None, pin_uv_auth_param: None,
pin_uv_auth_protocol: None, pin_uv_auth_protocol: None,
}; };
let config_response = process_config(&mut persistent_store, &mut client_pin, config_params); let config_response = process_config(&mut env, &mut client_pin, config_params);
assert_eq!(config_response, Ok(ResponseData::AuthenticatorConfig)); assert_eq!(config_response, Ok(ResponseData::AuthenticatorConfig));
assert!(persistent_store.has_always_uv().unwrap()); assert!(storage::has_always_uv(&mut env).unwrap());
let config_params = AuthenticatorConfigParameters { let config_params = AuthenticatorConfigParameters {
sub_command: ConfigSubCommand::ToggleAlwaysUv, sub_command: ConfigSubCommand::ToggleAlwaysUv,
@@ -185,7 +179,7 @@ mod test {
pin_uv_auth_param: None, pin_uv_auth_param: None,
pin_uv_auth_protocol: None, pin_uv_auth_protocol: None,
}; };
let config_response = process_config(&mut persistent_store, &mut client_pin, config_params); let config_response = process_config(&mut env, &mut client_pin, config_params);
if ENFORCE_ALWAYS_UV { if ENFORCE_ALWAYS_UV {
assert_eq!( assert_eq!(
config_response, config_response,
@@ -193,18 +187,17 @@ mod test {
); );
} else { } else {
assert_eq!(config_response, Ok(ResponseData::AuthenticatorConfig)); assert_eq!(config_response, Ok(ResponseData::AuthenticatorConfig));
assert!(!persistent_store.has_always_uv().unwrap()); assert!(!storage::has_always_uv(&mut env).unwrap());
} }
} }
fn test_helper_process_toggle_always_uv_with_pin(pin_uv_auth_protocol: PinUvAuthProtocol) { fn test_helper_process_toggle_always_uv_with_pin(pin_uv_auth_protocol: PinUvAuthProtocol) {
let mut env = TestEnv::new(); let mut env = TestEnv::new();
let mut persistent_store = PersistentStore::new(&mut env);
let key_agreement_key = crypto::ecdh::SecKey::gensk(env.rng()); let key_agreement_key = crypto::ecdh::SecKey::gensk(env.rng());
let pin_uv_auth_token = [0x55; 32]; let pin_uv_auth_token = [0x55; 32];
let mut client_pin = let mut client_pin =
ClientPin::new_test(key_agreement_key, pin_uv_auth_token, pin_uv_auth_protocol); ClientPin::new_test(key_agreement_key, pin_uv_auth_token, pin_uv_auth_protocol);
persistent_store.set_pin(&[0x88; 16], 4).unwrap(); storage::set_pin(&mut env, &[0x88; 16], 4).unwrap();
let mut config_data = vec![0xFF; 32]; let mut config_data = vec![0xFF; 32];
config_data.extend(&[0x0D, ConfigSubCommand::ToggleAlwaysUv as u8]); config_data.extend(&[0x0D, ConfigSubCommand::ToggleAlwaysUv as u8]);
@@ -216,7 +209,7 @@ mod test {
pin_uv_auth_param: Some(pin_uv_auth_param.clone()), pin_uv_auth_param: Some(pin_uv_auth_param.clone()),
pin_uv_auth_protocol: Some(pin_uv_auth_protocol), pin_uv_auth_protocol: Some(pin_uv_auth_protocol),
}; };
let config_response = process_config(&mut persistent_store, &mut client_pin, config_params); let config_response = process_config(&mut env, &mut client_pin, config_params);
if ENFORCE_ALWAYS_UV { if ENFORCE_ALWAYS_UV {
assert_eq!( assert_eq!(
config_response, config_response,
@@ -225,7 +218,7 @@ mod test {
return; return;
} }
assert_eq!(config_response, Ok(ResponseData::AuthenticatorConfig)); assert_eq!(config_response, Ok(ResponseData::AuthenticatorConfig));
assert!(persistent_store.has_always_uv().unwrap()); assert!(storage::has_always_uv(&mut env).unwrap());
let config_params = AuthenticatorConfigParameters { let config_params = AuthenticatorConfigParameters {
sub_command: ConfigSubCommand::ToggleAlwaysUv, sub_command: ConfigSubCommand::ToggleAlwaysUv,
@@ -233,9 +226,9 @@ mod test {
pin_uv_auth_param: Some(pin_uv_auth_param), pin_uv_auth_param: Some(pin_uv_auth_param),
pin_uv_auth_protocol: Some(pin_uv_auth_protocol), pin_uv_auth_protocol: Some(pin_uv_auth_protocol),
}; };
let config_response = process_config(&mut persistent_store, &mut client_pin, config_params); let config_response = process_config(&mut env, &mut client_pin, config_params);
assert_eq!(config_response, Ok(ResponseData::AuthenticatorConfig)); assert_eq!(config_response, Ok(ResponseData::AuthenticatorConfig));
assert!(!persistent_store.has_always_uv().unwrap()); assert!(!storage::has_always_uv(&mut env).unwrap());
} }
#[test] #[test]
@@ -270,7 +263,6 @@ mod test {
#[test] #[test]
fn test_process_set_min_pin_length() { fn test_process_set_min_pin_length() {
let mut env = TestEnv::new(); let mut env = TestEnv::new();
let mut persistent_store = PersistentStore::new(&mut env);
let key_agreement_key = crypto::ecdh::SecKey::gensk(env.rng()); let key_agreement_key = crypto::ecdh::SecKey::gensk(env.rng());
let pin_uv_auth_token = [0x55; 32]; let pin_uv_auth_token = [0x55; 32];
let mut client_pin = let mut client_pin =
@@ -279,13 +271,13 @@ mod test {
// First, increase minimum PIN length from 4 to 6 without PIN auth. // First, increase minimum PIN length from 4 to 6 without PIN auth.
let min_pin_length = 6; let min_pin_length = 6;
let config_params = create_min_pin_config_params(min_pin_length, None); let config_params = create_min_pin_config_params(min_pin_length, None);
let config_response = process_config(&mut persistent_store, &mut client_pin, config_params); let config_response = process_config(&mut env, &mut client_pin, config_params);
assert_eq!(config_response, Ok(ResponseData::AuthenticatorConfig)); assert_eq!(config_response, Ok(ResponseData::AuthenticatorConfig));
assert_eq!(persistent_store.min_pin_length(), Ok(min_pin_length)); assert_eq!(storage::min_pin_length(&mut env), Ok(min_pin_length));
// Second, increase minimum PIN length from 6 to 8 with PIN auth. // Second, increase minimum PIN length from 6 to 8 with PIN auth.
// The stored PIN or its length don't matter since we control the token. // The stored PIN or its length don't matter since we control the token.
persistent_store.set_pin(&[0x88; 16], 8).unwrap(); storage::set_pin(&mut env, &[0x88; 16], 8).unwrap();
let min_pin_length = 8; let min_pin_length = 8;
let mut config_params = create_min_pin_config_params(min_pin_length, None); let mut config_params = create_min_pin_config_params(min_pin_length, None);
let pin_uv_auth_param = vec![ let pin_uv_auth_param = vec![
@@ -293,9 +285,9 @@ mod test {
0xB2, 0xDE, 0xB2, 0xDE,
]; ];
config_params.pin_uv_auth_param = Some(pin_uv_auth_param); config_params.pin_uv_auth_param = Some(pin_uv_auth_param);
let config_response = process_config(&mut persistent_store, &mut client_pin, config_params); let config_response = process_config(&mut env, &mut client_pin, config_params);
assert_eq!(config_response, Ok(ResponseData::AuthenticatorConfig)); assert_eq!(config_response, Ok(ResponseData::AuthenticatorConfig));
assert_eq!(persistent_store.min_pin_length(), Ok(min_pin_length)); assert_eq!(storage::min_pin_length(&mut env), Ok(min_pin_length));
// Third, decreasing the minimum PIN length from 8 to 7 fails. // Third, decreasing the minimum PIN length from 8 to 7 fails.
let mut config_params = create_min_pin_config_params(7, None); let mut config_params = create_min_pin_config_params(7, None);
@@ -304,18 +296,17 @@ mod test {
0xA7, 0x71, 0xA7, 0x71,
]; ];
config_params.pin_uv_auth_param = Some(pin_uv_auth_param); config_params.pin_uv_auth_param = Some(pin_uv_auth_param);
let config_response = process_config(&mut persistent_store, &mut client_pin, config_params); let config_response = process_config(&mut env, &mut client_pin, config_params);
assert_eq!( assert_eq!(
config_response, config_response,
Err(Ctap2StatusCode::CTAP2_ERR_PIN_POLICY_VIOLATION) Err(Ctap2StatusCode::CTAP2_ERR_PIN_POLICY_VIOLATION)
); );
assert_eq!(persistent_store.min_pin_length(), Ok(min_pin_length)); assert_eq!(storage::min_pin_length(&mut env), Ok(min_pin_length));
} }
#[test] #[test]
fn test_process_set_min_pin_length_rp_ids() { fn test_process_set_min_pin_length_rp_ids() {
let mut env = TestEnv::new(); let mut env = TestEnv::new();
let mut persistent_store = PersistentStore::new(&mut env);
let key_agreement_key = crypto::ecdh::SecKey::gensk(env.rng()); let key_agreement_key = crypto::ecdh::SecKey::gensk(env.rng());
let pin_uv_auth_token = [0x55; 32]; let pin_uv_auth_token = [0x55; 32];
let mut client_pin = let mut client_pin =
@@ -326,11 +317,11 @@ mod test {
let min_pin_length_rp_ids = vec!["example.com".to_string()]; let min_pin_length_rp_ids = vec!["example.com".to_string()];
let config_params = let config_params =
create_min_pin_config_params(min_pin_length, Some(min_pin_length_rp_ids.clone())); create_min_pin_config_params(min_pin_length, Some(min_pin_length_rp_ids.clone()));
let config_response = process_config(&mut persistent_store, &mut client_pin, config_params); let config_response = process_config(&mut env, &mut client_pin, config_params);
assert_eq!(config_response, Ok(ResponseData::AuthenticatorConfig)); assert_eq!(config_response, Ok(ResponseData::AuthenticatorConfig));
assert_eq!(persistent_store.min_pin_length(), Ok(min_pin_length)); assert_eq!(storage::min_pin_length(&mut env), Ok(min_pin_length));
assert_eq!( assert_eq!(
persistent_store.min_pin_length_rp_ids(), storage::min_pin_length_rp_ids(&mut env),
Ok(min_pin_length_rp_ids) Ok(min_pin_length_rp_ids)
); );
@@ -338,7 +329,7 @@ mod test {
let min_pin_length = 8; let min_pin_length = 8;
let min_pin_length_rp_ids = vec!["another.example.com".to_string()]; let min_pin_length_rp_ids = vec!["another.example.com".to_string()];
// The stored PIN or its length don't matter since we control the token. // The stored PIN or its length don't matter since we control the token.
persistent_store.set_pin(&[0x88; 16], 8).unwrap(); storage::set_pin(&mut env, &[0x88; 16], 8).unwrap();
let mut config_params = let mut config_params =
create_min_pin_config_params(min_pin_length, Some(min_pin_length_rp_ids.clone())); create_min_pin_config_params(min_pin_length, Some(min_pin_length_rp_ids.clone()));
let pin_uv_auth_param = vec![ let pin_uv_auth_param = vec![
@@ -346,11 +337,11 @@ mod test {
0xD6, 0xDA, 0xD6, 0xDA,
]; ];
config_params.pin_uv_auth_param = Some(pin_uv_auth_param.clone()); config_params.pin_uv_auth_param = Some(pin_uv_auth_param.clone());
let config_response = process_config(&mut persistent_store, &mut client_pin, config_params); let config_response = process_config(&mut env, &mut client_pin, config_params);
assert_eq!(config_response, Ok(ResponseData::AuthenticatorConfig)); assert_eq!(config_response, Ok(ResponseData::AuthenticatorConfig));
assert_eq!(persistent_store.min_pin_length(), Ok(min_pin_length)); assert_eq!(storage::min_pin_length(&mut env), Ok(min_pin_length));
assert_eq!( assert_eq!(
persistent_store.min_pin_length_rp_ids(), storage::min_pin_length_rp_ids(&mut env),
Ok(min_pin_length_rp_ids.clone()) Ok(min_pin_length_rp_ids.clone())
); );
@@ -359,14 +350,14 @@ mod test {
let mut config_params = let mut config_params =
create_min_pin_config_params(9, Some(min_pin_length_rp_ids.clone())); create_min_pin_config_params(9, Some(min_pin_length_rp_ids.clone()));
config_params.pin_uv_auth_param = Some(pin_uv_auth_param.clone()); config_params.pin_uv_auth_param = Some(pin_uv_auth_param.clone());
let config_response = process_config(&mut persistent_store, &mut client_pin, config_params); let config_response = process_config(&mut env, &mut client_pin, config_params);
assert_eq!( assert_eq!(
config_response, config_response,
Err(Ctap2StatusCode::CTAP2_ERR_PIN_AUTH_INVALID) Err(Ctap2StatusCode::CTAP2_ERR_PIN_AUTH_INVALID)
); );
assert_eq!(persistent_store.min_pin_length(), Ok(min_pin_length)); assert_eq!(storage::min_pin_length(&mut env), Ok(min_pin_length));
assert_eq!( assert_eq!(
persistent_store.min_pin_length_rp_ids(), storage::min_pin_length_rp_ids(&mut env),
Ok(min_pin_length_rp_ids.clone()) Ok(min_pin_length_rp_ids.clone())
); );
@@ -377,14 +368,14 @@ mod test {
Some(vec!["counter.example.com".to_string()]), Some(vec!["counter.example.com".to_string()]),
); );
config_params.pin_uv_auth_param = Some(pin_uv_auth_param); config_params.pin_uv_auth_param = Some(pin_uv_auth_param);
let config_response = process_config(&mut persistent_store, &mut client_pin, config_params); let config_response = process_config(&mut env, &mut client_pin, config_params);
assert_eq!( assert_eq!(
config_response, config_response,
Err(Ctap2StatusCode::CTAP2_ERR_PIN_AUTH_INVALID) Err(Ctap2StatusCode::CTAP2_ERR_PIN_AUTH_INVALID)
); );
assert_eq!(persistent_store.min_pin_length(), Ok(min_pin_length)); assert_eq!(storage::min_pin_length(&mut env), Ok(min_pin_length));
assert_eq!( assert_eq!(
persistent_store.min_pin_length_rp_ids(), storage::min_pin_length_rp_ids(&mut env),
Ok(min_pin_length_rp_ids) Ok(min_pin_length_rp_ids)
); );
} }
@@ -392,13 +383,12 @@ mod test {
#[test] #[test]
fn test_process_set_min_pin_length_force_pin_change_implicit() { fn test_process_set_min_pin_length_force_pin_change_implicit() {
let mut env = TestEnv::new(); let mut env = TestEnv::new();
let mut persistent_store = PersistentStore::new(&mut env);
let key_agreement_key = crypto::ecdh::SecKey::gensk(env.rng()); let key_agreement_key = crypto::ecdh::SecKey::gensk(env.rng());
let pin_uv_auth_token = [0x55; 32]; let pin_uv_auth_token = [0x55; 32];
let mut client_pin = let mut client_pin =
ClientPin::new_test(key_agreement_key, pin_uv_auth_token, PinUvAuthProtocol::V1); ClientPin::new_test(key_agreement_key, pin_uv_auth_token, PinUvAuthProtocol::V1);
persistent_store.set_pin(&[0x88; 16], 4).unwrap(); storage::set_pin(&mut env, &[0x88; 16], 4).unwrap();
// Increase min PIN, force PIN change. // Increase min PIN, force PIN change.
let min_pin_length = 6; let min_pin_length = 6;
let mut config_params = create_min_pin_config_params(min_pin_length, None); let mut config_params = create_min_pin_config_params(min_pin_length, None);
@@ -407,28 +397,27 @@ mod test {
0xA8, 0xC8, 0xA8, 0xC8,
]); ]);
config_params.pin_uv_auth_param = pin_uv_auth_param; config_params.pin_uv_auth_param = pin_uv_auth_param;
let config_response = process_config(&mut persistent_store, &mut client_pin, config_params); let config_response = process_config(&mut env, &mut client_pin, config_params);
assert_eq!(config_response, Ok(ResponseData::AuthenticatorConfig)); assert_eq!(config_response, Ok(ResponseData::AuthenticatorConfig));
assert_eq!(persistent_store.min_pin_length(), Ok(min_pin_length)); assert_eq!(storage::min_pin_length(&mut env), Ok(min_pin_length));
assert_eq!(persistent_store.has_force_pin_change(), Ok(true)); assert_eq!(storage::has_force_pin_change(&mut env), Ok(true));
} }
#[test] #[test]
fn test_process_set_min_pin_length_force_pin_change_explicit() { fn test_process_set_min_pin_length_force_pin_change_explicit() {
let mut env = TestEnv::new(); let mut env = TestEnv::new();
let mut persistent_store = PersistentStore::new(&mut env);
let key_agreement_key = crypto::ecdh::SecKey::gensk(env.rng()); let key_agreement_key = crypto::ecdh::SecKey::gensk(env.rng());
let pin_uv_auth_token = [0x55; 32]; let pin_uv_auth_token = [0x55; 32];
let mut client_pin = let mut client_pin =
ClientPin::new_test(key_agreement_key, pin_uv_auth_token, PinUvAuthProtocol::V1); ClientPin::new_test(key_agreement_key, pin_uv_auth_token, PinUvAuthProtocol::V1);
persistent_store.set_pin(&[0x88; 16], 4).unwrap(); storage::set_pin(&mut env, &[0x88; 16], 4).unwrap();
let pin_uv_auth_param = Some(vec![ let pin_uv_auth_param = Some(vec![
0xE3, 0x74, 0xF4, 0x27, 0xBE, 0x7D, 0x40, 0xB5, 0x71, 0xB6, 0xB4, 0x1A, 0xD2, 0xC1, 0xE3, 0x74, 0xF4, 0x27, 0xBE, 0x7D, 0x40, 0xB5, 0x71, 0xB6, 0xB4, 0x1A, 0xD2, 0xC1,
0x53, 0xD7, 0x53, 0xD7,
]); ]);
let set_min_pin_length_params = SetMinPinLengthParams { let set_min_pin_length_params = SetMinPinLengthParams {
new_min_pin_length: Some(persistent_store.min_pin_length().unwrap()), new_min_pin_length: Some(storage::min_pin_length(&mut env).unwrap()),
min_pin_length_rp_ids: None, min_pin_length_rp_ids: None,
force_change_pin: Some(true), force_change_pin: Some(true),
}; };
@@ -440,15 +429,14 @@ mod test {
pin_uv_auth_param, pin_uv_auth_param,
pin_uv_auth_protocol: Some(PinUvAuthProtocol::V1), pin_uv_auth_protocol: Some(PinUvAuthProtocol::V1),
}; };
let config_response = process_config(&mut persistent_store, &mut client_pin, config_params); let config_response = process_config(&mut env, &mut client_pin, config_params);
assert_eq!(config_response, Ok(ResponseData::AuthenticatorConfig)); assert_eq!(config_response, Ok(ResponseData::AuthenticatorConfig));
assert_eq!(persistent_store.has_force_pin_change(), Ok(true)); assert_eq!(storage::has_force_pin_change(&mut env), Ok(true));
} }
#[test] #[test]
fn test_process_config_vendor_prototype() { fn test_process_config_vendor_prototype() {
let mut env = TestEnv::new(); let mut env = TestEnv::new();
let mut persistent_store = PersistentStore::new(&mut env);
let key_agreement_key = crypto::ecdh::SecKey::gensk(env.rng()); let key_agreement_key = crypto::ecdh::SecKey::gensk(env.rng());
let pin_uv_auth_token = [0x55; 32]; let pin_uv_auth_token = [0x55; 32];
let mut client_pin = let mut client_pin =
@@ -460,7 +448,7 @@ mod test {
pin_uv_auth_param: None, pin_uv_auth_param: None,
pin_uv_auth_protocol: None, pin_uv_auth_protocol: None,
}; };
let config_response = process_config(&mut persistent_store, &mut client_pin, config_params); let config_response = process_config(&mut env, &mut client_pin, config_params);
assert_eq!( assert_eq!(
config_response, config_response,
Err(Ctap2StatusCode::CTAP1_ERR_INVALID_PARAMETER) Err(Ctap2StatusCode::CTAP1_ERR_INVALID_PARAMETER)

View File

@@ -21,8 +21,8 @@ use super::data_formats::{
}; };
use super::response::{AuthenticatorCredentialManagementResponse, ResponseData}; use super::response::{AuthenticatorCredentialManagementResponse, ResponseData};
use super::status_code::Ctap2StatusCode; use super::status_code::Ctap2StatusCode;
use super::storage::PersistentStore;
use super::{StatefulCommand, StatefulPermission}; use super::{StatefulCommand, StatefulPermission};
use crate::ctap::storage;
use crate::env::Env; use crate::env::Env;
use alloc::collections::BTreeSet; use alloc::collections::BTreeSet;
use alloc::string::String; use alloc::string::String;
@@ -33,12 +33,10 @@ use crypto::Hash256;
use libtock_drivers::timer::ClockValue; use libtock_drivers::timer::ClockValue;
/// Generates a set with all existing RP IDs. /// Generates a set with all existing RP IDs.
fn get_stored_rp_ids<E: Env>( fn get_stored_rp_ids(env: &mut impl Env) -> Result<BTreeSet<String>, Ctap2StatusCode> {
persistent_store: &PersistentStore<E>,
) -> Result<BTreeSet<String>, Ctap2StatusCode> {
let mut rp_set = BTreeSet::new(); let mut rp_set = BTreeSet::new();
let mut iter_result = Ok(()); let mut iter_result = Ok(());
for (_, credential) in persistent_store.iter_credentials(&mut iter_result)? { for (_, credential) in storage::iter_credentials(env, &mut iter_result)? {
rp_set.insert(credential.rp_id); rp_set.insert(credential.rp_id);
} }
iter_result?; iter_result?;
@@ -109,8 +107,8 @@ fn enumerate_credentials_response(
/// Check if the token permissions have the correct associated RP ID. /// Check if the token permissions have the correct associated RP ID.
/// ///
/// Either no RP ID is associated, or the RP ID matches the stored credential. /// Either no RP ID is associated, or the RP ID matches the stored credential.
fn check_rp_id_permissions<E: Env>( fn check_rp_id_permissions(
persistent_store: &mut PersistentStore<E>, env: &mut impl Env,
client_pin: &mut ClientPin, client_pin: &mut ClientPin,
credential_id: &[u8], credential_id: &[u8],
) -> Result<(), Ctap2StatusCode> { ) -> Result<(), Ctap2StatusCode> {
@@ -118,30 +116,30 @@ fn check_rp_id_permissions<E: Env>(
if client_pin.has_no_rp_id_permission().is_ok() { if client_pin.has_no_rp_id_permission().is_ok() {
return Ok(()); return Ok(());
} }
let (_, credential) = persistent_store.find_credential_item(credential_id)?; let (_, credential) = storage::find_credential_item(env, credential_id)?;
client_pin.has_no_or_rp_id_permission(&credential.rp_id) client_pin.has_no_or_rp_id_permission(&credential.rp_id)
} }
/// Processes the subcommand getCredsMetadata for CredentialManagement. /// Processes the subcommand getCredsMetadata for CredentialManagement.
fn process_get_creds_metadata<E: Env>( fn process_get_creds_metadata(
persistent_store: &PersistentStore<E>, env: &mut impl Env,
) -> Result<AuthenticatorCredentialManagementResponse, Ctap2StatusCode> { ) -> Result<AuthenticatorCredentialManagementResponse, Ctap2StatusCode> {
Ok(AuthenticatorCredentialManagementResponse { Ok(AuthenticatorCredentialManagementResponse {
existing_resident_credentials_count: Some(persistent_store.count_credentials()? as u64), existing_resident_credentials_count: Some(storage::count_credentials(env)? as u64),
max_possible_remaining_resident_credentials_count: Some( max_possible_remaining_resident_credentials_count: Some(
persistent_store.remaining_credentials()? as u64, storage::remaining_credentials(env)? as u64,
), ),
..Default::default() ..Default::default()
}) })
} }
/// Processes the subcommand enumerateRPsBegin for CredentialManagement. /// Processes the subcommand enumerateRPsBegin for CredentialManagement.
fn process_enumerate_rps_begin<E: Env>( fn process_enumerate_rps_begin(
persistent_store: &PersistentStore<E>, env: &mut impl Env,
stateful_command_permission: &mut StatefulPermission, stateful_command_permission: &mut StatefulPermission,
now: ClockValue, now: ClockValue,
) -> Result<AuthenticatorCredentialManagementResponse, Ctap2StatusCode> { ) -> Result<AuthenticatorCredentialManagementResponse, Ctap2StatusCode> {
let rp_set = get_stored_rp_ids(persistent_store)?; let rp_set = get_stored_rp_ids(env)?;
let total_rps = rp_set.len(); let total_rps = rp_set.len();
if total_rps > 1 { if total_rps > 1 {
@@ -156,12 +154,12 @@ fn process_enumerate_rps_begin<E: Env>(
} }
/// Processes the subcommand enumerateRPsGetNextRP for CredentialManagement. /// Processes the subcommand enumerateRPsGetNextRP for CredentialManagement.
fn process_enumerate_rps_get_next_rp<E: Env>( fn process_enumerate_rps_get_next_rp(
persistent_store: &PersistentStore<E>, env: &mut impl Env,
stateful_command_permission: &mut StatefulPermission, stateful_command_permission: &mut StatefulPermission,
) -> Result<AuthenticatorCredentialManagementResponse, Ctap2StatusCode> { ) -> Result<AuthenticatorCredentialManagementResponse, Ctap2StatusCode> {
let rp_id_index = stateful_command_permission.next_enumerate_rp()?; let rp_id_index = stateful_command_permission.next_enumerate_rp()?;
let rp_set = get_stored_rp_ids(persistent_store)?; let rp_set = get_stored_rp_ids(env)?;
// A BTreeSet is already sorted. // A BTreeSet is already sorted.
let rp_id = rp_set let rp_id = rp_set
.into_iter() .into_iter()
@@ -171,8 +169,8 @@ fn process_enumerate_rps_get_next_rp<E: Env>(
} }
/// Processes the subcommand enumerateCredentialsBegin for CredentialManagement. /// Processes the subcommand enumerateCredentialsBegin for CredentialManagement.
fn process_enumerate_credentials_begin<E: Env>( fn process_enumerate_credentials_begin(
persistent_store: &PersistentStore<E>, env: &mut impl Env,
stateful_command_permission: &mut StatefulPermission, stateful_command_permission: &mut StatefulPermission,
client_pin: &mut ClientPin, client_pin: &mut ClientPin,
sub_command_params: CredentialManagementSubCommandParameters, sub_command_params: CredentialManagementSubCommandParameters,
@@ -183,7 +181,7 @@ fn process_enumerate_credentials_begin<E: Env>(
.ok_or(Ctap2StatusCode::CTAP2_ERR_MISSING_PARAMETER)?; .ok_or(Ctap2StatusCode::CTAP2_ERR_MISSING_PARAMETER)?;
client_pin.has_no_or_rp_id_hash_permission(&rp_id_hash[..])?; client_pin.has_no_or_rp_id_hash_permission(&rp_id_hash[..])?;
let mut iter_result = Ok(()); let mut iter_result = Ok(());
let iter = persistent_store.iter_credentials(&mut iter_result)?; let iter = storage::iter_credentials(env, &mut iter_result)?;
let mut rp_credentials: Vec<usize> = iter let mut rp_credentials: Vec<usize> = iter
.filter_map(|(key, credential)| { .filter_map(|(key, credential)| {
let cred_rp_id_hash = Sha256::hash(credential.rp_id.as_bytes()); let cred_rp_id_hash = Sha256::hash(credential.rp_id.as_bytes());
@@ -199,7 +197,7 @@ fn process_enumerate_credentials_begin<E: Env>(
let current_key = rp_credentials let current_key = rp_credentials
.pop() .pop()
.ok_or(Ctap2StatusCode::CTAP2_ERR_NO_CREDENTIALS)?; .ok_or(Ctap2StatusCode::CTAP2_ERR_NO_CREDENTIALS)?;
let credential = persistent_store.get_credential(current_key)?; let credential = storage::get_credential(env, current_key)?;
if total_credentials > 1 { if total_credentials > 1 {
stateful_command_permission stateful_command_permission
.set_command(now, StatefulCommand::EnumerateCredentials(rp_credentials)); .set_command(now, StatefulCommand::EnumerateCredentials(rp_credentials));
@@ -208,18 +206,18 @@ fn process_enumerate_credentials_begin<E: Env>(
} }
/// Processes the subcommand enumerateCredentialsGetNextCredential for CredentialManagement. /// Processes the subcommand enumerateCredentialsGetNextCredential for CredentialManagement.
fn process_enumerate_credentials_get_next_credential<E: Env>( fn process_enumerate_credentials_get_next_credential(
persistent_store: &PersistentStore<E>, env: &mut impl Env,
stateful_command_permission: &mut StatefulPermission, stateful_command_permission: &mut StatefulPermission,
) -> Result<AuthenticatorCredentialManagementResponse, Ctap2StatusCode> { ) -> Result<AuthenticatorCredentialManagementResponse, Ctap2StatusCode> {
let credential_key = stateful_command_permission.next_enumerate_credential()?; let credential_key = stateful_command_permission.next_enumerate_credential()?;
let credential = persistent_store.get_credential(credential_key)?; let credential = storage::get_credential(env, credential_key)?;
enumerate_credentials_response(credential, None) enumerate_credentials_response(credential, None)
} }
/// Processes the subcommand deleteCredential for CredentialManagement. /// Processes the subcommand deleteCredential for CredentialManagement.
fn process_delete_credential<E: Env>( fn process_delete_credential(
persistent_store: &mut PersistentStore<E>, env: &mut impl Env,
client_pin: &mut ClientPin, client_pin: &mut ClientPin,
sub_command_params: CredentialManagementSubCommandParameters, sub_command_params: CredentialManagementSubCommandParameters,
) -> Result<(), Ctap2StatusCode> { ) -> Result<(), Ctap2StatusCode> {
@@ -227,13 +225,13 @@ fn process_delete_credential<E: Env>(
.credential_id .credential_id
.ok_or(Ctap2StatusCode::CTAP2_ERR_MISSING_PARAMETER)? .ok_or(Ctap2StatusCode::CTAP2_ERR_MISSING_PARAMETER)?
.key_id; .key_id;
check_rp_id_permissions(persistent_store, client_pin, &credential_id)?; check_rp_id_permissions(env, client_pin, &credential_id)?;
persistent_store.delete_credential(&credential_id) storage::delete_credential(env, &credential_id)
} }
/// Processes the subcommand updateUserInformation for CredentialManagement. /// Processes the subcommand updateUserInformation for CredentialManagement.
fn process_update_user_information<E: Env>( fn process_update_user_information(
persistent_store: &mut PersistentStore<E>, env: &mut impl Env,
client_pin: &mut ClientPin, client_pin: &mut ClientPin,
sub_command_params: CredentialManagementSubCommandParameters, sub_command_params: CredentialManagementSubCommandParameters,
) -> Result<(), Ctap2StatusCode> { ) -> Result<(), Ctap2StatusCode> {
@@ -244,13 +242,13 @@ fn process_update_user_information<E: Env>(
let user = sub_command_params let user = sub_command_params
.user .user
.ok_or(Ctap2StatusCode::CTAP2_ERR_MISSING_PARAMETER)?; .ok_or(Ctap2StatusCode::CTAP2_ERR_MISSING_PARAMETER)?;
check_rp_id_permissions(persistent_store, client_pin, &credential_id)?; check_rp_id_permissions(env, client_pin, &credential_id)?;
persistent_store.update_credential(&credential_id, user) storage::update_credential(env, &credential_id, user)
} }
/// Processes the CredentialManagement command and all its subcommands. /// Processes the CredentialManagement command and all its subcommands.
pub fn process_credential_management<E: Env>( pub fn process_credential_management(
persistent_store: &mut PersistentStore<E>, env: &mut impl Env,
stateful_command_permission: &mut StatefulPermission, stateful_command_permission: &mut StatefulPermission,
client_pin: &mut ClientPin, client_pin: &mut ClientPin,
cred_management_params: AuthenticatorCredentialManagementParameters, cred_management_params: AuthenticatorCredentialManagementParameters,
@@ -306,37 +304,34 @@ pub fn process_credential_management<E: Env>(
let response = match sub_command { let response = match sub_command {
CredentialManagementSubCommand::GetCredsMetadata => { CredentialManagementSubCommand::GetCredsMetadata => {
client_pin.has_no_rp_id_permission()?; client_pin.has_no_rp_id_permission()?;
Some(process_get_creds_metadata(persistent_store)?) Some(process_get_creds_metadata(env)?)
} }
CredentialManagementSubCommand::EnumerateRpsBegin => { CredentialManagementSubCommand::EnumerateRpsBegin => {
client_pin.has_no_rp_id_permission()?; client_pin.has_no_rp_id_permission()?;
Some(process_enumerate_rps_begin( Some(process_enumerate_rps_begin(
persistent_store, env,
stateful_command_permission, stateful_command_permission,
now, now,
)?) )?)
} }
CredentialManagementSubCommand::EnumerateRpsGetNextRp => Some( CredentialManagementSubCommand::EnumerateRpsGetNextRp => Some(
process_enumerate_rps_get_next_rp(persistent_store, stateful_command_permission)?, process_enumerate_rps_get_next_rp(env, stateful_command_permission)?,
), ),
CredentialManagementSubCommand::EnumerateCredentialsBegin => { CredentialManagementSubCommand::EnumerateCredentialsBegin => {
Some(process_enumerate_credentials_begin( Some(process_enumerate_credentials_begin(
persistent_store, env,
stateful_command_permission, stateful_command_permission,
client_pin, client_pin,
sub_command_params.ok_or(Ctap2StatusCode::CTAP2_ERR_MISSING_PARAMETER)?, sub_command_params.ok_or(Ctap2StatusCode::CTAP2_ERR_MISSING_PARAMETER)?,
now, now,
)?) )?)
} }
CredentialManagementSubCommand::EnumerateCredentialsGetNextCredential => { CredentialManagementSubCommand::EnumerateCredentialsGetNextCredential => Some(
Some(process_enumerate_credentials_get_next_credential( process_enumerate_credentials_get_next_credential(env, stateful_command_permission)?,
persistent_store, ),
stateful_command_permission,
)?)
}
CredentialManagementSubCommand::DeleteCredential => { CredentialManagementSubCommand::DeleteCredential => {
process_delete_credential( process_delete_credential(
persistent_store, env,
client_pin, client_pin,
sub_command_params.ok_or(Ctap2StatusCode::CTAP2_ERR_MISSING_PARAMETER)?, sub_command_params.ok_or(Ctap2StatusCode::CTAP2_ERR_MISSING_PARAMETER)?,
)?; )?;
@@ -344,7 +339,7 @@ pub fn process_credential_management<E: Env>(
} }
CredentialManagementSubCommand::UpdateUserInformation => { CredentialManagementSubCommand::UpdateUserInformation => {
process_update_user_information( process_update_user_information(
persistent_store, env,
client_pin, client_pin,
sub_command_params.ok_or(Ctap2StatusCode::CTAP2_ERR_MISSING_PARAMETER)?, sub_command_params.ok_or(Ctap2StatusCode::CTAP2_ERR_MISSING_PARAMETER)?,
)?; )?;
@@ -396,7 +391,7 @@ mod test {
let mut ctap_state = CtapState::new(&mut env, DUMMY_CLOCK_VALUE); let mut ctap_state = CtapState::new(&mut env, DUMMY_CLOCK_VALUE);
ctap_state.client_pin = client_pin; ctap_state.client_pin = client_pin;
ctap_state.persistent_store.set_pin(&[0u8; 16], 4).unwrap(); storage::set_pin(&mut env, &[0u8; 16], 4).unwrap();
let management_data = vec![CredentialManagementSubCommand::GetCredsMetadata as u8]; let management_data = vec![CredentialManagementSubCommand::GetCredsMetadata as u8];
let pin_uv_auth_param = authenticate_pin_uv_auth_token( let pin_uv_auth_param = authenticate_pin_uv_auth_token(
&pin_uv_auth_token, &pin_uv_auth_token,
@@ -411,7 +406,7 @@ mod test {
pin_uv_auth_param: Some(pin_uv_auth_param.clone()), pin_uv_auth_param: Some(pin_uv_auth_param.clone()),
}; };
let cred_management_response = process_credential_management( let cred_management_response = process_credential_management(
&mut ctap_state.persistent_store, &mut env,
&mut ctap_state.stateful_command_permission, &mut ctap_state.stateful_command_permission,
&mut ctap_state.client_pin, &mut ctap_state.client_pin,
cred_management_params, cred_management_params,
@@ -427,10 +422,7 @@ mod test {
_ => panic!("Invalid response type"), _ => panic!("Invalid response type"),
}; };
ctap_state storage::store_credential(&mut env, credential_source).unwrap();
.persistent_store
.store_credential(credential_source)
.unwrap();
let cred_management_params = AuthenticatorCredentialManagementParameters { let cred_management_params = AuthenticatorCredentialManagementParameters {
sub_command: CredentialManagementSubCommand::GetCredsMetadata, sub_command: CredentialManagementSubCommand::GetCredsMetadata,
@@ -439,7 +431,7 @@ mod test {
pin_uv_auth_param: Some(pin_uv_auth_param), pin_uv_auth_param: Some(pin_uv_auth_param),
}; };
let cred_management_response = process_credential_management( let cred_management_response = process_credential_management(
&mut ctap_state.persistent_store, &mut env,
&mut ctap_state.stateful_command_permission, &mut ctap_state.stateful_command_permission,
&mut ctap_state.client_pin, &mut ctap_state.client_pin,
cred_management_params, cred_management_params,
@@ -481,16 +473,10 @@ mod test {
let mut ctap_state = CtapState::new(&mut env, DUMMY_CLOCK_VALUE); let mut ctap_state = CtapState::new(&mut env, DUMMY_CLOCK_VALUE);
ctap_state.client_pin = client_pin; ctap_state.client_pin = client_pin;
ctap_state storage::store_credential(&mut env, credential_source1).unwrap();
.persistent_store storage::store_credential(&mut env, credential_source2).unwrap();
.store_credential(credential_source1)
.unwrap();
ctap_state
.persistent_store
.store_credential(credential_source2)
.unwrap();
ctap_state.persistent_store.set_pin(&[0u8; 16], 4).unwrap(); storage::set_pin(&mut env, &[0u8; 16], 4).unwrap();
let pin_uv_auth_param = Some(vec![ let pin_uv_auth_param = Some(vec![
0x1A, 0xA4, 0x96, 0xDA, 0x62, 0x80, 0x28, 0x13, 0xEB, 0x32, 0xB9, 0xF1, 0xD2, 0xA9, 0x1A, 0xA4, 0x96, 0xDA, 0x62, 0x80, 0x28, 0x13, 0xEB, 0x32, 0xB9, 0xF1, 0xD2, 0xA9,
0xD0, 0xD1, 0xD0, 0xD1,
@@ -503,7 +489,7 @@ mod test {
pin_uv_auth_param, pin_uv_auth_param,
}; };
let cred_management_response = process_credential_management( let cred_management_response = process_credential_management(
&mut ctap_state.persistent_store, &mut env,
&mut ctap_state.stateful_command_permission, &mut ctap_state.stateful_command_permission,
&mut ctap_state.client_pin, &mut ctap_state.client_pin,
cred_management_params, cred_management_params,
@@ -527,7 +513,7 @@ mod test {
pin_uv_auth_param: None, pin_uv_auth_param: None,
}; };
let cred_management_response = process_credential_management( let cred_management_response = process_credential_management(
&mut ctap_state.persistent_store, &mut env,
&mut ctap_state.stateful_command_permission, &mut ctap_state.stateful_command_permission,
&mut ctap_state.client_pin, &mut ctap_state.client_pin,
cred_management_params, cred_management_params,
@@ -552,7 +538,7 @@ mod test {
pin_uv_auth_param: None, pin_uv_auth_param: None,
}; };
let cred_management_response = process_credential_management( let cred_management_response = process_credential_management(
&mut ctap_state.persistent_store, &mut env,
&mut ctap_state.stateful_command_permission, &mut ctap_state.stateful_command_permission,
&mut ctap_state.client_pin, &mut ctap_state.client_pin,
cred_management_params, cred_management_params,
@@ -580,13 +566,10 @@ mod test {
for i in 0..NUM_CREDENTIALS { for i in 0..NUM_CREDENTIALS {
let mut credential = credential_source.clone(); let mut credential = credential_source.clone();
credential.rp_id = i.to_string(); credential.rp_id = i.to_string();
ctap_state storage::store_credential(&mut env, credential).unwrap();
.persistent_store
.store_credential(credential)
.unwrap();
} }
ctap_state.persistent_store.set_pin(&[0u8; 16], 4).unwrap(); storage::set_pin(&mut env, &[0u8; 16], 4).unwrap();
let pin_uv_auth_param = Some(vec![ let pin_uv_auth_param = Some(vec![
0x1A, 0xA4, 0x96, 0xDA, 0x62, 0x80, 0x28, 0x13, 0xEB, 0x32, 0xB9, 0xF1, 0xD2, 0xA9, 0x1A, 0xA4, 0x96, 0xDA, 0x62, 0x80, 0x28, 0x13, 0xEB, 0x32, 0xB9, 0xF1, 0xD2, 0xA9,
0xD0, 0xD1, 0xD0, 0xD1,
@@ -604,7 +587,7 @@ mod test {
for _ in 0..NUM_CREDENTIALS { for _ in 0..NUM_CREDENTIALS {
let cred_management_response = process_credential_management( let cred_management_response = process_credential_management(
&mut ctap_state.persistent_store, &mut env,
&mut ctap_state.stateful_command_permission, &mut ctap_state.stateful_command_permission,
&mut ctap_state.client_pin, &mut ctap_state.client_pin,
cred_management_params, cred_management_params,
@@ -634,7 +617,7 @@ mod test {
} }
let cred_management_response = process_credential_management( let cred_management_response = process_credential_management(
&mut ctap_state.persistent_store, &mut env,
&mut ctap_state.stateful_command_permission, &mut ctap_state.stateful_command_permission,
&mut ctap_state.client_pin, &mut ctap_state.client_pin,
cred_management_params, cred_management_params,
@@ -663,16 +646,10 @@ mod test {
let mut ctap_state = CtapState::new(&mut env, DUMMY_CLOCK_VALUE); let mut ctap_state = CtapState::new(&mut env, DUMMY_CLOCK_VALUE);
ctap_state.client_pin = client_pin; ctap_state.client_pin = client_pin;
ctap_state storage::store_credential(&mut env, credential_source1).unwrap();
.persistent_store storage::store_credential(&mut env, credential_source2).unwrap();
.store_credential(credential_source1)
.unwrap();
ctap_state
.persistent_store
.store_credential(credential_source2)
.unwrap();
ctap_state.persistent_store.set_pin(&[0u8; 16], 4).unwrap(); storage::set_pin(&mut env, &[0u8; 16], 4).unwrap();
let pin_uv_auth_param = Some(vec![ let pin_uv_auth_param = Some(vec![
0xF8, 0xB0, 0x3C, 0xC1, 0xD5, 0x58, 0x9C, 0xB7, 0x4D, 0x42, 0xA1, 0x64, 0x14, 0x28, 0xF8, 0xB0, 0x3C, 0xC1, 0xD5, 0x58, 0x9C, 0xB7, 0x4D, 0x42, 0xA1, 0x64, 0x14, 0x28,
0x2B, 0x68, 0x2B, 0x68,
@@ -692,7 +669,7 @@ mod test {
pin_uv_auth_param, pin_uv_auth_param,
}; };
let cred_management_response = process_credential_management( let cred_management_response = process_credential_management(
&mut ctap_state.persistent_store, &mut env,
&mut ctap_state.stateful_command_permission, &mut ctap_state.stateful_command_permission,
&mut ctap_state.client_pin, &mut ctap_state.client_pin,
cred_management_params, cred_management_params,
@@ -715,7 +692,7 @@ mod test {
pin_uv_auth_param: None, pin_uv_auth_param: None,
}; };
let cred_management_response = process_credential_management( let cred_management_response = process_credential_management(
&mut ctap_state.persistent_store, &mut env,
&mut ctap_state.stateful_command_permission, &mut ctap_state.stateful_command_permission,
&mut ctap_state.client_pin, &mut ctap_state.client_pin,
cred_management_params, cred_management_params,
@@ -739,7 +716,7 @@ mod test {
pin_uv_auth_param: None, pin_uv_auth_param: None,
}; };
let cred_management_response = process_credential_management( let cred_management_response = process_credential_management(
&mut ctap_state.persistent_store, &mut env,
&mut ctap_state.stateful_command_permission, &mut ctap_state.stateful_command_permission,
&mut ctap_state.client_pin, &mut ctap_state.client_pin,
cred_management_params, cred_management_params,
@@ -764,12 +741,9 @@ mod test {
let mut ctap_state = CtapState::new(&mut env, DUMMY_CLOCK_VALUE); let mut ctap_state = CtapState::new(&mut env, DUMMY_CLOCK_VALUE);
ctap_state.client_pin = client_pin; ctap_state.client_pin = client_pin;
ctap_state storage::store_credential(&mut env, credential_source).unwrap();
.persistent_store
.store_credential(credential_source)
.unwrap();
ctap_state.persistent_store.set_pin(&[0u8; 16], 4).unwrap(); storage::set_pin(&mut env, &[0u8; 16], 4).unwrap();
let pin_uv_auth_param = Some(vec![ let pin_uv_auth_param = Some(vec![
0xBD, 0xE3, 0xEF, 0x8A, 0x77, 0x01, 0xB1, 0x69, 0x19, 0xE6, 0x62, 0xB9, 0x9B, 0x89, 0xBD, 0xE3, 0xEF, 0x8A, 0x77, 0x01, 0xB1, 0x69, 0x19, 0xE6, 0x62, 0xB9, 0x9B, 0x89,
0x9C, 0x64, 0x9C, 0x64,
@@ -792,7 +766,7 @@ mod test {
pin_uv_auth_param: pin_uv_auth_param.clone(), pin_uv_auth_param: pin_uv_auth_param.clone(),
}; };
let cred_management_response = process_credential_management( let cred_management_response = process_credential_management(
&mut ctap_state.persistent_store, &mut env,
&mut ctap_state.stateful_command_permission, &mut ctap_state.stateful_command_permission,
&mut ctap_state.client_pin, &mut ctap_state.client_pin,
cred_management_params, cred_management_params,
@@ -810,7 +784,7 @@ mod test {
pin_uv_auth_param, pin_uv_auth_param,
}; };
let cred_management_response = process_credential_management( let cred_management_response = process_credential_management(
&mut ctap_state.persistent_store, &mut env,
&mut ctap_state.stateful_command_permission, &mut ctap_state.stateful_command_permission,
&mut ctap_state.client_pin, &mut ctap_state.client_pin,
cred_management_params, cred_management_params,
@@ -835,12 +809,9 @@ mod test {
let mut ctap_state = CtapState::new(&mut env, DUMMY_CLOCK_VALUE); let mut ctap_state = CtapState::new(&mut env, DUMMY_CLOCK_VALUE);
ctap_state.client_pin = client_pin; ctap_state.client_pin = client_pin;
ctap_state storage::store_credential(&mut env, credential_source).unwrap();
.persistent_store
.store_credential(credential_source)
.unwrap();
ctap_state.persistent_store.set_pin(&[0u8; 16], 4).unwrap(); storage::set_pin(&mut env, &[0u8; 16], 4).unwrap();
let pin_uv_auth_param = Some(vec![ let pin_uv_auth_param = Some(vec![
0xA5, 0x55, 0x8F, 0x03, 0xC3, 0xD3, 0x73, 0x1C, 0x07, 0xDA, 0x1F, 0x8C, 0xC7, 0xBD, 0xA5, 0x55, 0x8F, 0x03, 0xC3, 0xD3, 0x73, 0x1C, 0x07, 0xDA, 0x1F, 0x8C, 0xC7, 0xBD,
0x9D, 0xB7, 0x9D, 0xB7,
@@ -869,7 +840,7 @@ mod test {
pin_uv_auth_param, pin_uv_auth_param,
}; };
let cred_management_response = process_credential_management( let cred_management_response = process_credential_management(
&mut ctap_state.persistent_store, &mut env,
&mut ctap_state.stateful_command_permission, &mut ctap_state.stateful_command_permission,
&mut ctap_state.client_pin, &mut ctap_state.client_pin,
cred_management_params, cred_management_params,
@@ -880,11 +851,10 @@ mod test {
Ok(ResponseData::AuthenticatorCredentialManagement(None)) Ok(ResponseData::AuthenticatorCredentialManagement(None))
); );
let updated_credential = ctap_state let updated_credential =
.persistent_store storage::find_credential(&mut env, "example.com", &[0x1D; 32], false)
.find_credential("example.com", &[0x1D; 32], false) .unwrap()
.unwrap() .unwrap();
.unwrap();
assert_eq!(updated_credential.user_handle, vec![0x01]); assert_eq!(updated_credential.user_handle, vec![0x01]);
assert_eq!(&updated_credential.user_name.unwrap(), "new_name"); assert_eq!(&updated_credential.user_name.unwrap(), "new_name");
assert_eq!( assert_eq!(
@@ -899,7 +869,7 @@ mod test {
let mut env = TestEnv::new(); let mut env = TestEnv::new();
let mut ctap_state = CtapState::new(&mut env, DUMMY_CLOCK_VALUE); let mut ctap_state = CtapState::new(&mut env, DUMMY_CLOCK_VALUE);
ctap_state.persistent_store.set_pin(&[0u8; 16], 4).unwrap(); storage::set_pin(&mut env, &[0u8; 16], 4).unwrap();
let cred_management_params = AuthenticatorCredentialManagementParameters { let cred_management_params = AuthenticatorCredentialManagementParameters {
sub_command: CredentialManagementSubCommand::GetCredsMetadata, sub_command: CredentialManagementSubCommand::GetCredsMetadata,
@@ -908,7 +878,7 @@ mod test {
pin_uv_auth_param: Some(vec![0u8; 16]), pin_uv_auth_param: Some(vec![0u8; 16]),
}; };
let cred_management_response = process_credential_management( let cred_management_response = process_credential_management(
&mut ctap_state.persistent_store, &mut env,
&mut ctap_state.stateful_command_permission, &mut ctap_state.stateful_command_permission,
&mut ctap_state.client_pin, &mut ctap_state.client_pin,
cred_management_params, cred_management_params,

View File

@@ -14,6 +14,7 @@
use super::apdu::{Apdu, ApduStatusCode}; use super::apdu::{Apdu, ApduStatusCode};
use super::CtapState; use super::CtapState;
use crate::ctap::storage;
use crate::env::Env; use crate::env::Env;
use alloc::vec::Vec; use alloc::vec::Vec;
use arrayref::array_ref; use arrayref::array_ref;
@@ -178,14 +179,14 @@ impl Ctap1Command {
const VENDOR_SPECIFIC_FIRST: u8 = 0x40; const VENDOR_SPECIFIC_FIRST: u8 = 0x40;
const VENDOR_SPECIFIC_LAST: u8 = 0xBF; const VENDOR_SPECIFIC_LAST: u8 = 0xBF;
pub fn process_command<E: Env>( pub fn process_command(
env: &mut E, env: &mut impl Env,
message: &[u8], message: &[u8],
ctap_state: &mut CtapState<E>, ctap_state: &mut CtapState,
clock_value: ClockValue, clock_value: ClockValue,
) -> Result<Vec<u8>, Ctap1StatusCode> { ) -> Result<Vec<u8>, Ctap1StatusCode> {
if !ctap_state if !ctap_state
.allows_ctap1() .allows_ctap1(env)
.map_err(|_| Ctap1StatusCode::SW_INTERNAL_EXCEPTION)? .map_err(|_| Ctap1StatusCode::SW_INTERNAL_EXCEPTION)?
{ {
return Err(Ctap1StatusCode::SW_COMMAND_NOT_ALLOWED); return Err(Ctap1StatusCode::SW_COMMAND_NOT_ALLOWED);
@@ -243,11 +244,11 @@ impl Ctap1Command {
// +------+-------------------+-----------------+------------+--------------------+ // +------+-------------------+-----------------+------------+--------------------+
// + 0x00 | application (32B) | challenge (32B) | key handle | User pub key (65B) | // + 0x00 | application (32B) | challenge (32B) | key handle | User pub key (65B) |
// +------+-------------------+-----------------+------------+--------------------+ // +------+-------------------+-----------------+------------+--------------------+
fn process_register<E: Env>( fn process_register(
env: &mut E, env: &mut impl Env,
challenge: [u8; 32], challenge: [u8; 32],
application: [u8; 32], application: [u8; 32],
ctap_state: &mut CtapState<E>, ctap_state: &mut CtapState,
) -> Result<Vec<u8>, Ctap1StatusCode> { ) -> Result<Vec<u8>, Ctap1StatusCode> {
let sk = crypto::ecdsa::SecKey::gensk(env.rng()); let sk = crypto::ecdsa::SecKey::gensk(env.rng());
let pk = sk.genpk(); let pk = sk.genpk();
@@ -259,14 +260,10 @@ impl Ctap1Command {
return Err(Ctap1StatusCode::SW_INTERNAL_EXCEPTION); return Err(Ctap1StatusCode::SW_INTERNAL_EXCEPTION);
} }
let certificate = ctap_state let certificate = storage::attestation_certificate(env)
.persistent_store
.attestation_certificate()
.map_err(|_| Ctap1StatusCode::SW_MEMERR)? .map_err(|_| Ctap1StatusCode::SW_MEMERR)?
.ok_or(Ctap1StatusCode::SW_INTERNAL_EXCEPTION)?; .ok_or(Ctap1StatusCode::SW_INTERNAL_EXCEPTION)?;
let private_key = ctap_state let private_key = storage::attestation_private_key(env)
.persistent_store
.attestation_private_key()
.map_err(|_| Ctap1StatusCode::SW_INTERNAL_EXCEPTION)? .map_err(|_| Ctap1StatusCode::SW_INTERNAL_EXCEPTION)?
.ok_or(Ctap1StatusCode::SW_INTERNAL_EXCEPTION)?; .ok_or(Ctap1StatusCode::SW_INTERNAL_EXCEPTION)?;
@@ -307,16 +304,16 @@ impl Ctap1Command {
// +-------------------+---------+--------------+-----------------+ // +-------------------+---------+--------------+-----------------+
// + application (32B) | UP (1B) | Counter (4B) | challenge (32B) | // + application (32B) | UP (1B) | Counter (4B) | challenge (32B) |
// +-------------------+---------+--------------+-----------------+ // +-------------------+---------+--------------+-----------------+
fn process_authenticate<E: Env>( fn process_authenticate(
env: &mut E, env: &mut impl Env,
challenge: [u8; 32], challenge: [u8; 32],
application: [u8; 32], application: [u8; 32],
key_handle: Vec<u8>, key_handle: Vec<u8>,
flags: Ctap1Flags, flags: Ctap1Flags,
ctap_state: &mut CtapState<E>, ctap_state: &mut CtapState,
) -> Result<Vec<u8>, Ctap1StatusCode> { ) -> Result<Vec<u8>, Ctap1StatusCode> {
let credential_source = ctap_state let credential_source = ctap_state
.decrypt_credential_source(key_handle, &application) .decrypt_credential_source(env, key_handle, &application)
.map_err(|_| Ctap1StatusCode::SW_WRONG_DATA)?; .map_err(|_| Ctap1StatusCode::SW_WRONG_DATA)?;
if let Some(credential_source) = credential_source { if let Some(credential_source) = credential_source {
if flags == Ctap1Flags::CheckOnly { if flags == Ctap1Flags::CheckOnly {
@@ -326,7 +323,11 @@ impl Ctap1Command {
.increment_global_signature_counter(env) .increment_global_signature_counter(env)
.map_err(|_| Ctap1StatusCode::SW_WRONG_DATA)?; .map_err(|_| Ctap1StatusCode::SW_WRONG_DATA)?;
let mut signature_data = ctap_state let mut signature_data = ctap_state
.generate_auth_data(&application, Ctap1Command::USER_PRESENCE_INDICATOR_BYTE) .generate_auth_data(
env,
&application,
Ctap1Command::USER_PRESENCE_INDICATOR_BYTE,
)
.map_err(|_| Ctap1StatusCode::SW_WRONG_DATA)?; .map_err(|_| Ctap1StatusCode::SW_WRONG_DATA)?;
signature_data.extend(&challenge); signature_data.extend(&challenge);
let signature = credential_source let signature = credential_source
@@ -400,7 +401,7 @@ mod test {
env.user_presence() env.user_presence()
.set(|_| panic!("Unexpected user presence check in CTAP1")); .set(|_| panic!("Unexpected user presence check in CTAP1"));
let mut ctap_state = CtapState::new(&mut env, START_CLOCK_VALUE); let mut ctap_state = CtapState::new(&mut env, START_CLOCK_VALUE);
ctap_state.persistent_store.toggle_always_uv().unwrap(); storage::toggle_always_uv(&mut env).unwrap();
let application = [0x0A; 32]; let application = [0x0A; 32];
let message = create_register_message(&application); let message = create_register_message(&application);
@@ -428,10 +429,7 @@ mod test {
assert_eq!(response, Err(Ctap1StatusCode::SW_INTERNAL_EXCEPTION)); assert_eq!(response, Err(Ctap1StatusCode::SW_INTERNAL_EXCEPTION));
let fake_key = [0x41u8; key_material::ATTESTATION_PRIVATE_KEY_LENGTH]; let fake_key = [0x41u8; key_material::ATTESTATION_PRIVATE_KEY_LENGTH];
assert!(ctap_state assert!(storage::set_attestation_private_key(&mut env, &fake_key).is_ok());
.persistent_store
.set_attestation_private_key(&fake_key)
.is_ok());
ctap_state.u2f_up_state.consume_up(START_CLOCK_VALUE); ctap_state.u2f_up_state.consume_up(START_CLOCK_VALUE);
ctap_state.u2f_up_state.grant_up(START_CLOCK_VALUE); ctap_state.u2f_up_state.grant_up(START_CLOCK_VALUE);
let response = let response =
@@ -440,10 +438,7 @@ mod test {
assert_eq!(response, Err(Ctap1StatusCode::SW_INTERNAL_EXCEPTION)); assert_eq!(response, Err(Ctap1StatusCode::SW_INTERNAL_EXCEPTION));
let fake_cert = [0x99u8; 100]; // Arbitrary length let fake_cert = [0x99u8; 100]; // Arbitrary length
assert!(ctap_state assert!(storage::set_attestation_certificate(&mut env, &fake_cert[..]).is_ok());
.persistent_store
.set_attestation_certificate(&fake_cert[..])
.is_ok());
ctap_state.u2f_up_state.consume_up(START_CLOCK_VALUE); ctap_state.u2f_up_state.consume_up(START_CLOCK_VALUE);
ctap_state.u2f_up_state.grant_up(START_CLOCK_VALUE); ctap_state.u2f_up_state.grant_up(START_CLOCK_VALUE);
let response = let response =
@@ -452,7 +447,11 @@ mod test {
assert_eq!(response[0], Ctap1Command::LEGACY_BYTE); assert_eq!(response[0], Ctap1Command::LEGACY_BYTE);
assert_eq!(response[66], CREDENTIAL_ID_SIZE as u8); assert_eq!(response[66], CREDENTIAL_ID_SIZE as u8);
assert!(ctap_state assert!(ctap_state
.decrypt_credential_source(response[67..67 + CREDENTIAL_ID_SIZE].to_vec(), &application) .decrypt_credential_source(
&mut env,
response[67..67 + CREDENTIAL_ID_SIZE].to_vec(),
&application
)
.unwrap() .unwrap()
.is_some()); .is_some());
const CERT_START: usize = 67 + CREDENTIAL_ID_SIZE; const CERT_START: usize = 67 + CREDENTIAL_ID_SIZE;
@@ -677,10 +676,7 @@ mod test {
assert_eq!(response[0], 0x01); assert_eq!(response[0], 0x01);
check_signature_counter( check_signature_counter(
array_ref!(response, 1, 4), array_ref!(response, 1, 4),
ctap_state storage::global_signature_counter(&mut env).unwrap(),
.persistent_store
.global_signature_counter()
.unwrap(),
); );
} }
@@ -709,10 +705,7 @@ mod test {
assert_eq!(response[0], 0x01); assert_eq!(response[0], 0x01);
check_signature_counter( check_signature_counter(
array_ref!(response, 1, 4), array_ref!(response, 1, 4),
ctap_state storage::global_signature_counter(&mut env).unwrap(),
.persistent_store
.global_signature_counter()
.unwrap(),
); );
} }

View File

@@ -146,12 +146,12 @@ impl CtapHid {
// Process an incoming USB HID packet, and optionally returns a list of outgoing packets to // Process an incoming USB HID packet, and optionally returns a list of outgoing packets to
// send as a reply. // send as a reply.
pub fn process_hid_packet<E: Env>( pub fn process_hid_packet(
&mut self, &mut self,
env: &mut E, env: &mut impl Env,
packet: &HidPacket, packet: &HidPacket,
clock_value: ClockValue, clock_value: ClockValue,
ctap_state: &mut CtapState<E>, ctap_state: &mut CtapState,
) -> HidPacketIterator { ) -> HidPacketIterator {
// TODO: Send COMMAND_KEEPALIVE every 100ms? // TODO: Send COMMAND_KEEPALIVE every 100ms?
match self match self
@@ -442,10 +442,10 @@ mod test {
const DUMMY_CLOCK_VALUE: ClockValue = ClockValue::new(0, CLOCK_FREQUENCY_HZ); const DUMMY_CLOCK_VALUE: ClockValue = ClockValue::new(0, CLOCK_FREQUENCY_HZ);
const DUMMY_TIMESTAMP: Timestamp<isize> = Timestamp::from_ms(0); const DUMMY_TIMESTAMP: Timestamp<isize> = Timestamp::from_ms(0);
fn process_messages<E: Env>( fn process_messages(
env: &mut E, env: &mut TestEnv,
ctap_hid: &mut CtapHid, ctap_hid: &mut CtapHid,
ctap_state: &mut CtapState<E>, ctap_state: &mut CtapState,
request: Vec<Message>, request: Vec<Message>,
) -> Option<Vec<Message>> { ) -> Option<Vec<Message>> {
let mut result = Vec::new(); let mut result = Vec::new();
@@ -466,10 +466,10 @@ mod test {
Some(result) Some(result)
} }
fn cid_from_init<E: Env>( fn cid_from_init(
env: &mut E, env: &mut TestEnv,
ctap_hid: &mut CtapHid, ctap_hid: &mut CtapHid,
ctap_state: &mut CtapState<E>, ctap_state: &mut CtapState,
) -> ChannelID { ) -> ChannelID {
let nonce = vec![0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0]; let nonce = vec![0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0];
let reply = process_messages( let reply = process_messages(

View File

@@ -17,7 +17,7 @@ use super::command::AuthenticatorLargeBlobsParameters;
use super::customization::MAX_MSG_SIZE; use super::customization::MAX_MSG_SIZE;
use super::response::{AuthenticatorLargeBlobsResponse, ResponseData}; use super::response::{AuthenticatorLargeBlobsResponse, ResponseData};
use super::status_code::Ctap2StatusCode; use super::status_code::Ctap2StatusCode;
use super::storage::PersistentStore; use crate::ctap::storage;
use crate::env::Env; use crate::env::Env;
use alloc::vec; use alloc::vec;
use alloc::vec::Vec; use alloc::vec::Vec;
@@ -45,9 +45,9 @@ impl LargeBlobs {
} }
/// Process the large blob command. /// Process the large blob command.
pub fn process_command<E: Env>( pub fn process_command(
&mut self, &mut self,
persistent_store: &mut PersistentStore<E>, env: &mut impl Env,
client_pin: &mut ClientPin, client_pin: &mut ClientPin,
large_blobs_params: AuthenticatorLargeBlobsParameters, large_blobs_params: AuthenticatorLargeBlobsParameters,
) -> Result<ResponseData, Ctap2StatusCode> { ) -> Result<ResponseData, Ctap2StatusCode> {
@@ -66,7 +66,7 @@ impl LargeBlobs {
if get > MAX_FRAGMENT_LENGTH || offset.checked_add(get).is_none() { if get > MAX_FRAGMENT_LENGTH || offset.checked_add(get).is_none() {
return Err(Ctap2StatusCode::CTAP1_ERR_INVALID_LENGTH); return Err(Ctap2StatusCode::CTAP1_ERR_INVALID_LENGTH);
} }
let config = persistent_store.get_large_blob_array(offset, get)?; let config = storage::get_large_blob_array(env, offset, get)?;
return Ok(ResponseData::AuthenticatorLargeBlobs(Some( return Ok(ResponseData::AuthenticatorLargeBlobs(Some(
AuthenticatorLargeBlobsResponse { config }, AuthenticatorLargeBlobsResponse { config },
))); )));
@@ -85,7 +85,7 @@ impl LargeBlobs {
if offset != self.expected_next_offset { if offset != self.expected_next_offset {
return Err(Ctap2StatusCode::CTAP1_ERR_INVALID_SEQ); return Err(Ctap2StatusCode::CTAP1_ERR_INVALID_SEQ);
} }
if persistent_store.pin_hash()?.is_some() || persistent_store.has_always_uv()? { if storage::pin_hash(env)?.is_some() || storage::has_always_uv(env)? {
let pin_uv_auth_param = let pin_uv_auth_param =
pin_uv_auth_param.ok_or(Ctap2StatusCode::CTAP2_ERR_PUAT_REQUIRED)?; pin_uv_auth_param.ok_or(Ctap2StatusCode::CTAP2_ERR_PUAT_REQUIRED)?;
let pin_uv_auth_protocol = let pin_uv_auth_protocol =
@@ -122,7 +122,7 @@ impl LargeBlobs {
self.buffer = Vec::new(); self.buffer = Vec::new();
return Err(Ctap2StatusCode::CTAP2_ERR_INTEGRITY_FAILURE); return Err(Ctap2StatusCode::CTAP2_ERR_INTEGRITY_FAILURE);
} }
persistent_store.commit_large_blob_array(&self.buffer)?; storage::commit_large_blob_array(env, &self.buffer)?;
self.buffer = Vec::new(); self.buffer = Vec::new();
} }
return Ok(ResponseData::AuthenticatorLargeBlobs(None)); return Ok(ResponseData::AuthenticatorLargeBlobs(None));
@@ -143,7 +143,6 @@ mod test {
#[test] #[test]
fn test_process_command_get_empty() { fn test_process_command_get_empty() {
let mut env = TestEnv::new(); let mut env = TestEnv::new();
let mut persistent_store = PersistentStore::new(&mut env);
let key_agreement_key = crypto::ecdh::SecKey::gensk(env.rng()); let key_agreement_key = crypto::ecdh::SecKey::gensk(env.rng());
let pin_uv_auth_token = [0x55; 32]; let pin_uv_auth_token = [0x55; 32];
let mut client_pin = let mut client_pin =
@@ -163,7 +162,7 @@ mod test {
pin_uv_auth_protocol: None, pin_uv_auth_protocol: None,
}; };
let large_blobs_response = let large_blobs_response =
large_blobs.process_command(&mut persistent_store, &mut client_pin, large_blobs_params); large_blobs.process_command(&mut env, &mut client_pin, large_blobs_params);
match large_blobs_response.unwrap() { match large_blobs_response.unwrap() {
ResponseData::AuthenticatorLargeBlobs(Some(response)) => { ResponseData::AuthenticatorLargeBlobs(Some(response)) => {
assert_eq!(response.config, large_blob); assert_eq!(response.config, large_blob);
@@ -175,7 +174,6 @@ mod test {
#[test] #[test]
fn test_process_command_commit_and_get() { fn test_process_command_commit_and_get() {
let mut env = TestEnv::new(); let mut env = TestEnv::new();
let mut persistent_store = PersistentStore::new(&mut env);
let key_agreement_key = crypto::ecdh::SecKey::gensk(env.rng()); let key_agreement_key = crypto::ecdh::SecKey::gensk(env.rng());
let pin_uv_auth_token = [0x55; 32]; let pin_uv_auth_token = [0x55; 32];
let mut client_pin = let mut client_pin =
@@ -196,7 +194,7 @@ mod test {
pin_uv_auth_protocol: None, pin_uv_auth_protocol: None,
}; };
let large_blobs_response = let large_blobs_response =
large_blobs.process_command(&mut persistent_store, &mut client_pin, large_blobs_params); large_blobs.process_command(&mut env, &mut client_pin, large_blobs_params);
assert_eq!( assert_eq!(
large_blobs_response, large_blobs_response,
Ok(ResponseData::AuthenticatorLargeBlobs(None)) Ok(ResponseData::AuthenticatorLargeBlobs(None))
@@ -211,7 +209,7 @@ mod test {
pin_uv_auth_protocol: None, pin_uv_auth_protocol: None,
}; };
let large_blobs_response = let large_blobs_response =
large_blobs.process_command(&mut persistent_store, &mut client_pin, large_blobs_params); large_blobs.process_command(&mut env, &mut client_pin, large_blobs_params);
assert_eq!( assert_eq!(
large_blobs_response, large_blobs_response,
Ok(ResponseData::AuthenticatorLargeBlobs(None)) Ok(ResponseData::AuthenticatorLargeBlobs(None))
@@ -226,7 +224,7 @@ mod test {
pin_uv_auth_protocol: None, pin_uv_auth_protocol: None,
}; };
let large_blobs_response = let large_blobs_response =
large_blobs.process_command(&mut persistent_store, &mut client_pin, large_blobs_params); large_blobs.process_command(&mut env, &mut client_pin, large_blobs_params);
match large_blobs_response.unwrap() { match large_blobs_response.unwrap() {
ResponseData::AuthenticatorLargeBlobs(Some(response)) => { ResponseData::AuthenticatorLargeBlobs(Some(response)) => {
assert_eq!(response.config, large_blob); assert_eq!(response.config, large_blob);
@@ -238,7 +236,6 @@ mod test {
#[test] #[test]
fn test_process_command_commit_unexpected_offset() { fn test_process_command_commit_unexpected_offset() {
let mut env = TestEnv::new(); let mut env = TestEnv::new();
let mut persistent_store = PersistentStore::new(&mut env);
let key_agreement_key = crypto::ecdh::SecKey::gensk(env.rng()); let key_agreement_key = crypto::ecdh::SecKey::gensk(env.rng());
let pin_uv_auth_token = [0x55; 32]; let pin_uv_auth_token = [0x55; 32];
let mut client_pin = let mut client_pin =
@@ -259,7 +256,7 @@ mod test {
pin_uv_auth_protocol: None, pin_uv_auth_protocol: None,
}; };
let large_blobs_response = let large_blobs_response =
large_blobs.process_command(&mut persistent_store, &mut client_pin, large_blobs_params); large_blobs.process_command(&mut env, &mut client_pin, large_blobs_params);
assert_eq!( assert_eq!(
large_blobs_response, large_blobs_response,
Ok(ResponseData::AuthenticatorLargeBlobs(None)) Ok(ResponseData::AuthenticatorLargeBlobs(None))
@@ -275,7 +272,7 @@ mod test {
pin_uv_auth_protocol: None, pin_uv_auth_protocol: None,
}; };
let large_blobs_response = let large_blobs_response =
large_blobs.process_command(&mut persistent_store, &mut client_pin, large_blobs_params); large_blobs.process_command(&mut env, &mut client_pin, large_blobs_params);
assert_eq!( assert_eq!(
large_blobs_response, large_blobs_response,
Err(Ctap2StatusCode::CTAP1_ERR_INVALID_SEQ), Err(Ctap2StatusCode::CTAP1_ERR_INVALID_SEQ),
@@ -285,7 +282,6 @@ mod test {
#[test] #[test]
fn test_process_command_commit_unexpected_length() { fn test_process_command_commit_unexpected_length() {
let mut env = TestEnv::new(); let mut env = TestEnv::new();
let mut persistent_store = PersistentStore::new(&mut env);
let key_agreement_key = crypto::ecdh::SecKey::gensk(env.rng()); let key_agreement_key = crypto::ecdh::SecKey::gensk(env.rng());
let pin_uv_auth_token = [0x55; 32]; let pin_uv_auth_token = [0x55; 32];
let mut client_pin = let mut client_pin =
@@ -307,7 +303,7 @@ mod test {
pin_uv_auth_protocol: None, pin_uv_auth_protocol: None,
}; };
let large_blobs_response = let large_blobs_response =
large_blobs.process_command(&mut persistent_store, &mut client_pin, large_blobs_params); large_blobs.process_command(&mut env, &mut client_pin, large_blobs_params);
assert_eq!( assert_eq!(
large_blobs_response, large_blobs_response,
Ok(ResponseData::AuthenticatorLargeBlobs(None)) Ok(ResponseData::AuthenticatorLargeBlobs(None))
@@ -322,7 +318,7 @@ mod test {
pin_uv_auth_protocol: None, pin_uv_auth_protocol: None,
}; };
let large_blobs_response = let large_blobs_response =
large_blobs.process_command(&mut persistent_store, &mut client_pin, large_blobs_params); large_blobs.process_command(&mut env, &mut client_pin, large_blobs_params);
assert_eq!( assert_eq!(
large_blobs_response, large_blobs_response,
Err(Ctap2StatusCode::CTAP1_ERR_INVALID_PARAMETER), Err(Ctap2StatusCode::CTAP1_ERR_INVALID_PARAMETER),
@@ -332,7 +328,6 @@ mod test {
#[test] #[test]
fn test_process_command_commit_end_offset_overflow() { fn test_process_command_commit_end_offset_overflow() {
let mut env = TestEnv::new(); let mut env = TestEnv::new();
let mut persistent_store = PersistentStore::new(&mut env);
let key_agreement_key = crypto::ecdh::SecKey::gensk(env.rng()); let key_agreement_key = crypto::ecdh::SecKey::gensk(env.rng());
let pin_uv_auth_token = [0x55; 32]; let pin_uv_auth_token = [0x55; 32];
let mut client_pin = let mut client_pin =
@@ -348,7 +343,7 @@ mod test {
pin_uv_auth_protocol: None, pin_uv_auth_protocol: None,
}; };
assert_eq!( assert_eq!(
large_blobs.process_command(&mut persistent_store, &mut client_pin, large_blobs_params), large_blobs.process_command(&mut env, &mut client_pin, large_blobs_params),
Err(Ctap2StatusCode::CTAP1_ERR_INVALID_LENGTH), Err(Ctap2StatusCode::CTAP1_ERR_INVALID_LENGTH),
); );
} }
@@ -356,7 +351,6 @@ mod test {
#[test] #[test]
fn test_process_command_commit_unexpected_hash() { fn test_process_command_commit_unexpected_hash() {
let mut env = TestEnv::new(); let mut env = TestEnv::new();
let mut persistent_store = PersistentStore::new(&mut env);
let key_agreement_key = crypto::ecdh::SecKey::gensk(env.rng()); let key_agreement_key = crypto::ecdh::SecKey::gensk(env.rng());
let pin_uv_auth_token = [0x55; 32]; let pin_uv_auth_token = [0x55; 32];
let mut client_pin = let mut client_pin =
@@ -376,7 +370,7 @@ mod test {
pin_uv_auth_protocol: None, pin_uv_auth_protocol: None,
}; };
let large_blobs_response = let large_blobs_response =
large_blobs.process_command(&mut persistent_store, &mut client_pin, large_blobs_params); large_blobs.process_command(&mut env, &mut client_pin, large_blobs_params);
assert_eq!( assert_eq!(
large_blobs_response, large_blobs_response,
Err(Ctap2StatusCode::CTAP2_ERR_INTEGRITY_FAILURE), Err(Ctap2StatusCode::CTAP2_ERR_INTEGRITY_FAILURE),
@@ -385,7 +379,6 @@ mod test {
fn test_helper_process_command_commit_with_pin(pin_uv_auth_protocol: PinUvAuthProtocol) { fn test_helper_process_command_commit_with_pin(pin_uv_auth_protocol: PinUvAuthProtocol) {
let mut env = TestEnv::new(); let mut env = TestEnv::new();
let mut persistent_store = PersistentStore::new(&mut env);
let key_agreement_key = crypto::ecdh::SecKey::gensk(env.rng()); let key_agreement_key = crypto::ecdh::SecKey::gensk(env.rng());
let pin_uv_auth_token = [0x55; 32]; let pin_uv_auth_token = [0x55; 32];
let mut client_pin = let mut client_pin =
@@ -397,7 +390,7 @@ mod test {
let mut large_blob = vec![0x1B; DATA_LEN]; let mut large_blob = vec![0x1B; DATA_LEN];
large_blob.extend_from_slice(&Sha256::hash(&large_blob[..])[..TRUNCATED_HASH_LEN]); large_blob.extend_from_slice(&Sha256::hash(&large_blob[..])[..TRUNCATED_HASH_LEN]);
persistent_store.set_pin(&[0u8; 16], 4).unwrap(); storage::set_pin(&mut env, &[0u8; 16], 4).unwrap();
let mut large_blob_data = vec![0xFF; 32]; let mut large_blob_data = vec![0xFF; 32];
// Command constant and offset bytes. // Command constant and offset bytes.
large_blob_data.extend(&[0x0C, 0x00, 0x00, 0x00, 0x00, 0x00]); large_blob_data.extend(&[0x0C, 0x00, 0x00, 0x00, 0x00, 0x00]);
@@ -417,7 +410,7 @@ mod test {
pin_uv_auth_protocol: Some(pin_uv_auth_protocol), pin_uv_auth_protocol: Some(pin_uv_auth_protocol),
}; };
let large_blobs_response = let large_blobs_response =
large_blobs.process_command(&mut persistent_store, &mut client_pin, large_blobs_params); large_blobs.process_command(&mut env, &mut client_pin, large_blobs_params);
assert_eq!( assert_eq!(
large_blobs_response, large_blobs_response,
Ok(ResponseData::AuthenticatorLargeBlobs(None)) Ok(ResponseData::AuthenticatorLargeBlobs(None))

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

15
src/env/mod.rs vendored
View File

@@ -2,7 +2,7 @@ use crate::api::upgrade_storage::UpgradeStorage;
use crate::ctap::hid::ChannelID; use crate::ctap::hid::ChannelID;
use crate::ctap::status_code::Ctap2StatusCode; use crate::ctap::status_code::Ctap2StatusCode;
use crypto::rng256::Rng256; use crypto::rng256::Rng256;
use persistent_store::{Storage, StorageResult}; use persistent_store::{Storage, Store};
#[cfg(feature = "std")] #[cfg(feature = "std")]
pub mod test; pub mod test;
@@ -24,14 +24,11 @@ pub trait Env {
fn rng(&mut self) -> &mut Self::Rng; fn rng(&mut self) -> &mut Self::Rng;
fn user_presence(&mut self) -> &mut Self::UserPresence; fn user_presence(&mut self) -> &mut Self::UserPresence;
fn store(&mut self) -> &mut Store<Self::Storage>;
/// Returns the unique storage instance. /// Returns the upgrade storage instance.
/// ///
/// This function is called at most once. Implementation may panic if called more than once. /// Upgrade storage is optional, so implementations may return `None`. However, implementations
fn storage(&mut self) -> StorageResult<Self::Storage>; /// should either always return `None` or always return `Some`.
fn upgrade_storage(&mut self) -> Option<&mut Self::UpgradeStorage>;
/// Returns the unique upgrade storage instance.
///
/// This function is called at most once. Implementation may panic if called more than once.
fn upgrade_storage(&mut self) -> StorageResult<Self::UpgradeStorage>;
} }

52
src/env/test/mod.rs vendored
View File

@@ -3,26 +3,55 @@ use crate::ctap::hid::ChannelID;
use crate::ctap::status_code::Ctap2StatusCode; use crate::ctap::status_code::Ctap2StatusCode;
use crate::env::{Env, UserPresence}; use crate::env::{Env, UserPresence};
use crypto::rng256::ThreadRng256; use crypto::rng256::ThreadRng256;
use persistent_store::{BufferOptions, BufferStorage, StorageResult}; use persistent_store::{BufferOptions, BufferStorage, Store};
mod upgrade_storage; mod upgrade_storage;
pub struct TestEnv { pub struct TestEnv {
rng: ThreadRng256, rng: ThreadRng256,
user_presence: TestUserPresence, user_presence: TestUserPresence,
store: Store<BufferStorage>,
upgrade_storage: Option<BufferUpgradeStorage>,
} }
pub struct TestUserPresence { pub struct TestUserPresence {
check: Box<dyn Fn(ChannelID) -> Result<(), Ctap2StatusCode>>, check: Box<dyn Fn(ChannelID) -> Result<(), Ctap2StatusCode>>,
} }
fn new_storage() -> BufferStorage {
// Use the Nordic configuration.
const PAGE_SIZE: usize = 0x1000;
const NUM_PAGES: usize = 20;
let store = vec![0xff; NUM_PAGES * PAGE_SIZE].into_boxed_slice();
let options = BufferOptions {
word_size: 4,
page_size: PAGE_SIZE,
max_word_writes: 2,
max_page_erases: 10000,
strict_mode: true,
};
BufferStorage::new(store, options)
}
impl TestEnv { impl TestEnv {
pub fn new() -> Self { pub fn new() -> Self {
let rng = ThreadRng256 {}; let rng = ThreadRng256 {};
let user_presence = TestUserPresence { let user_presence = TestUserPresence {
check: Box::new(|_| Ok(())), check: Box::new(|_| Ok(())),
}; };
TestEnv { rng, user_presence } let storage = new_storage();
let store = Store::new(storage).ok().unwrap();
let upgrade_storage = Some(BufferUpgradeStorage::new().unwrap());
TestEnv {
rng,
user_presence,
store,
upgrade_storage,
}
}
pub fn disable_upgrade_storage(&mut self) {
self.upgrade_storage = None;
} }
} }
@@ -52,22 +81,11 @@ impl Env for TestEnv {
&mut self.user_presence &mut self.user_presence
} }
fn storage(&mut self) -> StorageResult<Self::Storage> { fn store(&mut self) -> &mut Store<Self::Storage> {
// Use the Nordic configuration. &mut self.store
const PAGE_SIZE: usize = 0x1000;
const NUM_PAGES: usize = 20;
let store = vec![0xff; NUM_PAGES * PAGE_SIZE].into_boxed_slice();
let options = BufferOptions {
word_size: 4,
page_size: PAGE_SIZE,
max_word_writes: 2,
max_page_erases: 10000,
strict_mode: true,
};
Ok(BufferStorage::new(store, options))
} }
fn upgrade_storage(&mut self) -> StorageResult<Self::UpgradeStorage> { fn upgrade_storage(&mut self) -> Option<&mut Self::UpgradeStorage> {
BufferUpgradeStorage::new() self.upgrade_storage.as_mut()
} }
} }

29
src/env/tock/mod.rs vendored
View File

@@ -14,14 +14,14 @@ use libtock_drivers::console::Console;
use libtock_drivers::result::{FlexUnwrap, TockError}; use libtock_drivers::result::{FlexUnwrap, TockError};
use libtock_drivers::timer::Duration; use libtock_drivers::timer::Duration;
use libtock_drivers::{led, timer, usb_ctap_hid}; use libtock_drivers::{led, timer, usb_ctap_hid};
use persistent_store::StorageResult; use persistent_store::{StorageResult, Store};
mod storage; mod storage;
pub struct TockEnv { pub struct TockEnv {
rng: TockRng256, rng: TockRng256,
storage: bool, store: Store<SyscallStorage>,
upgrade_storage: bool, upgrade_storage: SyscallUpgradeStorage,
} }
impl TockEnv { impl TockEnv {
@@ -34,10 +34,13 @@ impl TockEnv {
// Make sure the environment was not already taken. // Make sure the environment was not already taken.
static TAKEN: AtomicBool = AtomicBool::new(false); static TAKEN: AtomicBool = AtomicBool::new(false);
assert!(!TAKEN.fetch_or(true, Ordering::SeqCst)); assert!(!TAKEN.fetch_or(true, Ordering::SeqCst));
let storage = unsafe { steal_storage() }.unwrap();
let store = Store::new(storage).ok().unwrap();
let upgrade_storage = SyscallUpgradeStorage::new().unwrap();
TockEnv { TockEnv {
rng: TockRng256 {}, rng: TockRng256 {},
storage: false, store,
upgrade_storage: false, upgrade_storage,
} }
} }
} }
@@ -75,23 +78,15 @@ impl Env for TockEnv {
self self
} }
fn storage(&mut self) -> StorageResult<Self::Storage> { fn store(&mut self) -> &mut Store<Self::Storage> {
assert_once(&mut self.storage); &mut self.store
unsafe { steal_storage() }
} }
fn upgrade_storage(&mut self) -> StorageResult<Self::UpgradeStorage> { fn upgrade_storage(&mut self) -> Option<&mut Self::UpgradeStorage> {
assert_once(&mut self.upgrade_storage); Some(&mut self.upgrade_storage)
SyscallUpgradeStorage::new()
} }
} }
/// Asserts a boolean is false and sets it to true.
fn assert_once(b: &mut bool) {
assert!(!*b);
*b = true;
}
// Returns whether the keepalive was sent, or false if cancelled. // Returns whether the keepalive was sent, or false if cancelled.
fn send_keepalive_up_needed( fn send_keepalive_up_needed(
cid: ChannelID, cid: ChannelID,

View File

@@ -35,7 +35,7 @@ pub mod env;
/// CTAP implementation parameterized by its environment. /// CTAP implementation parameterized by its environment.
pub struct Ctap<E: Env> { pub struct Ctap<E: Env> {
env: E, env: E,
state: CtapState<E>, state: CtapState,
hid: CtapHid, hid: CtapHid,
} }
@@ -49,7 +49,7 @@ impl<E: Env> Ctap<E> {
Ctap { env, state, hid } Ctap { env, state, hid }
} }
pub fn state(&mut self) -> &mut CtapState<E> { pub fn state(&mut self) -> &mut CtapState {
&mut self.state &mut self.state
} }