Skip to content

Commit

Permalink
Formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
danstiner committed Jan 4, 2018
1 parent d6b9baa commit 34a5b6b
Show file tree
Hide file tree
Showing 21 changed files with 433 additions and 366 deletions.
27 changes: 16 additions & 11 deletions softu2f-bin/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;

Expand Down Expand Up @@ -83,7 +83,9 @@ fn output_to_packet(output_event: OutputEvent) -> Option<Packet> {
}

fn packet_to_input(packet: Packet) -> Box<Future<Item = InputEvent, Error = StreamError>> {
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 {
Expand Down Expand Up @@ -125,10 +127,7 @@ fn pre_sudo_env() -> Option<PreSudoEnvironment> {
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 },
})
}

Expand All @@ -137,7 +136,7 @@ fn pre_sudo_env() -> Option<PreSudoEnvironment> {
Err(_) => {
eprintln!("Usage: sudo --preserve-env {}", program_name());
None
},
}
}
}

Expand All @@ -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();
Expand All @@ -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!()));
Expand Down
21 changes: 13 additions & 8 deletions softu2f-bin/src/user_file_storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,11 @@ pub struct UserFileStorage {
}

impl UserFileStorage {
pub fn new(path: PathBuf, security_ids: SecurityIds, logger: Logger) -> io::Result<UserFileStorage> {
pub fn new(
path: PathBuf,
security_ids: SecurityIds,
logger: Logger,
) -> io::Result<UserFileStorage> {
let store = Self::load_store(&path, security_ids)?;
Ok(UserFileStorage {
logger: logger,
Expand Down Expand Up @@ -70,10 +74,10 @@ impl SecretStore for UserFileStorage {
&self,
key: &ApplicationKey,
) -> Box<Future<Item = (), Error = io::Error>> {
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())
}
Expand Down Expand Up @@ -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()?;
}
Expand Down
11 changes: 6 additions & 5 deletions softu2f-bin/src/user_presence.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
})
}),
)
}
}
Expand Down
28 changes: 14 additions & 14 deletions softu2f-test-user-presence/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -44,17 +44,17 @@ fn notify(parameters: UserPresenceTestParameters) -> io::Result<bool> {
.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)
}
Expand All @@ -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::<bool, UserPresenceTestParameters>(&handle)
.unwrap();
Expand Down
8 changes: 4 additions & 4 deletions system-daemon/src/bidirectional_pipe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()),
};
Expand All @@ -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);
}
}
}
Expand Down
15 changes: 12 additions & 3 deletions system-daemon/src/definitions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}
}
Expand Down Expand Up @@ -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<u8> {
self.bytes
Expand Down
85 changes: 47 additions & 38 deletions system-daemon/src/device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Pipe<Item = Packet, Error = io::Error, SinkItem = Packet, SinkError = io::Error>>;

type SocketPipe = Box<
Pipe<
Item = SocketInput,
Error = io::Error,
SinkItem = SocketOutput,
SinkError = io::Error,
>,
Pipe<Item = SocketInput, Error = io::Error, SinkItem = SocketOutput, SinkError = io::Error>,
>;

trait Pipe: Stream + Sink {}
Expand Down Expand Up @@ -101,7 +107,10 @@ fn initialize(
handle: &Handle,
logger: &Logger,
_request: CreateDeviceRequest,
) -> (Box<Future<Item = SocketPipe, Error = io::Error>>, PacketPipe) {
) -> (
Box<Future<Item = SocketPipe, Error = io::Error>>,
PacketPipe,
) {
info!(logger, "initialize");
let create_params = CreateParams {
name: String::from("SoftU2F-Linux"),
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -168,7 +175,9 @@ fn into_transport<T: AsyncRead + Write + 'static>(device: UHIDDevice<T>) -> 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),
Expand Down Expand Up @@ -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),
Expand Down
Loading

0 comments on commit 34a5b6b

Please sign in to comment.