use zeroize::Zeroizing;
use crate::cbor::{self, Value};
use crate::core::Connection;
use super::pin_protocol::PinProtocol;
use super::session::Ctap2Session;
use super::types::{CredentialInfo, RpInfo};
use super::{Ctap2Error, build_args_map, ctap2_cmd};
use crate::webauthn::types::{PublicKeyCredentialDescriptor, PublicKeyCredentialUserEntity};
mod cred_mgmt_cmd {
pub(super) const GET_CREDS_METADATA: u8 = 0x01;
pub(super) const ENUMERATE_RPS_BEGIN: u8 = 0x02;
pub(super) const ENUMERATE_RPS_NEXT: u8 = 0x03;
pub(super) const ENUMERATE_CREDS_BEGIN: u8 = 0x04;
pub(super) const ENUMERATE_CREDS_NEXT: u8 = 0x05;
pub(super) const DELETE_CREDENTIAL: u8 = 0x06;
pub(super) const UPDATE_USER_INFO: u8 = 0x07;
}
mod cred_mgmt_result_key {
pub(super) const EXISTING_CRED_COUNT: i64 = 0x01;
pub(super) const MAX_REMAINING_COUNT: i64 = 0x02;
pub(super) const TOTAL_RPS: i64 = 0x05;
pub(super) const TOTAL_CREDENTIALS: i64 = 0x09;
}
pub struct CredentialManagement<C: Connection> {
session: Ctap2Session<C>,
protocol: PinProtocol,
pin_token: Zeroizing<Vec<u8>>,
use_legacy: bool,
}
impl<C: Connection + 'static> CredentialManagement<C> {
pub fn is_supported(info: &super::Info) -> bool {
if info.options.get("credMgmt") == Some(&true) {
return true;
}
info.versions.contains(&"FIDO_2_1_PRE".to_string())
&& info.options.get("credentialMgmtPreview") == Some(&true)
}
pub fn is_readonly_supported(info: &super::Info) -> bool {
info.options.get("perCredMgmtRO") == Some(&true)
}
#[allow(clippy::result_large_err)]
pub fn new(
session: Ctap2Session<C>,
protocol: PinProtocol,
pin_token: Vec<u8>,
) -> Result<Self, (Ctap2Error<C::Error>, Ctap2Session<C>)> {
let info = &session.cached_info;
if !Self::is_supported(info) {
return Err((
Ctap2Error::InvalidResponse(
"Authenticator does not support credentialManagement".into(),
),
session,
));
}
let use_legacy = info.options.get("credMgmt") != Some(&true);
Ok(Self {
session,
protocol,
pin_token: Zeroizing::new(pin_token),
use_legacy,
})
}
pub fn into_session(self) -> Ctap2Session<C> {
self.session
}
pub fn is_update_supported(&self) -> bool {
!self.use_legacy
}
fn cmd_byte(&self) -> u8 {
if self.use_legacy {
ctap2_cmd::CREDENTIAL_MGMT_PRE
} else {
ctap2_cmd::CREDENTIAL_MGMT
}
}
fn call(
&mut self,
sub_cmd: u8,
sub_cmd_params: Option<&Value>,
auth: bool,
) -> Result<Value, Ctap2Error<C::Error>> {
let (protocol_ver, pin_uv_param) = if auth {
let mut msg = vec![sub_cmd];
if let Some(p) = sub_cmd_params {
msg.extend_from_slice(&cbor::encode(p));
}
let param = self.protocol.authenticate(&self.pin_token, &msg);
(
Some(Value::Int(self.protocol.version() as i64)),
Some(Value::Bytes(param)),
)
} else {
(None, None)
};
let data = build_args_map(&[
Some(Value::Int(sub_cmd as i64)), sub_cmd_params.cloned(), protocol_ver, pin_uv_param, ]);
self.session
.send_cbor(self.cmd_byte(), Some(&data), None, None)
}
pub fn get_metadata(&mut self) -> Result<(u32, u32), Ctap2Error<C::Error>> {
log::debug!("Getting credential metadata");
let resp = self.call(cred_mgmt_cmd::GET_CREDS_METADATA, None, true)?;
let existing = resp
.map_get_int(cred_mgmt_result_key::EXISTING_CRED_COUNT)
.and_then(|v| v.as_int())
.ok_or_else(|| {
Ctap2Error::InvalidResponse("missing existingResidentCredentialsCount".into())
})? as u32;
let remaining = resp
.map_get_int(cred_mgmt_result_key::MAX_REMAINING_COUNT)
.and_then(|v| v.as_int())
.ok_or_else(|| {
Ctap2Error::InvalidResponse(
"missing maxPossibleRemainingResidentCredentialsCount".into(),
)
})? as u32;
Ok((existing, remaining))
}
pub fn enumerate_rps(&mut self) -> Result<Vec<RpInfo>, Ctap2Error<C::Error>> {
log::debug!("Enumerating relying parties");
let first = self.call(cred_mgmt_cmd::ENUMERATE_RPS_BEGIN, None, true)?;
let total = first
.map_get_int(cred_mgmt_result_key::TOTAL_RPS)
.and_then(|v| v.as_int())
.unwrap_or(0) as usize;
if total == 0 {
return Ok(Vec::new());
}
let mut values = Vec::with_capacity(total);
values.push(first);
for _ in 1..total {
values.push(self.call(cred_mgmt_cmd::ENUMERATE_RPS_NEXT, None, false)?);
}
Ok(values.iter().filter_map(RpInfo::from_cbor).collect())
}
pub fn enumerate_creds(
&mut self,
rp_id_hash: &[u8],
) -> Result<Vec<CredentialInfo>, Ctap2Error<C::Error>> {
log::debug!("Enumerating credentials");
let params = Value::Map(vec![(Value::Int(0x01), Value::Bytes(rp_id_hash.to_vec()))]);
let first = self.call(cred_mgmt_cmd::ENUMERATE_CREDS_BEGIN, Some(¶ms), true)?;
let total = first
.map_get_int(cred_mgmt_result_key::TOTAL_CREDENTIALS)
.and_then(|v| v.as_int())
.unwrap_or(0) as usize;
if total == 0 {
return Ok(Vec::new());
}
let mut values = Vec::with_capacity(total);
values.push(first);
for _ in 1..total {
values.push(self.call(cred_mgmt_cmd::ENUMERATE_CREDS_NEXT, None, false)?);
}
Ok(values
.iter()
.filter_map(CredentialInfo::from_cbor)
.collect())
}
pub fn delete_cred(
&mut self,
credential_id: &PublicKeyCredentialDescriptor,
) -> Result<(), Ctap2Error<C::Error>> {
log::debug!("Deleting credential");
let params = Value::Map(vec![(Value::Int(0x02), credential_id.to_cbor())]);
self.call(cred_mgmt_cmd::DELETE_CREDENTIAL, Some(¶ms), true)?;
log::info!("Credential deleted");
Ok(())
}
pub fn update_user_info(
&mut self,
credential_id: &PublicKeyCredentialDescriptor,
user: &PublicKeyCredentialUserEntity,
) -> Result<(), Ctap2Error<C::Error>> {
log::debug!("Updating user info");
if self.use_legacy {
return Err(Ctap2Error::InvalidResponse(
"updateUserInfo not supported in preview mode".into(),
));
}
let params = Value::Map(vec![
(Value::Int(0x02), credential_id.to_cbor()),
(Value::Int(0x03), user.to_cbor()),
]);
self.call(cred_mgmt_cmd::UPDATE_USER_INFO, Some(¶ms), true)?;
log::info!("User info updated");
Ok(())
}
}