adds storage changes for credential management

This commit is contained in:
Fabian Kaczmarczyck
2021-01-11 11:51:01 +01:00
parent 32d5ff91d4
commit 18ebeebb3e
3 changed files with 163 additions and 32 deletions

View File

@@ -848,13 +848,19 @@ where
CtapState::<R, CheckUserPresence>::PIN_PROTOCOL_VERSION, CtapState::<R, CheckUserPresence>::PIN_PROTOCOL_VERSION,
]), ]),
max_credential_count_in_list: MAX_CREDENTIAL_COUNT_IN_LIST.map(|c| c as u64), max_credential_count_in_list: MAX_CREDENTIAL_COUNT_IN_LIST.map(|c| c as u64),
// #TODO(106) update with version 2.1 of HMAC-secret // TODO(#106) update with version 2.1 of HMAC-secret
max_credential_id_length: Some(CREDENTIAL_ID_SIZE as u64), max_credential_id_length: Some(CREDENTIAL_ID_SIZE as u64),
transports: Some(vec![AuthenticatorTransport::Usb]), transports: Some(vec![AuthenticatorTransport::Usb]),
algorithms: Some(vec![ES256_CRED_PARAM]), algorithms: Some(vec![ES256_CRED_PARAM]),
default_cred_protect: DEFAULT_CRED_PROTECT, default_cred_protect: DEFAULT_CRED_PROTECT,
min_pin_length: self.persistent_store.min_pin_length()?, min_pin_length: self.persistent_store.min_pin_length()?,
firmware_version: None, firmware_version: None,
max_cred_blob_length: None,
// TODO(kaczmarczyck) update when extension is implemented
max_rp_ids_for_set_min_pin_length: None,
remaining_discoverable_credentials: Some(
self.persistent_store.remaining_credentials()? as u64,
),
}, },
)) ))
} }
@@ -1015,7 +1021,7 @@ mod test {
let mut ctap_state = CtapState::new(&mut rng, user_immediately_present, DUMMY_CLOCK_VALUE); let mut ctap_state = CtapState::new(&mut rng, user_immediately_present, DUMMY_CLOCK_VALUE);
let info_reponse = ctap_state.process_command(&[0x04], DUMMY_CHANNEL_ID, DUMMY_CLOCK_VALUE); let info_reponse = ctap_state.process_command(&[0x04], DUMMY_CHANNEL_ID, DUMMY_CLOCK_VALUE);
let mut expected_response = vec![0x00, 0xAA, 0x01]; let mut expected_response = vec![0x00, 0xAB, 0x01];
// The version array differs with CTAP1, always including 2.0 and 2.1. // The version array differs with CTAP1, always including 2.0 and 2.1.
#[cfg(not(feature = "with_ctap1"))] #[cfg(not(feature = "with_ctap1"))]
let version_count = 2; let version_count = 2;
@@ -1039,7 +1045,7 @@ mod test {
0x65, 0x6E, 0x74, 0x50, 0x69, 0x6E, 0xF4, 0x05, 0x19, 0x04, 0x00, 0x06, 0x81, 0x01, 0x65, 0x6E, 0x74, 0x50, 0x69, 0x6E, 0xF4, 0x05, 0x19, 0x04, 0x00, 0x06, 0x81, 0x01,
0x08, 0x18, 0x70, 0x09, 0x81, 0x63, 0x75, 0x73, 0x62, 0x0A, 0x81, 0xA2, 0x63, 0x61, 0x08, 0x18, 0x70, 0x09, 0x81, 0x63, 0x75, 0x73, 0x62, 0x0A, 0x81, 0xA2, 0x63, 0x61,
0x6C, 0x67, 0x26, 0x64, 0x74, 0x79, 0x70, 0x65, 0x6A, 0x70, 0x75, 0x62, 0x6C, 0x69, 0x6C, 0x67, 0x26, 0x64, 0x74, 0x79, 0x70, 0x65, 0x6A, 0x70, 0x75, 0x62, 0x6C, 0x69,
0x63, 0x2D, 0x6B, 0x65, 0x79, 0x0D, 0x04, 0x63, 0x2D, 0x6B, 0x65, 0x79, 0x0D, 0x04, 0x14, 0x18, 0x96,
] ]
.iter(), .iter(),
); );

