use sha2::{Digest, Sha256};
use zeroize::Zeroizing;
use crate::cbor::Value;
use crate::core::Connection;
use super::pin_protocol::{CoseKey, PinProtocol};
use super::session::Ctap2Session;
use super::{Ctap2Error, Info, build_args_map, ctap2_cmd};
#[derive(Clone)]
pub struct Ctap2Pin(crate::__internal::SecretValue<Vec<u8>>);
impl Ctap2Pin {
pub fn new(pin: &str) -> Result<Self, String> {
if pin.len() < 4 {
return Err("PIN must be at least 4 bytes".into());
}
let padded_len = pin.len().max(64).next_multiple_of(16);
if padded_len > 255 {
return Err("PIN must be at most 255 bytes when padded".into());
}
Ok(Self(crate::__internal::SecretValue::new(
pin.as_bytes().to_vec(),
)))
}
pub(crate) fn as_bytes(&self) -> &[u8] {
self.0.expose_secret()
}
}
impl std::fmt::Debug for Ctap2Pin {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Ctap2Pin([REDACTED])")
}
}
mod client_pin_cmd {
pub(super) const GET_PIN_RETRIES: u8 = 0x01;
pub(super) const GET_KEY_AGREEMENT: u8 = 0x02;
pub(super) const SET_PIN: u8 = 0x03;
pub(super) const CHANGE_PIN: u8 = 0x04;
pub(super) const GET_TOKEN_USING_PIN_LEGACY: u8 = 0x05;
pub(super) const GET_TOKEN_USING_UV: u8 = 0x06;
pub(super) const GET_UV_RETRIES: u8 = 0x07;
pub(super) const GET_TOKEN_USING_PIN: u8 = 0x09;
}
mod client_pin_result_key {
pub(super) const KEY_AGREEMENT: i64 = 0x01;
pub(super) const PIN_UV_TOKEN: i64 = 0x02;
pub(super) const PIN_RETRIES: i64 = 0x03;
pub(super) const POWER_CYCLE_STATE: i64 = 0x04;
pub(super) const UV_RETRIES: i64 = 0x05;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Permissions(u8);
impl Permissions {
pub const MAKE_CREDENTIAL: Self = Self(0x01);
pub const GET_ASSERTION: Self = Self(0x02);
pub const CREDENTIAL_MGMT: Self = Self(0x04);
pub const BIO_ENROLL: Self = Self(0x08);
pub const LARGE_BLOB_WRITE: Self = Self(0x10);
pub const AUTHENTICATOR_CFG: Self = Self(0x20);
pub const PERSISTENT_CREDENTIAL_MGMT: Self = Self(0x40);
pub const fn new(bits: u8) -> Self {
Self(bits)
}
pub const fn bits(self) -> u8 {
self.0
}
}
impl std::ops::BitOr for Permissions {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
impl std::ops::BitOrAssign for Permissions {
fn bitor_assign(&mut self, rhs: Self) {
self.0 |= rhs.0;
}
}
pub struct ClientPin<C: Connection> {
session: Ctap2Session<C>,
protocol: PinProtocol,
}
fn pad_pin(pin: &Ctap2Pin) -> Zeroizing<Vec<u8>> {
let pin_bytes = pin.as_bytes();
let mut padded = Zeroizing::new(pin_bytes.to_vec());
if padded.len() < 64 {
padded.resize(64, 0);
}
let remainder = padded.len() % 16;
if remainder != 0 {
let new_len = padded.len() + (16 - remainder);
padded.resize(new_len, 0);
}
padded
}
impl<C: Connection + 'static> ClientPin<C> {
#[allow(clippy::result_large_err)]
pub fn new(session: Ctap2Session<C>) -> Result<Self, (Ctap2Error<C::Error>, Ctap2Session<C>)> {
match Self::select_protocol(&session.cached_info) {
Ok(protocol) => Ok(Self { session, protocol }),
Err(e) => Err((e, session)),
}
}
pub fn new_with_protocol(session: Ctap2Session<C>, protocol: PinProtocol) -> Self {
Self { session, protocol }
}
pub fn protocol(&self) -> PinProtocol {
self.protocol
}
pub fn into_session(self) -> Ctap2Session<C> {
self.session
}
#[allow(clippy::too_many_arguments)]
fn send(
&mut self,
sub_cmd: u8,
key_agreement: Option<&CoseKey>,
pin_uv_param: Option<&[u8]>,
new_pin_enc: Option<&[u8]>,
pin_hash_enc: Option<&[u8]>,
permissions: Option<u8>,
permissions_rpid: Option<&str>,
on_keepalive: Option<&mut dyn FnMut(u8)>,
cancel: Option<&dyn Fn() -> bool>,
) -> Result<Value, Ctap2Error<C::Error>> {
let data = build_args_map(&[
Some(Value::Int(self.protocol.version() as i64)), Some(Value::Int(sub_cmd as i64)), key_agreement.cloned(), pin_uv_param.map(|b| Value::Bytes(b.to_vec())), new_pin_enc.map(|b| Value::Bytes(b.to_vec())), pin_hash_enc.map(|b| Value::Bytes(b.to_vec())), None, None, permissions.map(|p| Value::Int(p as i64)), permissions_rpid.map(|s| Value::Text(s.to_string())), ]);
self.session
.send_cbor(ctap2_cmd::CLIENT_PIN, Some(&data), on_keepalive, cancel)
}
pub fn get_pin_retries(&mut self) -> Result<(u32, Option<u32>), Ctap2Error<C::Error>> {
log::debug!("Getting PIN retries");
let resp = self.send(
client_pin_cmd::GET_PIN_RETRIES,
None,
None,
None,
None,
None,
None,
None,
None,
)?;
let retries = resp
.map_get_int(client_pin_result_key::PIN_RETRIES)
.and_then(|v| v.as_int())
.ok_or_else(|| Ctap2Error::InvalidResponse("missing pinRetries".into()))?
as u32;
let pcs = resp
.map_get_int(client_pin_result_key::POWER_CYCLE_STATE)
.and_then(|v| v.as_int())
.map(|n| n as u32);
Ok((retries, pcs))
}
pub fn get_uv_retries(&mut self) -> Result<u32, Ctap2Error<C::Error>> {
log::debug!("Getting UV retries");
let resp = self.send(
client_pin_cmd::GET_UV_RETRIES,
None,
None,
None,
None,
None,
None,
None,
None,
)?;
let retries = resp
.map_get_int(client_pin_result_key::UV_RETRIES)
.and_then(|v| v.as_int())
.ok_or_else(|| Ctap2Error::InvalidResponse("missing uvRetries".into()))?
as u32;
Ok(retries)
}
pub fn set_pin(&mut self, pin: &Ctap2Pin) -> Result<(), Ctap2Error<C::Error>> {
log::debug!("Setting PIN");
let (key_agreement, shared_secret) = self.get_shared_secret()?;
let pin_padded = pad_pin(pin);
let new_pin_enc = self.protocol.encrypt(&shared_secret, &pin_padded);
let pin_uv_param = self.protocol.authenticate(&shared_secret, &new_pin_enc);
self.send(
client_pin_cmd::SET_PIN,
Some(&key_agreement),
Some(&pin_uv_param),
Some(&new_pin_enc),
None,
None,
None,
None,
None,
)?;
log::info!("PIN has been set");
Ok(())
}
pub fn change_pin(
&mut self,
old_pin: &Ctap2Pin,
new_pin: &Ctap2Pin,
) -> Result<(), Ctap2Error<C::Error>> {
log::debug!("Changing PIN");
let (key_agreement, shared_secret) = self.get_shared_secret()?;
let pin_hash_full = Zeroizing::<[u8; 32]>::new(Sha256::digest(old_pin.as_bytes()).into());
let pin_hash_enc = self.protocol.encrypt(&shared_secret, &pin_hash_full[..16]);
let new_pin_padded = pad_pin(new_pin);
let new_pin_enc = self.protocol.encrypt(&shared_secret, &new_pin_padded);
let mut auth_msg = new_pin_enc.clone();
auth_msg.extend_from_slice(&pin_hash_enc);
let pin_uv_param = self.protocol.authenticate(&shared_secret, &auth_msg);
self.send(
client_pin_cmd::CHANGE_PIN,
Some(&key_agreement),
Some(&pin_uv_param),
Some(&new_pin_enc),
Some(&pin_hash_enc),
None,
None,
None,
None,
)?;
log::info!("PIN has been changed");
Ok(())
}
pub fn get_pin_token(
&mut self,
pin: &Ctap2Pin,
permissions: Option<Permissions>,
permissions_rpid: Option<&str>,
) -> Result<Vec<u8>, Ctap2Error<C::Error>> {
log::debug!("Getting PIN token");
let (key_agreement, shared_secret) = self.get_shared_secret()?;
let pin_hash_full = Zeroizing::<[u8; 32]>::new(Sha256::digest(pin.as_bytes()).into());
let pin_hash_enc = self.protocol.encrypt(&shared_secret, &pin_hash_full[..16]);
let (sub_cmd, perms, rpid) =
if Self::is_token_supported(&self.session.cached_info) && permissions.is_some() {
(
client_pin_cmd::GET_TOKEN_USING_PIN,
permissions.map(|p| p.bits()),
permissions_rpid,
)
} else {
(client_pin_cmd::GET_TOKEN_USING_PIN_LEGACY, None, None)
};
let resp = self.send(
sub_cmd,
Some(&key_agreement),
None,
None,
Some(&pin_hash_enc),
perms,
rpid,
None,
None,
)?;
let token_enc = resp
.map_get_int(client_pin_result_key::PIN_UV_TOKEN)
.and_then(|v| v.as_bytes())
.ok_or_else(|| Ctap2Error::InvalidResponse("missing pinUvToken".into()))?;
let token = self
.protocol
.decrypt(&shared_secret, token_enc)
.map_err(Ctap2Error::InvalidResponse)?;
self.protocol
.validate_token(&token)
.map_err(Ctap2Error::InvalidResponse)?;
Ok(token)
}
pub fn get_uv_token(
&mut self,
permissions: Option<Permissions>,
permissions_rpid: Option<&str>,
on_keepalive: Option<&mut dyn FnMut(u8)>,
cancel: Option<&dyn Fn() -> bool>,
) -> Result<Vec<u8>, Ctap2Error<C::Error>> {
log::debug!("Getting UV token");
let (key_agreement, shared_secret) = self.get_shared_secret()?;
let resp = self.send(
client_pin_cmd::GET_TOKEN_USING_UV,
Some(&key_agreement),
None,
None,
None,
permissions.map(|p| p.bits()),
permissions_rpid,
on_keepalive,
cancel,
)?;
let token_enc = resp
.map_get_int(client_pin_result_key::PIN_UV_TOKEN)
.and_then(|v| v.as_bytes())
.ok_or_else(|| Ctap2Error::InvalidResponse("missing pinUvToken".into()))?;
let token = self
.protocol
.decrypt(&shared_secret, token_enc)
.map_err(Ctap2Error::InvalidResponse)?;
self.protocol
.validate_token(&token)
.map_err(Ctap2Error::InvalidResponse)?;
Ok(token)
}
pub fn is_supported(info: &Info) -> bool {
info.options.contains_key("clientPin")
}
pub fn is_token_supported(info: &Info) -> bool {
info.options.get("pinUvAuthToken") == Some(&true)
}
fn select_protocol(info: &Info) -> Result<PinProtocol, Ctap2Error<C::Error>> {
for &version in &[2u32, 1] {
if info.pin_uv_protocols.contains(&version) {
return Ok(match version {
2 => PinProtocol::V2,
_ => PinProtocol::V1,
});
}
}
Err(Ctap2Error::InvalidResponse(
"No compatible PIN/UV protocol supported".into(),
))
}
pub(crate) fn get_shared_secret(
&mut self,
) -> Result<(CoseKey, Zeroizing<Vec<u8>>), Ctap2Error<C::Error>> {
let resp = self.send(
client_pin_cmd::GET_KEY_AGREEMENT,
None,
None,
None,
None,
None,
None,
None,
None,
)?;
let peer_key = resp
.map_get_int(client_pin_result_key::KEY_AGREEMENT)
.ok_or_else(|| Ctap2Error::InvalidResponse("missing keyAgreement".into()))?;
self.protocol
.encapsulate(peer_key)
.map_err(|e| Ctap2Error::InvalidResponse(format!("key agreement failed: {e}")))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_pad_pin() {
let padded = pad_pin(&Ctap2Pin::new("1234").unwrap());
assert_eq!(padded.len(), 64);
assert_eq!(&padded[..4], b"1234");
assert!(padded[4..].iter().all(|&b| b == 0));
assert!(Ctap2Pin::new("123").is_err());
let long = Ctap2Pin::new(&"a".repeat(64)).unwrap();
let padded = pad_pin(&long);
assert_eq!(padded.len(), 64);
}
}