Skip to main content

capsules_extra/usb/
ctap.rs

1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2022.
4
5//! Client to Authenticator Protocol CTAPv2 over USB HID
6//!
7//! Based on the spec avaliable at: <https://fidoalliance.org/specs/fido-v2.0-id-20180227/fido-client-to-authenticator-protocol-v2.0-id-20180227.html>
8
9use core::cmp;
10
11use super::descriptors;
12use super::descriptors::Buffer64;
13use super::descriptors::DescriptorType;
14use super::descriptors::EndpointAddress;
15use super::descriptors::EndpointDescriptor;
16use super::descriptors::HIDCountryCode;
17use super::descriptors::HIDDescriptor;
18use super::descriptors::HIDSubordinateDescriptor;
19use super::descriptors::InterfaceDescriptor;
20use super::descriptors::ReportDescriptor;
21use super::descriptors::TransferDirection;
22use super::usbc_client_ctrl::ClientCtrl;
23
24use kernel::ErrorCode;
25use kernel::hil;
26use kernel::hil::usb::TransferType;
27use kernel::utilities::cells::OptionalCell;
28use kernel::utilities::cells::TakeCell;
29use tock_registers_v0::interfaces::{Readable, Writeable};
30
31/// Use 1 Interrupt transfer IN/OUT endpoint
32const ENDPOINT_NUM: usize = 1;
33
34const OUT_BUFFER: usize = 0;
35const IN_BUFFER: usize = 1;
36
37static LANGUAGES: &[u16; 1] = &[
38    0x0409, // English (United States)
39];
40/// Max packet size specified by spec
41pub const MAX_CTRL_PACKET_SIZE: u8 = 64;
42
43const N_ENDPOINTS: usize = 2;
44
45/// The HID report descriptor for CTAP.
46///
47/// This is a combination of:
48///     - the CTAP spec, example 8
49///     - USB HID spec examples
50/// Plus it matches: <https://chromium.googlesource.com/chromiumos/platform2/+/master/u2fd/u2fhid.cc>
51static REPORT_DESCRIPTOR: &[u8] = &[
52    0x06, 0xD0, 0xF1, // HID_UsagePage ( FIDO_USAGE_PAGE ),
53    0x09, 0x01, // HID_Usage ( FIDO_USAGE_CTAPHID ),
54    0xA1, 0x01, // HID_Collection ( HID_Application ),
55    0x09, 0x20, // HID_Usage ( FIDO_USAGE_DATA_IN ),
56    0x15, 0x00, // HID_LogicalMin ( 0 ),
57    0x26, 0xFF, 0x00, // HID_LogicalMaxS ( 0xff ),
58    0x75, 0x08, // HID_ReportSize ( 8 ),
59    0x95, 0x40, // HID_ReportCount ( HID_INPUT_REPORT_BYTES ),
60    0x81, 0x02, // HID_Input ( HID_Data | HID_Absolute | HID_Variable ),
61    0x09, 0x21, // HID_Usage ( FIDO_USAGE_DATA_OUT ),
62    0x15, 0x00, // HID_LogicalMin ( 0 ),
63    0x26, 0xFF, 0x00, // HID_LogicalMaxS ( 0xff ),
64    0x75, 0x08, // HID_ReportSize ( 8 ),
65    0x95, 0x40, // HID_ReportCount ( HID_OUTPUT_REPORT_BYTES ),
66    0x91, 0x02, // HID_Output ( HID_Data | HID_Absolute | HID_Variable ),
67    0xC0, // HID_EndCollection
68];
69
70static REPORT: ReportDescriptor<'static> = ReportDescriptor {
71    desc: REPORT_DESCRIPTOR,
72};
73
74static SUB_HID_DESCRIPTOR: &[HIDSubordinateDescriptor] = &[HIDSubordinateDescriptor {
75    typ: DescriptorType::Report,
76    len: REPORT_DESCRIPTOR.len() as u16,
77}];
78
79static HID_DESCRIPTOR: HIDDescriptor<'static> = HIDDescriptor {
80    hid_class: 0x0110,
81    country_code: HIDCountryCode::NotSupported,
82    sub_descriptors: SUB_HID_DESCRIPTOR,
83};
84
85/// Implementation of the CTAP HID (Human Interface Device)
86pub struct CtapHid<'a, U: 'a> {
87    /// Helper USB client library for handling many USB operations.
88    client_ctrl: ClientCtrl<'a, 'static, U>,
89
90    /// 64 byte buffers for each endpoint.
91    buffers: [Buffer64; N_ENDPOINTS],
92
93    client: OptionalCell<&'a dyn hil::usb_hid::Client<'a, [u8; 64]>>,
94
95    /// A buffer to hold the data we want to send
96    send_buffer: TakeCell<'static, [u8; 64]>,
97
98    /// A holder for the buffer to receive bytes into. We use this as a flag as
99    /// well, if we have a buffer then we are actively doing a receive.
100    recv_buffer: TakeCell<'static, [u8; 64]>,
101}
102
103impl<'a, U: hil::usb::UsbController<'a>> CtapHid<'a, U> {
104    pub fn new(
105        controller: &'a U,
106        vendor_id: u16,
107        product_id: u16,
108        strings: &'static [&'static str; 3],
109    ) -> Self {
110        let interfaces: &mut [InterfaceDescriptor] = &mut [InterfaceDescriptor {
111            interface_number: 0,
112            interface_class: 0x03,    // HID
113            interface_subclass: 0x00, // No subcall
114            interface_protocol: 0x00, // No protocol
115            ..InterfaceDescriptor::default()
116        }];
117
118        let endpoints: &[&[EndpointDescriptor]] = &[&[
119            EndpointDescriptor {
120                endpoint_address: EndpointAddress::new_const(
121                    ENDPOINT_NUM,
122                    TransferDirection::DeviceToHost,
123                ),
124                transfer_type: TransferType::Interrupt,
125                max_packet_size: 64,
126                interval: 5,
127            },
128            EndpointDescriptor {
129                endpoint_address: EndpointAddress::new_const(
130                    ENDPOINT_NUM,
131                    TransferDirection::HostToDevice,
132                ),
133                transfer_type: TransferType::Interrupt,
134                max_packet_size: 64,
135                interval: 5,
136            },
137        ]];
138
139        let (device_descriptor_buffer, other_descriptor_buffer) =
140            descriptors::create_descriptor_buffers(
141                descriptors::DeviceDescriptor {
142                    vendor_id,
143                    product_id,
144                    manufacturer_string: 1,
145                    product_string: 2,
146                    serial_number_string: 3,
147                    class: 0x03, // Class: HID
148                    max_packet_size_ep0: MAX_CTRL_PACKET_SIZE,
149                    ..descriptors::DeviceDescriptor::default()
150                },
151                descriptors::ConfigurationDescriptor::default(),
152                interfaces,
153                endpoints,
154                Some(&HID_DESCRIPTOR),
155                None,
156            );
157
158        CtapHid {
159            client_ctrl: ClientCtrl::new(
160                controller,
161                device_descriptor_buffer,
162                other_descriptor_buffer,
163                Some(&HID_DESCRIPTOR),
164                Some(&REPORT),
165                LANGUAGES,
166                strings,
167            ),
168            buffers: [Buffer64::default(), Buffer64::default()],
169            client: OptionalCell::empty(),
170            send_buffer: TakeCell::empty(),
171            recv_buffer: TakeCell::empty(),
172        }
173    }
174
175    #[inline]
176    fn controller(&self) -> &'a U {
177        self.client_ctrl.controller()
178    }
179
180    pub fn set_client(&'a self, client: &'a dyn hil::usb_hid::Client<'a, [u8; 64]>) {
181        self.client.set(client);
182    }
183}
184
185impl<'a, U: hil::usb::UsbController<'a>> hil::usb_hid::UsbHid<'a, [u8; 64]> for CtapHid<'a, U> {
186    fn send_buffer(
187        &'a self,
188        send: &'static mut [u8; 64],
189    ) -> Result<usize, (ErrorCode, &'static mut [u8; 64])> {
190        let len = send.len();
191
192        self.send_buffer.replace(send);
193        self.controller().endpoint_resume_in(ENDPOINT_NUM);
194
195        Ok(len)
196    }
197
198    fn send_cancel(&'a self) -> Result<&'static mut [u8; 64], ErrorCode> {
199        match self.send_buffer.take() {
200            Some(buf) => Ok(buf),
201            None => Err(ErrorCode::BUSY),
202        }
203    }
204
205    fn receive_buffer(
206        &'a self,
207        recv: &'static mut [u8; 64],
208    ) -> Result<(), (ErrorCode, &'static mut [u8; 64])> {
209        self.recv_buffer.replace(recv);
210        self.controller().endpoint_resume_out(ENDPOINT_NUM);
211        Ok(())
212    }
213
214    fn receive_cancel(&'a self) -> Result<&'static mut [u8; 64], ErrorCode> {
215        match self.recv_buffer.take() {
216            Some(buf) => Ok(buf),
217            None => Err(ErrorCode::BUSY),
218        }
219    }
220}
221
222impl<'a, U: hil::usb::UsbController<'a>> hil::usb::Client<'a> for CtapHid<'a, U> {
223    fn enable(&'a self) {
224        // Set up the default control endpoint
225        self.client_ctrl.enable();
226
227        // Setup buffers for IN and OUT data transfer.
228        self.controller()
229            .endpoint_set_out_buffer(ENDPOINT_NUM, &self.buffers[OUT_BUFFER].buf);
230        self.controller()
231            .endpoint_set_in_buffer(ENDPOINT_NUM, &self.buffers[IN_BUFFER].buf);
232        self.controller()
233            .endpoint_in_out_enable(TransferType::Interrupt, ENDPOINT_NUM);
234    }
235
236    fn attach(&'a self) {
237        self.client_ctrl.attach();
238    }
239
240    fn bus_reset(&'a self) {}
241
242    /// Handle a Control Setup transaction.
243    fn ctrl_setup(&'a self, endpoint: usize) -> hil::usb::CtrlSetupResult {
244        self.client_ctrl.ctrl_setup(endpoint)
245    }
246
247    /// Handle a Control In transaction
248    fn ctrl_in(&'a self, endpoint: usize) -> hil::usb::CtrlInResult {
249        self.client_ctrl.ctrl_in(endpoint)
250    }
251
252    /// Handle a Control Out transaction
253    fn ctrl_out(&'a self, endpoint: usize, packet_bytes: u32) -> hil::usb::CtrlOutResult {
254        self.client_ctrl.ctrl_out(endpoint, packet_bytes)
255    }
256
257    fn ctrl_status(&'a self, endpoint: usize) {
258        self.client_ctrl.ctrl_status(endpoint)
259    }
260
261    /// Handle the completion of a Control transfer
262    fn ctrl_status_complete(&'a self, endpoint: usize) {
263        if self.send_buffer.is_some() {
264            self.controller().endpoint_resume_in(ENDPOINT_NUM);
265        }
266
267        self.client_ctrl.ctrl_status_complete(endpoint)
268    }
269
270    /// Handle a Bulk/Interrupt IN transaction.
271    ///
272    /// This is called when we can send data to the host. It should get called
273    /// when we tell the controller we want to resume the IN endpoint (meaning
274    /// we know we have data to send) and afterwards until we return
275    /// `hil::usb::InResult::Delay` from this function. That means we can use
276    /// this as a callback to mean that the transmission finished by waiting
277    /// until this function is called when we don't have anything left to send.
278    fn packet_in(&'a self, transfer_type: TransferType, _endpoint: usize) -> hil::usb::InResult {
279        match transfer_type {
280            TransferType::Interrupt => {
281                self.send_buffer
282                    .take()
283                    .map_or(hil::usb::InResult::Delay, |buf| {
284                        // Get packet that we have shared with the underlying
285                        // USB stack to copy the tx into.
286                        let packet = &self.buffers[IN_BUFFER].buf;
287
288                        // Copy from the TX buffer to the outgoing USB packet.
289                        for i in 0..64 {
290                            packet[i].set(buf[i]);
291                        }
292
293                        // Put the TX buffer back so we can keep sending from it.
294                        self.send_buffer.replace(buf);
295
296                        // Return that we have data to send.
297                        hil::usb::InResult::Packet(64)
298                    })
299            }
300            TransferType::Bulk | TransferType::Control | TransferType::Isochronous => {
301                panic!("Transfer protocol not supported by CTAP v2");
302            }
303        }
304    }
305
306    /// Handle a Bulk/Interrupt OUT transaction
307    ///
308    /// This is data going from the host to the device (us)
309    fn packet_out(
310        &'a self,
311        transfer_type: TransferType,
312        endpoint: usize,
313        packet_bytes: u32,
314    ) -> hil::usb::OutResult {
315        match transfer_type {
316            TransferType::Interrupt => {
317                // If we have a receive buffer we can copy the incoming data in.
318                // If we do not have a buffer, then we apply back pressure by
319                // returning `hil::usb::OutResult::Delay` to the USB stack until
320                // we get a receive call.
321                self.recv_buffer
322                    .take()
323                    .map_or(hil::usb::OutResult::Delay, |buf| {
324                        // How many more bytes can we store in our RX buffer?
325                        let copy_length = cmp::min(packet_bytes as usize, buf.len());
326
327                        // Do the copy into the RX buffer.
328                        let packet = &self.buffers[OUT_BUFFER].buf;
329                        for i in 0..copy_length {
330                            buf[i] = packet[i].get();
331                        }
332
333                        // Notify the client
334                        self.client.map(move |client| {
335                            client.packet_received(Ok(()), buf, endpoint);
336                        });
337
338                        hil::usb::OutResult::Ok
339                    })
340            }
341            TransferType::Bulk | TransferType::Control | TransferType::Isochronous => {
342                panic!("Transfer protocol not supported by CTAP v2");
343            }
344        }
345    }
346
347    fn packet_transmitted(&'a self, endpoint: usize) {
348        self.send_buffer.take().map(|buf| {
349            self.client.map(move |client| {
350                client.packet_transmitted(Ok(()), buf, endpoint);
351            });
352        });
353    }
354}