View File

@@ -107,7 +107,6 @@ impl From<AuthenticatorGetAssertionResponse> for cbor::Value {
#[cfg_attr(test, derive(PartialEq))] #[cfg_attr(test, derive(PartialEq))]
#[cfg_attr(any(test, feature = "debug_ctap"), derive(Debug))] #[cfg_attr(any(test, feature = "debug_ctap"), derive(Debug))]
pub struct AuthenticatorGetInfoResponse { pub struct AuthenticatorGetInfoResponse {
// TODO(kaczmarczyck) add maxAuthenticatorConfigLength and defaultCredProtect
pub versions: Vec<String>, pub versions: Vec<String>,
pub extensions: Option<Vec<String>>, pub extensions: Option<Vec<String>>,
pub aaguid: [u8; 16], pub aaguid: [u8; 16],
@@ -121,6 +120,9 @@ pub struct AuthenticatorGetInfoResponse {
pub default_cred_protect: Option<CredentialProtectionPolicy>, pub default_cred_protect: Option<CredentialProtectionPolicy>,
pub min_pin_length: u8, pub min_pin_length: u8,
pub firmware_version: Option<u64>, pub firmware_version: Option<u64>,
pub max_cred_blob_length: Option<u64>,
pub max_rp_ids_for_set_min_pin_length: Option<u64>,
pub remaining_discoverable_credentials: Option<u64>,
} }
impl From<AuthenticatorGetInfoResponse> for cbor::Value { impl From<AuthenticatorGetInfoResponse> for cbor::Value {
@@ -139,6 +141,9 @@ impl From<AuthenticatorGetInfoResponse> for cbor::Value {
default_cred_protect, default_cred_protect,
min_pin_length, min_pin_length,
firmware_version, firmware_version,
max_cred_blob_length,
max_rp_ids_for_set_min_pin_length,
remaining_discoverable_credentials,
} = get_info_response; } = get_info_response;
let options_cbor: Option<cbor::Value> = options.map(|options| { let options_cbor: Option<cbor::Value> = options.map(|options| {
@@ -163,6 +168,9 @@ impl From<AuthenticatorGetInfoResponse> for cbor::Value {
0x0C => default_cred_protect.map(|p| p as u64), 0x0C => default_cred_protect.map(|p| p as u64),
0x0D => min_pin_length as u64, 0x0D => min_pin_length as u64,
0x0E => firmware_version, 0x0E => firmware_version,
0x0F => max_cred_blob_length,
0x10 => max_rp_ids_for_set_min_pin_length,
0x14 => remaining_discoverable_credentials,
} }
} }
} }
@@ -285,6 +293,9 @@ mod test {
default_cred_protect: None, default_cred_protect: None,
min_pin_length: 4, min_pin_length: 4,
firmware_version: None, firmware_version: None,
max_cred_blob_length: None,
max_rp_ids_for_set_min_pin_length: None,
remaining_discoverable_credentials: None,
}; };
let response_cbor: Option<cbor::Value> = let response_cbor: Option<cbor::Value> =
ResponseData::AuthenticatorGetInfo(get_info_response).into(); ResponseData::AuthenticatorGetInfo(get_info_response).into();
@@ -314,6 +325,9 @@ mod test {
default_cred_protect: Some(CredentialProtectionPolicy::UserVerificationRequired), default_cred_protect: Some(CredentialProtectionPolicy::UserVerificationRequired),
min_pin_length: 4, min_pin_length: 4,
firmware_version: Some(0), firmware_version: Some(0),
max_cred_blob_length: Some(1024),
max_rp_ids_for_set_min_pin_length: Some(8),
remaining_discoverable_credentials: Some(150),
}; };
let response_cbor: Option<cbor::Value> = let response_cbor: Option<cbor::Value> =
ResponseData::AuthenticatorGetInfo(get_info_response).into(); ResponseData::AuthenticatorGetInfo(get_info_response).into();
@@ -331,6 +345,9 @@ mod test {
0x0C => CredentialProtectionPolicy::UserVerificationRequired as u64, 0x0C => CredentialProtectionPolicy::UserVerificationRequired as u64,
0x0D => 4, 0x0D => 4,
0x0E => 0, 0x0E => 0,
0x0F => 1024,
0x10 => 8,
0x14 => 150,
}; };
assert_eq!(response_cbor, Some(expected_cbor)); assert_eq!(response_cbor, Some(expected_cbor));
} }

