This is especially important for developers, which tend to have at least one Yubikey hanging off their machines.
150 lines
5 KiB
Rust
150 lines
5 KiB
Rust
use std::{collections::HashMap, ffi::CString};
|
|
use std::sync::{Arc, Mutex};
|
|
|
|
use pcsc::{PNP_NOTIFICATION, Protocols, ReaderState, State};
|
|
use tokio::task::spawn_blocking;
|
|
|
|
use crate::{Card, ResultAPDU};
|
|
|
|
pub struct PCSCCard {
|
|
pub card: pcsc::Card,
|
|
pub buf: [u8; 0x10002],
|
|
}
|
|
|
|
impl Card for PCSCCard {
|
|
async fn transmit(
|
|
&mut self,
|
|
apdu: crate::OwnedCommandAPDU,
|
|
) -> std::io::Result<crate::ResultAPDU> {
|
|
let mut apdu_buf = vec![
|
|
apdu.class.encode().unwrap(),
|
|
apdu.instruction,
|
|
apdu.parameter[0],
|
|
apdu.parameter[1],
|
|
];
|
|
let extended =
|
|
apdu.command.len() > 0xFF || apdu.expected_length.map(|f| f > 0xFF) == Some(true);
|
|
|
|
if extended {
|
|
apdu_buf.push(0);
|
|
apdu_buf.extend_from_slice(&(apdu.command.len() as u16).to_be_bytes());
|
|
} else if !apdu.command.is_empty() {
|
|
apdu_buf.push(apdu.command.len() as u8);
|
|
}
|
|
|
|
apdu_buf.extend_from_slice(&apdu.command);
|
|
|
|
if extended {
|
|
apdu_buf.extend_from_slice(
|
|
&(apdu.expected_length.unwrap_or_default() as u16).to_be_bytes(),
|
|
);
|
|
} else if apdu.expected_length != Some(0) {
|
|
apdu_buf.push(apdu.expected_length.unwrap_or_default() as u8);
|
|
}
|
|
|
|
self.transmit_raw(&apdu_buf).await
|
|
}
|
|
async fn transmit_raw(&mut self, apdu_buf: &[u8]) -> std::io::Result<crate::ResultAPDU> {
|
|
let ret_len = self
|
|
.card
|
|
.transmit(apdu_buf, &mut self.buf)
|
|
.map_err(|f| std::io::Error::new(std::io::ErrorKind::BrokenPipe, f))?
|
|
.len();
|
|
|
|
let data = self.buf[..ret_len - 2].to_vec();
|
|
let sw = (self.buf[ret_len - 2] as u16) << 8 | (self.buf[ret_len - 1] as u16);
|
|
|
|
Ok(ResultAPDU { data, status: sw })
|
|
}
|
|
}
|
|
|
|
impl PCSCCard {
|
|
pub fn new() -> Self {
|
|
let ctx = pcsc::Context::establish(pcsc::Scope::User).unwrap();
|
|
let readers = ctx.list_readers_owned().unwrap();
|
|
let reader = readers.first().unwrap();
|
|
|
|
let mut rs = [ReaderState::new(reader.to_owned(), State::empty())];
|
|
loop {
|
|
ctx.get_status_change(None, &mut rs[..]).unwrap();
|
|
rs[0].sync_current_state();
|
|
|
|
if rs[0].event_state().contains(State::PRESENT) {
|
|
let card = ctx
|
|
.connect(reader, pcsc::ShareMode::Shared, Protocols::ANY)
|
|
.unwrap();
|
|
|
|
return Self {
|
|
card,
|
|
buf: [0; 0x10002],
|
|
};
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
struct PCSCCardFinderInner {
|
|
ctx: pcsc::Context,
|
|
reader_states: Vec<ReaderState>,
|
|
event_count: HashMap<CString, u32>,
|
|
}
|
|
|
|
pub struct PCSCCardFinder(Arc<Mutex<PCSCCardFinderInner>>);
|
|
|
|
impl PCSCCardFinder {
|
|
pub fn new() -> Self {
|
|
Self(Arc::new(Mutex::new(PCSCCardFinderInner {
|
|
ctx: pcsc::Context::establish(pcsc::Scope::User).unwrap(),
|
|
reader_states: vec![
|
|
ReaderState::new(PNP_NOTIFICATION(), State::UNAWARE),
|
|
],
|
|
event_count: HashMap::new(),
|
|
})))
|
|
}
|
|
|
|
pub async fn find_valid(&mut self) -> PCSCCard {
|
|
let mut readers_buf = [0; 2048];
|
|
|
|
loop {
|
|
{
|
|
let mut m = self.0.lock().unwrap();
|
|
m.reader_states.retain(|reader| !reader.event_state().intersects(State::IGNORE | State::UNKNOWN));
|
|
|
|
for reader in m.ctx.list_readers(&mut readers_buf).unwrap() {
|
|
if !m.reader_states.iter().any(|f| f.name() == reader) {
|
|
m.reader_states.push(ReaderState::new(reader, State::UNAWARE));
|
|
}
|
|
}
|
|
|
|
for reader in &mut m.reader_states {
|
|
reader.sync_current_state();
|
|
}
|
|
}
|
|
|
|
let c = self.0.clone();
|
|
spawn_blocking(move || { let mut c = c.lock().unwrap(); let c = &mut *c; c.ctx.get_status_change(None, &mut c.reader_states) }).await.unwrap().unwrap();
|
|
|
|
let mut m = self.0.lock().unwrap();
|
|
let m = &mut *m;
|
|
|
|
for reader in &mut m.reader_states {
|
|
if reader.name() == PNP_NOTIFICATION() {
|
|
continue
|
|
}
|
|
|
|
// Anything with "Yubico" in it will never be valid.
|
|
if reader.name().to_bytes().starts_with(b"Yubico") {
|
|
continue
|
|
}
|
|
|
|
let last_event_count = m.event_count.insert(reader.name().to_owned(), reader.event_count());
|
|
if reader.event_state().contains(State::PRESENT) && !reader.event_state().contains(State::INUSE) && Some(reader.event_count()) != last_event_count {
|
|
// Newly present card, let's give it a try.
|
|
if let Ok(card) = m.ctx.connect(reader.name(), pcsc::ShareMode::Shared, Protocols::ANY) {
|
|
return PCSCCard { card, buf: [0; 0x10002] }
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|