| 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::commands::StatusCode, |
| 9 |
ctap2::server::{ |
| 10 |
PublicKeyCredentialDescriptor, PublicKeyCredentialParameters, |
| 11 |
PublicKeyCredentialUserEntity, RelyingParty, ResidentKeyRequirement, Transport, |
| 12 |
UserVerificationRequirement, |
| 13 |
}, |
| 14 |
errors::{AuthenticatorError, CommandError, HIDError, UnsupportedOption}, |
| 15 |
statecallback::StateCallback, |
| 16 |
Pin, StatusPinUv, StatusUpdate, |
| 17 |
}; |
| 18 |
|
| 19 |
use getopts::Options; |
| 20 |
use sha2::{Digest, Sha256}; |
| 21 |
use std::sync::mpsc::{channel, RecvError}; |
| 22 |
use std::{env, thread}; |
| 23 |
|
| 24 |
fn print_usage(program: &str, opts: Options) { |
| 25 |
let brief = format!("Usage: {program} [options]"); |
| 26 |
print!("{}", opts.usage(&brief)); |
| 27 |
} |
| 28 |
|
| 29 |
fn main() { |
| 30 |
env_logger::init(); |
| 31 |
|
| 32 |
let args: Vec<String> = env::args().collect(); |
| 33 |
let program = args[0].clone(); |
| 34 |
|
| 35 |
let mut opts = Options::new(); |
| 36 |
opts.optflag("h", "help", "print this help menu").optopt( |
| 37 |
"t", |
| 38 |
"timeout", |
| 39 |
"timeout in seconds", |
| 40 |
"SEC", |
| 41 |
); |
| 42 |
opts.optflag("h", "help", "print this help menu"); |
| 43 |
let matches = match opts.parse(&args[1..]) { |
| 44 |
Ok(m) => m, |
| 45 |
Err(f) => panic!("{}", f.to_string()), |
| 46 |
}; |
| 47 |
if matches.opt_present("help") { |
| 48 |
print_usage(&program, opts); |
| 49 |
return; |
| 50 |
} |
| 51 |
|
| 52 |
let mut manager = |
| 53 |
AuthenticatorService::new().expect("The auth service should initialize safely"); |
| 54 |
|
| 55 |
manager.add_u2f_usb_hid_platform_transports(); |
| 56 |
|
| 57 |
let timeout_ms = match matches.opt_get_default::<u64>("timeout", 25) { |
| 58 |
Ok(timeout_s) => { |
| 59 |
println!("Using {}s as the timeout", &timeout_s); |
| 60 |
timeout_s * 1_000 |
| 61 |
} |
| 62 |
Err(e) => { |
| 63 |
println!("{e}"); |
| 64 |
print_usage(&program, opts); |
| 65 |
return; |
| 66 |
} |
| 67 |
}; |
| 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"}"# |
| 74 |
); |
| 75 |
let chall_bytes = Sha256::digest(challenge_str.as_bytes()).into(); |
| 76 |
|
| 77 |
let (status_tx, status_rx) = channel::<StatusUpdate>(); |
| 78 |
thread::spawn(move || loop { |
| 79 |
match status_rx.recv() { |
| 80 |
Ok(StatusUpdate::InteractiveManagement(..)) => { |
| 81 |
panic!("STATUS: This can't happen when doing non-interactive usage"); |
| 82 |
} |
| 83 |
Ok(StatusUpdate::SelectDeviceNotice) => { |
| 84 |
println!("STATUS: Please select a device by touching one of them."); |
| 85 |
} |
| 86 |
Ok(StatusUpdate::PresenceRequired) => { |
| 87 |
println!("STATUS: waiting for user presence"); |
| 88 |
} |
| 89 |
Ok(StatusUpdate::PinUvError(StatusPinUv::PinRequired(sender))) => { |
| 90 |
let raw_pin = |
| 91 |
rpassword::prompt_password_stderr("Enter PIN: ").expect("Failed to read PIN"); |
| 92 |
sender.send(Pin::new(&raw_pin)).expect("Failed to send PIN"); |
| 93 |
continue; |
| 94 |
} |
| 95 |
Ok(StatusUpdate::PinUvError(StatusPinUv::InvalidPin(sender, attempts))) => { |
| 96 |
println!( |
| 97 |
"Wrong PIN! {}", |
| 98 |
attempts.map_or("Try again.".to_string(), |a| format!( |
| 99 |
"You have {a} attempts left." |
| 100 |
)) |
| 101 |
); |
| 102 |
let raw_pin = |
| 103 |
rpassword::prompt_password_stderr("Enter PIN: ").expect("Failed to read PIN"); |
| 104 |
sender.send(Pin::new(&raw_pin)).expect("Failed to send PIN"); |
| 105 |
continue; |
| 106 |
} |
| 107 |
Ok(StatusUpdate::PinUvError(StatusPinUv::PinAuthBlocked)) => { |
| 108 |
panic!("Too many failed attempts in one row. Your device has been temporarily blocked. Please unplug it and plug in again.") |
| 109 |
} |
| 110 |
Ok(StatusUpdate::PinUvError(StatusPinUv::PinBlocked)) => { |
| 111 |
panic!("Too many failed attempts. Your device has been blocked. Reset it.") |
| 112 |
} |
| 113 |
Ok(StatusUpdate::PinUvError(StatusPinUv::InvalidUv(attempts))) => { |
| 114 |
println!( |
| 115 |
"Wrong UV! {}", |
| 116 |
attempts.map_or("Try again.".to_string(), |a| format!( |
| 117 |
"You have {a} attempts left." |
| 118 |
)) |
| 119 |
); |
| 120 |
continue; |
| 121 |
} |
| 122 |
Ok(StatusUpdate::PinUvError(StatusPinUv::UvBlocked)) => { |
| 123 |
println!("Too many failed UV-attempts."); |
| 124 |
continue; |
| 125 |
} |
| 126 |
Ok(StatusUpdate::PinUvError(e)) => { |
| 127 |
panic!("Unexpected error: {:?}", e) |
| 128 |
} |
| 129 |
Ok(StatusUpdate::SelectResultNotice(_, _)) => { |
| 130 |
panic!("Unexpected select device notice") |
| 131 |
} |
| 132 |
Err(RecvError) => { |
| 133 |
println!("STATUS: end"); |
| 134 |
return; |
| 135 |
} |
| 136 |
} |
| 137 |
}); |
| 138 |
|
| 139 |
let user = PublicKeyCredentialUserEntity { |
| 140 |
id: "user_id".as_bytes().to_vec(), |
| 141 |
name: Some("A. User".to_string()), |
| 142 |
display_name: None, |
| 143 |
}; |
| 144 |
let origin = "https://example.com".to_string(); |
| 145 |
let mut ctap_args = RegisterArgs { |
| 146 |
client_data_hash: chall_bytes, |
| 147 |
relying_party: RelyingParty { |
| 148 |
id: "example.com".to_string(), |
| 149 |
name: None, |
| 150 |
}, |
| 151 |
origin: origin.clone(), |
| 152 |
user, |
| 153 |
pub_cred_params: vec![ |
| 154 |
PublicKeyCredentialParameters { |
| 155 |
alg: COSEAlgorithm::ES256, |
| 156 |
}, |
| 157 |
PublicKeyCredentialParameters { |
| 158 |
alg: COSEAlgorithm::RS256, |
| 159 |
}, |
| 160 |
], |
| 161 |
exclude_list: vec![], |
| 162 |
user_verification_req: UserVerificationRequirement::Preferred, |
| 163 |
resident_key_req: ResidentKeyRequirement::Discouraged, |
| 164 |
extensions: Default::default(), |
| 165 |
pin: None, |
| 166 |
use_ctap1_fallback: false, |
| 167 |
}; |
| 168 |
|
| 169 |
let mut registered_key_handle = None; |
| 170 |
loop { |
| 171 |
let (register_tx, register_rx) = channel(); |
| 172 |
let callback = StateCallback::new(Box::new(move |rv| { |
| 173 |
register_tx.send(rv).unwrap(); |
| 174 |
})); |
| 175 |
|
| 176 |
if let Err(e) = manager.register(timeout_ms, ctap_args.clone(), status_tx.clone(), callback) |
| 177 |
{ |
| 178 |
panic!("Couldn't register: {:?}", e); |
| 179 |
}; |
| 180 |
|
| 181 |
let register_result = register_rx |
| 182 |
.recv() |
| 183 |
.expect("Problem receiving, unable to continue"); |
| 184 |
match register_result { |
| 185 |
Ok(a) => { |
| 186 |
println!("Ok!"); |
| 187 |
println!("Registering again with the key_handle we just got back. This should result in a 'already registered' error."); |
| 188 |
let key_handle = a |
| 189 |
.att_obj |
| 190 |
.auth_data |
| 191 |
.credential_data |
| 192 |
.unwrap() |
| 193 |
.credential_id |
| 194 |
.clone(); |
| 195 |
let pub_key = PublicKeyCredentialDescriptor { |
| 196 |
id: key_handle, |
| 197 |
transports: vec![Transport::USB], |
| 198 |
}; |
| 199 |
ctap_args.exclude_list = vec![pub_key.clone()]; |
| 200 |
registered_key_handle = Some(pub_key); |
| 201 |
continue; |
| 202 |
} |
| 203 |
Err(AuthenticatorError::CredentialExcluded) => { |
| 204 |
println!("Got an 'already registered' error, as expected."); |
| 205 |
if ctap_args.exclude_list.len() > 1 { |
| 206 |
println!("Quitting."); |
| 207 |
break; |
| 208 |
} |
| 209 |
println!("Extending the list to contain more invalid handles."); |
| 210 |
let registered_handle = ctap_args.exclude_list[0].clone(); |
| 211 |
ctap_args.exclude_list = vec![]; |
| 212 |
for ii in 0..10 { |
| 213 |
ctap_args.exclude_list.push(PublicKeyCredentialDescriptor { |
| 214 |
id: vec![ii; 50], |
| 215 |
transports: vec![Transport::USB], |
| 216 |
}); |
| 217 |
} |
| 218 |
ctap_args.exclude_list.push(registered_handle); |
| 219 |
continue; |
| 220 |
} |
| 221 |
Err(e) => panic!("Registration failed: {:?}", e), |
| 222 |
}; |
| 223 |
} |
| 224 |
|
| 225 |
// Signing |
| 226 |
let mut ctap_args = SignArgs { |
| 227 |
client_data_hash: chall_bytes, |
| 228 |
origin, |
| 229 |
relying_party_id: "example.com".to_string(), |
| 230 |
allow_list: vec![], |
| 231 |
extensions: Default::default(), |
| 232 |
pin: None, |
| 233 |
use_ctap1_fallback: false, |
| 234 |
user_verification_req: UserVerificationRequirement::Preferred, |
| 235 |
user_presence_req: true, |
| 236 |
}; |
| 237 |
|
| 238 |
let mut no_cred_errors_done = false; |
| 239 |
loop { |
| 240 |
let (sign_tx, sign_rx) = channel(); |
| 241 |
let callback = StateCallback::new(Box::new(move |rv| { |
| 242 |
sign_tx.send(rv).unwrap(); |
| 243 |
})); |
| 244 |
|
| 245 |
if let Err(e) = manager.sign(timeout_ms, ctap_args.clone(), status_tx.clone(), callback) { |
| 246 |
panic!("Couldn't sign: {:?}", e); |
| 247 |
}; |
| 248 |
|
| 249 |
let sign_result = sign_rx |
| 250 |
.recv() |
| 251 |
.expect("Problem receiving, unable to continue"); |
| 252 |
match sign_result { |
| 253 |
Ok(_) => { |
| 254 |
if !no_cred_errors_done { |
| 255 |
panic!("Should have errored out with NoCredentials, but it succeeded."); |
| 256 |
} |
| 257 |
println!("Successfully signed!"); |
| 258 |
if ctap_args.allow_list.len() > 1 { |
| 259 |
println!("Quitting."); |
| 260 |
break; |
| 261 |
} |
| 262 |
println!("Signing again with a long allow_list that needs pre-flighting."); |
| 263 |
let registered_handle = registered_key_handle.as_ref().unwrap().clone(); |
| 264 |
ctap_args.allow_list = vec![]; |
| 265 |
for ii in 0..10 { |
| 266 |
ctap_args.allow_list.push(PublicKeyCredentialDescriptor { |
| 267 |
id: vec![ii; 50], |
| 268 |
transports: vec![Transport::USB], |
| 269 |
}); |
| 270 |
} |
| 271 |
ctap_args.allow_list.push(registered_handle); |
| 272 |
continue; |
| 273 |
} |
| 274 |
Err(AuthenticatorError::HIDError(HIDError::Command(CommandError::StatusCode( |
| 275 |
StatusCode::NoCredentials, |
| 276 |
None, |
| 277 |
)))) |
| 278 |
| Err(AuthenticatorError::UnsupportedOption(UnsupportedOption::EmptyAllowList)) => { |
| 279 |
if ctap_args.allow_list.is_empty() { |
| 280 |
// Try again with a list of false creds. We should end up here again. |
| 281 |
println!( |
| 282 |
"Got an 'no credentials' error, as expected with an empty allow-list." |
| 283 |
); |
| 284 |
println!("Extending the list to contain only fake handles."); |
| 285 |
ctap_args.allow_list = vec![]; |
| 286 |
for ii in 0..10 { |
| 287 |
ctap_args.allow_list.push(PublicKeyCredentialDescriptor { |
| 288 |
id: vec![ii; 50], |
| 289 |
transports: vec![Transport::USB], |
| 290 |
}); |
| 291 |
} |
| 292 |
} else { |
| 293 |
println!( |
| 294 |
"Got an 'no credentials' error, as expected with an all-fake allow-list." |
| 295 |
); |
| 296 |
println!("Extending the list to contain one valid handle."); |
| 297 |
let registered_handle = registered_key_handle.as_ref().unwrap().clone(); |
| 298 |
ctap_args.allow_list = vec![registered_handle]; |
| 299 |
no_cred_errors_done = true; |
| 300 |
} |
| 301 |
continue; |
| 302 |
} |
| 303 |
Err(e) => panic!("Registration failed: {:?}", e), |
| 304 |
}; |
| 305 |
} |
| 306 |
println!("Done") |
| 307 |
} |