use std::collections::HashMap;
use std::fmt;
use thiserror::Error;
use crate::__internal::tlv::{parse_tlv_dict, parse_tlv_list, tlv_encode};
use crate::core::{Connection, Transport, Version, bytes2int, int2bytes};
use crate::fido::FidoConnection;
use crate::fido::FidoError;
use crate::otp::{
OtpConnection, OtpError, OtpProtocol, STATUS_OFFSET_PROG_SEQ, verify_and_strip_crc,
};
use crate::smartcard::{Aid, SmartCardConnection, SmartCardError, SmartCardProtocol};
use crate::yubiotp::ConfigSlot;
const INS_SET_MODE: u8 = 0x16;
const INS_READ_CONFIG: u8 = 0x1D;
const INS_WRITE_CONFIG: u8 = 0x1C;
const INS_DEVICE_RESET: u8 = 0x1F;
const INS_READ_STORAGE_INFO: u8 = 0x30;
const P1_DEVICE_CONFIG: u8 = 0x11;
const CONFIG_SLOT_DEVICE_CONFIG: u8 = 0x11;
const TAG_USB_SUPPORTED: u32 = 0x01;
const TAG_SERIAL: u32 = 0x02;
const TAG_USB_ENABLED: u32 = 0x03;
const TAG_FORM_FACTOR: u32 = 0x04;
const TAG_VERSION: u32 = 0x05;
const TAG_AUTO_EJECT_TIMEOUT: u32 = 0x06;
const TAG_CHALRESP_TIMEOUT: u32 = 0x07;
const TAG_DEVICE_FLAGS: u32 = 0x08;
#[allow(dead_code)]
const TAG_APP_VERSIONS: u32 = 0x09;
const TAG_CONFIG_LOCK: u32 = 0x0A;
const TAG_UNLOCK: u32 = 0x0B;
const TAG_REBOOT: u32 = 0x0C;
const TAG_NFC_SUPPORTED: u32 = 0x0D;
const TAG_NFC_ENABLED: u32 = 0x0E;
#[allow(dead_code)]
const TAG_IAP_DETECTION: u32 = 0x0F;
const TAG_MORE_DATA: u32 = 0x10;
#[allow(dead_code)]
const TAG_FREE_FORM: u32 = 0x11;
#[allow(dead_code)]
const TAG_HID_INIT_DELAY: u32 = 0x12;
const TAG_PART_NUMBER: u32 = 0x13;
const TAG_FIPS_CAPABLE: u32 = 0x14;
const TAG_FIPS_APPROVED: u32 = 0x15;
const TAG_PIN_COMPLEXITY: u32 = 0x16;
const TAG_NFC_RESTRICTED: u32 = 0x17;
const TAG_RESET_BLOCKED: u32 = 0x18;
const TAG_VERSION_QUALIFIER: u32 = 0x19;
const TAG_FPS_VERSION: u32 = 0x20;
const TAG_STM_VERSION: u32 = 0x21;
const TAG_NAME: u32 = 0x1B;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Capability(pub u16);
impl Capability {
pub const OTP: Self = Self(0x01);
pub const U2F: Self = Self(0x02);
pub const OPENPGP: Self = Self(0x08);
pub const PIV: Self = Self(0x10);
pub const OATH: Self = Self(0x20);
pub const HSMAUTH: Self = Self(0x100);
pub const FIDO2: Self = Self(0x200);
pub const FIDOCCID: Self = Self(0x1000);
pub const NONE: Self = Self(0);
fn from_fips(fips: u16) -> Self {
let mut c = 0u16;
if fips & (1 << 0) != 0 {
c |= Self::FIDO2.0;
}
if fips & (1 << 1) != 0 {
c |= Self::PIV.0;
}
if fips & (1 << 2) != 0 {
c |= Self::OPENPGP.0;
}
if fips & (1 << 3) != 0 {
c |= Self::OATH.0;
}
if fips & (1 << 4) != 0 {
c |= Self::HSMAUTH.0;
}
Self(c)
}
pub fn is_empty(self) -> bool {
self.0 == 0
}
pub fn contains(self, other: Self) -> bool {
self.0 & other.0 == other.0
}
pub const ALL: &[Self] = &[
Self::OTP,
Self::U2F,
Self::FIDO2,
Self::OATH,
Self::PIV,
Self::OPENPGP,
Self::HSMAUTH,
Self::FIDOCCID,
];
pub fn display_name(self) -> &'static str {
match self {
Self::OTP => "Yubico OTP",
Self::U2F => "FIDO U2F",
Self::FIDO2 => "FIDO2",
Self::OATH => "OATH",
Self::PIV => "PIV",
Self::OPENPGP => "OpenPGP",
Self::HSMAUTH => "YubiHSM Auth",
Self::FIDOCCID => "FIDO over USB CCID",
_ => "Unknown",
}
}
}
impl std::ops::BitOr for Capability {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
impl std::ops::BitOrAssign for Capability {
fn bitor_assign(&mut self, rhs: Self) {
self.0 |= rhs.0;
}
}
impl std::ops::BitAnd for Capability {
type Output = Self;
fn bitand(self, rhs: Self) -> Self {
Self(self.0 & rhs.0)
}
}
impl std::ops::BitAndAssign for Capability {
fn bitand_assign(&mut self, rhs: Self) {
self.0 &= rhs.0;
}
}
impl fmt::Display for Capability {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let names: &[(Self, &str)] = &[
(Self::OTP, "OTP"),
(Self::U2F, "U2F"),
(Self::OPENPGP, "OPENPGP"),
(Self::PIV, "PIV"),
(Self::OATH, "OATH"),
(Self::HSMAUTH, "HSMAUTH"),
(Self::FIDO2, "FIDO2"),
(Self::FIDOCCID, "FIDO_CCID"),
];
let mut parts = Vec::new();
for &(cap, name) in names {
if self.0 & cap.0 != 0 {
parts.push(name);
}
}
if parts.is_empty() {
write!(f, "None: 0x00")
} else {
write!(f, "{}: {:#06x}", parts.join("|"), self.0)
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[repr(u8)]
pub enum FormFactor {
Unknown = 0x00,
UsbAKeychain = 0x01,
UsbANano = 0x02,
UsbCKeychain = 0x03,
UsbCNano = 0x04,
UsbCLightning = 0x05,
UsbABio = 0x06,
UsbCBio = 0x07,
}
impl FormFactor {
pub fn from_code(code: u8) -> Self {
match code & 0x0F {
0x01 => Self::UsbAKeychain,
0x02 => Self::UsbANano,
0x03 => Self::UsbCKeychain,
0x04 => Self::UsbCNano,
0x05 => Self::UsbCLightning,
0x06 => Self::UsbABio,
0x07 => Self::UsbCBio,
_ => Self::Unknown,
}
}
pub fn is_bio(self) -> bool {
matches!(self, Self::UsbABio | Self::UsbCBio)
}
}
impl fmt::Display for FormFactor {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UsbAKeychain => write!(f, "Keychain (USB-A)"),
Self::UsbANano => write!(f, "Nano (USB-A)"),
Self::UsbCKeychain => write!(f, "Keychain (USB-C)"),
Self::UsbCNano => write!(f, "Nano (USB-C)"),
Self::UsbCLightning => write!(f, "Keychain (USB-C, Lightning)"),
Self::UsbABio => write!(f, "Bio (USB-A)"),
Self::UsbCBio => write!(f, "Bio (USB-C)"),
Self::Unknown => write!(f, "Unknown"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct DeviceFlag(pub u8);
impl DeviceFlag {
#[allow(dead_code)]
const REMOTE_WAKEUP: Self = Self(0x40);
pub const EJECT: Self = Self(0x80);
pub const NONE: Self = Self(0);
pub fn is_empty(self) -> bool {
self.0 == 0
}
}
impl std::ops::BitOr for DeviceFlag {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
impl std::ops::BitOrAssign for DeviceFlag {
fn bitor_assign(&mut self, rhs: Self) {
self.0 |= rhs.0;
}
}
impl std::ops::BitAnd for DeviceFlag {
type Output = Self;
fn bitand(self, rhs: Self) -> Self {
Self(self.0 & rhs.0)
}
}
impl fmt::Display for DeviceFlag {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "0x{:02x}", self.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum ReleaseType {
Alpha = 0,
Beta = 1,
Final = 2,
}
impl ReleaseType {
pub fn from_value(v: u8) -> Self {
match v {
0 => Self::Alpha,
1 => Self::Beta,
_ => Self::Final,
}
}
}
impl fmt::Display for ReleaseType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Alpha => write!(f, "alpha"),
Self::Beta => write!(f, "beta"),
Self::Final => write!(f, "final"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VersionQualifier {
pub version: Version,
pub release_type: ReleaseType,
pub iteration: u8,
}
impl VersionQualifier {
pub fn new(version: Version, release_type: ReleaseType, iteration: u8) -> Self {
Self {
version,
release_type,
iteration,
}
}
pub fn final_release(version: Version) -> Self {
Self {
version,
release_type: ReleaseType::Final,
iteration: 0,
}
}
}
impl fmt::Display for VersionQualifier {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}.{}.{}",
self.version, self.release_type, self.iteration
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UsbInterface(pub u8);
impl UsbInterface {
pub const OTP: Self = Self(0x01);
pub const CCID: Self = Self(0x02);
pub const FIDO: Self = Self(0x04);
pub fn contains(self, other: Self) -> bool {
self.0 & other.0 == other.0
}
}
impl std::ops::BitOr for UsbInterface {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
impl std::ops::BitAnd for UsbInterface {
type Output = Self;
fn bitand(self, rhs: Self) -> Self {
Self(self.0 & rhs.0)
}
}
impl fmt::Display for UsbInterface {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut parts = Vec::new();
if self.0 & Self::OTP.0 != 0 {
parts.push("OTP");
}
if self.0 & Self::FIDO.0 != 0 {
parts.push("FIDO");
}
if self.0 & Self::CCID.0 != 0 {
parts.push("CCID");
}
write!(f, "{}", parts.join(", "))
}
}
const MODES: [UsbInterface; 7] = [
UsbInterface::OTP, UsbInterface::CCID, UsbInterface(UsbInterface::OTP.0 | UsbInterface::CCID.0), UsbInterface::FIDO, UsbInterface(UsbInterface::OTP.0 | UsbInterface::FIDO.0), UsbInterface(UsbInterface::FIDO.0 | UsbInterface::CCID.0), UsbInterface(UsbInterface::OTP.0 | UsbInterface::FIDO.0 | UsbInterface::CCID.0), ];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Mode {
pub code: u8,
pub interfaces: UsbInterface,
}
impl Mode {
pub fn new(interfaces: UsbInterface) -> Option<Self> {
MODES
.iter()
.position(|m| m.0 == interfaces.0)
.map(|code| Self {
code: code as u8,
interfaces,
})
}
pub fn from_code(code: u8) -> Option<Self> {
let idx = (code & 0x07) as usize;
MODES.get(idx).map(|&interfaces| Self {
code: idx as u8,
interfaces,
})
}
}
impl fmt::Display for Mode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut parts = Vec::new();
if self.interfaces.0 & UsbInterface::OTP.0 != 0 {
parts.push("OTP");
}
if self.interfaces.0 & UsbInterface::CCID.0 != 0 {
parts.push("CCID");
}
if self.interfaces.0 & UsbInterface::FIDO.0 != 0 {
parts.push("FIDO");
}
write!(f, "{}", parts.join("+"))
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct DeviceConfig {
pub enabled_capabilities: HashMap<Transport, Capability>,
pub auto_eject_timeout: Option<u16>,
pub challenge_response_timeout: Option<u8>,
pub device_flags: Option<DeviceFlag>,
pub nfc_restricted: Option<bool>,
}
impl DeviceConfig {
fn get_bytes(
&self,
reboot: bool,
cur_lock_code: Option<&[u8]>,
new_lock_code: Option<&[u8]>,
) -> Result<Vec<u8>, SmartCardError> {
let mut buf = Vec::new();
if reboot {
buf.extend_from_slice(&tlv_encode(TAG_REBOOT, &[]));
}
if let Some(code) = cur_lock_code {
buf.extend_from_slice(&tlv_encode(TAG_UNLOCK, code));
}
if let Some(&usb_enabled) = self.enabled_capabilities.get(&Transport::Usb) {
buf.extend_from_slice(&tlv_encode(
TAG_USB_ENABLED,
&(usb_enabled.0).to_be_bytes()[..2],
));
}
if let Some(&nfc_enabled) = self.enabled_capabilities.get(&Transport::Nfc) {
buf.extend_from_slice(&tlv_encode(
TAG_NFC_ENABLED,
&(nfc_enabled.0).to_be_bytes()[..2],
));
}
if let Some(timeout) = self.auto_eject_timeout {
buf.extend_from_slice(&tlv_encode(TAG_AUTO_EJECT_TIMEOUT, &timeout.to_be_bytes()));
}
if let Some(timeout) = self.challenge_response_timeout {
buf.extend_from_slice(&tlv_encode(
TAG_CHALRESP_TIMEOUT,
&int2bytes(timeout as u64),
));
}
if let Some(flags) = self.device_flags {
buf.extend_from_slice(&tlv_encode(TAG_DEVICE_FLAGS, &int2bytes(flags.0 as u64)));
}
if let Some(code) = new_lock_code {
buf.extend_from_slice(&tlv_encode(TAG_CONFIG_LOCK, code));
}
if self.nfc_restricted == Some(true) {
buf.extend_from_slice(&tlv_encode(TAG_NFC_RESTRICTED, &[0x01]));
}
if buf.len() > 0xFF {
return Err(SmartCardError::InvalidData(
"DeviceConfiguration too large".into(),
));
}
let mut result = int2bytes(buf.len() as u64);
result.extend_from_slice(&buf);
Ok(result)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct DeviceInfo {
pub config: DeviceConfig,
pub serial: Option<u32>,
pub version: Version,
pub form_factor: FormFactor,
pub supported_capabilities: HashMap<Transport, Capability>,
pub is_locked: bool,
pub is_fips: bool,
pub is_sky: bool,
pub part_number: Option<String>,
pub fips_capable: Capability,
pub fips_approved: Capability,
pub pin_complexity: bool,
pub reset_blocked: Capability,
pub fps_version: Option<Version>,
pub stm_version: Option<Version>,
pub version_qualifier: VersionQualifier,
pub name: Option<String>,
}
impl DeviceInfo {
pub fn parse(encoded: &[u8], default_version: Version) -> Result<Self, SmartCardError> {
if encoded.is_empty() {
return Err(SmartCardError::InvalidData("Empty response".into()));
}
let expected_len = encoded[0] as usize;
if encoded.len() - 1 != expected_len {
return Err(SmartCardError::InvalidData("Invalid length".into()));
}
let tlvs = parse_tlv_dict(&encoded[1..])
.map_err(|e| SmartCardError::InvalidData(e.to_string()))?;
Self::parse_tlvs(&tlvs, default_version)
}
pub fn parse_tlvs(
data: &HashMap<u32, Vec<u8>>,
default_version: Version,
) -> Result<Self, SmartCardError> {
let locked = data.get(&TAG_CONFIG_LOCK).is_some_and(|v| v == &[0x01]);
let serial = {
let raw = bytes2int(data.get(&TAG_SERIAL).map_or(&[0u8][..], |v| v));
if raw == 0 { None } else { Some(raw as u32) }
};
let ff_value = bytes2int(data.get(&TAG_FORM_FACTOR).map_or(&[0u8][..], |v| v)) as u8;
let form_factor = FormFactor::from_code(ff_value);
let is_fips = ff_value & 0x80 != 0;
let is_sky = ff_value & 0x40 != 0;
let mut version = if let Some(v) = data.get(&TAG_VERSION) {
Version::from_bytes(v)
} else {
default_version
};
let auto_eject_to =
bytes2int(data.get(&TAG_AUTO_EJECT_TIMEOUT).map_or(&[0u8][..], |v| v)) as u16;
let chal_resp_to =
bytes2int(data.get(&TAG_CHALRESP_TIMEOUT).map_or(&[0u8][..], |v| v)) as u8;
let flags =
DeviceFlag(bytes2int(data.get(&TAG_DEVICE_FLAGS).map_or(&[0u8][..], |v| v)) as u8);
let mut supported = HashMap::new();
let mut enabled = HashMap::new();
if version == Version(4, 2, 4) {
supported.insert(Transport::Usb, Capability(0x3F));
} else if let Some(v) = data.get(&TAG_USB_SUPPORTED) {
supported.insert(Transport::Usb, Capability(bytes2int(v) as u16));
}
if let Some(v) = data.get(&TAG_USB_ENABLED) {
if !(version >= Version(4, 0, 0) && version < Version(5, 0, 0)) {
enabled.insert(Transport::Usb, Capability(bytes2int(v) as u16));
}
}
if let Some(v) = data.get(&TAG_NFC_SUPPORTED) {
supported.insert(Transport::Nfc, Capability(bytes2int(v) as u16));
if let Some(nfc_en) = data.get(&TAG_NFC_ENABLED) {
enabled.insert(Transport::Nfc, Capability(bytes2int(nfc_en) as u16));
}
}
let nfc_restricted = data.get(&TAG_NFC_RESTRICTED).is_some_and(|v| v == &[0x01]);
let part_number = data.get(&TAG_PART_NUMBER).and_then(|v| {
let s = String::from_utf8(v.clone()).ok()?;
if s.is_empty() { None } else { Some(s) }
});
let fips_capable = Capability::from_fips(bytes2int(
data.get(&TAG_FIPS_CAPABLE).map_or(&[0u8][..], |v| v),
) as u16);
let fips_approved = Capability::from_fips(bytes2int(
data.get(&TAG_FIPS_APPROVED).map_or(&[0u8][..], |v| v),
) as u16);
let pin_complexity = data.get(&TAG_PIN_COMPLEXITY).is_some_and(|v| v == &[0x01]);
let reset_blocked =
Capability(bytes2int(data.get(&TAG_RESET_BLOCKED).map_or(&[0u8][..], |v| v)) as u16);
let version_qualifier = if let Some(vq_data) = data.get(&TAG_VERSION_QUALIFIER) {
let vq_tlvs =
parse_tlv_dict(vq_data).map_err(|e| SmartCardError::InvalidData(e.to_string()))?;
let vq_version = vq_tlvs
.get(&0x01)
.map(|v| Version::from_bytes(v))
.unwrap_or(version);
let vq_type = vq_tlvs
.get(&0x02)
.map(|v| ReleaseType::from_value(bytes2int(v) as u8))
.unwrap_or(ReleaseType::Final);
let vq_iter = vq_tlvs.get(&0x03).map(|v| bytes2int(v) as u8).unwrap_or(0);
let vq = VersionQualifier::new(vq_version, vq_type, vq_iter);
if vq.release_type != ReleaseType::Final {
version = vq.version;
}
vq
} else {
VersionQualifier::final_release(version)
};
let fps_version = data
.get(&TAG_FPS_VERSION)
.map(|v| Version::from_bytes(v))
.filter(|&v| v != Version(0, 0, 0));
let stm_version = data
.get(&TAG_STM_VERSION)
.map(|v| Version::from_bytes(v))
.filter(|&v| v != Version(0, 0, 0));
let name = data.get(&TAG_NAME).and_then(|v| {
let s = String::from_utf8(v.clone()).ok()?;
if s.is_empty() { None } else { Some(s) }
});
let config = DeviceConfig {
enabled_capabilities: enabled,
auto_eject_timeout: Some(auto_eject_to),
challenge_response_timeout: Some(chal_resp_to),
device_flags: Some(flags),
nfc_restricted: Some(nfc_restricted),
};
Ok(Self {
config,
serial,
version,
form_factor,
supported_capabilities: supported,
is_locked: locked,
is_fips,
is_sky,
part_number,
fips_capable,
fips_approved,
pin_complexity,
reset_blocked,
fps_version,
stm_version,
version_qualifier,
name,
})
}
pub fn has_transport(&self, transport: Transport) -> bool {
self.supported_capabilities.contains_key(&transport)
}
pub fn version_name(&self) -> String {
if self.version_qualifier.release_type != ReleaseType::Final {
self.version_qualifier.to_string()
} else if self.version != Version(0, 0, 0) {
self.version.to_string()
} else {
"unknown".into()
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct StorageStatsEntry {
pub id: u8,
pub objects: u16,
pub pages: u16,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct StorageInfo {
pub entries: Vec<StorageStatsEntry>,
}
impl StorageInfo {
pub fn parse(encoded: &[u8]) -> Result<Self, SmartCardError> {
let tlvs =
parse_tlv_list(encoded).map_err(|e| SmartCardError::InvalidData(e.to_string()))?;
let mut storage_tlvs = tlvs.iter().filter(|(tag, _)| *tag == 0x01);
let Some((_, payload)) = storage_tlvs.next() else {
return Err(SmartCardError::InvalidData(
"Missing storage info TLV with tag 0x01".into(),
));
};
if storage_tlvs.next().is_some() {
return Err(SmartCardError::InvalidData(
"Duplicate storage info TLV with tag 0x01".into(),
));
}
let (records, remainder) = payload.as_chunks::<5>();
if !remainder.is_empty() {
return Err(SmartCardError::InvalidData(
"Incomplete storage info entry".into(),
));
}
let entries = records
.iter()
.map(|record| StorageStatsEntry {
id: record[0],
objects: u16::from_be_bytes([record[1], record[2]]),
pages: u16::from_be_bytes([record[3], record[4]]),
})
.collect();
Ok(Self { entries })
}
pub fn entry(&self, id: u8) -> Option<StorageStatsEntry> {
self.entries.iter().copied().find(|entry| entry.id == id)
}
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ManagementError<E: fmt::Debug + fmt::Display> {
#[error("Not supported: {0}")]
NotSupported(String),
#[error("Invalid data: {0}")]
InvalidData(String),
#[error("Connection error: {0}")]
Connection(E),
}
impl<E: fmt::Debug + fmt::Display> ManagementError<E> {
fn from_parse(e: SmartCardError) -> Self {
match e {
SmartCardError::InvalidData(msg) => Self::InvalidData(msg),
other => Self::InvalidData(other.to_string()),
}
}
}
impl<E: std::error::Error + Send + Sync + 'static> ManagementError<E> {
pub fn erase(self) -> ManagementError<Box<dyn std::error::Error + Send + Sync>> {
match self {
Self::NotSupported(msg) => ManagementError::NotSupported(msg),
Self::InvalidData(msg) => ManagementError::InvalidData(msg),
Self::Connection(e) => ManagementError::Connection(Box::new(e)),
}
}
}
pub type BoxedManagementError = ManagementError<Box<dyn std::error::Error + Send + Sync>>;
fn read_device_info_from_config<E: fmt::Debug + fmt::Display>(
version: Version,
read_config: &mut dyn FnMut(u8) -> Result<Vec<u8>, E>,
) -> Result<DeviceInfo, ManagementError<E>> {
let mut tlvs: HashMap<u32, Vec<u8>> = HashMap::new();
let mut page: u8 = 0;
let mut more_data: u8 = 1;
while more_data > 0 {
more_data -= 1;
let encoded = read_config(page).map_err(ManagementError::Connection)?;
if encoded.is_empty() {
return Err(ManagementError::InvalidData("Empty config response".into()));
}
let expected_len = encoded[0] as usize;
if encoded.len() - 1 != expected_len {
return Err(ManagementError::InvalidData("Invalid length".into()));
}
let mut page_tlvs = parse_tlv_dict(&encoded[1..])
.map_err(|e| ManagementError::InvalidData(e.to_string()))?;
if let Some(v) = page_tlvs.remove(&TAG_MORE_DATA)
&& let Some(&count) = v.last()
{
more_data = count;
}
tlvs.extend(page_tlvs);
page += 1;
}
DeviceInfo::parse_tlvs(&tlvs, version).map_err(ManagementError::from_parse)
}
fn resolve_dev_version<E: fmt::Debug + fmt::Display>(
version: &mut Version,
read_config: &mut dyn FnMut(u8) -> Result<Vec<u8>, E>,
) -> Result<(), ManagementError<E>> {
if *version == Version(0, 0, 1) {
let info = read_device_info_from_config(*version, read_config)?;
let resolved_version = info.version_qualifier.version;
if resolved_version == Version(0, 0, 1) {
return Err(ManagementError::InvalidData(
"DeviceInfo did not resolve dev version placeholder".into(),
));
}
*version = resolved_version;
}
Ok(())
}
fn management_to_smartcard_error(error: ManagementError<SmartCardError>) -> SmartCardError {
match error {
ManagementError::Connection(error) => error,
ManagementError::NotSupported(message) => SmartCardError::NotSupported(message),
ManagementError::InvalidData(message) => SmartCardError::InvalidData(message),
}
}
fn management_to_otp_error(error: ManagementError<OtpError>) -> OtpError {
match error {
ManagementError::Connection(error) => error,
ManagementError::NotSupported(message) | ManagementError::InvalidData(message) => {
OtpError::BadResponse(message)
}
}
}
fn management_to_fido_error(error: ManagementError<FidoError>) -> FidoError {
match error {
ManagementError::Connection(error) => error,
ManagementError::NotSupported(message) | ManagementError::InvalidData(message) => {
FidoError::Other(message)
}
}
}
fn validate_and_serialize_device_config<E: fmt::Debug + fmt::Display>(
version: Version,
config: &DeviceConfig,
reboot: bool,
cur_lock_code: Option<&[u8]>,
new_lock_code: Option<&[u8]>,
) -> Result<Vec<u8>, ManagementError<E>> {
if version < Version(5, 0, 0) {
return Err(ManagementError::NotSupported(
"write_device_config requires YubiKey 5.0.0 or later".into(),
));
}
if let Some(code) = cur_lock_code
&& code.len() != 16
{
return Err(ManagementError::InvalidData(
"Lock code must be 16 bytes".into(),
));
}
if let Some(code) = new_lock_code
&& code.len() != 16
{
return Err(ManagementError::InvalidData(
"Lock code must be 16 bytes".into(),
));
}
config
.get_bytes(reboot, cur_lock_code, new_lock_code)
.map_err(ManagementError::from_parse)
}
trait ManagementOps<E: std::error::Error + Send + Sync + 'static> {
fn version(&self) -> Version;
fn read_config(&mut self, page: u8) -> Result<Vec<u8>, E>;
fn write_config(&mut self, config: &[u8]) -> Result<(), E>;
fn set_mode(
&mut self,
mode_code: u8,
chalresp_timeout: u8,
auto_eject_timeout: u16,
) -> Result<(), E>;
fn into_connection_any(self: Box<Self>) -> Box<dyn std::any::Any>;
fn device_reset(&mut self) -> Result<(), ManagementError<E>> {
Err(ManagementError::NotSupported(
"device_reset is only supported over SmartCard (CCID)".into(),
))
}
fn read_storage_info(&mut self) -> Result<Vec<u8>, ManagementError<E>> {
Err(ManagementError::NotSupported(
"read_storage_info is only supported over SmartCard (CCID)".into(),
))
}
}
pub struct ManagementSession<C: Connection> {
inner: Box<dyn ManagementOps<C::Error>>,
_phantom: std::marker::PhantomData<C>,
}
impl<C: Connection + 'static> ManagementSession<C> {
pub fn version(&self) -> Version {
self.inner.version()
}
pub fn into_connection(self) -> C {
*self
.inner
.into_connection_any()
.downcast::<C>()
.expect("ManagementSession inner type mismatch (this is a bug)")
}
pub fn read_device_info(&mut self) -> Result<DeviceInfo, ManagementError<C::Error>> {
log::debug!("Reading device info");
if self.inner.version() < Version(4, 1, 0) {
return Err(ManagementError::NotSupported(
"DeviceInfo requires YubiKey 4.1.0 or later".into(),
));
}
let version = self.inner.version();
read_device_info_from_config(version, &mut |page| self.inner.read_config(page))
}
pub fn write_device_config(
&mut self,
config: &DeviceConfig,
reboot: bool,
cur_lock_code: Option<&[u8]>,
new_lock_code: Option<&[u8]>,
) -> Result<(), ManagementError<C::Error>> {
log::debug!("Writing device configuration");
let data = validate_and_serialize_device_config(
self.inner.version(),
config,
reboot,
cur_lock_code,
new_lock_code,
)?;
self.inner
.write_config(&data)
.map_err(ManagementError::Connection)?;
log::info!("Device configuration written");
Ok(())
}
pub fn set_mode(
&mut self,
mode_code: u8,
chalresp_timeout: u8,
auto_eject_timeout: u16,
) -> Result<(), ManagementError<C::Error>> {
log::debug!("Setting USB mode");
self.inner
.set_mode(mode_code, chalresp_timeout, auto_eject_timeout)
.map_err(ManagementError::Connection)?;
log::info!("USB mode configured");
Ok(())
}
fn from_inner(inner: Box<dyn ManagementOps<C::Error>>) -> Self {
Self {
inner,
_phantom: std::marker::PhantomData,
}
}
}
impl<C: SmartCardConnection + 'static> ManagementSession<C> {
pub fn new(connection: C) -> Result<Self, (ManagementError<SmartCardError>, C)> {
CcidManagement::open(connection)
.map(|inner| Self::from_inner(Box::new(inner)))
.map_err(|(e, conn)| (ManagementError::Connection(e), conn))
}
pub fn new_with_scp(
connection: C,
scp_key_params: &crate::smartcard::ScpKeyParams,
) -> Result<Self, (ManagementError<SmartCardError>, C)> {
CcidManagement::open_with_scp(connection, scp_key_params)
.map(|inner| Self::from_inner(Box::new(inner)))
.map_err(|(e, conn)| (ManagementError::Connection(e), conn))
}
pub fn device_reset(&mut self) -> Result<(), ManagementError<SmartCardError>> {
log::debug!("Performing device reset");
self.inner.device_reset()?;
log::info!("Device reset complete");
Ok(())
}
pub fn read_storage_info(&mut self) -> Result<StorageInfo, ManagementError<SmartCardError>> {
log::debug!("Reading storage info");
if self.version() < Version(6, 0, 0) {
return Err(ManagementError::NotSupported(
"read_storage_info requires YubiKey 6.0.0 or later".into(),
));
}
let encoded = self.inner.read_storage_info()?;
StorageInfo::parse(&encoded).map_err(ManagementError::from_parse)
}
}
impl<T: OtpConnection + 'static> ManagementSession<T> {
pub fn new_otp(connection: T) -> Result<Self, (ManagementError<OtpError>, T)> {
OtpManagement::open(connection)
.map(|inner| Self::from_inner(Box::new(inner)))
.map_err(|(e, conn)| (ManagementError::Connection(e), conn))
}
}
impl<C: FidoConnection + 'static> ManagementSession<C> {
pub fn new_fido(connection: C) -> Result<Self, (ManagementError<FidoError>, C)> {
FidoManagement::open(connection)
.map(|inner| Self::from_inner(Box::new(inner)))
.map_err(|(e, conn)| (ManagementError::Connection(e), conn))
}
}
struct CcidManagement<C: SmartCardConnection> {
protocol: SmartCardProtocol<C>,
version: Version,
}
impl<C: SmartCardConnection> CcidManagement<C> {
fn ccid_read_config(
protocol: &mut SmartCardProtocol<C>,
page: u8,
) -> Result<Vec<u8>, SmartCardError> {
protocol.send_apdu(0, INS_READ_CONFIG, page, 0, &[])
}
fn open(connection: C) -> Result<Self, (SmartCardError, C)> {
let mut protocol = SmartCardProtocol::new(connection);
let select_bytes = match protocol.select(Aid::MANAGEMENT) {
Ok(v) => v,
Err(e) => return Err((e, protocol.into_connection())),
};
Self::init(protocol, &select_bytes)
}
fn open_with_scp(
connection: C,
scp_key_params: &crate::smartcard::ScpKeyParams,
) -> Result<Self, (SmartCardError, C)> {
let mut protocol = SmartCardProtocol::new(connection);
let select_bytes = match protocol.select(Aid::MANAGEMENT) {
Ok(v) => v,
Err(e) => return Err((e, protocol.into_connection())),
};
if let Err(e) = protocol.init_scp(scp_key_params) {
return Err((e, protocol.into_connection()));
}
Self::init(protocol, &select_bytes)
}
fn init(
mut protocol: SmartCardProtocol<C>,
select_bytes: &[u8],
) -> Result<Self, (SmartCardError, C)> {
log::debug!("Opening CcidManagement");
let select_bytes =
if select_bytes.len() >= 2 && select_bytes[select_bytes.len() - 2..] == [0x90, 0x00] {
&select_bytes[..select_bytes.len() - 2]
} else {
select_bytes
};
let version_str = match std::str::from_utf8(select_bytes) {
Ok(v) => v,
Err(_) => {
return Err((
SmartCardError::InvalidData("Invalid version string".into()),
protocol.into_connection(),
));
}
};
let mut version = match parse_version_string(version_str) {
Ok(v) => v,
Err(e) => {
return Err((
SmartCardError::InvalidData(e.to_string()),
protocol.into_connection(),
));
}
};
if let Err(error) = resolve_dev_version(&mut version, &mut |page| {
Self::ccid_read_config(&mut protocol, page)
}) {
return Err((
management_to_smartcard_error(error),
protocol.into_connection(),
));
}
if version.0 == 3 {
let mut conn = protocol.into_connection();
let _ = conn.send_and_receive(&[0xa4, 0x04, 0x00, 0x08]);
protocol = SmartCardProtocol::new(conn);
if let Err(e) = protocol.select(Aid::OTP) {
return Err((e, protocol.into_connection()));
}
}
protocol.configure(version);
Ok(Self { protocol, version })
}
}
impl<C: SmartCardConnection + 'static> ManagementOps<SmartCardError> for CcidManagement<C> {
fn version(&self) -> Version {
self.version
}
fn read_config(&mut self, page: u8) -> Result<Vec<u8>, SmartCardError> {
Self::ccid_read_config(&mut self.protocol, page)
}
fn write_config(&mut self, config: &[u8]) -> Result<(), SmartCardError> {
self.protocol.send_apdu(0, INS_WRITE_CONFIG, 0, 0, config)?;
Ok(())
}
fn set_mode(
&mut self,
mode_code: u8,
chalresp_timeout: u8,
auto_eject_timeout: u16,
) -> Result<(), SmartCardError> {
let data = [
mode_code,
chalresp_timeout,
(auto_eject_timeout & 0xFF) as u8,
(auto_eject_timeout >> 8) as u8,
];
if self.version.0 == 3 {
self.protocol
.send_apdu(0, 0x01, CONFIG_SLOT_DEVICE_CONFIG, 0, &data)?;
} else {
self.protocol
.send_apdu(0, INS_SET_MODE, P1_DEVICE_CONFIG, 0, &data)?;
}
Ok(())
}
fn into_connection_any(self: Box<Self>) -> Box<dyn std::any::Any> {
Box::new(self.protocol.into_connection())
}
fn device_reset(&mut self) -> Result<(), ManagementError<SmartCardError>> {
self.protocol
.send_apdu(0, INS_DEVICE_RESET, 0, 0, &[])
.map_err(ManagementError::Connection)?;
Ok(())
}
fn read_storage_info(&mut self) -> Result<Vec<u8>, ManagementError<SmartCardError>> {
self.protocol
.send_apdu(0, INS_READ_STORAGE_INFO, 0, 0, &[])
.map_err(ManagementError::Connection)
}
}
struct OtpManagement<T: OtpConnection> {
protocol: OtpProtocol<T>,
version: Version,
}
impl<T: OtpConnection> OtpManagement<T> {
fn otp_read_config(protocol: &mut OtpProtocol<T>, page: u8) -> Result<Vec<u8>, OtpError> {
let data = int2bytes(page as u64);
let response =
protocol.send_and_receive(ConfigSlot::Yk4Capabilities as u8, Some(&data), Some(-1))?;
match response {
Some(raw) => {
let r_len = raw[0] as usize;
let checked = verify_and_strip_crc(&raw, r_len + 1)?;
Ok(checked)
}
None => Err(OtpError::BadResponse("Expected data response".into())),
}
}
fn open(connection: T) -> Result<Self, (OtpError, T)> {
log::debug!("Opening OtpManagement");
let mut protocol = match OtpProtocol::new(connection) {
Ok(p) => p,
Err((e, conn)) => return Err((e, conn)),
};
let mut version = protocol.version;
if let Err(error) = resolve_dev_version(&mut version, &mut |page| {
Self::otp_read_config(&mut protocol, page)
}) {
return Err((management_to_otp_error(error), protocol.into_connection()));
}
if version >= Version(1, 0, 0) && version < Version(3, 0, 0) {
return Err((
OtpError::BadResponse(
"Management over OTP not supported for YubiKey v1.x-v2.x".into(),
),
protocol.into_connection(),
));
}
Ok(Self { protocol, version })
}
}
impl<T: OtpConnection + 'static> ManagementOps<OtpError> for OtpManagement<T> {
fn version(&self) -> Version {
self.version
}
fn read_config(&mut self, page: u8) -> Result<Vec<u8>, OtpError> {
Self::otp_read_config(&mut self.protocol, page)
}
fn write_config(&mut self, config: &[u8]) -> Result<(), OtpError> {
self.protocol
.send_and_receive(ConfigSlot::Yk4SetDeviceInfo as u8, Some(config), None)?;
Ok(())
}
fn set_mode(
&mut self,
mode_code: u8,
chalresp_timeout: u8,
auto_eject_timeout: u16,
) -> Result<(), OtpError> {
let data = [
mode_code,
chalresp_timeout,
(auto_eject_timeout & 0xFF) as u8,
(auto_eject_timeout >> 8) as u8,
];
let empty = self.protocol.read_status()?[STATUS_OFFSET_PROG_SEQ] == 0;
match self
.protocol
.send_and_receive(ConfigSlot::DeviceConfig as u8, Some(&data), None)
{
Err(OtpError::CommandRejected(_)) if empty => Ok(()),
other => other.map(|_| ()),
}
}
fn into_connection_any(self: Box<Self>) -> Box<dyn std::any::Any> {
Box::new(self.protocol.into_connection())
}
}
fn parse_version_string(s: &str) -> Result<Version, ManagementError<std::convert::Infallible>> {
let parts: Vec<&str> = s.trim().split('.').collect();
if parts.len() == 3
&& let (Ok(a), Ok(b), Ok(c)) = (
parts[0].parse::<u8>(),
parts[1].parse::<u8>(),
parts[2].parse::<u8>(),
)
{
return Ok(Version(a, b, c));
}
for window in s.split_whitespace() {
let segs: Vec<&str> = window.split('.').collect();
if segs.len() == 3
&& let (Ok(a), Ok(b), Ok(c)) = (
segs[0].parse::<u8>(),
segs[1].parse::<u8>(),
segs[2].parse::<u8>(),
)
{
return Ok(Version(a, b, c));
}
}
Err(ManagementError::InvalidData(format!(
"Invalid version string: {s:?}"
)))
}
const CTAP_VENDOR_FIRST: u8 = 0x40;
const CTAP_YUBIKEY_DEVICE_CONFIG: u8 = CTAP_VENDOR_FIRST;
const CTAP_READ_CONFIG: u8 = CTAP_VENDOR_FIRST + 2;
const CTAP_WRITE_CONFIG: u8 = CTAP_VENDOR_FIRST + 3;
struct FidoManagement<C: FidoConnection> {
connection: C,
version: Version,
}
impl<C: FidoConnection> FidoManagement<C> {
fn fido_read_config(connection: &mut C, page: u8) -> Result<Vec<u8>, FidoError> {
let data = int2bytes(page as u64);
connection.call(CTAP_READ_CONFIG, &data, None, None)
}
fn open(mut connection: C) -> Result<Self, (FidoError, C)> {
log::debug!("Opening FidoManagement");
let mut version = connection.device_version();
if let Err(error) = resolve_dev_version(&mut version, &mut |page| {
Self::fido_read_config(&mut connection, page)
}) {
return Err((management_to_fido_error(error), connection));
}
if version.0 < 4 && !(version.0 == 0 && connection.capabilities().has_cbor()) {
version = Version(3, 0, 0); }
Ok(Self {
connection,
version,
})
}
}
impl<C: FidoConnection + 'static> ManagementOps<FidoError> for FidoManagement<C> {
fn version(&self) -> Version {
self.version
}
fn read_config(&mut self, page: u8) -> Result<Vec<u8>, FidoError> {
Self::fido_read_config(&mut self.connection, page)
}
fn write_config(&mut self, config: &[u8]) -> Result<(), FidoError> {
self.connection
.call(CTAP_WRITE_CONFIG, config, None, None)?;
Ok(())
}
fn set_mode(
&mut self,
mode_code: u8,
chalresp_timeout: u8,
auto_eject_timeout: u16,
) -> Result<(), FidoError> {
let data = [
mode_code,
chalresp_timeout,
(auto_eject_timeout & 0xFF) as u8,
(auto_eject_timeout >> 8) as u8,
];
self.connection
.call(CTAP_YUBIKEY_DEVICE_CONFIG, &data, None, None)?;
Ok(())
}
fn into_connection_any(self: Box<Self>) -> Box<dyn std::any::Any> {
Box::new(self.connection)
}
}
#[cfg(test)]
mod tests {
use super::*;
const STORAGE_RESPONSE: &[u8] = &[
0x01, 0x1e, 0x00, 0x00, 0x91, 0x01, 0x95, 0x01, 0x00, 0x02, 0x00, 0x07, 0x02, 0x00, 0x03,
0x00, 0x18, 0x03, 0x00, 0x04, 0x00, 0x20, 0x04, 0x00, 0x06, 0x00, 0x0c, 0x05, 0x00, 0x00,
0x00, 0x00,
];
#[test]
fn test_storage_info_parse() {
let info = StorageInfo::parse(STORAGE_RESPONSE).unwrap();
let expected = [
(0, 145, 405),
(1, 2, 7),
(2, 3, 24),
(3, 4, 32),
(4, 6, 12),
(5, 0, 0),
];
assert_eq!(
info.entries,
expected.map(|(id, objects, pages)| StorageStatsEntry { id, objects, pages })
);
assert_eq!(info.entry(0), Some(info.entries[0]));
assert_eq!(info.entry(5), Some(info.entries[5]));
assert_eq!(info.entry(99), None);
}
#[test]
fn test_storage_info_preserves_unknown_ids_and_inline_objects() {
let info = StorageInfo::parse(&tlv_encode(
1,
&[0xff, 0xff, 0xff, 0xff, 0xff, 1, 0, 1, 0, 0],
))
.unwrap();
assert_eq!(
info.entries,
[
StorageStatsEntry {
id: 0xff,
objects: u16::MAX,
pages: u16::MAX,
},
StorageStatsEntry {
id: 1,
objects: 1,
pages: 0
},
]
);
}
#[test]
fn test_storage_info_empty_and_long_form_payloads() {
assert_eq!(StorageInfo::parse(&[1, 0]).unwrap(), StorageInfo::default());
let payload: Vec<u8> = (0..26).flat_map(|id| [id, 0, id, 0, 1]).collect();
let encoded = tlv_encode(1, &payload);
assert_eq!(&encoded[..3], &[1, 0x81, 130]);
let info = StorageInfo::parse(&encoded).unwrap();
assert_eq!(info.entries.len(), 26);
assert_eq!(info.entry(25).unwrap().objects, 25);
}
#[test]
fn test_storage_info_rejects_incomplete_records() {
for complete_records in [0, 1] {
for extra_bytes in 1..5 {
let encoded = tlv_encode(1, &vec![0; complete_records * 5 + extra_bytes]);
assert!(matches!(
StorageInfo::parse(&encoded),
Err(SmartCardError::InvalidData(_))
));
}
}
}
#[test]
fn test_storage_info_ignores_unknown_tlvs() {
let extra = tlv_encode(0x7f49, &[0xff; 128]);
let expected = StorageInfo::parse(STORAGE_RESPONSE).unwrap();
for encoded in [
[extra.as_slice(), STORAGE_RESPONSE].concat(),
[STORAGE_RESPONSE, extra.as_slice()].concat(),
[extra.as_slice(), STORAGE_RESPONSE, extra.as_slice()].concat(),
] {
assert_eq!(StorageInfo::parse(&encoded).unwrap(), expected);
}
}
#[test]
fn test_storage_info_rejects_invalid_tlv() {
for encoded in [
&[][..],
&[2, 0],
&[1],
&[1, 5, 0],
&[1, 0, 1, 0],
&[1, 0, 0xff],
&[2, 0, 3, 0],
&[1, 0, 2, 0, 1, 0],
&[1, 0, 2, 1],
&[2, 1],
] {
assert!(matches!(
StorageInfo::parse(encoded),
Err(SmartCardError::InvalidData(_))
));
}
}
#[derive(Debug)]
struct StorageConnection {
version: &'static str,
response: Vec<u8>,
sw: u16,
sent: Vec<Vec<u8>>,
}
impl Default for StorageConnection {
fn default() -> Self {
Self {
version: "6.0.0",
response: STORAGE_RESPONSE.to_vec(),
sw: 0x9000,
sent: Vec::new(),
}
}
}
impl Connection for StorageConnection {
type Error = SmartCardError;
fn close(&mut self) {}
}
impl SmartCardConnection for StorageConnection {
fn transport(&self) -> Transport {
Transport::Usb
}
fn send_and_receive(&mut self, apdu: &[u8]) -> Result<(Vec<u8>, u16), SmartCardError> {
self.sent.push(apdu.to_vec());
match apdu[1] {
0xa4 => Ok((self.version.as_bytes().to_vec(), 0x9000)),
INS_READ_STORAGE_INFO => {
assert_eq!(apdu, &[0, 0x30, 0, 0, 0, 0, 0]);
Ok((self.response.clone(), self.sw))
}
_ => panic!("Unexpected APDU: {apdu:?}"),
}
}
}
#[test]
fn test_read_storage_info_command() {
let mut session = ManagementSession::new(StorageConnection::default()).unwrap();
assert_eq!(
session.read_storage_info().unwrap(),
StorageInfo::parse(STORAGE_RESPONSE).unwrap()
);
assert_eq!(session.into_connection().sent.len(), 2);
}
#[test]
fn test_read_storage_info_rejects_older_firmware_before_command() {
for version in ["4.4.5", "5.7.2"] {
let connection = StorageConnection {
version,
..Default::default()
};
let mut session = ManagementSession::new(connection).unwrap();
assert!(matches!(
session.read_storage_info(),
Err(ManagementError::NotSupported(_))
));
assert_eq!(session.into_connection().sent.len(), 1);
}
}
#[test]
fn test_read_storage_info_propagates_errors() {
let connection = StorageConnection {
sw: 0x6d00,
..Default::default()
};
let mut session = ManagementSession::new(connection).unwrap();
assert!(matches!(
session.read_storage_info(),
Err(ManagementError::Connection(SmartCardError::Apdu {
sw: 0x6d00,
..
}))
));
let connection = StorageConnection {
response: vec![1, 1, 0],
..Default::default()
};
let mut session = ManagementSession::new(connection).unwrap();
assert!(matches!(
session.read_storage_info(),
Err(ManagementError::InvalidData(_))
));
}
#[test]
fn test_capability_bitflags() {
let c = Capability::OTP | Capability::FIDO2;
assert!(c.contains(Capability::OTP));
assert!(c.contains(Capability::FIDO2));
assert!(!c.contains(Capability::PIV));
assert_eq!(c.0, 0x201);
let masked = c & Capability::OTP;
assert_eq!(masked, Capability::OTP);
}
#[test]
fn test_capability_from_fips() {
let c = Capability::from_fips(0b11111);
assert!(c.contains(Capability::FIDO2));
assert!(c.contains(Capability::PIV));
assert!(c.contains(Capability::OPENPGP));
assert!(c.contains(Capability::OATH));
assert!(c.contains(Capability::HSMAUTH));
}
#[test]
fn test_capability_display() {
let c = Capability::OTP | Capability::PIV;
let s = c.to_string();
assert!(s.contains("OTP"));
assert!(s.contains("PIV"));
}
#[test]
fn test_form_factor_from_code() {
assert_eq!(FormFactor::from_code(0x01), FormFactor::UsbAKeychain);
assert_eq!(FormFactor::from_code(0x07), FormFactor::UsbCBio);
assert_eq!(FormFactor::from_code(0x00), FormFactor::Unknown);
assert_eq!(FormFactor::from_code(0x81), FormFactor::UsbAKeychain);
assert_eq!(FormFactor::from_code(0xC3), FormFactor::UsbCKeychain);
assert_eq!(FormFactor::from_code(0xFF), FormFactor::Unknown); }
#[test]
fn test_form_factor_is_bio() {
assert!(FormFactor::UsbABio.is_bio());
assert!(FormFactor::UsbCBio.is_bio());
assert!(!FormFactor::UsbAKeychain.is_bio());
}
#[test]
fn test_device_flag_operations() {
let f = DeviceFlag::REMOTE_WAKEUP | DeviceFlag::EJECT;
assert_eq!(f.0, 0xC0);
assert!(!f.is_empty());
assert!(DeviceFlag::NONE.is_empty());
}
#[test]
fn test_mode_from_code() {
let m = Mode::from_code(0).unwrap();
assert_eq!(m.interfaces, UsbInterface::OTP);
assert_eq!(m.code, 0);
let m = Mode::from_code(6).unwrap();
assert_eq!(
m.interfaces.0,
UsbInterface::OTP.0 | UsbInterface::FIDO.0 | UsbInterface::CCID.0
);
let m = Mode::from_code(0x83).unwrap();
assert_eq!(m.interfaces, UsbInterface::FIDO);
assert!(Mode::from_code(7).is_none());
}
#[test]
fn test_device_config_get_bytes_empty() {
let config = DeviceConfig::default();
let bytes = config.get_bytes(false, None, None).unwrap();
assert_eq!(bytes, vec![0x00]);
}
#[test]
fn test_device_config_get_bytes_with_reboot() {
let config = DeviceConfig::default();
let bytes = config.get_bytes(true, None, None).unwrap();
assert_eq!(bytes[0] as usize, bytes.len() - 1);
assert_eq!(bytes[1], TAG_REBOOT as u8);
assert_eq!(bytes[2], 0x00);
}
#[test]
fn test_device_config_get_bytes_with_capabilities() {
let mut config = DeviceConfig::default();
config
.enabled_capabilities
.insert(Transport::Usb, Capability(0x003F));
let bytes = config.get_bytes(false, None, None).unwrap();
assert_eq!(bytes[0] as usize, bytes.len() - 1);
assert_eq!(bytes[1], TAG_USB_ENABLED as u8);
assert_eq!(bytes[2], 0x02); assert_eq!(bytes[3], 0x00);
assert_eq!(bytes[4], 0x3F);
}
#[test]
fn test_device_info_parse() {
let mut payload = Vec::new();
payload.extend_from_slice(&tlv_encode(TAG_VERSION, &[5, 7, 1]));
payload.extend_from_slice(&tlv_encode(TAG_SERIAL, &0x00BC614Eu32.to_be_bytes()));
payload.extend_from_slice(&tlv_encode(TAG_FORM_FACTOR, &[0x03]));
payload.extend_from_slice(&tlv_encode(TAG_USB_SUPPORTED, &[0x02, 0x3F]));
payload.extend_from_slice(&tlv_encode(TAG_USB_ENABLED, &[0x02, 0x3F]));
let mut encoded = vec![payload.len() as u8];
encoded.extend_from_slice(&payload);
let info = DeviceInfo::parse(&encoded, Version(0, 0, 0)).unwrap();
assert_eq!(info.version, Version(5, 7, 1));
assert_eq!(info.serial, Some(12345678));
assert_eq!(info.form_factor, FormFactor::UsbCKeychain);
assert_eq!(
info.supported_capabilities.get(&Transport::Usb),
Some(&Capability(0x023F))
);
assert_eq!(
info.config.enabled_capabilities.get(&Transport::Usb),
Some(&Capability(0x023F))
);
assert!(!info.is_fips);
assert!(!info.is_sky);
assert!(!info.is_locked);
}
#[test]
fn test_device_info_parse_fips_sky_flags() {
let mut payload = Vec::new();
payload.extend_from_slice(&tlv_encode(TAG_VERSION, &[5, 4, 3]));
payload.extend_from_slice(&tlv_encode(TAG_FORM_FACTOR, &[0xC3]));
payload.extend_from_slice(&tlv_encode(TAG_USB_SUPPORTED, &[0x00, 0x3F]));
let mut encoded = vec![payload.len() as u8];
encoded.extend_from_slice(&payload);
let info = DeviceInfo::parse(&encoded, Version(0, 0, 0)).unwrap();
assert!(info.is_fips);
assert!(info.is_sky);
assert_eq!(info.form_factor, FormFactor::UsbCKeychain);
}
#[test]
fn test_device_info_parse_v424_workaround() {
let mut payload = Vec::new();
payload.extend_from_slice(&tlv_encode(TAG_VERSION, &[4, 2, 4]));
payload.extend_from_slice(&tlv_encode(TAG_USB_SUPPORTED, &[0xFF, 0xFF])); payload.extend_from_slice(&tlv_encode(TAG_USB_ENABLED, &[0x00, 0x3F]));
let mut encoded = vec![payload.len() as u8];
encoded.extend_from_slice(&payload);
let info = DeviceInfo::parse(&encoded, Version(0, 0, 0)).unwrap();
assert_eq!(
info.supported_capabilities.get(&Transport::Usb),
Some(&Capability(0x3F))
);
assert!(
!info
.config
.enabled_capabilities
.contains_key(&Transport::Usb)
);
}
#[test]
fn test_device_info_parse_yk4_usb_enabled_skip() {
let mut payload = Vec::new();
payload.extend_from_slice(&tlv_encode(TAG_VERSION, &[4, 3, 7]));
payload.extend_from_slice(&tlv_encode(TAG_USB_SUPPORTED, &[0x00, 0x3F]));
payload.extend_from_slice(&tlv_encode(TAG_USB_ENABLED, &[0x00, 0x3F]));
let mut encoded = vec![payload.len() as u8];
encoded.extend_from_slice(&payload);
let info = DeviceInfo::parse(&encoded, Version(0, 0, 0)).unwrap();
assert!(
!info
.config
.enabled_capabilities
.contains_key(&Transport::Usb)
);
}
#[test]
fn test_device_info_parse_with_nfc() {
let mut payload = Vec::new();
payload.extend_from_slice(&tlv_encode(TAG_VERSION, &[5, 2, 0]));
payload.extend_from_slice(&tlv_encode(TAG_USB_SUPPORTED, &[0x02, 0x3F]));
payload.extend_from_slice(&tlv_encode(TAG_USB_ENABLED, &[0x02, 0x3F]));
payload.extend_from_slice(&tlv_encode(TAG_NFC_SUPPORTED, &[0x02, 0x3F]));
payload.extend_from_slice(&tlv_encode(TAG_NFC_ENABLED, &[0x00, 0x3F]));
payload.extend_from_slice(&tlv_encode(TAG_NFC_RESTRICTED, &[0x01]));
let mut encoded = vec![payload.len() as u8];
encoded.extend_from_slice(&payload);
let info = DeviceInfo::parse(&encoded, Version(0, 0, 0)).unwrap();
assert!(info.has_transport(Transport::Nfc));
assert_eq!(
info.supported_capabilities.get(&Transport::Nfc),
Some(&Capability(0x023F))
);
assert_eq!(info.config.nfc_restricted, Some(true));
}
#[test]
fn test_device_info_parse_version_qualifier() {
let mut vq_inner = Vec::new();
vq_inner.extend_from_slice(&tlv_encode(0x01, &[5, 8, 0]));
vq_inner.extend_from_slice(&tlv_encode(0x02, &[0x00])); vq_inner.extend_from_slice(&tlv_encode(0x03, &[0x03]));
let mut payload = Vec::new();
payload.extend_from_slice(&tlv_encode(TAG_VERSION, &[5, 7, 1]));
payload.extend_from_slice(&tlv_encode(TAG_USB_SUPPORTED, &[0x02, 0x3F]));
payload.extend_from_slice(&tlv_encode(TAG_VERSION_QUALIFIER, &vq_inner));
let mut encoded = vec![payload.len() as u8];
encoded.extend_from_slice(&payload);
let info = DeviceInfo::parse(&encoded, Version(0, 0, 0)).unwrap();
assert_eq!(info.version, Version(5, 8, 0));
assert_eq!(info.version_qualifier.release_type, ReleaseType::Alpha);
assert_eq!(info.version_qualifier.iteration, 3);
}
#[test]
fn test_device_info_parse_part_number_and_fips() {
let mut payload = Vec::new();
payload.extend_from_slice(&tlv_encode(TAG_VERSION, &[5, 7, 1]));
payload.extend_from_slice(&tlv_encode(TAG_USB_SUPPORTED, &[0x02, 0x3F]));
payload.extend_from_slice(&tlv_encode(TAG_PART_NUMBER, b"YK5C"));
payload.extend_from_slice(&tlv_encode(TAG_FIPS_CAPABLE, &[0x07])); payload.extend_from_slice(&tlv_encode(TAG_FIPS_APPROVED, &[0x03])); payload.extend_from_slice(&tlv_encode(TAG_PIN_COMPLEXITY, &[0x01]));
payload.extend_from_slice(&tlv_encode(TAG_CONFIG_LOCK, &[0x01]));
let mut encoded = vec![payload.len() as u8];
encoded.extend_from_slice(&payload);
let info = DeviceInfo::parse(&encoded, Version(0, 0, 0)).unwrap();
assert_eq!(info.part_number.as_deref(), Some("YK5C"));
assert!(info.fips_capable.contains(Capability::FIDO2));
assert!(info.fips_capable.contains(Capability::PIV));
assert!(info.fips_capable.contains(Capability::OPENPGP));
assert!(info.fips_approved.contains(Capability::FIDO2));
assert!(info.fips_approved.contains(Capability::PIV));
assert!(!info.fips_approved.contains(Capability::OPENPGP));
assert!(info.pin_complexity);
assert!(info.is_locked);
}
#[test]
fn test_device_info_parse_name() {
let mut payload = Vec::new();
payload.extend_from_slice(&tlv_encode(TAG_VERSION, &[6, 0, 0]));
payload.extend_from_slice(&tlv_encode(TAG_USB_SUPPORTED, &[0x02, 0x3F]));
payload.extend_from_slice(&tlv_encode(TAG_NAME, b"A Custom Name"));
let mut encoded = vec![payload.len() as u8];
encoded.extend_from_slice(&payload);
let info = DeviceInfo::parse(&encoded, Version(0, 0, 0)).unwrap();
assert_eq!(info.name.as_deref(), Some("A Custom Name"));
assert_eq!(crate::device::get_name(&info), "A Custom Name");
}
#[test]
fn test_version_qualifier_display() {
let vq = VersionQualifier::new(Version(5, 8, 0), ReleaseType::Alpha, 3);
assert_eq!(vq.to_string(), "5.8.0.alpha.3");
}
#[test]
fn test_parse_version_string() {
assert_eq!(parse_version_string("5.7.1").unwrap(), Version(5, 7, 1));
assert_eq!(parse_version_string("4.2.4").unwrap(), Version(4, 2, 4));
assert!(parse_version_string("invalid").is_err());
assert!(parse_version_string("5.7").is_err());
}
#[test]
fn test_bytes2int() {
assert_eq!(bytes2int(&[]), 0);
assert_eq!(bytes2int(&[0x01]), 1);
assert_eq!(bytes2int(&[0x01, 0x00]), 256);
assert_eq!(bytes2int(&[0x00, 0xBC, 0x61, 0x4E]), 12345678);
}
#[test]
fn test_release_type_display() {
assert_eq!(ReleaseType::Alpha.to_string(), "alpha");
assert_eq!(ReleaseType::Beta.to_string(), "beta");
assert_eq!(ReleaseType::Final.to_string(), "final");
}
}