Debian Codegraph @

third_party/rust/authenticator/src/transport/hidproto.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 // Shared code for platforms that use raw HID access (Linux, FreeBSD, etc.)
6
7 #![cfg_attr(
8 feature = "cargo-clippy",
9 allow(clippy::cast_lossless, clippy::needless_lifetimes)
10 )]
11
12 #[cfg(target_os = "linux")]
13 use std::io;
14 use std::mem;
15
16 use crate::consts::{FIDO_USAGE_PAGE, FIDO_USAGE_U2FHID};
17 #[cfg(target_os = "linux")]
18 use crate::consts::{INIT_HEADER_SIZE, MAX_HID_RPT_SIZE};
19
20 // The 4 MSBs (the tag) are set when it's a long item.
21 const HID_MASK_LONG_ITEM_TAG: u8 = 0b1111_0000;
22 // The 2 LSBs denote the size of a short item.
23 const HID_MASK_SHORT_ITEM_SIZE: u8 = 0b0000_0011;
24 // The 6 MSBs denote the tag (4) and type (2).
25 const HID_MASK_ITEM_TAGTYPE: u8 = 0b1111_1100;
26 // tag=0000, type=10 (local)
27 const HID_ITEM_TAGTYPE_USAGE: u8 = 0b0000_1000;
28 // tag=0000, type=01 (global)
29 const HID_ITEM_TAGTYPE_USAGE_PAGE: u8 = 0b0000_0100;
30 // tag=1000, type=00 (main)
31 const HID_ITEM_TAGTYPE_INPUT: u8 = 0b1000_0000;
32 // tag=1001, type=00 (main)
33 const HID_ITEM_TAGTYPE_OUTPUT: u8 = 0b1001_0000;
34 // tag=1001, type=01 (global)
35 const HID_ITEM_TAGTYPE_REPORT_COUNT: u8 = 0b1001_0100;
36
37 pub struct ReportDescriptor {
38 pub value: Vec<u8>,
39 }
40
41 impl ReportDescriptor {
42 fn iter(self) -> ReportDescriptorIterator {
43 ReportDescriptorIterator::new(self)
44 }
45 }
46
47 #[derive(Debug)]
48 pub enum Data {
49 UsagePage { data: u32 },
50 Usage { data: u32 },
51 Input,
52 Output,
53 ReportCount { data: u32 },
54 }
55
56 pub struct ReportDescriptorIterator {
57 desc: ReportDescriptor,
58 pos: usize,
59 }
60
61 impl ReportDescriptorIterator {
62 fn new(desc: ReportDescriptor) -> Self {
63 Self { desc, pos: 0 }
64 }
65
66 fn next_item(&mut self) -> Option<Data> {
67 let item = get_hid_item(&self.desc.value[self.pos..]);
68 if item.is_none() {
69 self.pos = self.desc.value.len(); // Close, invalid data.
70 return None;
71 }
72
73 let (tag_type, key_len, data) = item.unwrap();
74
75 // Advance if we have a valid item.
76 self.pos += key_len + data.len();
77
78 // We only check short items.
79 if key_len > 1 {
80 return None; // Check next item.
81 }
82
83 // Short items have max. length of 4 bytes.
84 assert!(data.len() <= mem::size_of::<u32>());
85
86 // Convert data bytes to a uint.
87 let data = read_uint_le(data);
88 match tag_type {
89 HID_ITEM_TAGTYPE_USAGE_PAGE => Some(Data::UsagePage { data }),
90 HID_ITEM_TAGTYPE_USAGE => Some(Data::Usage { data }),
91 HID_ITEM_TAGTYPE_INPUT => Some(Data::Input),
92 HID_ITEM_TAGTYPE_OUTPUT => Some(Data::Output),
93 HID_ITEM_TAGTYPE_REPORT_COUNT => Some(Data::ReportCount { data }),
94 _ => None,
95 }
96 }
97 }
98
99 impl Iterator for ReportDescriptorIterator {
100 type Item = Data;
101
102 fn next(&mut self) -> Option<Self::Item> {
103 if self.pos >= self.desc.value.len() {
104 return None;
105 }
106
107 self.next_item().or_else(|| self.next())
108 }
109 }
110
111 fn get_hid_item<'a>(buf: &'a [u8]) -> Option<(u8, usize, &'a [u8])> {
112 if (buf[0] & HID_MASK_LONG_ITEM_TAG) == HID_MASK_LONG_ITEM_TAG {
113 get_hid_long_item(buf)
114 } else {
115 get_hid_short_item(buf)
116 }
117 }
118
119 fn get_hid_long_item<'a>(buf: &'a [u8]) -> Option<(u8, usize, &'a [u8])> {
120 // A valid long item has at least three bytes.
121 if buf.len() < 3 {
122 return None;
123 }
124
125 let len = buf[1] as usize;
126
127 // Ensure that there are enough bytes left in the buffer.
128 if len > buf.len() - 3 {
129 return None;
130 }
131
132 Some((buf[2], 3 /* key length */, &buf[3..]))
133 }
134
135 fn get_hid_short_item<'a>(buf: &'a [u8]) -> Option<(u8, usize, &'a [u8])> {
136 // This is a short item. The bottom two bits of the key
137 // contain the length of the data section (value) for this key.
138 let len = match buf[0] & HID_MASK_SHORT_ITEM_SIZE {
139 s @ 0..=2 => s as usize,
140 _ => 4, /* _ == 3 */
141 };
142
143 // Ensure that there are enough bytes left in the buffer.
144 if len > buf.len() - 1 {
145 return None;
146 }
147
148 Some((
149 buf[0] & HID_MASK_ITEM_TAGTYPE,
150 1, /* key length */
151 &buf[1..=len],
152 ))
153 }
154
155 fn read_uint_le(buf: &[u8]) -> u32 {
156 assert!(buf.len() <= 4);
157 // Parse the number in little endian byte order.
158 buf.iter()
159 .rev()
160 .fold(0, |num, b| (num << 8) | (u32::from(*b)))
161 }
162
163 pub fn has_fido_usage(desc: ReportDescriptor) -> bool {
164 let mut usage_page = None;
165 let mut usage = None;
166
167 for data in desc.iter() {
168 match data {
169 Data::UsagePage { data } => usage_page = Some(data),
170 Data::Usage { data } => usage = Some(data),
171 _ => {}
172 }
173
174 // Check the values we found.
175 if let (Some(usage_page), Some(usage)) = (usage_page, usage) {
176 return usage_page == u32::from(FIDO_USAGE_PAGE)
177 && usage == u32::from(FIDO_USAGE_U2FHID);
178 }
179 }
180
181 false
182 }
183
184 #[cfg(target_os = "linux")]
185 pub fn read_hid_rpt_sizes(desc: ReportDescriptor) -> io::Result<(usize, usize)> {
186 let mut in_rpt_count = None;
187 let mut out_rpt_count = None;
188 let mut last_rpt_count = None;
189
190 for data in desc.iter() {
191 match data {
192 Data::ReportCount { data } => {
193 if last_rpt_count.is_some() {
194 return Err(io::Error::new(
195 io::ErrorKind::InvalidInput,
196 "Duplicate HID_ReportCount",
197 ));
198 }
199 last_rpt_count = Some(data as usize);
200 }
201 Data::Input => {
202 if last_rpt_count.is_none() {
203 return Err(io::Error::new(
204 io::ErrorKind::InvalidInput,
205 "HID_Input should be preceded by HID_ReportCount",
206 ));
207 }
208 if in_rpt_count.is_some() {
209 return Err(io::Error::new(
210 io::ErrorKind::InvalidInput,
211 "Duplicate HID_ReportCount",
212 ));
213 }
214 in_rpt_count = last_rpt_count;
215 last_rpt_count = None
216 }
217 Data::Output => {
218 if last_rpt_count.is_none() {
219 return Err(io::Error::new(
220 io::ErrorKind::InvalidInput,
221 "HID_Output should be preceded by HID_ReportCount",
222 ));
223 }
224 if out_rpt_count.is_some() {
225 return Err(io::Error::new(
226 io::ErrorKind::InvalidInput,
227 "Duplicate HID_ReportCount",
228 ));
229 }
230 out_rpt_count = last_rpt_count;
231 last_rpt_count = None;
232 }
233 _ => {}
234 }
235 }
236
237 match (in_rpt_count, out_rpt_count) {
238 (Some(in_count), Some(out_count)) => {
239 if in_count > INIT_HEADER_SIZE
240 && in_count <= MAX_HID_RPT_SIZE
241 && out_count > INIT_HEADER_SIZE
242 && out_count <= MAX_HID_RPT_SIZE
243 {
244 Ok((in_count, out_count))
245 } else {
246 Err(io::Error::new(
247 io::ErrorKind::InvalidData,
248 "Report size is too small or too large",
249 ))
250 }
251 }
252 _ => Err(io::Error::new(
253 io::ErrorKind::InvalidData,
254 "Failed to extract report sizes from report descriptor",
255 )),
256 }
257 }