use std::time::Duration;
use crate::core::{Connection, Version, patch_version};
use crate::fido::FidoConnection;
use crate::fido::FidoError;
use crate::smartcard::{Aid, SmartCardConnection, SmartCardError, SmartCardProtocol};
const CTAPHID_CBOR: u8 = 0x10;
const CTAPHID_MSG: u8 = 0x03;
const NFCCTAP_MSG: u8 = 0x10;
const NFCCTAP_GETRESPONSE: u8 = 0x11;
const SW_KEEPALIVE: u16 = 0x9100;
const NFCCTAP_POLL_INTERVAL: Duration = Duration::from_millis(100);
const NFCCTAP_CANCEL: u8 = 0x11;
#[derive(Debug)]
pub enum CtapError<E: std::error::Error + Send + Sync + 'static> {
Connection(E),
NotSupported(String),
InvalidResponse(String),
}
impl<E: std::error::Error + Send + Sync + 'static> std::fmt::Display for CtapError<E> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Connection(e) => write!(f, "Connection error: {e}"),
Self::NotSupported(msg) => write!(f, "Not supported: {msg}"),
Self::InvalidResponse(msg) => write!(f, "Invalid response: {msg}"),
}
}
}
impl<E: std::error::Error + Send + Sync + 'static> std::error::Error for CtapError<E> {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Connection(e) => Some(e),
_ => None,
}
}
}
impl<E: std::error::Error + Send + Sync + 'static> CtapError<E> {
pub fn erase(self) -> String {
self.to_string()
}
}
impl<E: std::error::Error + Send + Sync + 'static> From<E> for CtapError<E> {
fn from(e: E) -> Self {
Self::Connection(e)
}
}
trait CtapBackend<E: std::error::Error + Send + Sync + 'static>: Send {
fn version(&self) -> Version;
fn call_cbor(
&mut self,
data: &[u8],
on_keepalive: Option<&mut dyn FnMut(u8)>,
cancel: Option<&dyn Fn() -> bool>,
) -> Result<Vec<u8>, CtapError<E>>;
fn call_msg(&mut self, data: &[u8]) -> Result<Vec<u8>, CtapError<E>>;
fn has_ctap2(&self) -> bool;
fn has_ctap1(&self) -> bool;
fn into_connection_any(self: Box<Self>) -> Box<dyn std::any::Any>;
}
pub struct CtapSession<C: Connection> {
inner: Box<dyn CtapBackend<C::Error>>,
_phantom: std::marker::PhantomData<C>,
}
impl<C: Connection + 'static> CtapSession<C> {
pub fn version(&self) -> Version {
self.inner.version()
}
pub fn has_ctap2(&self) -> bool {
self.inner.has_ctap2()
}
pub fn has_ctap1(&self) -> bool {
self.inner.has_ctap1()
}
pub fn call_cbor(
&mut self,
data: &[u8],
on_keepalive: Option<&mut dyn FnMut(u8)>,
cancel: Option<&dyn Fn() -> bool>,
) -> Result<Vec<u8>, CtapError<C::Error>> {
self.inner.call_cbor(data, on_keepalive, cancel)
}
pub fn call_msg(&mut self, data: &[u8]) -> Result<Vec<u8>, CtapError<C::Error>> {
self.inner.call_msg(data)
}
pub fn into_connection(self) -> C {
*self
.inner
.into_connection_any()
.downcast::<C>()
.expect("CtapSession inner type mismatch (this is a bug)")
}
fn from_inner(inner: Box<dyn CtapBackend<C::Error>>) -> Self {
Self {
inner,
_phantom: std::marker::PhantomData,
}
}
}
impl<C: SmartCardConnection + Send + 'static> CtapSession<C> {
pub fn new(connection: C) -> Result<Self, (CtapError<SmartCardError>, C)> {
CcidCtap::open(connection).map(|inner| Self::from_inner(Box::new(inner)))
}
pub fn new_with_scp(
connection: C,
scp_key_params: &crate::smartcard::ScpKeyParams,
) -> Result<Self, (CtapError<SmartCardError>, C)> {
CcidCtap::open_with_scp(connection, scp_key_params)
.map(|inner| Self::from_inner(Box::new(inner)))
}
}
impl<C: FidoConnection + Send + 'static> CtapSession<C> {
pub fn new_fido(connection: C) -> Result<Self, (CtapError<FidoError>, C)> {
HidCtap::open(connection).map(|inner| Self::from_inner(Box::new(inner)))
}
}
struct CcidCtap<C: SmartCardConnection> {
protocol: SmartCardProtocol<C>,
version: Version,
has_ctap2: bool,
has_ctap1: bool,
}
impl<C: SmartCardConnection> CcidCtap<C> {
fn open(connection: C) -> Result<Self, (CtapError<SmartCardError>, C)> {
let mut protocol = SmartCardProtocol::new(connection);
let resp = match protocol.select(Aid::FIDO) {
Ok(resp) => resp,
Err(e) => return Err((CtapError::Connection(e), protocol.into_connection())),
};
Self::init(protocol, &resp)
}
fn open_with_scp(
connection: C,
scp_key_params: &crate::smartcard::ScpKeyParams,
) -> Result<Self, (CtapError<SmartCardError>, C)> {
let mut protocol = SmartCardProtocol::new(connection);
let resp = match protocol.select(Aid::FIDO) {
Ok(resp) => resp,
Err(e) => return Err((CtapError::Connection(e), protocol.into_connection())),
};
if let Err(e) = protocol.init_scp(scp_key_params) {
return Err((CtapError::Connection(e), protocol.into_connection()));
}
Self::init(protocol, &resp)
}
fn init(
mut protocol: SmartCardProtocol<C>,
select_resp: &[u8],
) -> Result<Self, (CtapError<SmartCardError>, C)> {
log::debug!("Opening CcidCtap (SmartCard/NFC)");
let has_ctap1 = select_resp == b"U2F_V2";
let has_ctap2 = protocol
.send_apdu(0x80, NFCCTAP_MSG, 0x80, 0x00, &[0x04])
.is_ok();
if !has_ctap2 && !has_ctap1 {
return Err((
CtapError::NotSupported("Device supports neither CTAP2 nor CTAP1".into()),
protocol.into_connection(),
));
}
let version = patch_version(Version(0, 0, 0));
Ok(Self {
protocol,
version,
has_ctap2,
has_ctap1,
})
}
fn nfcctap_call_cbor(
&mut self,
data: &[u8],
on_keepalive: Option<&mut dyn FnMut(u8)>,
cancel: Option<&dyn Fn() -> bool>,
) -> Result<Vec<u8>, CtapError<SmartCardError>> {
match self.protocol.send_apdu(0x80, NFCCTAP_MSG, 0x80, 0x00, data) {
Ok(resp) => Ok(resp),
Err(SmartCardError::Apdu { data: ka_data, sw }) if sw == SW_KEEPALIVE => {
self.nfcctap_poll(ka_data, on_keepalive, cancel)
}
Err(SmartCardError::Apdu { sw, .. }) => Err(CtapError::InvalidResponse(format!(
"NFCCTAP error: SW={sw:04X}"
))),
Err(e) => Err(CtapError::Connection(e)),
}
}
fn nfcctap_poll(
&mut self,
initial_ka: Vec<u8>,
mut on_keepalive: Option<&mut dyn FnMut(u8)>,
cancel: Option<&dyn Fn() -> bool>,
) -> Result<Vec<u8>, CtapError<SmartCardError>> {
let mut last_ka: Option<u8> = None;
if let Some(&status) = initial_ka.first() {
last_ka = Some(status);
if let Some(ref mut cb) = on_keepalive {
cb(status);
}
}
loop {
std::thread::sleep(NFCCTAP_POLL_INTERVAL);
let p1 = if cancel.is_some_and(|f| f()) {
NFCCTAP_CANCEL
} else {
0x00
};
match self
.protocol
.send_apdu(0x80, NFCCTAP_GETRESPONSE, p1, 0x00, &[])
{
Ok(resp) => return Ok(resp),
Err(SmartCardError::Apdu { data, sw }) if sw == SW_KEEPALIVE => {
if let Some(&status) = data.first()
&& last_ka != Some(status)
{
last_ka = Some(status);
if let Some(ref mut cb) = on_keepalive {
cb(status);
}
}
}
Err(SmartCardError::Apdu { sw, .. }) => {
return Err(CtapError::InvalidResponse(format!(
"NFCCTAP error: SW={sw:04X}"
)));
}
Err(e) => return Err(CtapError::Connection(e)),
}
}
}
fn nfcctap_call_msg(&mut self, data: &[u8]) -> Result<Vec<u8>, CtapError<SmartCardError>> {
if data.len() < 4 {
return Err(CtapError::InvalidResponse("APDU too short".into()));
}
let (cla, ins, p1, p2) = (data[0], data[1], data[2], data[3]);
let payload = if data.len() > 5 {
let end = 5 + data[4] as usize;
if end > data.len() {
return Err(CtapError::InvalidResponse(
"Payload length exceeds data".into(),
));
}
&data[5..end]
} else {
&[]
};
match self.protocol.send_apdu(cla, ins, p1, p2, payload) {
Ok(resp) => {
let mut result = resp;
result.push(0x90);
result.push(0x00);
Ok(result)
}
Err(SmartCardError::Apdu { data, sw }) => {
let mut result = data;
result.push((sw >> 8) as u8);
result.push((sw & 0xFF) as u8);
Ok(result)
}
Err(e) => Err(CtapError::Connection(e)),
}
}
}
impl<C: SmartCardConnection + Send + 'static> CtapBackend<SmartCardError> for CcidCtap<C> {
fn version(&self) -> Version {
self.version
}
fn call_cbor(
&mut self,
data: &[u8],
on_keepalive: Option<&mut dyn FnMut(u8)>,
cancel: Option<&dyn Fn() -> bool>,
) -> Result<Vec<u8>, CtapError<SmartCardError>> {
self.nfcctap_call_cbor(data, on_keepalive, cancel)
}
fn call_msg(&mut self, data: &[u8]) -> Result<Vec<u8>, CtapError<SmartCardError>> {
self.nfcctap_call_msg(data)
}
fn has_ctap2(&self) -> bool {
self.has_ctap2
}
fn has_ctap1(&self) -> bool {
self.has_ctap1
}
fn into_connection_any(self: Box<Self>) -> Box<dyn std::any::Any> {
Box::new(self.protocol.into_connection())
}
}
struct HidCtap<C: FidoConnection> {
connection: C,
version: Version,
has_ctap2: bool,
has_ctap1: bool,
}
impl<C: FidoConnection> HidCtap<C> {
fn open(connection: C) -> Result<Self, (CtapError<FidoError>, C)> {
log::debug!("Opening HidCtap (FIDO HID)");
let caps = connection.capabilities();
let has_ctap2 = caps.has_cbor();
let has_ctap1 = !caps.has_nmsg();
if !has_ctap2 && !has_ctap1 {
return Err((
CtapError::NotSupported("Device supports neither CTAP2 nor CTAP1".into()),
connection,
));
}
let version = patch_version(connection.device_version());
Ok(Self {
connection,
version,
has_ctap2,
has_ctap1,
})
}
}
impl<C: FidoConnection + Send + 'static> CtapBackend<FidoError> for HidCtap<C> {
fn version(&self) -> Version {
self.version
}
fn call_cbor(
&mut self,
data: &[u8],
on_keepalive: Option<&mut dyn FnMut(u8)>,
cancel: Option<&dyn Fn() -> bool>,
) -> Result<Vec<u8>, CtapError<FidoError>> {
self.connection
.call(CTAPHID_CBOR, data, on_keepalive, cancel)
.map_err(CtapError::Connection)
}
fn call_msg(&mut self, data: &[u8]) -> Result<Vec<u8>, CtapError<FidoError>> {
self.connection
.call(CTAPHID_MSG, data, None, None)
.map_err(CtapError::Connection)
}
fn has_ctap2(&self) -> bool {
self.has_ctap2
}
fn has_ctap1(&self) -> bool {
self.has_ctap1
}
fn into_connection_any(self: Box<Self>) -> Box<dyn std::any::Any> {
Box::new(self.connection)
}
}