Debian Codegraph @

third_party/rust/authenticator/src/statemachine.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 use crate::authenticatorservice::{RegisterArgs, SignArgs};
6
7 use crate::ctap2;
8
9 use crate::ctap2::commands::client_pin::Pin;
10
11 use crate::errors::AuthenticatorError;
12 use crate::statecallback::StateCallback;
13 use crate::status_update::{send_status, InteractiveUpdate};
14 use crate::transport::device_selector::{
15 BlinkResult, Device, DeviceBuildParameters, DeviceCommand, DeviceSelectorEvent,
16 };
17 use crate::transport::platform::transaction::Transaction;
18 use crate::transport::{hid::HIDDevice, FidoDevice, FidoProtocol};
19 use crate::{InteractiveRequest, ManageResult};
20 use std::sync::mpsc::{channel, RecvTimeoutError, Sender};
21
22 use std::time::Duration;
23
24 #[derive(Default)]
25 pub struct StateMachine {
26 transaction: Option<Transaction>,
27 }
28
29 impl StateMachine {
30 pub fn new() -> Self {
31 Default::default()
32 }
33
34 fn init_device(
35 info: DeviceBuildParameters,
36 selector: &Sender<DeviceSelectorEvent>,
37 ) -> Option<Device> {
38 // Create a new device.
39 let mut dev = match Device::new(info) {
40 Ok(dev) => dev,
41 Err((e, id)) => {
42 info!("error happened with device: {}", e);
43 let _ = selector.send(DeviceSelectorEvent::NotAToken(id));
44 return None;
45 }
46 };
47
48 // Try initializing it.
49 if let Err(e) = dev.init() {
50 warn!("error while initializing device: {}", e);
51 let _ = selector.send(DeviceSelectorEvent::NotAToken(dev.id()));
52 return None;
53 }
54
55 Some(dev)
56 }
57
58 fn wait_for_device_selector(
59 dev: &mut Device,
60 selector: &Sender<DeviceSelectorEvent>,
61 status: &Sender<crate::StatusUpdate>,
62 keep_alive: &dyn Fn() -> bool,
63 ) -> bool {
64 let (tx, rx) = channel();
65 if selector
66 .send(DeviceSelectorEvent::ImAToken((dev.id(), tx)))
67 .is_err()
68 {
69 // If we fail to register with the device selector, then we're not going
70 // to be selected.
71 return false;
72 }
73
74 // We can be cancelled from the user (through keep_alive()) or from the device selector
75 // (through a DeviceCommand::Cancel on rx). We'll combine those signals into a single
76 // predicate to pass to Device::block_and_blink.
77 let keep_blinking = || keep_alive() && !matches!(rx.try_recv(), Ok(DeviceCommand::Cancel));
78
79 // Blocking recv. DeviceSelector will tell us what to do
80 match rx.recv() {
81 Ok(DeviceCommand::Blink) => {
82 // The caller wants the user to choose a device. Send a status update and blink
83 // this device. NOTE: We send one status update per device, so the recipient should be
84 // prepared to receive the message multiple times.
85 send_status(status, crate::StatusUpdate::SelectDeviceNotice);
86 match dev.block_and_blink(&keep_blinking) {
87 BlinkResult::DeviceSelected => {
88 // User selected us. Let DeviceSelector know, so it can cancel all other
89 // outstanding open blink-requests. If we fail to send the SelectedToken
90 // message to the device selector, then don't consider this token as having
91 // been selected.
92 selector
93 .send(DeviceSelectorEvent::SelectedToken(dev.id()))
94 .is_ok()
95 }
96 BlinkResult::Cancelled => {
97 info!("Device {:?} was not selected", dev.id());
98 false
99 }
100 }
101 }
102 Ok(DeviceCommand::Cancel) => {
103 info!("Device {:?} was not selected", dev.id());
104 false
105 }
106 Ok(DeviceCommand::Removed) => {
107 info!("Device {:?} was removed", dev.id());
108 false
109 }
110 Ok(DeviceCommand::Continue) => true,
111 Err(_) => {
112 warn!("Error when trying to receive messages from DeviceSelector! Exiting.");
113 false
114 }
115 }
116 }
117
118 pub fn register(
119 &mut self,
120 timeout: u64,
121 args: RegisterArgs,
122 status: Sender<crate::StatusUpdate>,
123 callback: StateCallback<crate::Result<crate::RegisterResult>>,
124 ) {
125 // Abort any prior register/sign calls.
126 self.cancel();
127 let cbc = callback.clone();
128 let transaction = Transaction::new(
129 timeout,
130 cbc.clone(),
131 status,
132 move |info, selector, status, alive| {
133 let mut dev = match Self::init_device(info, &selector) {
134 Some(dev) => dev,
135 None => return,
136 };
137 if !Self::wait_for_device_selector(&mut dev, &selector, &status, alive) {
138 return;
139 };
140
141 if args.use_ctap1_fallback {
142 dev.downgrade_to_ctap1();
143 }
144
145 info!("Device {:?} continues with the register process", dev.id());
146 if ctap2::register(&mut dev, args.clone(), status, callback.clone(), alive) {
147 // ctap2::register returns true if it called the callback with Ok(..). Cancel
148 // all other tokens in case we skipped the "blinking"-action and went straight
149 // for the actual request.
150 let _ = selector.send(DeviceSelectorEvent::SelectedToken(dev.id()));
151 }
152 },
153 );
154
155 self.transaction = Some(try_or!(transaction, |e| cbc.call(Err(e))));
156 }
157
158 pub fn sign(
159 &mut self,
160 timeout: u64,
161 args: SignArgs,
162 status: Sender<crate::StatusUpdate>,
163 callback: StateCallback<crate::Result<crate::SignResult>>,
164 ) {
165 // Abort any prior register/sign calls.
166 self.cancel();
167 let cbc = callback.clone();
168
169 let transaction = Transaction::new(
170 timeout,
171 callback.clone(),
172 status,
173 move |info, selector, status, alive| {
174 let mut dev = match Self::init_device(info, &selector) {
175 Some(dev) => dev,
176 None => return,
177 };
178 if !Self::wait_for_device_selector(&mut dev, &selector, &status, alive) {
179 return;
180 };
181
182 if args.use_ctap1_fallback {
183 dev.downgrade_to_ctap1();
184 }
185
186 info!("Device {:?} continues with the signing process", dev.id());
187 if ctap2::sign(&mut dev, args.clone(), status, callback.clone(), alive) {
188 // ctap2::sign returns true if it called the callback with Ok(..). Cancel all
189 // other tokens in case we skipped the "blinking"-action and went straight for
190 // the actual request.
191 let _ = selector.send(DeviceSelectorEvent::SelectedToken(dev.id()));
192 }
193 },
194 );
195
196 self.transaction = Some(try_or!(transaction, move |e| cbc.call(Err(e))));
197 }
198
199 // This blocks.
200 pub fn cancel(&mut self) {
201 if let Some(mut transaction) = self.transaction.take() {
202 info!("Statemachine was cancelled. Cancelling transaction now.");
203 transaction.cancel();
204 }
205 }
206
207 pub fn reset(
208 &mut self,
209 timeout: u64,
210 status: Sender<crate::StatusUpdate>,
211 callback: StateCallback<crate::Result<crate::ResetResult>>,
212 ) {
213 // Abort any prior register/sign calls.
214 self.cancel();
215 let cbc = callback.clone();
216
217 let transaction = Transaction::new(
218 timeout,
219 callback.clone(),
220 status,
221 move |info, selector, status, alive| {
222 let mut dev = match Self::init_device(info, &selector) {
223 Some(dev) => dev,
224 None => return,
225 };
226
227 if dev.get_protocol() != FidoProtocol::CTAP2 {
228 info!("Device does not support CTAP2");
229 let _ = selector.send(DeviceSelectorEvent::NotAToken(dev.id()));
230 return;
231 }
232
233 if !Self::wait_for_device_selector(&mut dev, &selector, &status, alive) {
234 return;
235 };
236 ctap2::reset_helper(&mut dev, selector, status, callback.clone(), alive);
237 },
238 );
239
240 self.transaction = Some(try_or!(transaction, move |e| cbc.call(Err(e))));
241 }
242
243 pub fn set_pin(
244 &mut self,
245 timeout: u64,
246 new_pin: Pin,
247 status: Sender<crate::StatusUpdate>,
248 callback: StateCallback<crate::Result<crate::ResetResult>>,
249 ) {
250 // Abort any prior register/sign calls.
251 self.cancel();
252
253 let cbc = callback.clone();
254
255 let transaction = Transaction::new(
256 timeout,
257 callback.clone(),
258 status,
259 move |info, selector, status, alive| {
260 let mut dev = match Self::init_device(info, &selector) {
261 Some(dev) => dev,
262 None => return,
263 };
264
265 if dev.get_protocol() != FidoProtocol::CTAP2 {
266 info!("Device does not support CTAP2");
267 let _ = selector.send(DeviceSelectorEvent::NotAToken(dev.id()));
268 return;
269 }
270
271 if !Self::wait_for_device_selector(&mut dev, &selector, &status, alive) {
272 return;
273 };
274
275 ctap2::set_or_change_pin_helper(
276 &mut dev,
277 None,
278 new_pin.clone(),
279 status,
280 callback.clone(),
281 alive,
282 );
283 },
284 );
285 self.transaction = Some(try_or!(transaction, move |e| cbc.call(Err(e))));
286 }
287
288 // Function to interactively manage a specific token.
289 // Difference to register/sign: These want to do something and don't care
290 // with which token they do it.
291 // This function wants to manipulate a specific token. For this, we first
292 // have to select one and then do something with it, based on what it
293 // supports (Set PIN, Change PIN, Reset, etc.).
294 // Hence, we first go through the discovery-phase, then provide the user
295 // with the AuthenticatorInfo and then let them interactively decide what to do
296 pub fn manage(
297 &mut self,
298 timeout: u64,
299 status: Sender<crate::StatusUpdate>,
300 callback: StateCallback<crate::Result<crate::ManageResult>>,
301 ) {
302 // Abort any prior register/sign calls.
303 self.cancel();
304 let cbc = callback.clone();
305
306 let transaction = Transaction::new(
307 timeout,
308 callback.clone(),
309 status,
310 move |info, selector, status, alive| {
311 let mut dev = match Self::init_device(info, &selector) {
312 Some(dev) => dev,
313 None => return,
314 };
315
316 if dev.get_protocol() != FidoProtocol::CTAP2 {
317 info!("Device does not support CTAP2");
318 let _ = selector.send(DeviceSelectorEvent::NotAToken(dev.id()));
319 return;
320 }
321
322 if !Self::wait_for_device_selector(&mut dev, &selector, &status, alive) {
323 return;
324 };
325
326 info!("Device {:?} selected for interactive management.", dev.id());
327
328 // Sending the user the info about the token
329 let (tx, rx) = channel();
330 send_status(
331 &status,
332 crate::StatusUpdate::InteractiveManagement(InteractiveUpdate::StartManagement(
333 (tx, dev.get_authenticator_info().cloned()),
334 )),
335 );
336 while alive() {
337 match rx.recv_timeout(Duration::from_millis(400)) {
338 Ok(InteractiveRequest::Quit) => {
339 callback.call(Ok(ManageResult::Success));
340 break;
341 }
342 Ok(InteractiveRequest::Reset) => {
343 ctap2::reset_helper(
344 &mut dev,
345 selector,
346 status,
347 callback.clone(),
348 alive,
349 );
350 }
351 Ok(InteractiveRequest::ChangePIN(curr_pin, new_pin)) => {
352 ctap2::set_or_change_pin_helper(
353 &mut dev,
354 Some(curr_pin),
355 new_pin,
356 status,
357 callback.clone(),
358 alive,
359 );
360 }
361 Ok(InteractiveRequest::SetPIN(pin)) => {
362 ctap2::set_or_change_pin_helper(
363 &mut dev,
364 None,
365 pin,
366 status,
367 callback.clone(),
368 alive,
369 );
370 }
371 Ok(InteractiveRequest::ChangeConfig(authcfg, puat)) => {
372 ctap2::configure_authenticator(
373 &mut dev,
374 puat,
375 authcfg,
376 status.clone(),
377 callback.clone(),
378 alive,
379 );
380 continue;
381 }
382 Ok(InteractiveRequest::CredentialManagement(cred_management, puat)) => {
383 ctap2::credential_management(
384 &mut dev,
385 puat,
386 cred_management,
387 status.clone(),
388 callback.clone(),
389 alive,
390 );
391 continue;
392 }
393 Ok(InteractiveRequest::BioEnrollment(bio_enrollment, puat)) => {
394 ctap2::bio_enrollment(
395 &mut dev,
396 puat,
397 bio_enrollment,
398 status.clone(),
399 callback.clone(),
400 alive,
401 );
402 continue;
403 }
404 Err(RecvTimeoutError::Timeout) => {
405 if !alive() {
406 // We got stopped at some point
407 callback.call(Err(AuthenticatorError::CancelledByUser));
408 break;
409 }
410 continue;
411 }
412 Err(RecvTimeoutError::Disconnected) => {
413 // recv() failed, because the other side is dropping the Sender.
414 info!(
415 "Callback dropped the channel, so we abort the interactive session"
416 );
417 callback.call(Err(AuthenticatorError::CancelledByUser));
418 }
419 }
420 break;
421 }
422 },
423 );
424
425 self.transaction = Some(try_or!(transaction, move |e| cbc.call(Err(e))));
426 }
427 }