| 1 |
use super::TestDevice; |
| 2 |
use crate::consts::{HIDCmd, CID_BROADCAST}; |
| 3 |
use crate::ctap2::commands::{CommandError, RequestCtap1, RequestCtap2, Retryable, StatusCode}; |
| 4 |
use crate::transport::errors::{ApduErrorStatus, HIDError}; |
| 5 |
use crate::transport::{FidoDevice, FidoDeviceIO, FidoProtocol}; |
| 6 |
use crate::u2ftypes::{U2FDeviceInfo, U2FHIDCont, U2FHIDInit, U2FHIDInitResp}; |
| 7 |
use crate::util::io_err; |
| 8 |
use rand::{thread_rng, RngCore}; |
| 9 |
use std::cmp::Eq; |
| 10 |
use std::fmt; |
| 11 |
use std::hash::Hash; |
| 12 |
use std::io; |
| 13 |
use std::io::{Read, Write}; |
| 14 |
use std::thread; |
| 15 |
use std::time::Duration; |
| 16 |
|
| 17 |
pub trait HIDDevice: FidoDevice + Read + Write { |
| 18 |
type BuildParameters: Sized; |
| 19 |
type Id: fmt::Debug + PartialEq + Eq + Hash + Sized; |
| 20 |
|
| 21 |
// Open device, verify that it is indeed a CTAP device and potentially read initial values |
| 22 |
fn new(parameters: Self::BuildParameters) -> Result<Self, (HIDError, Self::Id)>; |
| 23 |
fn id(&self) -> Self::Id; |
| 24 |
|
| 25 |
fn get_device_info(&self) -> U2FDeviceInfo; |
| 26 |
fn set_device_info(&mut self, dev_info: U2FDeviceInfo); |
| 27 |
|
| 28 |
// Channel ID management |
| 29 |
fn get_cid(&self) -> &[u8; 4]; |
| 30 |
fn set_cid(&mut self, cid: [u8; 4]); |
| 31 |
|
| 32 |
// HID report sizes |
| 33 |
fn in_rpt_size(&self) -> usize; |
| 34 |
fn out_rpt_size(&self) -> usize; |
| 35 |
|
| 36 |
fn get_property(&self, prop_name: &str) -> io::Result<String>; |
| 37 |
|
| 38 |
// Initialize on a protocol-level |
| 39 |
fn pre_init(&mut self) -> Result<(), HIDError> { |
| 40 |
if self.initialized() { |
| 41 |
return Ok(()); |
| 42 |
} |
| 43 |
|
| 44 |
let mut nonce = [0u8; 8]; |
| 45 |
thread_rng().fill_bytes(&mut nonce); |
| 46 |
|
| 47 |
// Send Init to broadcast address to create a new channel |
| 48 |
self.set_cid(CID_BROADCAST); |
| 49 |
let (cmd, raw) = HIDDevice::sendrecv(self, HIDCmd::Init, &nonce, &|| true)?; |
| 50 |
if cmd != HIDCmd::Init { |
| 51 |
return Err(HIDError::DeviceError); |
| 52 |
} |
| 53 |
|
| 54 |
let rsp = U2FHIDInitResp::read(&raw, &nonce)?; |
| 55 |
// Set the new Channel ID |
| 56 |
self.set_cid(rsp.cid); |
| 57 |
|
| 58 |
let vendor = self |
| 59 |
.get_property("Manufacturer") |
| 60 |
.unwrap_or_else(|_| String::from("Unknown Vendor")); |
| 61 |
let product = self |
| 62 |
.get_property("Product") |
| 63 |
.unwrap_or_else(|_| String::from("Unknown Device")); |
| 64 |
|
| 65 |
let info = U2FDeviceInfo { |
| 66 |
vendor_name: vendor.as_bytes().to_vec(), |
| 67 |
device_name: product.as_bytes().to_vec(), |
| 68 |
version_interface: rsp.version_interface, |
| 69 |
version_major: rsp.version_major, |
| 70 |
version_minor: rsp.version_minor, |
| 71 |
version_build: rsp.version_build, |
| 72 |
cap_flags: rsp.cap_flags, |
| 73 |
}; |
| 74 |
debug!("{:?}: {:?}", self.id(), info); |
| 75 |
self.set_device_info(info); |
| 76 |
|
| 77 |
// A CTAPHID host SHALL accept a response size that is longer than the |
| 78 |
// anticipated size to allow for future extensions of the protocol, yet |
| 79 |
// maintaining backwards compatibility. Future versions will maintain |
| 80 |
// the response structure of the current version, but additional fields |
| 81 |
// may be added. |
| 82 |
|
| 83 |
Ok(()) |
| 84 |
} |
| 85 |
|
| 86 |
fn sendrecv( |
| 87 |
&mut self, |
| 88 |
cmd: HIDCmd, |
| 89 |
send: &[u8], |
| 90 |
keep_alive: &dyn Fn() -> bool, |
| 91 |
) -> io::Result<(HIDCmd, Vec<u8>)> { |
| 92 |
self.u2f_write(cmd.into(), send)?; |
| 93 |
debug!("sent to Device {:?} cmd={:?}: {:?}", self.id(), cmd, send); |
| 94 |
loop { |
| 95 |
let (cmd, data) = self.u2f_read()?; |
| 96 |
if cmd != HIDCmd::Keepalive { |
| 97 |
debug!( |
| 98 |
"got from Device {:?} status={:?}: {:?}", |
| 99 |
self.id(), |
| 100 |
cmd, |
| 101 |
data |
| 102 |
); |
| 103 |
return Ok((cmd, data)); |
| 104 |
} |
| 105 |
// The authenticator might send us HIDCmd::Keepalive messages indefinitely, e.g. if |
| 106 |
// it's waiting for user presence. The keep_alive function is used to cancel the |
| 107 |
// transaction. |
| 108 |
if !keep_alive() { |
| 109 |
break; |
| 110 |
} |
| 111 |
} |
| 112 |
|
| 113 |
// If this is a CTAP2 device we can tell the authenticator to cancel the transaction on its |
| 114 |
// side as well. There's nothing to do for U2F/CTAP1 devices. |
| 115 |
if self.get_protocol() == FidoProtocol::CTAP2 { |
| 116 |
self.u2f_write(u8::from(HIDCmd::Cancel), &[])?; |
| 117 |
} |
| 118 |
// For CTAP2 devices we expect to read |
| 119 |
// (HIDCmd::Cbor, [CTAP2_ERR_KEEPALIVE_CANCEL]) |
| 120 |
// for U2F/CTAP1 we expect to read |
| 121 |
// (HIDCmd::Keepalive, [status]). |
| 122 |
self.u2f_read() |
| 123 |
} |
| 124 |
|
| 125 |
fn u2f_write(&mut self, cmd: u8, send: &[u8]) -> io::Result<()> { |
| 126 |
let mut count = U2FHIDInit::write(self, cmd, send)?; |
| 127 |
|
| 128 |
// Send continuation packets. |
| 129 |
let mut sequence = 0u8; |
| 130 |
while count < send.len() { |
| 131 |
count += U2FHIDCont::write(self, sequence, &send[count..])?; |
| 132 |
sequence += 1; |
| 133 |
} |
| 134 |
|
| 135 |
Ok(()) |
| 136 |
} |
| 137 |
|
| 138 |
fn u2f_read(&mut self) -> io::Result<(HIDCmd, Vec<u8>)> { |
| 139 |
// Now we read. This happens in 2 chunks: The initial packet, which has |
| 140 |
// the size we expect overall, then continuation packets, which will |
| 141 |
// fill in data until we have everything. |
| 142 |
let (cmd, data) = { |
| 143 |
let (cmd, mut data) = U2FHIDInit::read(self)?; |
| 144 |
|
| 145 |
trace!("init frame data read: {:04X?}", &data); |
| 146 |
let mut sequence = 0u8; |
| 147 |
while data.len() < data.capacity() { |
| 148 |
let max = data.capacity() - data.len(); |
| 149 |
data.extend_from_slice(&U2FHIDCont::read(self, sequence, max)?); |
| 150 |
sequence += 1; |
| 151 |
} |
| 152 |
(cmd, data) |
| 153 |
}; |
| 154 |
trace!("u2f_read({:?}) cmd={:?}: {:04X?}", self.id(), cmd, &data); |
| 155 |
Ok((cmd, data)) |
| 156 |
} |
| 157 |
} |
| 158 |
|
| 159 |
#[cfg(not(test))] |
| 160 |
impl<T: HIDDevice> TestDevice for T {} |
| 161 |
|
| 162 |
impl<T: HIDDevice + TestDevice> FidoDeviceIO for T { |
| 163 |
fn send_msg_cancellable<Out, Req: RequestCtap1<Output = Out> + RequestCtap2<Output = Out>>( |
| 164 |
&mut self, |
| 165 |
msg: &Req, |
| 166 |
keep_alive: &dyn Fn() -> bool, |
| 167 |
) -> Result<Out, HIDError> { |
| 168 |
if !self.initialized() { |
| 169 |
return Err(HIDError::DeviceNotInitialized); |
| 170 |
} |
| 171 |
|
| 172 |
match self.get_protocol() { |
| 173 |
FidoProtocol::CTAP1 => self.send_ctap1_cancellable(msg, keep_alive), |
| 174 |
FidoProtocol::CTAP2 => self.send_cbor_cancellable(msg, keep_alive), |
| 175 |
} |
| 176 |
} |
| 177 |
|
| 178 |
fn send_cbor_cancellable<Req: RequestCtap2>( |
| 179 |
&mut self, |
| 180 |
msg: &Req, |
| 181 |
keep_alive: &dyn Fn() -> bool, |
| 182 |
) -> Result<Req::Output, HIDError> { |
| 183 |
debug!("sending {:?} to {:?}", msg, self); |
| 184 |
#[cfg(test)] |
| 185 |
{ |
| 186 |
if self.skip_serialization() { |
| 187 |
return self.send_ctap2_unserialized(msg); |
| 188 |
} |
| 189 |
} |
| 190 |
|
| 191 |
let mut data = msg.wire_format()?; |
| 192 |
let mut buf: Vec<u8> = Vec::with_capacity(data.len() + 1); |
| 193 |
// CTAP2 command |
| 194 |
buf.push(msg.command() as u8); |
| 195 |
// payload |
| 196 |
buf.append(&mut data); |
| 197 |
let buf = buf; |
| 198 |
|
| 199 |
let (cmd, resp) = self.sendrecv(HIDCmd::Cbor, &buf, keep_alive)?; |
| 200 |
if cmd == HIDCmd::Cbor { |
| 201 |
Ok(msg.handle_response_ctap2(self, &resp)?) |
| 202 |
} else { |
| 203 |
Err(HIDError::UnexpectedCmd(cmd.into())) |
| 204 |
} |
| 205 |
} |
| 206 |
|
| 207 |
fn send_ctap1_cancellable<Req: RequestCtap1>( |
| 208 |
&mut self, |
| 209 |
msg: &Req, |
| 210 |
keep_alive: &dyn Fn() -> bool, |
| 211 |
) -> Result<Req::Output, HIDError> { |
| 212 |
debug!("sending {:?} to {:?}", msg, self); |
| 213 |
#[cfg(test)] |
| 214 |
{ |
| 215 |
if self.skip_serialization() { |
| 216 |
return self.send_ctap1_unserialized(msg); |
| 217 |
} |
| 218 |
} |
| 219 |
let (data, add_info) = msg.ctap1_format()?; |
| 220 |
|
| 221 |
while keep_alive() { |
| 222 |
// sendrecv will not block with a CTAP1 device |
| 223 |
let (cmd, mut data) = self.sendrecv(HIDCmd::Msg, &data, &|| true)?; |
| 224 |
if cmd == HIDCmd::Msg { |
| 225 |
if data.len() < 2 { |
| 226 |
return Err(io_err("Unexpected Response: shorter than expected").into()); |
| 227 |
} |
| 228 |
let split_at = data.len() - 2; |
| 229 |
let status = data.split_off(split_at); |
| 230 |
// This will bubble up error if status != no error |
| 231 |
let status = ApduErrorStatus::from([status[0], status[1]]); |
| 232 |
|
| 233 |
match msg.handle_response_ctap1(self, status, &data, &add_info) { |
| 234 |
Ok(out) => return Ok(out), |
| 235 |
Err(Retryable::Retry) => { |
| 236 |
// sleep 100ms then loop again |
| 237 |
// TODO(baloo): meh, use tokio instead? |
| 238 |
thread::sleep(Duration::from_millis(100)); |
| 239 |
} |
| 240 |
Err(Retryable::Error(e)) => return Err(e), |
| 241 |
} |
| 242 |
} else { |
| 243 |
return Err(HIDError::UnexpectedCmd(cmd.into())); |
| 244 |
} |
| 245 |
} |
| 246 |
|
| 247 |
Err(HIDError::Command(CommandError::StatusCode( |
| 248 |
StatusCode::KeepaliveCancel, |
| 249 |
None, |
| 250 |
))) |
| 251 |
} |
| 252 |
} |