| 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, PublicKeyCredentialDescriptor, |
| 10 |
PublicKeyCredentialParameters, PublicKeyCredentialUserEntity, RelyingParty, |
| 11 |
ResidentKeyRequirement, Transport, UserVerificationRequirement, |
| 12 |
}, |
| 13 |
statecallback::StateCallback, |
| 14 |
Pin, StatusPinUv, StatusUpdate, |
| 15 |
}; |
| 16 |
use getopts::Options; |
| 17 |
use sha2::{Digest, Sha256}; |
| 18 |
use std::sync::mpsc::{channel, RecvError}; |
| 19 |
use std::{env, io, thread}; |
| 20 |
use std::io::Write; |
| 21 |
|
| 22 |
fn print_usage(program: &str, opts: Options) { |
| 23 |
println!("------------------------------------------------------------------------"); |
| 24 |
println!("This program registers 3x the same origin with different users and"); |
| 25 |
println!("requests 'discoverable credentials' for them."); |
| 26 |
println!("After that, we try to log in to that origin and list all credentials found."); |
| 27 |
println!("------------------------------------------------------------------------"); |
| 28 |
let brief = format!("Usage: {program} [options]"); |
| 29 |
print!("{}", opts.usage(&brief)); |
| 30 |
} |
| 31 |
|
| 32 |
fn ask_user_choice(choices: &[PublicKeyCredentialUserEntity]) -> Option<usize> { |
| 33 |
for (idx, op) in choices.iter().enumerate() { |
| 34 |
println!("({idx}) \"{}\"", op.name.as_ref().unwrap()); |
| 35 |
} |
| 36 |
println!("({}) Cancel", choices.len()); |
| 37 |
|
| 38 |
let mut input = String::new(); |
| 39 |
loop { |
| 40 |
input.clear(); |
| 41 |
print!("Your choice: "); |
| 42 |
io::stdout() |
| 43 |
.lock() |
| 44 |
.flush() |
| 45 |
.expect("Failed to flush stdout!"); |
| 46 |
io::stdin() |
| 47 |
.read_line(&mut input) |
| 48 |
.expect("error: unable to read user input"); |
| 49 |
if let Ok(idx) = input.trim().parse::<usize>() { |
| 50 |
if idx < choices.len() { |
| 51 |
// Add a newline in case of success for better separation of in/output |
| 52 |
println!(); |
| 53 |
return Some(idx); |
| 54 |
} else if idx == choices.len() { |
| 55 |
println!(); |
| 56 |
return None; |
| 57 |
} |
| 58 |
println!("invalid input"); |
| 59 |
} |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
fn register_user(manager: &mut AuthenticatorService, username: &str, timeout_ms: u64) { |
| 64 |
println!(); |
| 65 |
println!("*********************************************************************"); |
| 66 |
println!("Asking a security key to register now with user: {username}"); |
| 67 |
println!("*********************************************************************"); |
| 68 |
|
| 69 |
println!("Asking a security key to register now..."); |
| 70 |
let challenge_str = format!( |
| 71 |
"{}{}{}{}", |
| 72 |
r#"{"challenge": "1vQ9mxionq0ngCnjD-wTsv1zUSrGRtFqG2xP09SbZ70","#, |
| 73 |
r#" "version": "U2F_V2", "appId": "http://example.com", "username": ""#, |
| 74 |
username, |
| 75 |
r#""}"# |
| 76 |
); |
| 77 |
let chall_bytes = Sha256::digest(challenge_str.as_bytes()).into(); |
| 78 |
|
| 79 |
let (status_tx, status_rx) = channel::<StatusUpdate>(); |
| 80 |
thread::spawn(move || loop { |
| 81 |
match status_rx.recv() { |
| 82 |
Ok(StatusUpdate::InteractiveManagement(..)) => { |
| 83 |
panic!("STATUS: This can't happen when doing non-interactive usage"); |
| 84 |
} |
| 85 |
Ok(StatusUpdate::SelectDeviceNotice) => { |
| 86 |
println!("STATUS: Please select a device by touching one of them."); |
| 87 |
} |
| 88 |
Ok(StatusUpdate::PresenceRequired) => { |
| 89 |
println!("STATUS: waiting for user presence"); |
| 90 |
} |
| 91 |
Ok(StatusUpdate::PinUvError(StatusPinUv::PinRequired(sender))) => { |
| 92 |
let raw_pin = |
| 93 |
rpassword::prompt_password_stderr("Enter PIN: ").expect("Failed to read PIN"); |
| 94 |
sender.send(Pin::new(&raw_pin)).expect("Failed to send PIN"); |
| 95 |
continue; |
| 96 |
} |
| 97 |
Ok(StatusUpdate::PinUvError(StatusPinUv::InvalidPin(sender, attempts))) => { |
| 98 |
println!( |
| 99 |
"Wrong PIN! {}", |
| 100 |
attempts.map_or("Try again.".to_string(), |a| format!( |
| 101 |
"You have {a} attempts left." |
| 102 |
)) |
| 103 |
); |
| 104 |
let raw_pin = |
| 105 |
rpassword::prompt_password_stderr("Enter PIN: ").expect("Failed to read PIN"); |
| 106 |
sender.send(Pin::new(&raw_pin)).expect("Failed to send PIN"); |
| 107 |
continue; |
| 108 |
} |
| 109 |
Ok(StatusUpdate::PinUvError(StatusPinUv::PinAuthBlocked)) => { |
| 110 |
panic!("Too many failed attempts in one row. Your device has been temporarily blocked. Please unplug it and plug in again.") |
| 111 |
} |
| 112 |
Ok(StatusUpdate::PinUvError(StatusPinUv::PinBlocked)) => { |
| 113 |
panic!("Too many failed attempts. Your device has been blocked. Reset it.") |
| 114 |
} |
| 115 |
Ok(StatusUpdate::PinUvError(StatusPinUv::InvalidUv(attempts))) => { |
| 116 |
println!( |
| 117 |
"Wrong UV! {}", |
| 118 |
attempts.map_or("Try again.".to_string(), |a| format!( |
| 119 |
"You have {a} attempts left." |
| 120 |
)) |
| 121 |
); |
| 122 |
continue; |
| 123 |
} |
| 124 |
Ok(StatusUpdate::PinUvError(StatusPinUv::UvBlocked)) => { |
| 125 |
println!("Too many failed UV-attempts."); |
| 126 |
continue; |
| 127 |
} |
| 128 |
Ok(StatusUpdate::PinUvError(e)) => { |
| 129 |
panic!("Unexpected error: {:?}", e) |
| 130 |
} |
| 131 |
Ok(StatusUpdate::SelectResultNotice(_, _)) => { |
| 132 |
panic!("Unexpected select result notice") |
| 133 |
} |
| 134 |
Err(RecvError) => { |
| 135 |
println!("STATUS: end"); |
| 136 |
return; |
| 137 |
} |
| 138 |
} |
| 139 |
}); |
| 140 |
|
| 141 |
let user = PublicKeyCredentialUserEntity { |
| 142 |
id: username.as_bytes().to_vec(), |
| 143 |
name: Some(username.to_string()), |
| 144 |
display_name: None, |
| 145 |
}; |
| 146 |
let origin = "https://example.com".to_string(); |
| 147 |
let ctap_args = RegisterArgs { |
| 148 |
client_data_hash: chall_bytes, |
| 149 |
relying_party: RelyingParty { |
| 150 |
id: "example.com".to_string(), |
| 151 |
name: None, |
| 152 |
}, |
| 153 |
origin, |
| 154 |
user, |
| 155 |
pub_cred_params: vec![ |
| 156 |
PublicKeyCredentialParameters { |
| 157 |
alg: COSEAlgorithm::ES256, |
| 158 |
}, |
| 159 |
PublicKeyCredentialParameters { |
| 160 |
alg: COSEAlgorithm::RS256, |
| 161 |
}, |
| 162 |
], |
| 163 |
exclude_list: vec![PublicKeyCredentialDescriptor { |
| 164 |
id: vec![], |
| 165 |
transports: vec![Transport::USB, Transport::NFC], |
| 166 |
}], |
| 167 |
user_verification_req: UserVerificationRequirement::Required, |
| 168 |
resident_key_req: ResidentKeyRequirement::Required, |
| 169 |
extensions: AuthenticationExtensionsClientInputs { |
| 170 |
cred_props: Some(true), |
| 171 |
..Default::default() |
| 172 |
}, |
| 173 |
pin: None, |
| 174 |
use_ctap1_fallback: false, |
| 175 |
}; |
| 176 |
|
| 177 |
let attestation_object; |
| 178 |
loop { |
| 179 |
let (register_tx, register_rx) = channel(); |
| 180 |
let callback = StateCallback::new(Box::new(move |rv| { |
| 181 |
register_tx.send(rv).unwrap(); |
| 182 |
})); |
| 183 |
|
| 184 |
if let Err(e) = manager.register(timeout_ms, ctap_args, status_tx, callback) { |
| 185 |
panic!("Couldn't register: {:?}", e); |
| 186 |
}; |
| 187 |
|
| 188 |
let register_result = register_rx |
| 189 |
.recv() |
| 190 |
.expect("Problem receiving, unable to continue"); |
| 191 |
match register_result { |
| 192 |
Ok(a) => { |
| 193 |
println!("Ok!"); |
| 194 |
attestation_object = a; |
| 195 |
break; |
| 196 |
} |
| 197 |
Err(e) => panic!("Registration failed: {:?}", e), |
| 198 |
}; |
| 199 |
} |
| 200 |
|
| 201 |
println!("Register result: {:?}", &attestation_object); |
| 202 |
} |
| 203 |
|
| 204 |
fn main() { |
| 205 |
env_logger::init(); |
| 206 |
|
| 207 |
let args: Vec<String> = env::args().collect(); |
| 208 |
let program = args[0].clone(); |
| 209 |
|
| 210 |
let mut opts = Options::new(); |
| 211 |
opts.optflag("h", "help", "print this help menu").optopt( |
| 212 |
"t", |
| 213 |
"timeout", |
| 214 |
"timeout in seconds", |
| 215 |
"SEC", |
| 216 |
); |
| 217 |
opts.optflag( |
| 218 |
"s", |
| 219 |
"skip_reg", |
| 220 |
"Skip registration"); |
| 221 |
|
| 222 |
opts.optflag("h", "help", "print this help menu"); |
| 223 |
let matches = match opts.parse(&args[1..]) { |
| 224 |
Ok(m) => m, |
| 225 |
Err(f) => panic!("{}", f.to_string()), |
| 226 |
}; |
| 227 |
if matches.opt_present("help") { |
| 228 |
print_usage(&program, opts); |
| 229 |
return; |
| 230 |
} |
| 231 |
|
| 232 |
let mut manager = |
| 233 |
AuthenticatorService::new().expect("The auth service should initialize safely"); |
| 234 |
manager.add_u2f_usb_hid_platform_transports(); |
| 235 |
|
| 236 |
let timeout_ms = match matches.opt_get_default::<u64>("timeout", 15) { |
| 237 |
Ok(timeout_s) => { |
| 238 |
println!("Using {}s as the timeout", &timeout_s); |
| 239 |
timeout_s * 1_000 |
| 240 |
} |
| 241 |
Err(e) => { |
| 242 |
println!("{e}"); |
| 243 |
print_usage(&program, opts); |
| 244 |
return; |
| 245 |
} |
| 246 |
}; |
| 247 |
|
| 248 |
if !matches.opt_present("skip_reg") { |
| 249 |
for username in &["A. User", "A. Nother", "Dr. Who"] { |
| 250 |
register_user(&mut manager, username, timeout_ms) |
| 251 |
} |
| 252 |
} |
| 253 |
|
| 254 |
println!(); |
| 255 |
println!("*********************************************************************"); |
| 256 |
println!("Asking a security key to sign now, with the data from the register..."); |
| 257 |
println!("*********************************************************************"); |
| 258 |
|
| 259 |
// Discovering creds: |
| 260 |
let allow_list = Vec::new(); |
| 261 |
let origin = "https://example.com".to_string(); |
| 262 |
let challenge_str = format!( |
| 263 |
"{}{}", |
| 264 |
r#"{"challenge": "1vQ9mxionq0ngCnjD-wTsv1zUSrGRtFqG2xP09SbZ70","#, |
| 265 |
r#" "version": "U2F_V2", "appId": "http://example.com" "#, |
| 266 |
); |
| 267 |
|
| 268 |
let (status_tx, status_rx) = channel::<StatusUpdate>(); |
| 269 |
thread::spawn(move || loop { |
| 270 |
match status_rx.recv() { |
| 271 |
Ok(StatusUpdate::InteractiveManagement(..)) => { |
| 272 |
panic!("STATUS: This can't happen when doing non-interactive usage"); |
| 273 |
} |
| 274 |
Ok(StatusUpdate::SelectDeviceNotice) => { |
| 275 |
println!("STATUS: Please select a device by touching one of them."); |
| 276 |
} |
| 277 |
Ok(StatusUpdate::PresenceRequired) => { |
| 278 |
println!("STATUS: waiting for user presence"); |
| 279 |
} |
| 280 |
Ok(StatusUpdate::PinUvError(StatusPinUv::PinRequired(sender))) => { |
| 281 |
let raw_pin = |
| 282 |
rpassword::prompt_password_stderr("Enter PIN: ").expect("Failed to read PIN"); |
| 283 |
sender.send(Pin::new(&raw_pin)).expect("Failed to send PIN"); |
| 284 |
continue; |
| 285 |
} |
| 286 |
Ok(StatusUpdate::PinUvError(StatusPinUv::InvalidPin(sender, attempts))) => { |
| 287 |
println!( |
| 288 |
"Wrong PIN! {}", |
| 289 |
attempts.map_or("Try again.".to_string(), |a| format!( |
| 290 |
"You have {a} attempts left." |
| 291 |
)) |
| 292 |
); |
| 293 |
let raw_pin = |
| 294 |
rpassword::prompt_password_stderr("Enter PIN: ").expect("Failed to read PIN"); |
| 295 |
sender.send(Pin::new(&raw_pin)).expect("Failed to send PIN"); |
| 296 |
continue; |
| 297 |
} |
| 298 |
Ok(StatusUpdate::PinUvError(StatusPinUv::PinAuthBlocked)) => { |
| 299 |
panic!("Too many failed attempts in one row. Your device has been temporarily blocked. Please unplug it and plug in again.") |
| 300 |
} |
| 301 |
Ok(StatusUpdate::PinUvError(StatusPinUv::PinBlocked)) => { |
| 302 |
panic!("Too many failed attempts. Your device has been blocked. Reset it.") |
| 303 |
} |
| 304 |
Ok(StatusUpdate::PinUvError(StatusPinUv::InvalidUv(attempts))) => { |
| 305 |
println!( |
| 306 |
"Wrong UV! {}", |
| 307 |
attempts.map_or("Try again.".to_string(), |a| format!( |
| 308 |
"You have {a} attempts left." |
| 309 |
)) |
| 310 |
); |
| 311 |
continue; |
| 312 |
} |
| 313 |
Ok(StatusUpdate::PinUvError(StatusPinUv::UvBlocked)) => { |
| 314 |
println!("Too many failed UV-attempts."); |
| 315 |
continue; |
| 316 |
} |
| 317 |
Ok(StatusUpdate::PinUvError(e)) => { |
| 318 |
panic!("Unexpected error: {:?}", e) |
| 319 |
} |
| 320 |
Ok(StatusUpdate::SelectResultNotice(index_sender, users)) => { |
| 321 |
println!("Multiple signatures returned. Select one or cancel."); |
| 322 |
let idx = ask_user_choice(&users); |
| 323 |
index_sender.send(idx).expect("Failed to send choice"); |
| 324 |
} |
| 325 |
Err(RecvError) => { |
| 326 |
println!("STATUS: end"); |
| 327 |
return; |
| 328 |
} |
| 329 |
} |
| 330 |
}); |
| 331 |
|
| 332 |
let chall_bytes = Sha256::digest(challenge_str.as_bytes()).into(); |
| 333 |
let ctap_args = SignArgs { |
| 334 |
client_data_hash: chall_bytes, |
| 335 |
origin, |
| 336 |
relying_party_id: "example.com".to_string(), |
| 337 |
allow_list, |
| 338 |
user_verification_req: UserVerificationRequirement::Required, |
| 339 |
user_presence_req: true, |
| 340 |
extensions: Default::default(), |
| 341 |
pin: None, |
| 342 |
use_ctap1_fallback: false, |
| 343 |
}; |
| 344 |
|
| 345 |
loop { |
| 346 |
let (sign_tx, sign_rx) = channel(); |
| 347 |
|
| 348 |
let callback = StateCallback::new(Box::new(move |rv| { |
| 349 |
sign_tx.send(rv).unwrap(); |
| 350 |
})); |
| 351 |
|
| 352 |
if let Err(e) = manager.sign(timeout_ms, ctap_args, status_tx, callback) { |
| 353 |
panic!("Couldn't sign: {:?}", e); |
| 354 |
} |
| 355 |
|
| 356 |
let sign_result = sign_rx |
| 357 |
.recv() |
| 358 |
.expect("Problem receiving, unable to continue"); |
| 359 |
|
| 360 |
match sign_result { |
| 361 |
Ok(assertion_object) => { |
| 362 |
println!("Assertion Object: {assertion_object:?}"); |
| 363 |
println!("-----------------------------------------------------------------"); |
| 364 |
println!("Found credentials:"); |
| 365 |
println!( |
| 366 |
"{:?}", |
| 367 |
assertion_object.assertion.user.clone().unwrap().name.unwrap() // Unwrapping here, as these shouldn't fail |
| 368 |
); |
| 369 |
println!("-----------------------------------------------------------------"); |
| 370 |
println!("Done."); |
| 371 |
break; |
| 372 |
} |
| 373 |
Err(e) => panic!("Signing failed: {:?}", e), |
| 374 |
} |
| 375 |
} |
| 376 |
} |