Skip to content

Commit

Permalink
Add logging-possiblity to send_msg()-functiongroup
Browse files Browse the repository at this point in the history
  • Loading branch information
Martin Sirringhaus committed Dec 7, 2023
1 parent b21f8fa commit 0946490
Show file tree
Hide file tree
Showing 17 changed files with 232 additions and 74 deletions.
9 changes: 9 additions & 0 deletions examples/ctap2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ fn main() {
opts.optflag("s", "hmac_secret", "With hmac-secret");
opts.optflag("h", "help", "print this help menu");
opts.optflag("f", "fallback", "Use CTAP1 fallback implementation");
opts.optflag("l", "logging", "Active request/response logging");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => panic!("{}", f.to_string()),
Expand Down Expand Up @@ -81,6 +82,7 @@ fn main() {
let mut chall_bytes = [0u8; 32];
thread_rng().fill_bytes(&mut chall_bytes);

let do_logging = matches.opt_present("logging");
let (status_tx, status_rx) = channel::<StatusUpdate>();
thread::spawn(move || loop {
match status_rx.recv() {
Expand Down Expand Up @@ -136,6 +138,13 @@ fn main() {
Ok(StatusUpdate::SelectResultNotice(_, _)) => {
panic!("Unexpected select device notice")
}
Ok(StatusUpdate::RequestLogging(dir, msg)) => {
if do_logging {
println!("{dir:?} -> ");
println!("{msg}");
println!("--------------------------------------");
}
}
Err(RecvError) => {
println!("STATUS: end");
return;
Expand Down
40 changes: 32 additions & 8 deletions examples/ctap2_discoverable_creds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ use authenticator::{
};
use getopts::Options;
use sha2::{Digest, Sha256};
use std::io::Write;
use std::sync::mpsc::{channel, RecvError};
use std::{env, io, thread};
use std::io::Write;

fn print_usage(program: &str, opts: Options) {
println!("------------------------------------------------------------------------");
Expand Down Expand Up @@ -60,7 +60,12 @@ fn ask_user_choice(choices: &[PublicKeyCredentialUserEntity]) -> Option<usize> {
}
}

fn register_user(manager: &mut AuthenticatorService, username: &str, timeout_ms: u64) {
fn register_user(
manager: &mut AuthenticatorService,
username: &str,
timeout_ms: u64,
do_logging: bool,
) {
println!();
println!("*********************************************************************");
println!("Asking a security key to register now with user: {username}");
Expand Down Expand Up @@ -133,6 +138,13 @@ fn register_user(manager: &mut AuthenticatorService, username: &str, timeout_ms:
Ok(StatusUpdate::SelectResultNotice(_, _)) => {
panic!("Unexpected select result notice")
}
Ok(StatusUpdate::RequestLogging(dir, msg)) => {
if do_logging {
println!("{dir:?} -> ");
println!("{msg}");
println!("--------------------------------------");
}
}
Err(RecvError) => {
println!("STATUS: end");
return;
Expand Down Expand Up @@ -216,12 +228,10 @@ fn main() {
"timeout in seconds",
"SEC",
);
opts.optflag(
"s",
"skip_reg",
"Skip registration");
opts.optflag("s", "skip_reg", "Skip registration");

opts.optflag("h", "help", "print this help menu");
opts.optflag("l", "logging", "Active request/response logging");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => panic!("{}", f.to_string()),
Expand All @@ -247,9 +257,10 @@ fn main() {
}
};

let do_logging = matches.opt_present("logging");
if !matches.opt_present("skip_reg") {
for username in &["A. User", "A. Nother", "Dr. Who"] {
register_user(&mut manager, username, timeout_ms)
register_user(&mut manager, username, timeout_ms, do_logging)
}
}

Expand Down Expand Up @@ -324,6 +335,13 @@ fn main() {
let idx = ask_user_choice(&users);
index_sender.send(idx).expect("Failed to send choice");
}
Ok(StatusUpdate::RequestLogging(dir, msg)) => {
if do_logging {
println!("{dir:?} -> ");
println!("{msg}");
println!("--------------------------------------");
}
}
Err(RecvError) => {
println!("STATUS: end");
return;
Expand Down Expand Up @@ -368,7 +386,13 @@ fn main() {
println!("Found credentials:");
println!(
"{:?}",
assertion_object.assertion.user.clone().unwrap().name.unwrap() // Unwrapping here, as these shouldn't fail
assertion_object
.assertion
.user
.clone()
.unwrap()
.name
.unwrap() // Unwrapping here, as these shouldn't fail
);
println!("-----------------------------------------------------------------");
println!("Done.");
Expand Down
13 changes: 11 additions & 2 deletions examples/interactive_management.rs
Original file line number Diff line number Diff line change
Expand Up @@ -573,7 +573,7 @@ fn handle_bio_enrollments(
}
}

fn interactive_status_callback(status_rx: Receiver<StatusUpdate>) {
fn interactive_status_callback(status_rx: Receiver<StatusUpdate>, do_logging: bool) {
let mut tx = None;
let mut auth_info = None;
loop {
Expand Down Expand Up @@ -730,6 +730,13 @@ fn interactive_status_callback(status_rx: Receiver<StatusUpdate>) {
Ok(StatusUpdate::SelectResultNotice(_, _)) => {
panic!("Unexpected select device notice")
}
Ok(StatusUpdate::RequestLogging(dir, msg)) => {
if do_logging {
println!("{dir:?} -> ");
println!("{msg}");
println!("--------------------------------------");
}
}
Err(RecvError) => {
println!("STATUS: end");
return;
Expand All @@ -752,6 +759,7 @@ fn main() {
"SEC",
);
opts.optflag("h", "help", "print this help menu");
opts.optflag("l", "logging", "Active request/response logging");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => panic!("{}", f.to_string()),
Expand All @@ -777,8 +785,9 @@ fn main() {
}
};

let do_logging = matches.opt_present("logging");
let (status_tx, status_rx) = channel::<StatusUpdate>();
thread::spawn(move || interactive_status_callback(status_rx));
thread::spawn(move || interactive_status_callback(status_rx, do_logging));

let (manage_tx, manage_rx) = channel();
let state_callback =
Expand Down
9 changes: 9 additions & 0 deletions examples/set_pin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ fn main() {
Ok(m) => m,
Err(f) => panic!("{}", f.to_string()),
};
opts.optflag("l", "logging", "Active request/response logging");
if matches.opt_present("help") {
print_usage(&program, opts);
return;
Expand Down Expand Up @@ -62,6 +63,7 @@ fn main() {
return;
}

let do_logging = matches.opt_present("logging");
let (status_tx, status_rx) = channel::<StatusUpdate>();
thread::spawn(move || loop {
match status_rx.recv() {
Expand Down Expand Up @@ -117,6 +119,13 @@ fn main() {
Ok(StatusUpdate::SelectResultNotice(_, _)) => {
panic!("Unexpected select device notice")
}
Ok(StatusUpdate::RequestLogging(dir, msg)) => {
if do_logging {
println!("{dir:?} -> ");
println!("{msg}");
println!("--------------------------------------");
}
}
Err(RecvError) => {
println!("STATUS: end");
return;
Expand Down
9 changes: 9 additions & 0 deletions examples/test_exclude_list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ fn main() {
Ok(m) => m,
Err(f) => panic!("{}", f.to_string()),
};
opts.optflag("l", "logging", "Active request/response logging");
if matches.opt_present("help") {
print_usage(&program, opts);
return;
Expand Down Expand Up @@ -76,6 +77,7 @@ fn main() {
challenge.update(challenge_str.as_bytes());
let chall_bytes = challenge.finalize().into();

let do_logging = matches.opt_present("logging");
let (status_tx, status_rx) = channel::<StatusUpdate>();
thread::spawn(move || loop {
match status_rx.recv() {
Expand Down Expand Up @@ -131,6 +133,13 @@ fn main() {
Ok(StatusUpdate::SelectResultNotice(_, _)) => {
panic!("Unexpected select device notice")
}
Ok(StatusUpdate::RequestLogging(dir, msg)) => {
if do_logging {
println!("{dir:?} -> ");
println!("{msg}");
println!("--------------------------------------");
}
}
Err(RecvError) => {
println!("STATUS: end");
return;
Expand Down
5 changes: 3 additions & 2 deletions src/authenticatorservice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@ use crate::ctap2::server::{
use crate::errors::*;
use crate::manager::Manager;
use crate::statecallback::StateCallback;
use serde::Serialize;
use std::sync::{mpsc::Sender, Arc, Mutex};

#[derive(Debug, Clone)]
#[derive(Debug, Clone, Serialize)]
pub struct RegisterArgs {
pub client_data_hash: [u8; 32],
pub relying_party: RelyingParty,
Expand All @@ -28,7 +29,7 @@ pub struct RegisterArgs {
pub use_ctap1_fallback: bool,
}

#[derive(Debug, Clone)]
#[derive(Debug, Clone, Serialize)]
pub struct SignArgs {
pub client_data_hash: [u8; 32],
pub origin: String,
Expand Down
19 changes: 15 additions & 4 deletions src/ctap2/commands/get_assertion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,7 @@ impl RequestCtap2 for GetAssertion {
let msg = GetNextAssertion;
// We already have one, so skipping 0
for _ in 1..number_of_credentials {
let assertion = dev.send_cbor(&msg)?;
let assertion = dev.send_cbor(&msg, None)?;
results.push(GetAssertionResult {
assertion: assertion.into(),
attachment: AuthenticatorAttachment::Unknown,
Expand Down Expand Up @@ -631,6 +631,7 @@ pub mod test {
use crate::transport::{FidoDevice, FidoDeviceIO, FidoProtocol};
use crate::u2ftypes::U2FDeviceInfo;
use rand::{thread_rng, RngCore};
use std::sync::mpsc::channel;

#[test]
fn test_get_assertion_ctap2() {
Expand Down Expand Up @@ -788,7 +789,7 @@ pub mod test {
attachment: AuthenticatorAttachment::Unknown,
extensions: Default::default(),
}];
let response = device.send_cbor(&assertion).unwrap();
let response = device.send_cbor(&assertion, None).unwrap();
assert_eq!(response, expected);
}

Expand Down Expand Up @@ -869,6 +870,7 @@ pub mod test {
device.set_cid(cid);

// ctap1 request
let (tx, _rx) = channel();
fill_device_ctap1(
&mut device,
cid,
Expand All @@ -880,6 +882,7 @@ pub mod test {
&assertion.allow_list,
&assertion.rp,
&assertion.client_data_hash,
&tx,
)
.expect("Did not find a key_handle, even though it should have");
assertion.allow_list = vec![key_handle];
Expand All @@ -892,7 +895,7 @@ pub mod test {
// Pre-flighting is not done automatically
fill_device_ctap1(&mut device, cid, U2F_REQUEST_USER_PRESENCE, SW_NO_ERROR);

let response = device.send_ctap1(&assertion).unwrap();
let response = device.send_ctap1(&assertion, None).unwrap();

// Check if response is correct
let expected_auth_data = AuthenticatorData {
Expand Down Expand Up @@ -958,12 +961,14 @@ pub mod test {

device.set_cid(cid);

let (tx, _rx) = channel();
assert_matches!(
do_credential_list_filtering_ctap1(
&mut device,
&assertion.allow_list,
&assertion.rp,
&assertion.client_data_hash,
&tx,
),
None
);
Expand All @@ -981,12 +986,14 @@ pub mod test {
for allow_list in [vec![], vec![too_long_key_handle.clone(); 5]] {
assertion.allow_list = allow_list;

let (tx, _rx) = channel();
assert_matches!(
do_credential_list_filtering_ctap1(
&mut device,
&assertion.allow_list,
&assertion.rp,
&assertion.client_data_hash,
&tx,
),
None
);
Expand Down Expand Up @@ -1017,11 +1024,13 @@ pub mod test {
U2F_CHECK_IS_REGISTERED,
SW_CONDITIONS_NOT_SATISFIED,
);
let (tx, _rx) = channel();
let key_handle = do_credential_list_filtering_ctap1(
&mut device,
&assertion.allow_list,
&assertion.rp,
&assertion.client_data_hash,
&tx,
)
.expect("Did not find a key_handle, even though it should have");
assertion.allow_list = vec![key_handle];
Expand All @@ -1034,7 +1043,7 @@ pub mod test {
// Pre-flighting is not done automatically
fill_device_ctap1(&mut device, cid, U2F_REQUEST_USER_PRESENCE, SW_NO_ERROR);

let response = device.send_ctap1(&assertion).unwrap();
let response = device.send_ctap1(&assertion, None).unwrap();

// Check if response is correct
let expected_auth_data = AuthenticatorData {
Expand Down Expand Up @@ -1299,12 +1308,14 @@ pub mod test {
msg.extend(&GET_ASSERTION_SAMPLE_RESPONSE_CTAP2[293..]);
device.add_read(&msg, 0);

let (tx, _rx) = channel();
assert_matches!(
do_credential_list_filtering_ctap2(
&mut device,
&assertion.allow_list,
&assertion.rp,
None,
&tx,
),
Ok(..)
);
Expand Down
4 changes: 2 additions & 2 deletions src/ctap2/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ pub(crate) fn repackage_pin_errors<D: FidoDevice>(
let cmd = GetPinRetries::new();
// Treat any error as if the device returned a valid response without a pinRetries
// field.
let resp = dev.send_cbor(&cmd).unwrap_or_default();
let resp = dev.send_cbor(&cmd, None).unwrap_or_default();
AuthenticatorError::PinError(PinError::InvalidPin(resp.pin_retries))
}
HIDError::Command(CommandError::StatusCode(StatusCode::PinAuthBlocked, _)) => {
Expand All @@ -183,7 +183,7 @@ pub(crate) fn repackage_pin_errors<D: FidoDevice>(
let cmd = GetUvRetries::new();
// Treat any error as if the device returned a valid response without a uvRetries
// field.
let resp = dev.send_cbor(&cmd).unwrap_or_default();
let resp = dev.send_cbor(&cmd, None).unwrap_or_default();
AuthenticatorError::PinError(PinError::InvalidUv(resp.uv_retries))
}
HIDError::Command(CommandError::StatusCode(StatusCode::UvBlocked, _)) => {
Expand Down
2 changes: 1 addition & 1 deletion src/ctap2/commands/reset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ pub mod tests {
msg.extend(add); // + maybe additional data
device.add_read(&msg, 0);

device.send_cbor(&Reset {})
device.send_cbor(&Reset {}, None)
}

#[test]
Expand Down
Loading

0 comments on commit 0946490

Please sign in to comment.