View File

@@ -16,6 +16,7 @@ mod key;
use crate::ctap::data_formats::{ use crate::ctap::data_formats::{
extract_array, extract_text_string, CredentialProtectionPolicy, PublicKeyCredentialSource, extract_array, extract_text_string, CredentialProtectionPolicy, PublicKeyCredentialSource,
PublicKeyCredentialUserEntity,
}; };
use crate::ctap::key_material; use crate::ctap::key_material;
use crate::ctap::pin_protocol_v1::PIN_AUTH_LENGTH; use crate::ctap::pin_protocol_v1::PIN_AUTH_LENGTH;
@@ -116,6 +117,29 @@ impl PersistentStore {
Ok(()) Ok(())
} }
/// Finds the key and value for a given credential ID.
///
/// # Errors
///
/// Returns `CTAP2_ERR_NO_CREDENTIALS` if the credential is not found.
fn find_credential_item(
&self,
credential_id: &[u8],
) -> Result<(usize, PublicKeyCredentialSource), Ctap2StatusCode> {
let mut iter_result = Ok(());
let iter = self.iter_credentials(&mut iter_result)?;
let mut credentials: Vec<(usize, PublicKeyCredentialSource)> = iter
.filter(|(_, credential)| credential.credential_id == credential_id)
.collect();
iter_result?;
if credentials.len() > 1 {
return Err(Ctap2StatusCode::CTAP2_ERR_VENDOR_INTERNAL_ERROR);
}
credentials
.pop()
.ok_or(Ctap2StatusCode::CTAP2_ERR_NO_CREDENTIALS)
}
/// Returns the first matching credential. /// Returns the first matching credential.
/// ///
/// Returns `None` if no credentials are matched or if `check_cred_protect` is set and the first /// Returns `None` if no credentials are matched or if `check_cred_protect` is set and the first
@@ -126,22 +150,17 @@ impl PersistentStore {
credential_id: &[u8], credential_id: &[u8],
check_cred_protect: bool, check_cred_protect: bool,
) -> Result<Option<PublicKeyCredentialSource>, Ctap2StatusCode> { ) -> Result<Option<PublicKeyCredentialSource>, Ctap2StatusCode> {
let mut iter_result = Ok(()); let credential = match self.find_credential_item(credential_id) {
let iter = self.iter_credentials(&mut iter_result)?; Err(Ctap2StatusCode::CTAP2_ERR_NO_CREDENTIALS) => return Ok(None),
// We don't check whether there is more than one matching credential to be able to exit Err(e) => return Err(e),
// early. Ok(credential) => credential.1,
let result = iter.map(|(_, credential)| credential).find(|credential| { };
credential.rp_id == rp_id && credential.credential_id == credential_id let is_protected = credential.cred_protect_policy
}); == Some(CredentialProtectionPolicy::UserVerificationRequired);
iter_result?; if credential.rp_id != rp_id || (check_cred_protect && is_protected) {
if let Some(cred) = &result { return Ok(None);
let user_verification_required = cred.cred_protect_policy
== Some(CredentialProtectionPolicy::UserVerificationRequired);
if check_cred_protect && user_verification_required {
return Ok(None);
}
} }
Ok(result) Ok(Some(credential))
} }
/// Stores or updates a credential. /// Stores or updates a credential.
@@ -196,6 +215,34 @@ impl PersistentStore {
Ok(()) Ok(())
} }
/// Deletes a credential.
///
/// # Errors
///
/// Returns `CTAP2_ERR_NO_CREDENTIALS` if the credential is not found.
pub fn _delete_credential(&mut self, credential_id: &[u8]) -> Result<(), Ctap2StatusCode> {
let (key, _) = self.find_credential_item(credential_id)?;
Ok(self.store.remove(key)?)
}
/// Updates a credential's user information.
///
/// # Errors
///
/// Returns `CTAP2_ERR_NO_CREDENTIALS` if the credential is not found.
pub fn _update_credential(
&mut self,
credential_id: &[u8],
user: PublicKeyCredentialUserEntity,
) -> Result<(), Ctap2StatusCode> {
let (key, mut credential) = self.find_credential_item(credential_id)?;
credential.user_name = user.user_name;
credential.user_display_name = user.user_display_name;
credential.user_icon = user.user_icon;
let value = serialize_credential(credential)?;
Ok(self.store.insert(key, &value)?)
}
/// Returns the list of matching credentials. /// Returns the list of matching credentials.
/// ///
/// Does not return credentials that are not discoverable if `check_cred_protect` is set. /// Does not return credentials that are not discoverable if `check_cred_protect` is set.
@@ -221,7 +268,6 @@ impl PersistentStore {
} }
/// Returns the number of credentials. /// Returns the number of credentials.
#[cfg(test)]
pub fn count_credentials(&self) -> Result<usize, Ctap2StatusCode> { pub fn count_credentials(&self) -> Result<usize, Ctap2StatusCode> {
let mut iter_result = Ok(()); let mut iter_result = Ok(());
let iter = self.iter_credentials(&mut iter_result)?; let iter = self.iter_credentials(&mut iter_result)?;
@@ -230,10 +276,17 @@ impl PersistentStore {
Ok(result) Ok(result)
} }
/// Returns the estimated number of credentials that can still be stored.
pub fn remaining_credentials(&self) -> Result<usize, Ctap2StatusCode> {
MAX_SUPPORTED_RESIDENTIAL_KEYS
.checked_sub(self.count_credentials()?)
.ok_or(Ctap2StatusCode::CTAP2_ERR_VENDOR_INTERNAL_ERROR)
}
/// Iterates through the credentials. /// Iterates through the credentials.
/// ///
/// If an error is encountered during iteration, it is written to `result`. /// If an error is encountered during iteration, it is written to `result`.
fn iter_credentials<'a>( pub fn iter_credentials<'a>(
&'a self, &'a self,
result: &'a mut Result<(), Ctap2StatusCode>, result: &'a mut Result<(), Ctap2StatusCode>,
) -> Result<IterCredentials<'a>, Ctap2StatusCode> { ) -> Result<IterCredentials<'a>, Ctap2StatusCode> {
@@ -494,7 +547,7 @@ impl From<persistent_store::StoreError> for Ctap2StatusCode {
} }
/// Iterator for credentials. /// Iterator for credentials.
struct IterCredentials<'a> { pub struct IterCredentials<'a> {
/// The store being iterated. /// The store being iterated.
store: &'a persistent_store::Store<Storage>, store: &'a persistent_store::Store<Storage>,
@@ -629,6 +682,66 @@ mod test {
assert!(persistent_store.count_credentials().unwrap() > 0); assert!(persistent_store.count_credentials().unwrap() > 0);
} }
#[test]
fn test_delete_credential() {
let mut rng = ThreadRng256 {};
let mut persistent_store = PersistentStore::new(&mut rng);
assert_eq!(persistent_store.count_credentials().unwrap(), 0);
let mut credential_ids = vec![];
for i in 0..MAX_SUPPORTED_RESIDENTIAL_KEYS {
let user_handle = i.to_ne_bytes().to_vec();
let credential_source = create_credential_source(&mut rng, "example.com", user_handle);
credential_ids.push(credential_source.credential_id.clone());
assert!(persistent_store.store_credential(credential_source).is_ok());
assert_eq!(persistent_store.count_credentials().unwrap(), i + 1);
}
let mut count = persistent_store.count_credentials().unwrap();
for credential_id in credential_ids {
assert!(persistent_store._delete_credential(&credential_id).is_ok());
count -= 1;
assert_eq!(persistent_store.count_credentials().unwrap(), count);
}
}
#[test]
fn test_update_credential() {
let mut rng = ThreadRng256 {};
let mut persistent_store = PersistentStore::new(&mut rng);
let user = PublicKeyCredentialUserEntity {
// User ID is ignored.
user_id: vec![0x00],
user_name: Some("name".to_string()),
user_display_name: Some("display_name".to_string()),
user_icon: Some("icon".to_string()),
};
assert_eq!(
persistent_store._update_credential(&[0x1D], user.clone()),
Err(Ctap2StatusCode::CTAP2_ERR_NO_CREDENTIALS)
);
let credential_source = create_credential_source(&mut rng, "example.com", vec![0x1D]);
let credential_id = credential_source.credential_id.clone();
assert!(persistent_store.store_credential(credential_source).is_ok());
let stored_credential = persistent_store
.find_credential("example.com", &credential_id, false)
.unwrap()
.unwrap();
assert_eq!(stored_credential.user_name, None);
assert_eq!(stored_credential.user_display_name, None);
assert_eq!(stored_credential.user_icon, None);
assert!(persistent_store
._update_credential(&credential_id, user.clone())
.is_ok());
let stored_credential = persistent_store
.find_credential("example.com", &credential_id, false)
.unwrap()
.unwrap();
assert_eq!(stored_credential.user_name, user.user_name);
assert_eq!(stored_credential.user_display_name, user.user_display_name);
assert_eq!(stored_credential.user_icon, user.user_icon);
}
#[test] #[test]
fn test_credential_order() { fn test_credential_order() {
let mut rng = ThreadRng256 {}; let mut rng = ThreadRng256 {};
@@ -645,17 +758,14 @@ mod test {
} }
#[test] #[test]
#[allow(clippy::assertions_on_constants)]
fn test_fill_store() { fn test_fill_store() {
let mut rng = ThreadRng256 {}; let mut rng = ThreadRng256 {};
let mut persistent_store = PersistentStore::new(&mut rng); let mut persistent_store = PersistentStore::new(&mut rng);
assert_eq!(persistent_store.count_credentials().unwrap(), 0); assert_eq!(persistent_store.count_credentials().unwrap(), 0);
// To make this test work for bigger storages, implement better int -> Vec conversion.
assert!(MAX_SUPPORTED_RESIDENTIAL_KEYS < 256);
for i in 0..MAX_SUPPORTED_RESIDENTIAL_KEYS { for i in 0..MAX_SUPPORTED_RESIDENTIAL_KEYS {
let credential_source = let user_handle = i.to_ne_bytes().to_vec();
create_credential_source(&mut rng, "example.com", vec![i as u8]); let credential_source = create_credential_source(&mut rng, "example.com", user_handle);
assert!(persistent_store.store_credential(credential_source).is_ok()); assert!(persistent_store.store_credential(credential_source).is_ok());
assert_eq!(persistent_store.count_credentials().unwrap(), i + 1); assert_eq!(persistent_store.count_credentials().unwrap(), i + 1);
} }
@@ -675,7 +785,6 @@ mod test {
} }
#[test] #[test]
#[allow(clippy::assertions_on_constants)]
fn test_overwrite() { fn test_overwrite() {
let mut rng = ThreadRng256 {}; let mut rng = ThreadRng256 {};
let mut persistent_store = PersistentStore::new(&mut rng); let mut persistent_store = PersistentStore::new(&mut rng);
@@ -699,11 +808,10 @@ mod test {
&[expected_credential] &[expected_credential]
); );
// To make this test work for bigger storages, implement better int -> Vec conversion. let mut persistent_store = PersistentStore::new(&mut rng);
assert!(MAX_SUPPORTED_RESIDENTIAL_KEYS < 256);
for i in 0..MAX_SUPPORTED_RESIDENTIAL_KEYS { for i in 0..MAX_SUPPORTED_RESIDENTIAL_KEYS {
let credential_source = let user_handle = i.to_ne_bytes().to_vec();
create_credential_source(&mut rng, "example.com", vec![i as u8]); let credential_source = create_credential_source(&mut rng, "example.com", user_handle);
assert!(persistent_store.store_credential(credential_source).is_ok()); assert!(persistent_store.store_credential(credential_source).is_ok());
assert_eq!(persistent_store.count_credentials().unwrap(), i + 1); assert_eq!(persistent_store.count_credentials().unwrap(), i + 1);
} }