From 34a5b6b6645bbb2e9b0c047cb438091e97ef1be6 Mon Sep 17 00:00:00 2001 From: Daniel Stiner Date: Wed, 3 Jan 2018 17:25:15 -0800 Subject: [PATCH] Formatting --- softu2f-bin/src/main.rs | 27 ++-- softu2f-bin/src/user_file_storage.rs | 21 ++- softu2f-bin/src/user_presence.rs | 11 +- softu2f-test-user-presence/src/main.rs | 28 ++-- system-daemon/src/bidirectional_pipe.rs | 8 +- system-daemon/src/definitions.rs | 15 +- system-daemon/src/device.rs | 85 +++++----- system-daemon/src/main.rs | 39 +++-- u2f-core/src/lib.rs | 145 ++++++++++-------- u2fhid-protocol/src/definitions.rs | 30 ++-- u2fhid-protocol/src/lib.rs | 30 ++-- u2fhid-protocol/src/protocol_state_machine.rs | 132 ++++++++-------- u2fhid-protocol/src/segmenting_sink.rs | 4 +- uhid-linux-tokio/src/character_device.rs | 24 ++- uhid-linux-tokio/src/lib.rs | 4 +- .../src/poll_evented_read_wrapper.rs | 2 +- uhid-linux-tokio/src/uhid_codec.rs | 39 +++-- uhid-linux-tokio/src/uhid_device.rs | 19 +-- user-daemon/src/file_storage.rs | 15 +- user-daemon/src/main.rs | 101 ++++++------ user-daemon/src/user_presence.rs | 20 +-- 21 files changed, 433 insertions(+), 366 deletions(-) diff --git a/softu2f-bin/src/main.rs b/softu2f-bin/src/main.rs index 17ec5a6..473afe3 100644 --- a/softu2f-bin/src/main.rs +++ b/softu2f-bin/src/main.rs @@ -7,8 +7,8 @@ extern crate futures; extern crate libc; extern crate rprompt; extern crate sandbox_ipc; -extern crate serde_json; extern crate serde; +extern crate serde_json; extern crate slog_term; extern crate softu2f_test_user_presence; extern crate tokio_core; @@ -25,14 +25,14 @@ use std::env; use std::io; use std::path::{Path, PathBuf}; -use futures::{future, Future, Stream, Sink}; +use futures::{future, Future, Sink, Stream}; use slog::{Drain, Logger}; use tokio_core::reactor::Core; use libc::{gid_t, uid_t}; use u2f_core::{SecureCryptoOperations, U2F}; use u2fhid_protocol::{Packet, U2FHID}; -use uhid_linux_tokio::{Bus, CreateParams, UHIDDevice, InputEvent, OutputEvent, StreamError}; +use uhid_linux_tokio::{Bus, CreateParams, InputEvent, OutputEvent, StreamError, UHIDDevice}; use user_file_storage::UserFileStorage; use user_presence::NotificationUserPresence; @@ -83,7 +83,9 @@ fn output_to_packet(output_event: OutputEvent) -> Option { } fn packet_to_input(packet: Packet) -> Box> { - Box::new(future::ok(InputEvent::Input { data: packet.into_bytes() })) + Box::new(future::ok(InputEvent::Input { + data: packet.into_bytes(), + })) } fn stream_error_to_io_error(err: StreamError) -> io::Error { @@ -125,10 +127,7 @@ fn pre_sudo_env() -> Option { Ok(PreSudoEnvironment { dbus_session_bus_address: dbus_session_bus_address, home: home, - security_ids: SecurityIds { - gid: gid, - uid: uid, - } + security_ids: SecurityIds { gid: gid, uid: uid }, }) } @@ -137,7 +136,7 @@ fn pre_sudo_env() -> Option { Err(_) => { eprintln!("Usage: sudo --preserve-env {}", program_name()); None - }, + } } } @@ -155,7 +154,9 @@ fn run(logger: slog::Logger, pre_sudo_env: PreSudoEnvironment) -> io::Result<()> }; let security_ids = pre_sudo_env.security_ids; - let store_path = [&pre_sudo_env.home, Path::new(".softu2f-secrets.json")].iter().collect(); + let store_path = [&pre_sudo_env.home, Path::new(".softu2f-secrets.json")] + .iter() + .collect(); let mut core = Core::new()?; let handle = core.handle(); @@ -170,7 +171,11 @@ fn run(logger: slog::Logger, pre_sudo_env: PreSudoEnvironment) -> io::Result<()> let attestation = u2f_core::self_signed_attestation(); let user_presence = Box::new(NotificationUserPresence::new(core.handle(), pre_sudo_env)); let operations = Box::new(SecureCryptoOperations::new(attestation)); - let storage = Box::new(UserFileStorage::new(store_path, security_ids, logger.new(o!()))?); + let storage = Box::new(UserFileStorage::new( + store_path, + security_ids, + logger.new(o!()), + )?); let service = U2F::new(user_presence, operations, storage, logger.new(o!()))?; let bind = U2FHID::bind_service(&handle, transport, service, logger.new(o!())); diff --git a/softu2f-bin/src/user_file_storage.rs b/softu2f-bin/src/user_file_storage.rs index a47a797..06a6af8 100644 --- a/softu2f-bin/src/user_file_storage.rs +++ b/softu2f-bin/src/user_file_storage.rs @@ -30,7 +30,11 @@ pub struct UserFileStorage { } impl UserFileStorage { - pub fn new(path: PathBuf, security_ids: SecurityIds, logger: Logger) -> io::Result { + pub fn new( + path: PathBuf, + security_ids: SecurityIds, + logger: Logger, + ) -> io::Result { let store = Self::load_store(&path, security_ids)?; Ok(UserFileStorage { logger: logger, @@ -70,10 +74,10 @@ impl SecretStore for UserFileStorage { &self, key: &ApplicationKey, ) -> Box> { - self.store.borrow_mut().application_keys.insert( - key.application, - key.clone(), - ); + self.store + .borrow_mut() + .application_keys + .insert(key.application, key.clone()); Box::new(self.save().into_future()) } @@ -136,9 +140,10 @@ where trace!(logger, "overwrite_file_atomic"; "path" => path.to_str().unwrap(), "tmp_path" => tmp_path.as_path().to_str().unwrap()); { - let file = OpenOptions::new().write(true).create_new(true).open( - &tmp_path, - )?; + let file = OpenOptions::new() + .write(true) + .create_new(true) + .open(&tmp_path)?; writer_fn(Box::new(file.try_clone()?))?; file.sync_all()?; } diff --git a/softu2f-bin/src/user_presence.rs b/softu2f-bin/src/user_presence.rs index 0c6f914..f99468f 100644 --- a/softu2f-bin/src/user_presence.rs +++ b/softu2f-bin/src/user_presence.rs @@ -9,9 +9,9 @@ use futures::future; use serde_json; use tokio_core::reactor::Handle; -use super::{DBUS_SESSION_BUS_ADDRESS_VAR, PreSudoEnvironment}; -use u2f_core::{ApplicationParameter, UserPresence, try_reverse_application_id}; -use softu2f_test_user_presence::{CHANNEL_ENV_VAR, UserPresenceTestParameters}; +use super::{PreSudoEnvironment, DBUS_SESSION_BUS_ADDRESS_VAR}; +use u2f_core::{try_reverse_application_id, ApplicationParameter, UserPresence}; +use softu2f_test_user_presence::{UserPresenceTestParameters, CHANNEL_ENV_VAR}; pub struct NotificationUserPresence { handle: Handle, @@ -65,10 +65,11 @@ impl NotificationUserPresence { .into_future() .map(|(response_option, _)| response_option.unwrap_or(false)) .map_err(|(err, _)| err) - }).then(move |res| { + }) + .then(move |res| { child.kill().ok(); // TODO Only allow certain failures res - }) + }), ) } } diff --git a/softu2f-test-user-presence/src/main.rs b/softu2f-test-user-presence/src/main.rs index 04fafe5..85d7fb4 100644 --- a/softu2f-test-user-presence/src/main.rs +++ b/softu2f-test-user-presence/src/main.rs @@ -12,12 +12,12 @@ extern crate tokio_core; use std::env; use std::io; -use futures::prelude::*; +use futures::prelude::*; use notify_rust::{Notification, NotificationHint, NotificationUrgency}; use time::Duration; use tokio_core::reactor::Core; -use softu2f_test_user_presence::{CHANNEL_ENV_VAR, UserPresenceTestParameters}; +use softu2f_test_user_presence::{UserPresenceTestParameters, CHANNEL_ENV_VAR}; // TODO this hardcoded keyword should be in the notifcation library const NOTIFICATION_CLOSE_ACTION: &str = "__closed"; @@ -44,17 +44,17 @@ fn notify(parameters: UserPresenceTestParameters) -> io::Result { .unwrap(); handle.wait_for_action({ - |action| match action { - "approve" => res = true, - "deny" => res = false, - "default" => res = false, - NOTIFICATION_CLOSE_ACTION => { - println!("the notification was closed"); - res = false; - } - _ => unreachable!("Unknown action taken on notification"), + |action| match action { + "approve" => res = true, + "deny" => res = false, + "default" => res = false, + NOTIFICATION_CLOSE_ACTION => { + println!("the notification was closed"); + res = false; } - }); + _ => unreachable!("Unknown action taken on notification"), + } + }); Ok(res) } @@ -63,8 +63,8 @@ fn main() { let mut core = Core::new().unwrap(); let handle = core.handle(); - let channel: ipc::ChildMessageChannel = json::from_str(&env::var(CHANNEL_ENV_VAR).unwrap()) - .unwrap(); + let channel: ipc::ChildMessageChannel = + json::from_str(&env::var(CHANNEL_ENV_VAR).unwrap()).unwrap(); let channel = channel .into_channel::(&handle) .unwrap(); diff --git a/system-daemon/src/bidirectional_pipe.rs b/system-daemon/src/bidirectional_pipe.rs index 4f3659d..d40b1d2 100644 --- a/system-daemon/src/bidirectional_pipe.rs +++ b/system-daemon/src/bidirectional_pipe.rs @@ -71,14 +71,14 @@ where // Send any buffered items, piped to opposing side if let Some(item) = self.buffer_a.take() { match self.side_b.start_send(item) { - Ok(AsyncSink::Ready) => { made_progress = true} + Ok(AsyncSink::Ready) => made_progress = true, Ok(AsyncSink::NotReady(rejected_item)) => self.buffer_a = Some(rejected_item), Err(err) => return Err(err.into()), }; } if let Some(item) = self.buffer_b.take() { match self.side_a.start_send(item) { - Ok(AsyncSink::Ready) => {made_progress = true} + Ok(AsyncSink::Ready) => made_progress = true, Ok(AsyncSink::NotReady(rejected_item)) => self.buffer_b = Some(rejected_item), Err(err) => return Err(err.into()), }; @@ -101,10 +101,10 @@ where // Exit loop if complete or no progress was made if streams_finished && sinks_flushed && no_items_buffered { - return Ok(Async::Ready(())) + return Ok(Async::Ready(())); } if !made_progress { - return Ok(Async::NotReady) + return Ok(Async::NotReady); } } } diff --git a/system-daemon/src/definitions.rs b/system-daemon/src/definitions.rs index 92efb44..69a6d34 100644 --- a/system-daemon/src/definitions.rs +++ b/system-daemon/src/definitions.rs @@ -20,8 +20,15 @@ impl slog::Value for SocketOutput { serializer: &mut slog::Serializer, ) -> slog::Result { match self { - &SocketOutput::CreateDeviceResponse(ref response) => slog::Value::serialize(&format!("CreateDeviceResponse({:?})", response), record, key, serializer), - &SocketOutput::Packet {..} => slog::Value::serialize(&"Packet", record, key, serializer) + &SocketOutput::CreateDeviceResponse(ref response) => slog::Value::serialize( + &format!("CreateDeviceResponse({:?})", response), + record, + key, + serializer, + ), + &SocketOutput::Packet { .. } => { + slog::Value::serialize(&"Packet", record, key, serializer) + } } } } @@ -55,7 +62,9 @@ pub struct Packet { impl Packet { pub fn from_bytes(bytes: &[u8]) -> Packet { - Packet { bytes: bytes.to_vec() } + Packet { + bytes: bytes.to_vec(), + } } pub fn into_bytes(self) -> Vec { self.bytes diff --git a/system-daemon/src/device.rs b/system-daemon/src/device.rs index 15be405..9658024 100644 --- a/system-daemon/src/device.rs +++ b/system-daemon/src/device.rs @@ -11,48 +11,54 @@ use take_mut::take; use bidirectional_pipe::BidirectionalPipe; use softu2f_system_daemon::*; -use uhid_linux_tokio::{Bus, CreateParams, UHIDDevice, InputEvent, OutputEvent, StreamError}; +use uhid_linux_tokio::{Bus, CreateParams, InputEvent, OutputEvent, StreamError, UHIDDevice}; const INPUT_REPORT_LEN: u8 = 64; const OUTPUT_REPORT_LEN: u8 = 64; // HID Report Descriptor from http://www.usb.org/developers/hidpage/HUTRR48.pdf const REPORT_DESCRIPTOR: [u8; 34] = [ - 0x06, 0xd0, 0xf1, // USAGE_PAGE (FIDO Alliance) - 0x09, 0x01, // USAGE (Keyboard) - 0xa1, 0x01, // COLLECTION (Application) - 0x09, 0x20, // USAGE (Input Report Data) - 0x15, 0x00, // LOGICAL_MINIMUM (0) - 0x26, 0xff, 0x00, // LOGICAL_MAXIMUM (255) - 0x75, 0x08, // REPORT_SIZE (8) - 0x95, INPUT_REPORT_LEN, // REPORT_COUNT (64) - 0x81, 0x02, // INPUT (Data,Var,Abs) - 0x09, 0x21, // USAGE(Output Report Data) - 0x15, 0x00, // LOGICAL_MINIMUM (0) - 0x26, 0xff, 0x00, // LOGICAL_MAXIMUM (255) - 0x75, 0x08, // REPORT_SIZE (8) - 0x95, OUTPUT_REPORT_LEN, // REPORT_COUNT (64) - 0x91, 0x02, // OUTPUT (Data,Var,Abs) - 0xc0, // END_COLLECTION + 0x06, + 0xd0, + 0xf1, // USAGE_PAGE (FIDO Alliance) + 0x09, + 0x01, // USAGE (Keyboard) + 0xa1, + 0x01, // COLLECTION (Application) + 0x09, + 0x20, // USAGE (Input Report Data) + 0x15, + 0x00, // LOGICAL_MINIMUM (0) + 0x26, + 0xff, + 0x00, // LOGICAL_MAXIMUM (255) + 0x75, + 0x08, // REPORT_SIZE (8) + 0x95, + INPUT_REPORT_LEN, // REPORT_COUNT (64) + 0x81, + 0x02, // INPUT (Data,Var,Abs) + 0x09, + 0x21, // USAGE(Output Report Data) + 0x15, + 0x00, // LOGICAL_MINIMUM (0) + 0x26, + 0xff, + 0x00, // LOGICAL_MAXIMUM (255) + 0x75, + 0x08, // REPORT_SIZE (8) + 0x95, + OUTPUT_REPORT_LEN, // REPORT_COUNT (64) + 0x91, + 0x02, // OUTPUT (Data,Var,Abs) + 0xc0, // END_COLLECTION ]; - -type PacketPipe = Box< - Pipe< - Item = Packet, - Error = io::Error, - SinkItem = Packet, - SinkError = io::Error, - >, ->; +type PacketPipe = + Box>; type SocketPipe = Box< - Pipe< - Item = SocketInput, - Error = io::Error, - SinkItem = SocketOutput, - SinkError = io::Error, - >, + Pipe, >; trait Pipe: Stream + Sink {} @@ -101,7 +107,10 @@ fn initialize( handle: &Handle, logger: &Logger, _request: CreateDeviceRequest, -) -> (Box>, PacketPipe) { +) -> ( + Box>, + PacketPipe, +) { info!(logger, "initialize"); let create_params = CreateParams { name: String::from("SoftU2F-Linux"), @@ -138,9 +147,7 @@ fn run( SocketInput::CreateDeviceRequest(_create_request) => None, SocketInput::Packet(packet) => Some(packet), }) - .with(|packet: Packet| { - Box::new(future::ok(SocketOutput::Packet(packet))) - }), + .with(|packet: Packet| Box::new(future::ok(SocketOutput::Packet(packet)))), ); BidirectionalPipe::new(mapped_socket_transport, uhid_transport) @@ -168,7 +175,9 @@ fn into_transport(device: UHIDDevice) -> Pack _ => None, }) .with(|packet: Packet| { - Box::new(future::ok(InputEvent::Input { data: packet.into_bytes() })) + Box::new(future::ok(InputEvent::Input { + data: packet.into_bytes(), + })) }) .map_err(stream_error_to_io_error) .sink_map_err(stream_error_to_io_error), @@ -281,7 +290,7 @@ impl Future for Device { DeviceState::Closed } }); - }; + } match res { Ok(AsyncLoop::Done(x)) => Ok(Async::Ready(x)), Ok(AsyncLoop::NotReady) => Ok(Async::NotReady), diff --git a/system-daemon/src/main.rs b/system-daemon/src/main.rs index 63146c1..0770cb6 100644 --- a/system-daemon/src/main.rs +++ b/system-daemon/src/main.rs @@ -28,7 +28,7 @@ use futures::future; use futures::prelude::*; use slog_journald::JournaldDrain; use slog::{Drain, Logger}; -use systemd::daemon::{is_socket_unix, SocketType, Listening}; +use systemd::daemon::{is_socket_unix, Listening, SocketType}; use tokio_core::reactor::{Core, Handle}; use tokio_io::codec::length_delimited; use tokio_serde_bincode::{ReadBincode, WriteBincode}; @@ -41,15 +41,22 @@ fn run(logger: Logger) -> io::Result<()> { let handle = core.handle(); let listen_fds_count = systemd::daemon::listen_fds(true)?; - assert_eq!(listen_fds_count, 1, "Expect exactly one socket from systemd"); + assert_eq!( + listen_fds_count, + 1, + "Expect exactly one socket from systemd" + ); let fd = systemd::daemon::LISTEN_FDS_START; - assert!(is_socket_unix( - fd, - Some(SocketType::Stream), - Listening::IsListening, - Some("/run/softu2f/softu2f.sock"), - )?, "Expect the softu2f socket fom systemd"); + assert!( + is_socket_unix( + fd, + Some(SocketType::Stream), + Listening::IsListening, + Some("/run/softu2f/softu2f.sock"), + )?, + "Expect the softu2f socket fom systemd" + ); let listener = unsafe { UnixListener::from_raw_fd(fd) }; let listener = tokio_uds::UnixListener::from_listener(listener, &handle)?; @@ -61,7 +68,11 @@ fn run(logger: Logger) -> io::Result<()> { })) } -fn accept(stream: tokio_uds::UnixStream, handle: &Handle, logger: &Logger) -> Box> { +fn accept( + stream: tokio_uds::UnixStream, + handle: &Handle, + logger: &Logger, +) -> Box> { let peer_cred = stream.peer_cred().unwrap(); let logger = logger.new(o!("uid" => peer_cred.uid)); @@ -76,10 +87,12 @@ fn accept(stream: tokio_uds::UnixStream, handle: &Handle, logger: &Logger) -> Bo other_err => io::Error::new(io::ErrorKind::Other, other_err), }); - Box::new(Device::new(peer_cred, mapped_err, handle, logger.new(o!())).or_else(move |err| { - error!(logger, "Error"; "err" => %err); - future::ok(()) - })) + Box::new( + Device::new(peer_cred, mapped_err, handle, logger.new(o!())).or_else(move |err| { + error!(logger, "Error"; "err" => %err); + future::ok(()) + }), + ) } fn main() { diff --git a/u2f-core/src/lib.rs b/u2f-core/src/lib.rs index 8af003d..91c96f3 100644 --- a/u2f-core/src/lib.rs +++ b/u2f-core/src/lib.rs @@ -3,11 +3,11 @@ extern crate assert_matches; #[macro_use] extern crate lazy_static; #[macro_use] +extern crate quick_error; +#[macro_use] extern crate serde_derive; #[macro_use] extern crate slog; -#[macro_use] -extern crate quick_error; extern crate base64; extern crate byteorder; @@ -38,7 +38,7 @@ use futures::Future; use futures::future; use openssl::bn::BigNumContext; use openssl::bn::BigNumContextRef; -use openssl::ec::{self, EcGroup, EcKey, EcPoint, EcGroupRef, EcPointRef}; +use openssl::ec::{self, EcGroup, EcGroupRef, EcKey, EcPoint, EcPointRef}; use openssl::hash::MessageDigest; use openssl::nid; use openssl::pkey::PKey; @@ -47,11 +47,11 @@ use openssl::x509::X509; use rand::OsRng; use rand::Rand; use rand::Rng; -use serde::{Serialize, Serializer, Deserialize, Deserializer}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; use slog::Drain; -use self_signed_attestation::{SELF_SIGNED_ATTESTATION_KEY_PEM, - SELF_SIGNED_ATTESTATION_CERTIFICATE_PEM}; +use self_signed_attestation::{SELF_SIGNED_ATTESTATION_CERTIFICATE_PEM, + SELF_SIGNED_ATTESTATION_KEY_PEM}; const REGISTER_COMMAND_CODE: u8 = 0x01; const AUTHENTICATE_COMMAND_CODE: u8 = 0x02; @@ -272,7 +272,9 @@ pub enum Response { signature: Box, user_present: bool, }, - Version { version_string: String }, + Version { + version_string: String, + }, DidWink, TestOfUserPresenceNotSatisfied, InvalidKeyHandle, @@ -438,9 +440,8 @@ where D: Deserializer<'de>, { use serde::de::Error; - String::deserialize(deserializer).and_then(|string| { - base64::decode(&string).map_err(|err| Error::custom(err.to_string())) - }) + String::deserialize(deserializer) + .and_then(|string| base64::decode(&string).map_err(|err| Error::custom(err.to_string()))) } impl slog::Value for ApplicationParameter { @@ -612,9 +613,10 @@ impl PublicKey { /// uncompressed point compression method. fn from_bytes(bytes: &[u8], ctx: &mut BigNumContext) -> Result { if bytes.len() != 65 { - return Err(String::from( - format!("Expected 65 bytes, found {}", bytes.len()), - )); + return Err(String::from(format!( + "Expected 65 bytes, found {}", + bytes.len() + ))); } if bytes[0] != EC_POINT_FORMAT_UNCOMPRESSED { return Err(String::from("Expected uncompressed point")); @@ -772,10 +774,9 @@ impl U2F { storage: Box, logger: L, ) -> io::Result { - let logger = logger.into().unwrap_or(slog::Logger::root( - slog_stdlog::StdLog.fuse(), - o!(), - )); + let logger = logger + .into() + .unwrap_or(slog::Logger::root(slog_stdlog::StdLog.fuse(), o!())); let inner = U2FInner { approval: approval, logger: logger, @@ -808,16 +809,16 @@ impl U2F { .from_err() }; - Box::new(application_key_future.and_then( - move |application_key_option| { + Box::new( + application_key_future.and_then(move |application_key_option| { match application_key_option { Some(application_key) => { Self::_authenticate_step2(self_rc, application, challenge, application_key) } None => Box::new(future::err(AuthenticateError::InvalidKeyHandle)), } - }, - )) + }), + ) } fn _authenticate_step2( @@ -965,9 +966,7 @@ impl U2F { .storage .add_application_key(&application_key) .from_err() - .and_then(move |_| { - Self::_register_step3(self_rc, challenge, application_key) - }), + .and_then(move |_| Self::_register_step3(self_rc, challenge, application_key)), ) } @@ -1030,7 +1029,10 @@ impl Service for U2F { }) .or_else(move |err| match err { RegisterError::ApprovalRequired => { - debug!(logger_clone, "Request::Register => TestOfUserPresenceNotSatisfied"); + debug!( + logger_clone, + "Request::Register => TestOfUserPresenceNotSatisfied" + ); Ok(Response::TestOfUserPresenceNotSatisfied) } RegisterError::Io(err) => { @@ -1050,7 +1052,9 @@ impl Service for U2F { application, key_handle, } => { - let logger = self.0.logger.new(o!("request" => "authenticate", "app_id" => application)); + let logger = self.0 + .logger + .new(o!("request" => "authenticate", "app_id" => application)); match control_code { AuthenticateControlCode::CheckOnly => { trace!(logger, "ControlCode::CheckOnly"); @@ -1067,34 +1071,41 @@ impl Service for U2F { AuthenticateControlCode::EnforceUserPresenceAndSign => { trace!(logger, "ControlCode::EnforceUserPresenceAndSign"); let logger_clone = logger.clone(); - Box::new(self.authenticate(application, challenge, key_handle).map(move |authentication| { - info!(logger, "authenticated"; "counter" => &authentication.counter, "user_present" => &authentication.user_present); - Response::Authentication { - counter: authentication.counter, - signature: authentication.signature, - user_present: authentication.user_present, - } - }).or_else(move |err| match err { - AuthenticateError::ApprovalRequired => { - info!(logger_clone, "TestOfUserPresenceNotSatisfied"); - Ok(Response::TestOfUserPresenceNotSatisfied) - } - AuthenticateError::InvalidKeyHandle => { - info!(logger_clone, "InvalidKeyHandle"); - Ok(Response::InvalidKeyHandle) - } - AuthenticateError::Io(err) => { - info!(logger_clone, "I/O error"; "error" => ?err); - Ok(Response::UnknownError) - } - AuthenticateError::Signing(err) => { - info!(logger_clone, "Signing error"; "error" => ?err); - Ok(Response::UnknownError) - } - })) + Box::new( + self.authenticate(application, challenge, key_handle) + .map(move |authentication| { + info!(logger, "authenticated"; "counter" => &authentication.counter, "user_present" => &authentication.user_present); + Response::Authentication { + counter: authentication.counter, + signature: authentication.signature, + user_present: authentication.user_present, + } + }) + .or_else(move |err| match err { + AuthenticateError::ApprovalRequired => { + info!(logger_clone, "TestOfUserPresenceNotSatisfied"); + Ok(Response::TestOfUserPresenceNotSatisfied) + } + AuthenticateError::InvalidKeyHandle => { + info!(logger_clone, "InvalidKeyHandle"); + Ok(Response::InvalidKeyHandle) + } + AuthenticateError::Io(err) => { + info!(logger_clone, "I/O error"; "error" => ?err); + Ok(Response::UnknownError) + } + AuthenticateError::Signing(err) => { + info!(logger_clone, "Signing error"; "error" => ?err); + Ok(Response::UnknownError) + } + }), + ) } AuthenticateControlCode::DontEnforceUserPresenceAndSign => { - trace!(logger, "Request::Authenticate::DontEnforceUserPresenceAndSign"); + trace!( + logger, + "Request::Authenticate::DontEnforceUserPresenceAndSign" + ); info!(logger, "Request::Authenticate::DontEnforceUserPresenceAndSign => TestOfUserPresenceNotSatisfied (Not implemented)"); // TODO Implement Box::new(futures::finished(Response::TestOfUserPresenceNotSatisfied)) @@ -1103,15 +1114,15 @@ impl Service for U2F { } Request::GetVersion => { trace!(logger, "Request::GetVersion"); - let response = Response::Version { version_string: self.get_version_string() }; + let response = Response::Version { + version_string: self.get_version_string(), + }; Box::new(future::ok(response)) } - Request::Wink => { - Box::new(self.wink().map(|_| Response::DidWink).or_else(move |err| { - info!(logger, "I/O error"; "error" => format!("{:?}", err)); - Ok(Response::UnknownError) - })) - } + Request::Wink => Box::new(self.wink().map(|_| Response::DidWink).or_else(move |err| { + info!(logger, "I/O error"; "error" => format!("{:?}", err)); + Ok(Response::UnknownError) + })), } } } @@ -1183,7 +1194,9 @@ pub struct SecureCryptoOperations { impl SecureCryptoOperations { pub fn new(attestation: Attestation) -> SecureCryptoOperations { - SecureCryptoOperations { attestation: attestation } + SecureCryptoOperations { + attestation: attestation, + } } fn generate_key() -> Key { @@ -1313,10 +1326,10 @@ mod tests { &self, key: &ApplicationKey, ) -> Box> { - self.0.borrow_mut().application_keys.insert( - key.application, - key.clone(), - ); + self.0 + .borrow_mut() + .application_keys + .insert(key.application, key.clone()); Box::new(future::ok(())) } @@ -1519,8 +1532,8 @@ AwEHoUQDQgAEryDZdIOGjRKLLyG6Mkc4oSVUDBndagZDDbdwLcUdNLzFlHx/yqYl .unwrap(); let user_presence_byte = user_presence_byte(true); - let user_public_key = PublicKey::from_bytes(®istration.user_public_key, &mut ctx) - .unwrap(); + let user_public_key = + PublicKey::from_bytes(®istration.user_public_key, &mut ctx).unwrap(); let user_pkey = PKey::from_ec_key(user_public_key.to_ec_key()).unwrap(); let signed_data = message_to_sign_for_authenticate( &application, diff --git a/u2fhid-protocol/src/definitions.rs b/u2fhid-protocol/src/definitions.rs index 39f0985..b470c58 100644 --- a/u2fhid-protocol/src/definitions.rs +++ b/u2fhid-protocol/src/definitions.rs @@ -190,9 +190,9 @@ impl Packet { U2FHID_WINK => Command::Wink, U2FHID_LOCK => Command::Lock, U2FHID_SYNC => Command::Sync, - id if id >= U2FHID_VENDOR_FIRST && id <= U2FHID_VENDOR_LAST => Command::Vendor { - identifier: id, - }, + id if id >= U2FHID_VENDOR_FIRST && id <= U2FHID_VENDOR_LAST => { + Command::Vendor { identifier: id } + } _ => return Err(()), }; let payload_len = reader.read_u16::().unwrap(); @@ -296,8 +296,12 @@ pub enum RequestMessage { impl RequestMessage { pub fn decode(command: &Command, data: &[u8]) -> Result { match command { - &Command::Msg => Ok(RequestMessage::EncapsulatedRequest { data: data.to_vec() }), - &Command::Ping => Ok(RequestMessage::Ping { data: data.to_vec() }), + &Command::Msg => Ok(RequestMessage::EncapsulatedRequest { + data: data.to_vec(), + }), + &Command::Ping => Ok(RequestMessage::Ping { + data: data.to_vec(), + }), &Command::Init => { if data.len() != 8 { Err(()) @@ -373,7 +377,9 @@ impl Response { #[derive(Debug)] pub enum ResponseMessage { - EncapsulatedResponse { data: Vec }, + EncapsulatedResponse { + data: Vec, + }, Init { nonce: [u8; 8], new_channel_id: ChannelId, @@ -383,8 +389,12 @@ pub enum ResponseMessage { build_device_version_number: u8, capabilities: CapabilityFlags, }, - Pong { data: Vec }, - Error { code: ErrorCode }, + Pong { + data: Vec, + }, + Error { + code: ErrorCode, + }, Wink, Lock, } @@ -409,7 +419,9 @@ impl slog::Value for ResponseMessage { impl From for ResponseMessage { fn from(response: u2f_core::Response) -> ResponseMessage { - ResponseMessage::EncapsulatedResponse { data: response.into_bytes() } + ResponseMessage::EncapsulatedResponse { + data: response.into_bytes(), + } } } diff --git a/u2fhid-protocol/src/lib.rs b/u2fhid-protocol/src/lib.rs index a77aa7b..7d78c3c 100644 --- a/u2fhid-protocol/src/lib.rs +++ b/u2fhid-protocol/src/lib.rs @@ -50,8 +50,7 @@ pub struct U2FHID { impl U2FHID where - T: Sink - + Stream, + T: Sink + Stream, { pub fn bind_service>>( handle: &Handle, @@ -59,10 +58,9 @@ where service: U2F, logger: L, ) -> U2FHID { - let logger = logger.into().unwrap_or(slog::Logger::root( - slog_stdlog::StdLog.fuse(), - o!(), - )); + let logger = logger + .into() + .unwrap_or(slog::Logger::root(slog_stdlog::StdLog.fuse(), o!())); let state_machine_logger = logger.new(o!()); U2FHID { logger: logger, @@ -74,18 +72,12 @@ where impl Future for U2FHID where - T: Sink - + Stream, + T: Sink + Stream, S: Service< Request = u2f_core::Request, Response = u2f_core::Response, Error = io::Error, - Future = Box< - Future< - Item = u2f_core::Response, - Error = io::Error, - >, - >, + Future = Box>, >, { type Item = (); @@ -132,11 +124,9 @@ where fn assert_send(s: &mut S, item: S::SinkItem) -> Result<(), S::SinkError> { match try!(s.start_send(item)) { AsyncSink::Ready => Ok(()), - AsyncSink::NotReady(_) => { - panic!( - "sink reported itself as ready after `poll_ready` but was \ - then unable to accept a message" - ) - } + AsyncSink::NotReady(_) => panic!( + "sink reported itself as ready after `poll_ready` but was \ + then unable to accept a message" + ), } } diff --git a/u2fhid-protocol/src/protocol_state_machine.rs b/u2fhid-protocol/src/protocol_state_machine.rs index 4696d4d..0aa1287 100644 --- a/u2fhid-protocol/src/protocol_state_machine.rs +++ b/u2fhid-protocol/src/protocol_state_machine.rs @@ -59,7 +59,9 @@ struct Channels { impl Channels { fn new() -> Channels { - Channels { next_allocation: MIN_CHANNEL_ID } + Channels { + next_allocation: MIN_CHANNEL_ID, + } } fn allocate(&mut self) -> Result { @@ -74,8 +76,8 @@ impl Channels { fn is_valid(&self, channel_id: ChannelId) -> bool { let is_broadcast = channel_id == BROADCAST_CHANNEL_ID; - let is_in_allocated_range = channel_id >= MIN_CHANNEL_ID && - channel_id < self.next_allocation; + let is_in_allocated_range = + channel_id >= MIN_CHANNEL_ID && channel_id < self.next_allocation; is_broadcast || is_in_allocated_range } } @@ -109,12 +111,12 @@ impl LockState { fn tick(&mut self) -> Result<(), io::Error> { // Check lock timeout let timed_out = match self { - &mut LockState::Locked { ref mut timeout, .. } => { - match timeout.poll()? { - Async::Ready(()) => true, - Async::NotReady => false, - } - } + &mut LockState::Locked { + ref mut timeout, .. + } => match timeout.poll()? { + Async::Ready(()) => true, + Async::NotReady => false, + }, _ => false, }; @@ -227,9 +229,10 @@ where let channel_id = packet.channel_id(); if !self.channels.is_valid(channel_id) { debug!(self.logger, "Invalid channel"; "id" => channel_id); - Ok(Some( - Self::error_output(ErrorCode::InvalidChannel, channel_id), - )) + Ok(Some(Self::error_output( + ErrorCode::InvalidChannel, + channel_id, + ))) } else { Ok(None) } @@ -254,13 +257,15 @@ where fn step_with_packet(&mut self, packet: Packet) -> Result, io::Error> { let transition = match (self.state.take(), packet) { - (State::Idle, - Packet::Initialization { - channel_id, - data, - payload_len, - command, - }) => { + ( + State::Idle, + Packet::Initialization { + channel_id, + data, + payload_len, + command, + }, + ) => { debug!(self.logger, "Begin transaction"; "channel_id" => &channel_id, "command" => &command, "payload_len" => payload_len); StateTransition { new_state: State::Receive(ReceiveState { @@ -303,23 +308,29 @@ where new_state: State::Receive(receive), output: Some(Response { channel_id: channel_id, - message: ResponseMessage::Error { code: ErrorCode::ChannelBusy }, + message: ResponseMessage::Error { + code: ErrorCode::ChannelBusy, + }, }), } } } - (State::Receive(mut receive), - Packet::Continuation { - channel_id, - sequence_number, - data, - }) => { + ( + State::Receive(mut receive), + Packet::Continuation { + channel_id, + sequence_number, + data, + }, + ) => { if channel_id != receive.channel_id { StateTransition { new_state: State::Receive(receive), output: Some(Response { channel_id: channel_id, - message: ResponseMessage::Error { code: ErrorCode::ChannelBusy }, + message: ResponseMessage::Error { + code: ErrorCode::ChannelBusy, + }, }), } } else if sequence_number != receive.next_sequence_number { @@ -362,10 +373,7 @@ where if receive.buffer.len() >= receive.payload_len { let bytes = &receive.buffer[0..receive.payload_len]; debug!(self.logger, "Received payload"; "len" => receive.payload_len, "bytes" => format!("0x{:02x}", bytes.iter().format(""))); - let message = RequestMessage::decode( - &receive.command, - bytes, - ).unwrap(); + let message = RequestMessage::decode(&receive.command, bytes).unwrap(); let response_future = self.handle_request(Request { channel_id: receive.channel_id, message: message, @@ -399,25 +407,19 @@ where fn try_complete_dispatch(&mut self) -> Result, io::Error> { let transition = match self.state.take() { - State::Dispatch(mut dispatch) => { - match dispatch.future.poll()? { - Async::Ready(response) => { - StateTransition { - new_state: State::Idle, - output: Some(Response { - channel_id: dispatch.channel_id, - message: response.into(), - }), - } - } - Async::NotReady => { - StateTransition { - new_state: State::Dispatch(dispatch), - output: None, - } - } - } - } + State::Dispatch(mut dispatch) => match dispatch.future.poll()? { + Async::Ready(response) => StateTransition { + new_state: State::Idle, + output: Some(Response { + channel_id: dispatch.channel_id, + message: response.into(), + }), + }, + Async::NotReady => StateTransition { + new_state: State::Dispatch(dispatch), + output: None, + }, + }, state => StateTransition { new_state: state, output: None, @@ -450,9 +452,9 @@ where RequestMessage::Init { nonce } => { // TODO Check what channnel message came in on // TODO check unwrap - let new_channel_id = self.channels.allocate().expect( - "Failed to allocate new channel", - ); + let new_channel_id = self.channels + .allocate() + .expect("Failed to allocate new channel"); debug!(self.logger, "RequestMessage::Init"; "new_channel_id" => new_channel_id); Ok(Box::new(future::ok(ResponseMessage::Init { nonce, @@ -561,13 +563,14 @@ mod tests { match res { Some(Response { - channel_id: response_channel_id, - message: ResponseMessage::Init { - new_channel_id, - nonce, - .. - }, - }) => { + channel_id: response_channel_id, + message: + ResponseMessage::Init { + new_channel_id, + nonce, + .. + }, + }) => { assert_eq!(response_channel_id, BROADCAST_CHANNEL_ID); assert_eq!(request_nonce, nonce); assert!(state_machine.channels.is_valid(new_channel_id)); @@ -600,9 +603,12 @@ mod tests { match res { Some(Response { - channel_id: response_channel_id, - message: ResponseMessage::Pong { data: response_data }, - }) => { + channel_id: response_channel_id, + message: + ResponseMessage::Pong { + data: response_data, + }, + }) => { assert_eq!(response_channel_id, channel_id); assert_eq!(response_data[..], ping_data); } diff --git a/u2fhid-protocol/src/segmenting_sink.rs b/u2fhid-protocol/src/segmenting_sink.rs index d27c28c..199be53 100644 --- a/u2fhid-protocol/src/segmenting_sink.rs +++ b/u2fhid-protocol/src/segmenting_sink.rs @@ -1,5 +1,5 @@ -use futures::{Poll, Async}; -use futures::{StartSend, AsyncSink}; +use futures::{Async, Poll}; +use futures::{AsyncSink, StartSend}; use futures::sink::Sink; use futures::stream::Stream; use futures::task::{self, Task}; diff --git a/uhid-linux-tokio/src/character_device.rs b/uhid-linux-tokio/src/character_device.rs index 72fc399..3d124df 100644 --- a/uhid-linux-tokio/src/character_device.rs +++ b/uhid-linux-tokio/src/character_device.rs @@ -131,9 +131,7 @@ where } Ok(n) => { if n != read_len { - return Err( - io::Error::new(io::ErrorKind::InvalidData, "short read").into(), - ); + return Err(io::Error::new(io::ErrorKind::InvalidData, "short read").into()); } let frame = self.decoder.decode(&mut BytesMut::from_buf(buffer))?; trace!(self.logger, "poll => Ok"; "frame" => &frame); @@ -165,19 +163,15 @@ where let bytes = buffer.take(); match self.inner.write(&bytes) { - Ok(0) => Err( - io::Error::new( - io::ErrorKind::WriteZero, - "failed to write item to transport", - ).into(), - ), + Ok(0) => Err(io::Error::new( + io::ErrorKind::WriteZero, + "failed to write item to transport", + ).into()), Ok(n) if n == bytes.len() => Ok(()), - Ok(_) => Err( - io::Error::new( - io::ErrorKind::Other, - "failed to write entire item to transport", - ).into(), - ), + Ok(_) => Err(io::Error::new( + io::ErrorKind::Other, + "failed to write entire item to transport", + ).into()), Err(e) => Err(e.into()), } } diff --git a/uhid-linux-tokio/src/lib.rs b/uhid-linux-tokio/src/lib.rs index 6ee73f8..cae8821 100644 --- a/uhid-linux-tokio/src/lib.rs +++ b/uhid-linux-tokio/src/lib.rs @@ -3,11 +3,11 @@ extern crate bitflags; extern crate bytes; #[macro_use] extern crate futures; -#[macro_use] -extern crate quick_error; extern crate mio; extern crate nix; #[macro_use] +extern crate quick_error; +#[macro_use] extern crate slog; extern crate slog_stdlog; extern crate tokio_core; diff --git a/uhid-linux-tokio/src/poll_evented_read_wrapper.rs b/uhid-linux-tokio/src/poll_evented_read_wrapper.rs index d240de5..79f3416 100644 --- a/uhid-linux-tokio/src/poll_evented_read_wrapper.rs +++ b/uhid-linux-tokio/src/poll_evented_read_wrapper.rs @@ -13,7 +13,7 @@ use futures::Async; use mio::event::Evented; use mio::Ready; use tokio_io::AsyncRead; -use tokio_core::reactor::{Handle, Remote, PollEvented}; +use tokio_core::reactor::{Handle, PollEvented, Remote}; /// A concrete implementation of a stream of readiness notifications for I/O /// objects that originates from an event loop. diff --git a/uhid-linux-tokio/src/uhid_codec.rs b/uhid-linux-tokio/src/uhid_codec.rs index 11eda06..3b37108 100644 --- a/uhid-linux-tokio/src/uhid_codec.rs +++ b/uhid-linux-tokio/src/uhid_codec.rs @@ -7,7 +7,7 @@ use std::slice; use bytes::BytesMut; use slog; -use character_device::{Encoder, Decoder}; +use character_device::{Decoder, Encoder}; use uhid_linux_sys as sys; quick_error! { @@ -86,17 +86,30 @@ pub enum InputEvent { data: Vec, }, Destroy, - Input { data: Vec }, - GetReportReply { id: u32, err: u16, data: Vec }, - SetReportReply { id: u32, err: u16 }, + Input { + data: Vec, + }, + GetReportReply { + id: u32, + err: u16, + data: Vec, + }, + SetReportReply { + id: u32, + err: u16, + }, } pub enum OutputEvent { - Start { dev_flags: DevFlags }, + Start { + dev_flags: DevFlags, + }, Stop, Open, Close, - Output { data: Vec }, + Output { + data: Vec, + }, GetReport { id: u32, report_number: u8, @@ -201,9 +214,9 @@ fn copy_bytes_sized(src: Vec, dst: &mut [u8]) -> Result return Err(StreamError::BufferOverflow(src_size, dst_size)); } - dst.get_mut(0..src_size).unwrap().copy_from_slice( - src.as_slice(), - ); + dst.get_mut(0..src_size) + .unwrap() + .copy_from_slice(src.as_slice()); Ok(src_size) } @@ -226,7 +239,9 @@ fn decode_event(event: sys::uhid_event) -> Result { match event_type { sys::uhid_event_type::UHID_START => Ok(unsafe { let payload = event.u.start.as_ref(); - OutputEvent::Start { dev_flags: mem::transmute(payload.dev_flags) } + OutputEvent::Start { + dev_flags: mem::transmute(payload.dev_flags), + } }), sys::uhid_event_type::UHID_STOP => Ok(OutputEvent::Stop), sys::uhid_event_type::UHID_OPEN => Ok(OutputEvent::Open), @@ -285,9 +300,7 @@ fn read_event(src: &mut BytesMut) -> Option { if src.len() >= uhid_event_size { let bytes = src.split_to(uhid_event_size); let ptr = bytes.as_ptr(); - Some(unsafe { - *mem::transmute::<*const u8, &sys::uhid_event>(ptr) - }) + Some(unsafe { *mem::transmute::<*const u8, &sys::uhid_event>(ptr) }) } else { None } diff --git a/uhid-linux-tokio/src/uhid_device.rs b/uhid-linux-tokio/src/uhid_device.rs index 5c75777..2e990ed 100644 --- a/uhid-linux-tokio/src/uhid_device.rs +++ b/uhid-linux-tokio/src/uhid_device.rs @@ -3,7 +3,7 @@ use std::io::{self, Write}; use std::os::unix::io::FromRawFd; use std::path::Path; -use futures::{Async, AsyncSink, Stream, Sink, Poll, StartSend}; +use futures::{Async, AsyncSink, Poll, Sink, StartSend, Stream}; use nix; use nix::fcntl; use slog_stdlog; @@ -14,7 +14,7 @@ use tokio_io::AsyncRead; use poll_evented_read_wrapper::PollEventedRead; use character_device_file::CharacterDeviceFile; -use character_device::{Encoder, Decoder, CharacterDevice, SyncSink}; +use character_device::{CharacterDevice, Decoder, Encoder, SyncSink}; use uhid_codec::*; pub struct UHIDDevice { @@ -54,8 +54,8 @@ impl UHIDDevice>> { let fd = fcntl::open( path, fcntl::O_RDWR | fcntl::O_CLOEXEC | fcntl::O_NONBLOCK, - nix::sys::stat::S_IRUSR | nix::sys::stat::S_IWUSR | nix::sys::stat::S_IRGRP | - nix::sys::stat::S_IWGRP, + nix::sys::stat::S_IRUSR | nix::sys::stat::S_IWUSR | nix::sys::stat::S_IRGRP + | nix::sys::stat::S_IWGRP, ).map_err(|err| { io::Error::new( io::ErrorKind::Other, @@ -81,10 +81,9 @@ where params: CreateParams, logger: L, ) -> UHIDDevice { - let logger = logger.into().unwrap_or(slog::Logger::root( - slog_stdlog::StdLog.fuse(), - o!(), - )); + let logger = logger + .into() + .unwrap_or(slog::Logger::root(slog_stdlog::StdLog.fuse(), o!())); let mut device = UHIDDevice { inner: CharacterDevice::new(inner, UHIDCodec, UHIDCodec, logger.new(o!())), logger: logger, @@ -110,7 +109,9 @@ where pub fn send_input(&mut self, data: &[u8]) -> Result<(), ::Error> { trace!(self.logger, "Send input event"); - self.inner.send(InputEvent::Input { data: data.to_vec() }) + self.inner.send(InputEvent::Input { + data: data.to_vec(), + }) } pub fn destory(mut self) -> Result<(), ::Error> { diff --git a/user-daemon/src/file_storage.rs b/user-daemon/src/file_storage.rs index 28a12cd..e40ea36 100644 --- a/user-daemon/src/file_storage.rs +++ b/user-daemon/src/file_storage.rs @@ -57,10 +57,10 @@ impl SecretStore for FileStorage { &self, key: &ApplicationKey, ) -> Box> { - self.store.borrow_mut().application_keys.insert( - key.application, - key.clone(), - ); + self.store + .borrow_mut() + .application_keys + .insert(key.application, key.clone()); Box::new(self.save().into_future()) } @@ -121,9 +121,10 @@ where tmp_path.set_extension(new_ext); { - let file = OpenOptions::new().write(true).create_new(true).open( - &tmp_path, - )?; + let file = OpenOptions::new() + .write(true) + .create_new(true) + .open(&tmp_path)?; writer_fn(Box::new(file.try_clone()?))?; file.sync_all()?; } diff --git a/user-daemon/src/main.rs b/user-daemon/src/main.rs index 6cfa6b5..84a5d02 100644 --- a/user-daemon/src/main.rs +++ b/user-daemon/src/main.rs @@ -5,8 +5,8 @@ extern crate serde_derive; #[macro_use] extern crate slog; -extern crate futures_cpupool; extern crate futures; +extern crate futures_cpupool; extern crate notify_rust; extern crate serde_json; extern crate slog_term; @@ -41,18 +41,16 @@ use user_presence::NotificationUserPresence; fn socket_output_to_packet(output_event: SocketOutput) -> Option { match output_event { - SocketOutput::Packet(raw_packet) => Some( - Packet::from_bytes(&raw_packet.into_bytes()).unwrap(), - ), + SocketOutput::Packet(raw_packet) => { + Some(Packet::from_bytes(&raw_packet.into_bytes()).unwrap()) + } _ => None, } } fn packet_to_socket_input(packet: Packet) -> Box> { Box::new(future::ok(SocketInput::Packet( - softu2f_system_daemon::Packet::from_bytes( - &packet.into_bytes(), - ), + softu2f_system_daemon::Packet::from_bytes(&packet.into_bytes()), ))) } @@ -87,52 +85,49 @@ fn run(logger: Logger) -> io::Result<()> { .send(SocketInput::CreateDeviceRequest(create_device_request)) .and_then(|socket| { info!(logger, "Sent create device request"); - socket.into_future().then(|res| -> Box< - Future< - Item = (), - Error = io::Error, - >, - > { - let (response, socket) = match res { - Ok((response, socket)) => (response, socket), - Err((err, _socket)) => { - // TODO close socket and any clean up - return Box::new(future::err(err)); - } - }; - - info!(logger, "Got response"; "response" => &response); - match response { - Some(SocketOutput::CreateDeviceResponse(create_response)) => { - create_response - } - _ => { - return Box::new(future::err(io::Error::new( - io::ErrorKind::Other, - "Expected create device response", - ))) - } - }; - - let transport = socket.filter_map(socket_output_to_packet).with( - packet_to_socket_input, - ); - - let attestation = u2f_core::self_signed_attestation(); - let user_presence = - Box::new(NotificationUserPresence::new(&handle, logger.new(o!()))); - let operations = Box::new(SecureCryptoOperations::new(attestation)); - let storage = Box::new(FileStorage::new(store_path).unwrap()); - - let service = U2F::new(user_presence, operations, storage, logger.new(o!())) - .unwrap(); - Box::new(U2FHID::bind_service( - &handle, - transport, - service, - logger.new(o!()), - )) - }) + socket + .into_future() + .then(|res| -> Box> { + let (response, socket) = match res { + Ok((response, socket)) => (response, socket), + Err((err, _socket)) => { + // TODO close socket and any clean up + return Box::new(future::err(err)); + } + }; + + info!(logger, "Got response"; "response" => &response); + match response { + Some(SocketOutput::CreateDeviceResponse(create_response)) => { + create_response + } + _ => { + return Box::new(future::err(io::Error::new( + io::ErrorKind::Other, + "Expected create device response", + ))) + } + }; + + let transport = socket + .filter_map(socket_output_to_packet) + .with(packet_to_socket_input); + + let attestation = u2f_core::self_signed_attestation(); + let user_presence = + Box::new(NotificationUserPresence::new(&handle, logger.new(o!()))); + let operations = Box::new(SecureCryptoOperations::new(attestation)); + let storage = Box::new(FileStorage::new(store_path).unwrap()); + + let service = + U2F::new(user_presence, operations, storage, logger.new(o!())).unwrap(); + Box::new(U2FHID::bind_service( + &handle, + transport, + service, + logger.new(o!()), + )) + }) }), )?; diff --git a/user-daemon/src/user_presence.rs b/user-daemon/src/user_presence.rs index 831e643..2a0b629 100644 --- a/user-daemon/src/user_presence.rs +++ b/user-daemon/src/user_presence.rs @@ -7,7 +7,7 @@ use notify_rust::{Notification, NotificationHint, NotificationUrgency}; use slog::Logger; use time::Duration; use tokio_core::reactor::Handle; -use u2f_core::{ApplicationParameter, UserPresence, try_reverse_application_id}; +use u2f_core::{try_reverse_application_id, ApplicationParameter, UserPresence}; // TODO this hardcoded keyword should be in the notifcation library const NOTIFICATION_CLOSE_ACTION: &str = "__closed"; @@ -56,15 +56,15 @@ impl NotificationUserPresence { let logger_clone_close = logger_clone.clone(); handle.wait_for_action(|action| match action { - "approve" => res = true, - "deny" => res = false, - "default" => res = false, - NOTIFICATION_CLOSE_ACTION => { - info!(logger_clone_close, "The notification was closed"); - res = false; - } - _ => unreachable!("Unknown action taken on notification"), - }); + "approve" => res = true, + "deny" => res = false, + "default" => res = false, + NOTIFICATION_CLOSE_ACTION => { + info!(logger_clone_close, "The notification was closed"); + res = false; + } + _ => unreachable!("Unknown action taken on notification"), + }); info!(logger_clone, "test_user_presence"; "result" => res);