Debian Codegraph @

third_party/rust/authenticator/src/transport/freebsd/device.rs

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 extern crate libc;
6
7 use crate::consts::{Capability, CID_BROADCAST, MAX_HID_RPT_SIZE};
8 use crate::ctap2::commands::get_info::AuthenticatorInfo;
9 use crate::transport::hid::HIDDevice;
10 use crate::transport::platform::uhid;
11 use crate::transport::{FidoDevice, FidoProtocol, HIDError, SharedSecret};
12 use crate::u2ftypes::U2FDeviceInfo;
13 use crate::util::from_unix_result;
14 use crate::util::io_err;
15 use std::ffi::{CString, OsString};
16 use std::hash::{Hash, Hasher};
17 use std::io::{self, Read, Write};
18 use std::mem;
19 use std::os::unix::prelude::*;
20
21 #[derive(Debug)]
22 pub struct Device {
23 path: OsString,
24 fd: libc::c_int,
25 cid: [u8; 4],
26 dev_info: Option<U2FDeviceInfo>,
27 secret: Option<SharedSecret>,
28 authenticator_info: Option<AuthenticatorInfo>,
29 protocol: FidoProtocol,
30 }
31
32 impl Device {
33 fn ping(&mut self) -> io::Result<()> {
34 for i in 0..10 {
35 let mut buf = vec![0u8; 1 + MAX_HID_RPT_SIZE];
36
37 buf[0] = 0; // report number
38 buf[1] = 0xff; // CID_BROADCAST
39 buf[2] = 0xff;
40 buf[3] = 0xff;
41 buf[4] = 0xff;
42 buf[5] = 0x81; // ping
43 buf[6] = 0;
44 buf[7] = 1; // one byte
45
46 if self.write(&buf)? != buf.len() {
47 return Err(io_err("write ping failed"));
48 }
49
50 // Wait for response
51 let mut pfd: libc::pollfd = unsafe { mem::zeroed() };
52 pfd.fd = self.fd;
53 pfd.events = libc::POLLIN;
54 let nfds = unsafe { libc::poll(&mut pfd, 1, 100) };
55 if nfds == -1 {
56 return Err(io::Error::last_os_error());
57 }
58 if nfds == 0 {
59 debug!("device timeout {}", i);
60 continue;
61 }
62
63 // Read response. When reports come in they are all
64 // exactly the same size, with no report id byte because
65 // there is only one report.
66 let n = self.read(&mut buf[1..])?;
67 if n != buf.len() - 1 {
68 return Err(io_err("read pong failed"));
69 }
70
71 return Ok(());
72 }
73
74 Err(io_err("no response from device"))
75 }
76 }
77
78 impl Drop for Device {
79 fn drop(&mut self) {
80 // Close the fd, ignore any errors.
81 let _ = unsafe { libc::close(self.fd) };
82 }
83 }
84
85 impl PartialEq for Device {
86 fn eq(&self, other: &Device) -> bool {
87 self.path == other.path
88 }
89 }
90
91 impl Eq for Device {}
92
93 impl Hash for Device {
94 fn hash<H: Hasher>(&self, state: &mut H) {
95 self.path.hash(state);
96 }
97 }
98
99 impl Read for Device {
100 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
101 let bufp = buf.as_mut_ptr() as *mut libc::c_void;
102 let rv = unsafe { libc::read(self.fd, bufp, buf.len()) };
103 from_unix_result(rv as usize)
104 }
105 }
106
107 impl Write for Device {
108 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
109 let report_id = buf[0] as i64;
110 // Skip report number when not using numbered reports.
111 let start = if report_id == 0x0 { 1 } else { 0 };
112 let data = &buf[start..];
113
114 let data_ptr = data.as_ptr() as *const libc::c_void;
115 let rv = unsafe { libc::write(self.fd, data_ptr, data.len()) };
116 from_unix_result(rv as usize + 1)
117 }
118
119 // USB HID writes don't buffer, so this will be a nop.
120 fn flush(&mut self) -> io::Result<()> {
121 Ok(())
122 }
123 }
124
125 impl HIDDevice for Device {
126 type BuildParameters = OsString;
127 type Id = OsString;
128
129 fn new(path: OsString) -> Result<Self, (HIDError, Self::Id)> {
130 let cstr =
131 CString::new(path.as_bytes()).map_err(|_| (HIDError::DeviceError, path.clone()))?;
132 let fd = unsafe { libc::open(cstr.as_ptr(), libc::O_RDWR) };
133 let fd = from_unix_result(fd).map_err(|e| (e.into(), path.clone()))?;
134 let mut res = Self {
135 path,
136 fd,
137 cid: CID_BROADCAST,
138 dev_info: None,
139 secret: None,
140 authenticator_info: None,
141 protocol: FidoProtocol::CTAP2,
142 };
143 if res.is_u2f() {
144 info!("new device {:?}", res.path);
145 Ok(res)
146 } else {
147 Err((HIDError::DeviceNotSupported, res.path.clone()))
148 }
149 }
150
151 fn id(&self) -> Self::Id {
152 self.path.clone()
153 }
154
155 fn get_cid(&self) -> &[u8; 4] {
156 &self.cid
157 }
158
159 fn set_cid(&mut self, cid: [u8; 4]) {
160 self.cid = cid;
161 }
162
163 fn in_rpt_size(&self) -> usize {
164 MAX_HID_RPT_SIZE
165 }
166
167 fn out_rpt_size(&self) -> usize {
168 MAX_HID_RPT_SIZE
169 }
170
171 fn get_property(&self, _prop_name: &str) -> io::Result<String> {
172 Err(io::Error::new(io::ErrorKind::Other, "Not implemented"))
173 }
174
175 fn get_device_info(&self) -> U2FDeviceInfo {
176 // unwrap is okay, as dev_info must have already been set, else
177 // a programmer error
178 self.dev_info.clone().unwrap()
179 }
180
181 fn set_device_info(&mut self, dev_info: U2FDeviceInfo) {
182 self.dev_info = Some(dev_info);
183 }
184 }
185
186 impl FidoDevice for Device {
187 fn pre_init(&mut self) -> Result<(), HIDError> {
188 HIDDevice::pre_init(self)
189 }
190
191 fn should_try_ctap2(&self) -> bool {
192 HIDDevice::get_device_info(self)
193 .cap_flags
194 .contains(Capability::CBOR)
195 }
196
197 fn initialized(&self) -> bool {
198 // During successful init, the broadcast channel id gets repplaced by an actual one
199 self.cid != CID_BROADCAST
200 }
201
202 fn is_u2f(&mut self) -> bool {
203 if !uhid::is_u2f_device(self.fd) {
204 return false;
205 }
206 if self.ping().is_err() {
207 return false;
208 }
209 true
210 }
211
212 fn get_shared_secret(&self) -> Option<&SharedSecret> {
213 self.secret.as_ref()
214 }
215
216 fn set_shared_secret(&mut self, secret: SharedSecret) {
217 self.secret = Some(secret);
218 }
219
220 fn get_authenticator_info(&self) -> Option<&AuthenticatorInfo> {
221 self.authenticator_info.as_ref()
222 }
223
224 fn set_authenticator_info(&mut self, authenticator_info: AuthenticatorInfo) {
225 self.authenticator_info = Some(authenticator_info);
226 }
227
228 fn get_protocol(&self) -> FidoProtocol {
229 self.protocol
230 }
231
232 fn downgrade_to_ctap1(&mut self) {
233 self.protocol = FidoProtocol::CTAP1;
234 }
235 }