Debian Codegraph @

third_party/rust/authenticator/examples/reset.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 authenticator::{
6 authenticatorservice::AuthenticatorService,
7 ctap2::commands::StatusCode,
8 errors::{AuthenticatorError, CommandError, HIDError},
9 statecallback::StateCallback,
10 StatusUpdate,
11 };
12 use getopts::Options;
13 use std::env;
14 use std::sync::mpsc::{channel, RecvError};
15
16 fn print_usage(program: &str, opts: Options) {
17 let brief = format!("Usage: {program} [options]");
18 print!("{}", opts.usage(&brief));
19 }
20
21 fn main() {
22 env_logger::init();
23
24 let args: Vec<String> = env::args().collect();
25 let program = args[0].clone();
26
27 let mut opts = Options::new();
28 opts.optflag("h", "help", "print this help menu").optopt(
29 "t",
30 "timeout",
31 "timeout in seconds",
32 "SEC",
33 );
34 opts.optflag("h", "help", "print this help menu");
35 let matches = match opts.parse(&args[1..]) {
36 Ok(m) => m,
37 Err(f) => panic!("{}", f.to_string()),
38 };
39 if matches.opt_present("help") {
40 print_usage(&program, opts);
41 return;
42 }
43
44 let mut manager =
45 AuthenticatorService::new().expect("The auth service should initialize safely");
46 manager.add_u2f_usb_hid_platform_transports();
47
48 let timeout_ms = match matches.opt_get_default::<u64>("timeout", 25) {
49 Ok(timeout_s) => {
50 println!("Using {}s as the timeout", &timeout_s);
51 timeout_s * 1_000
52 }
53 Err(e) => {
54 println!("{e}");
55 print_usage(&program, opts);
56 return;
57 }
58 };
59
60 println!(
61 "NOTE: Please unplug all devices, type in 'yes' and plug in the device that should be reset."
62 );
63 loop {
64 let mut s = String::new();
65 println!("ATTENTION: Resetting a device will wipe all credentials! Do you wish to continue? [yes/N]");
66 std::io::stdin()
67 .read_line(&mut s)
68 .expect("Did not enter a correct string");
69 let trimmed = s.trim();
70 if trimmed.is_empty() || trimmed == "N" || trimmed == "n" {
71 println!("Exiting without reset.");
72 return;
73 }
74 if trimmed == "y" {
75 println!("Please type in the whole word 'yes'");
76 continue;
77 }
78 if trimmed == "yes" {
79 break;
80 }
81 }
82
83 let (status_tx, status_rx) = channel::<StatusUpdate>();
84 let (reset_tx, reset_rx) = channel();
85 let rs_tx = reset_tx;
86 let callback = StateCallback::new(Box::new(move |rv| {
87 let _ = rs_tx.send(rv);
88 }));
89
90 if let Err(e) = manager.reset(timeout_ms, status_tx, callback) {
91 panic!("Couldn't register: {:?}", e);
92 };
93
94 loop {
95 match status_rx.recv() {
96 Ok(StatusUpdate::SelectDeviceNotice) => {
97 println!("ERROR: Please unplug all other tokens that should not be reset!");
98 // Needed to give the tokens enough time to start blinking
99 // otherwise we may cancel pre-maturely and this binary will hang
100 std::thread::sleep(std::time::Duration::from_millis(200));
101 manager.cancel().unwrap();
102 return;
103 }
104 Ok(StatusUpdate::PresenceRequired) => {
105 println!("STATUS: waiting for user presence");
106 break;
107 }
108 Ok(StatusUpdate::PinUvError(..)) => panic!("Reset should never ask for a PIN!"),
109 Ok(_) => { /* Ignore all other updates */ }
110 Err(RecvError) => {
111 println!("RecvError");
112 return;
113 }
114 }
115 }
116
117 let reset_result = reset_rx
118 .recv()
119 .expect("Problem receiving, unable to continue");
120 match reset_result {
121 Ok(()) => {
122 println!("Token successfully reset!");
123 }
124 Err(AuthenticatorError::HIDError(HIDError::Command(CommandError::StatusCode(
125 StatusCode::NotAllowed,
126 _,
127 )))) => {
128 println!("Resetting is only allowed within the first 10 seconds after powering up.");
129 println!("Please unplug your device, plug it back in and try again.");
130 }
131 Err(e) => panic!("Reset failed: {:?}", e),
132 };
133 }