Debian Codegraph @

third_party/rust/authenticator/examples/ctap2.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, RegisterArgs, SignArgs},
7 crypto::COSEAlgorithm,
8 ctap2::server::{
9 AuthenticationExtensionsClientInputs, CredentialProtectionPolicy,
10 PublicKeyCredentialDescriptor, PublicKeyCredentialParameters,
11 PublicKeyCredentialUserEntity, RelyingParty, ResidentKeyRequirement, Transport,
12 UserVerificationRequirement,
13 },
14 statecallback::StateCallback,
15 Pin, StatusPinUv, StatusUpdate,
16 };
17 use getopts::Options;
18 use rand::{thread_rng, RngCore};
19 use std::sync::mpsc::{channel, RecvError};
20 use std::{env, thread};
21
22 fn print_usage(program: &str, opts: Options) {
23 let brief = format!("Usage: {program} [options]");
24 print!("{}", opts.usage(&brief));
25 }
26
27 fn main() {
28 env_logger::init();
29
30 let args: Vec<String> = env::args().collect();
31 let program = args[0].clone();
32
33 let rp_id = "example.com".to_string();
34 let app_id = "https://fido.example.com/myApp".to_string();
35
36 let mut opts = Options::new();
37 opts.optflag("h", "help", "print this help menu").optopt(
38 "t",
39 "timeout",
40 "timeout in seconds",
41 "SEC",
42 );
43 opts.optflag(
44 "a",
45 "app_id",
46 &format!("Using App ID {app_id} from origin 'https://{rp_id}'"),
47 );
48 opts.optflag("s", "hmac_secret", "With hmac-secret");
49 opts.optflag("h", "help", "print this help menu");
50 opts.optflag("f", "fallback", "Use CTAP1 fallback implementation");
51 let matches = match opts.parse(&args[1..]) {
52 Ok(m) => m,
53 Err(f) => panic!("{}", f.to_string()),
54 };
55 if matches.opt_present("help") {
56 print_usage(&program, opts);
57 return;
58 }
59
60 let using_app_id = matches.opt_present("app_id");
61
62 let mut manager =
63 AuthenticatorService::new().expect("The auth service should initialize safely");
64 manager.add_u2f_usb_hid_platform_transports();
65
66 let fallback = matches.opt_present("fallback");
67
68 let timeout_ms = match matches.opt_get_default::<u64>("timeout", 25) {
69 Ok(timeout_s) => {
70 println!("Using {}s as the timeout", &timeout_s);
71 timeout_s * 1_000
72 }
73 Err(e) => {
74 println!("{e}");
75 print_usage(&program, opts);
76 return;
77 }
78 };
79
80 println!("Asking a security key to register now...");
81 let mut chall_bytes = [0u8; 32];
82 thread_rng().fill_bytes(&mut chall_bytes);
83
84 let (status_tx, status_rx) = channel::<StatusUpdate>();
85 thread::spawn(move || loop {
86 match status_rx.recv() {
87 Ok(StatusUpdate::InteractiveManagement(..)) => {
88 panic!("STATUS: This can't happen when doing non-interactive usage");
89 }
90 Ok(StatusUpdate::SelectDeviceNotice) => {
91 println!("STATUS: Please select a device by touching one of them.");
92 }
93 Ok(StatusUpdate::PresenceRequired) => {
94 println!("STATUS: waiting for user presence");
95 }
96 Ok(StatusUpdate::PinUvError(StatusPinUv::PinRequired(sender))) => {
97 let raw_pin =
98 rpassword::prompt_password_stderr("Enter PIN: ").expect("Failed to read PIN");
99 sender.send(Pin::new(&raw_pin)).expect("Failed to send PIN");
100 continue;
101 }
102 Ok(StatusUpdate::PinUvError(StatusPinUv::InvalidPin(sender, attempts))) => {
103 println!(
104 "Wrong PIN! {}",
105 attempts.map_or("Try again.".to_string(), |a| format!(
106 "You have {a} attempts left."
107 ))
108 );
109 let raw_pin =
110 rpassword::prompt_password_stderr("Enter PIN: ").expect("Failed to read PIN");
111 sender.send(Pin::new(&raw_pin)).expect("Failed to send PIN");
112 continue;
113 }
114 Ok(StatusUpdate::PinUvError(StatusPinUv::PinAuthBlocked)) => {
115 panic!("Too many failed attempts in one row. Your device has been temporarily blocked. Please unplug it and plug in again.")
116 }
117 Ok(StatusUpdate::PinUvError(StatusPinUv::PinBlocked)) => {
118 panic!("Too many failed attempts. Your device has been blocked. Reset it.")
119 }
120 Ok(StatusUpdate::PinUvError(StatusPinUv::InvalidUv(attempts))) => {
121 println!(
122 "Wrong UV! {}",
123 attempts.map_or("Try again.".to_string(), |a| format!(
124 "You have {a} attempts left."
125 ))
126 );
127 continue;
128 }
129 Ok(StatusUpdate::PinUvError(StatusPinUv::UvBlocked)) => {
130 println!("Too many failed UV-attempts.");
131 continue;
132 }
133 Ok(StatusUpdate::PinUvError(e)) => {
134 panic!("Unexpected error: {:?}", e)
135 }
136 Ok(StatusUpdate::SelectResultNotice(_, _)) => {
137 panic!("Unexpected select device notice")
138 }
139 Err(RecvError) => {
140 println!("STATUS: end");
141 return;
142 }
143 }
144 });
145
146 let user = PublicKeyCredentialUserEntity {
147 id: "user_id".as_bytes().to_vec(),
148 name: Some("A. User".to_string()),
149 display_name: None,
150 };
151 // If we're testing AppID support, then register with an RP ID that isn't valid for the origin.
152 let relying_party = RelyingParty {
153 id: if using_app_id {
154 app_id.clone()
155 } else {
156 rp_id.clone()
157 },
158 name: None,
159 };
160 let ctap_args = RegisterArgs {
161 client_data_hash: chall_bytes,
162 relying_party,
163 origin: format!("https://{rp_id}"),
164 user,
165 pub_cred_params: vec![
166 PublicKeyCredentialParameters {
167 alg: COSEAlgorithm::ES256,
168 },
169 PublicKeyCredentialParameters {
170 alg: COSEAlgorithm::RS256,
171 },
172 ],
173 exclude_list: vec![PublicKeyCredentialDescriptor {
174 id: vec![
175 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
176 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b,
177 0x1c, 0x1d, 0x1e, 0x1f,
178 ],
179 transports: vec![Transport::USB, Transport::NFC],
180 }],
181 user_verification_req: UserVerificationRequirement::Preferred,
182 resident_key_req: ResidentKeyRequirement::Discouraged,
183 extensions: AuthenticationExtensionsClientInputs {
184 cred_props: Some(true),
185 hmac_create_secret: Some(matches.opt_present("hmac_secret")),
186 min_pin_length: Some(true),
187 credential_protection_policy: Some(
188 CredentialProtectionPolicy::UserVerificationOptionalWithCredentialIDList,
189 ),
190 ..Default::default()
191 },
192 pin: None,
193 use_ctap1_fallback: fallback,
194 };
195
196 let attestation_object;
197 loop {
198 let (register_tx, register_rx) = channel();
199 let callback = StateCallback::new(Box::new(move |rv| {
200 register_tx.send(rv).unwrap();
201 }));
202
203 if let Err(e) = manager.register(timeout_ms, ctap_args, status_tx.clone(), callback) {
204 panic!("Couldn't register: {:?}", e);
205 };
206
207 let register_result = register_rx
208 .recv()
209 .expect("Problem receiving, unable to continue");
210 match register_result {
211 Ok(a) => {
212 println!("Ok!");
213 attestation_object = a;
214 break;
215 }
216 Err(e) => panic!("Registration failed: {:?}", e),
217 };
218 }
219
220 println!("Register result: {:?}", &attestation_object);
221
222 println!();
223 println!("*********************************************************************");
224 println!("Asking a security key to sign now, with the data from the register...");
225 println!("*********************************************************************");
226
227 let allow_list;
228 if let Some(cred_data) = attestation_object.att_obj.auth_data.credential_data {
229 allow_list = vec![PublicKeyCredentialDescriptor {
230 id: cred_data.credential_id,
231 transports: vec![Transport::USB],
232 }];
233 } else {
234 allow_list = Vec::new();
235 }
236
237 let ctap_args = SignArgs {
238 client_data_hash: chall_bytes,
239 origin: format!("https://{rp_id}"),
240 relying_party_id: rp_id,
241 allow_list,
242 user_verification_req: UserVerificationRequirement::Preferred,
243 user_presence_req: true,
244 extensions: AuthenticationExtensionsClientInputs {
245 app_id: using_app_id.then(|| app_id.clone()),
246 ..Default::default()
247 },
248 pin: None,
249 use_ctap1_fallback: fallback,
250 };
251
252 loop {
253 let (sign_tx, sign_rx) = channel();
254
255 let callback = StateCallback::new(Box::new(move |rv| {
256 sign_tx.send(rv).unwrap();
257 }));
258
259 if let Err(e) = manager.sign(timeout_ms, ctap_args, status_tx, callback) {
260 panic!("Couldn't sign: {:?}", e);
261 }
262
263 let sign_result = sign_rx
264 .recv()
265 .expect("Problem receiving, unable to continue");
266
267 match sign_result {
268 Ok(assertion_object) => {
269 println!("Assertion Object: {assertion_object:?}");
270 if using_app_id {
271 println!(
272 "Used AppID: {}",
273 assertion_object
274 .extensions
275 .app_id
276 .expect("app id extension should be set")
277 );
278 }
279 println!("Done.");
280 break;
281 }
282 Err(e) => panic!("Signing failed: {:?}", e),
283 }
284 }
285 }