Debian Codegraph @

third_party/rust/authenticator/src/transport/netbsd/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 use crate::consts::{Capability, CID_BROADCAST, MAX_HID_RPT_SIZE};
7 use crate::ctap2::commands::get_info::AuthenticatorInfo;
8 use crate::transport::hid::HIDDevice;
9 use crate::transport::platform::fd::Fd;
10 use crate::transport::platform::monitor::WrappedOpenDevice;
11 use crate::transport::platform::uhid;
12 use crate::transport::{FidoDevice, FidoProtocol, HIDError, SharedSecret};
13 use crate::u2ftypes::U2FDeviceInfo;
14 use crate::util::io_err;
15 use std::ffi::OsString;
16 use std::hash::{Hash, Hasher};
17 use std::io::{self, Read, Write};
18 use std::mem;
19
20 #[derive(Debug)]
21 pub struct Device {
22 path: OsString,
23 fd: Fd,
24 cid: [u8; 4],
25 dev_info: Option<U2FDeviceInfo>,
26 secret: Option<SharedSecret>,
27 authenticator_info: Option<AuthenticatorInfo>,
28 protocol: FidoProtocol,
29 }
30
31 impl Device {
32 fn ping(&mut self) -> io::Result<()> {
33 for i in 0..10 {
34 let mut buf = vec![0u8; 1 + MAX_HID_RPT_SIZE];
35
36 buf[0] = 0; // report number
37 buf[1] = 0xff; // CID_BROADCAST
38 buf[2] = 0xff;
39 buf[3] = 0xff;
40 buf[4] = 0xff;
41 buf[5] = 0x81; // ping
42 buf[6] = 0;
43 buf[7] = 1; // one byte
44
45 // Write ping request. Each write to the device contains
46 // exactly one report id byte[*] followed by exactly as
47 // many bytes as are in a report, and will be consumed all
48 // at once by /dev/uhidN. So we use plain write, not
49 // write_all to issue writes in a loop.
50 //
51 // [*] This is only for the internal authenticator-rs API,
52 // not for the USB HID protocol, which for a device with
53 // only one report id excludes the report id byte from the
54 // interrupt in/out pipe transfer format.
55 if self.write(&buf)? != buf.len() {
56 return Err(io_err("write ping failed"));
57 }
58
59 // Wait for response
60 let mut pfd: libc::pollfd = unsafe { mem::zeroed() };
61 pfd.fd = self.fd.fileno;
62 pfd.events = libc::POLLIN;
63 let nfds = unsafe { libc::poll(&mut pfd, 1, 100) };
64 if nfds == -1 {
65 return Err(io::Error::last_os_error());
66 }
67 if nfds == 0 {
68 debug!("device timeout {}", i);
69 continue;
70 }
71
72 // Read response. When reports come in they are all
73 // exactly the same size, with no report id byte because
74 // there is only one report.
75 let n = self.read(&mut buf[1..])?;
76 if n != buf.len() - 1 {
77 return Err(io_err("read pong failed"));
78 }
79
80 return Ok(());
81 }
82
83 Err(io_err("no response from device"))
84 }
85 }
86
87 impl PartialEq for Device {
88 fn eq(&self, other: &Device) -> bool {
89 self.fd == other.fd
90 }
91 }
92
93 impl Eq for Device {}
94
95 impl Hash for Device {
96 fn hash<H: Hasher>(&self, state: &mut H) {
97 self.fd.hash(state);
98 }
99 }
100
101 impl Read for Device {
102 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
103 let bufp = buf.as_mut_ptr() as *mut libc::c_void;
104 let nread = unsafe { libc::read(self.fd.fileno, bufp, buf.len()) };
105 if nread == -1 {
106 return Err(io::Error::last_os_error());
107 }
108 Ok(nread as usize)
109 }
110 }
111
112 impl Write for Device {
113 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
114 // Always skip the first byte (report number)
115 let data = &buf[1..];
116 let data_ptr = data.as_ptr() as *const libc::c_void;
117 let nwrit = unsafe { libc::write(self.fd.fileno, data_ptr, data.len()) };
118 if nwrit == -1 {
119 return Err(io::Error::last_os_error());
120 }
121 // Pretend we wrote the report number byte
122 Ok(nwrit as usize + 1)
123 }
124
125 fn flush(&mut self) -> io::Result<()> {
126 Ok(())
127 }
128 }
129
130 impl HIDDevice for Device {
131 type BuildParameters = WrappedOpenDevice;
132 type Id = OsString;
133
134 fn new(fido: WrappedOpenDevice) -> Result<Self, (HIDError, Self::Id)> {
135 debug!("device found: {:?}", fido);
136 let mut res = Self {
137 path: fido.os_path,
138 fd: fido.fd,
139 cid: CID_BROADCAST,
140 dev_info: None,
141 secret: None,
142 authenticator_info: None,
143 protocol: FidoProtocol::CTAP2,
144 };
145 if res.is_u2f() {
146 info!("new device {:?}", res.path);
147 Ok(res)
148 } else {
149 Err((HIDError::DeviceNotSupported, res.path.clone()))
150 }
151 }
152
153 fn id(&self) -> Self::Id {
154 self.path.clone()
155 }
156
157 fn get_cid(&self) -> &[u8; 4] {
158 &self.cid
159 }
160
161 fn set_cid(&mut self, cid: [u8; 4]) {
162 self.cid = cid;
163 }
164
165 fn in_rpt_size(&self) -> usize {
166 MAX_HID_RPT_SIZE
167 }
168
169 fn out_rpt_size(&self) -> usize {
170 MAX_HID_RPT_SIZE
171 }
172
173 fn get_property(&self, _prop_name: &str) -> io::Result<String> {
174 Err(io::Error::new(io::ErrorKind::Other, "Not implemented"))
175 }
176
177 fn get_device_info(&self) -> U2FDeviceInfo {
178 // unwrap is okay, as dev_info must have already been set, else
179 // a programmer error
180 self.dev_info.clone().unwrap()
181 }
182
183 fn set_device_info(&mut self, dev_info: U2FDeviceInfo) {
184 self.dev_info = Some(dev_info);
185 }
186 }
187
188 impl FidoDevice for Device {
189 fn pre_init(&mut self) -> Result<(), HIDError> {
190 HIDDevice::pre_init(self)
191 }
192
193 fn should_try_ctap2(&self) -> bool {
194 HIDDevice::get_device_info(self)
195 .cap_flags
196 .contains(Capability::CBOR)
197 }
198
199 fn initialized(&self) -> bool {
200 // During successful init, the broadcast channel id gets repplaced by an actual one
201 self.cid != CID_BROADCAST
202 }
203
204 fn is_u2f(&mut self) -> bool {
205 if !uhid::is_u2f_device(&self.fd) {
206 return false;
207 }
208 // This step is not strictly necessary -- NetBSD puts fido
209 // devices into raw mode automatically by default, but in
210 // principle that might change, and this serves as a test to
211 // verify that we're running on a kernel with support for raw
212 // mode at all so we don't get confused issuing writes that try
213 // to set the report descriptor rather than transfer data on
214 // the output interrupt pipe as we need.
215 match uhid::hid_set_raw(&self.fd, true) {
216 Ok(_) => (),
217 Err(_) => return false,
218 }
219 if self.ping().is_err() {
220 return false;
221 }
222 true
223 }
224
225 fn get_shared_secret(&self) -> Option<&SharedSecret> {
226 self.secret.as_ref()
227 }
228
229 fn set_shared_secret(&mut self, secret: SharedSecret) {
230 self.secret = Some(secret);
231 }
232
233 fn get_authenticator_info(&self) -> Option<&AuthenticatorInfo> {
234 self.authenticator_info.as_ref()
235 }
236
237 fn set_authenticator_info(&mut self, authenticator_info: AuthenticatorInfo) {
238 self.authenticator_info = Some(authenticator_info);
239 }
240
241 fn get_protocol(&self) -> FidoProtocol {
242 self.protocol
243 }
244
245 fn downgrade_to_ctap1(&mut self) {
246 self.protocol = FidoProtocol::CTAP1;
247 }
248 }