diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/bin/roughenough-client.rs | 7 | ||||
-rw-r--r-- | src/bin/roughenough-kms.rs | 2 | ||||
-rw-r--r-- | src/bin/roughenough-server.rs | 36 | ||||
-rw-r--r-- | src/config/environment.rs | 2 | ||||
-rw-r--r-- | src/config/file.rs | 7 | ||||
-rw-r--r-- | src/config/memory.rs | 10 | ||||
-rw-r--r-- | src/config/mod.rs | 15 | ||||
-rw-r--r-- | src/key/mod.rs | 1 | ||||
-rw-r--r-- | src/kms/awskms.rs | 1 | ||||
-rw-r--r-- | src/kms/envelope.rs | 9 | ||||
-rw-r--r-- | src/kms/gcpkms.rs | 12 | ||||
-rw-r--r-- | src/kms/mod.rs | 2 | ||||
-rw-r--r-- | src/lib.rs | 4 | ||||
-rw-r--r-- | src/server.rs | 65 |
14 files changed, 98 insertions, 75 deletions
diff --git a/src/bin/roughenough-client.rs b/src/bin/roughenough-client.rs index e1122b4..570dc47 100644 --- a/src/bin/roughenough-client.rs +++ b/src/bin/roughenough-client.rs @@ -27,9 +27,9 @@ use byteorder::{LittleEndian, ReadBytesExt}; use chrono::offset::Utc; use chrono::TimeZone; +use std::collections::HashMap; use std::fs::File; use std::io::Write; -use std::collections::HashMap; use std::iter::Iterator; use std::net::{ToSocketAddrs, UdpSocket}; @@ -273,13 +273,14 @@ fn main() { } let mut requests = Vec::with_capacity(num_requests); - let mut file = out.map(|o | File::create(o).expect("Failed to create file!")); + let mut file = out.map(|o| File::create(o).expect("Failed to create file!")); for _ in 0..num_requests { let nonce = create_nonce(); let mut socket = UdpSocket::bind("0.0.0.0:0").expect("Couldn't open UDP socket"); let request = make_request(&nonce); - file.as_mut().map(|f| f.write_all(&request).expect("Failed to write to file!")); + file.as_mut() + .map(|f| f.write_all(&request).expect("Failed to write to file!")); requests.push((nonce, request, socket)); } diff --git a/src/bin/roughenough-kms.rs b/src/bin/roughenough-kms.rs index 6563224..1cea22e 100644 --- a/src/bin/roughenough-kms.rs +++ b/src/bin/roughenough-kms.rs @@ -30,8 +30,8 @@ use roughenough::VERSION; #[cfg(feature = "awskms")] fn aws_kms(kms_key: &str, plaintext_seed: &[u8]) { - use roughenough::kms::EnvelopeEncryption; use roughenough::kms::AwsKms; + use roughenough::kms::EnvelopeEncryption; let client = AwsKms::from_arn(kms_key).unwrap(); diff --git a/src/bin/roughenough-server.rs b/src/bin/roughenough-server.rs index 39ef26f..6c6a118 100644 --- a/src/bin/roughenough-server.rs +++ b/src/bin/roughenough-server.rs @@ -44,13 +44,10 @@ use std::env; use std::process; use std::sync::atomic::Ordering; - use roughenough::config; use roughenough::config::ServerConfig; -use roughenough::VERSION; use roughenough::server::Server; - - +use roughenough::VERSION; macro_rules! check_ctrlc { ($keep_running:expr) => { @@ -58,22 +55,27 @@ macro_rules! check_ctrlc { warn!("Ctrl-C caught, exiting..."); return; } - } + }; } - - - - fn polling_loop(config: Box<ServerConfig>) { let mut server = Server::new(config); info!("Long-term public key : {}", server.get_public_key()); info!("Online public key : {}", server.get_online_key()); - info!("Max response batch size : {}", server.get_config().batch_size()); - info!("Status updates every : {} seconds", server.get_config().status_interval().as_secs()); - info!("Server listening on : {}:{}", server.get_config().interface(), server.get_config().port()); - + info!( + "Max response batch size : {}", + server.get_config().batch_size() + ); + info!( + "Status updates every : {} seconds", + server.get_config().status_interval().as_secs() + ); + info!( + "Server listening on : {}:{}", + server.get_config().interface(), + server.get_config().port() + ); let kr = server.get_keep_running(); let kr_new = kr.clone(); @@ -81,13 +83,11 @@ fn polling_loop(config: Box<ServerConfig>) { ctrlc::set_handler(move || kr.store(false, Ordering::Release)) .expect("failed setting Ctrl-C handler"); - loop { check_ctrlc!(kr_new); if server.process_events() { return; } - } } @@ -106,7 +106,11 @@ pub fn main() { simple_logger::init_with_level(Level::Info).unwrap(); - info!("Roughenough server v{}{} starting", VERSION, kms_support_str()); + info!( + "Roughenough server v{}{} starting", + VERSION, + kms_support_str() + ); let mut args = env::args(); if args.len() != 2 { diff --git a/src/config/environment.rs b/src/config/environment.rs index 533f5c0..5edb6d0 100644 --- a/src/config/environment.rs +++ b/src/config/environment.rs @@ -19,8 +19,8 @@ use std::time::Duration; use config::ServerConfig; use config::{DEFAULT_BATCH_SIZE, DEFAULT_STATUS_INTERVAL}; -use Error; use key::KeyProtection; +use Error; /// /// Obtain a Roughenough server configuration ([ServerConfig](trait.ServerConfig.html)) diff --git a/src/config/file.rs b/src/config/file.rs index bef0f1e..b0f8b4d 100644 --- a/src/config/file.rs +++ b/src/config/file.rs @@ -21,8 +21,8 @@ use yaml_rust::YamlLoader; use config::ServerConfig; use config::{DEFAULT_BATCH_SIZE, DEFAULT_STATUS_INTERVAL}; -use Error; use key::KeyProtection; +use Error; /// /// Read a Roughenough server configuration ([ServerConfig](trait.ServerConfig.html)) @@ -86,7 +86,9 @@ impl FileConfig { config.status_interval = Duration::from_secs(val as u64) } "key_protection" => { - let val = value.as_str().unwrap() + let val = value + .as_str() + .unwrap() .parse() .expect(format!("invalid key_protection value: {:?}", value).as_ref()); config.key_protection = val @@ -125,7 +127,6 @@ impl ServerConfig for FileConfig { self.status_interval } - fn key_protection(&self) -> &KeyProtection { &self.key_protection } diff --git a/src/config/memory.rs b/src/config/memory.rs index 6f35532..1227075 100644 --- a/src/config/memory.rs +++ b/src/config/memory.rs @@ -1,11 +1,10 @@ -use std::time::Duration; use config::ServerConfig; use config::{DEFAULT_BATCH_SIZE, DEFAULT_STATUS_INTERVAL}; use key::KeyProtection; +use std::time::Duration; use hex; - /// A purely in-memory Roughenough config /// This is useful for fuzzing a server without the need /// to create additioanl files. @@ -15,7 +14,7 @@ pub struct MemoryConfig { pub seed: Vec<u8>, pub batch_size: u8, pub status_interval: Duration, - pub key_protection: KeyProtection + pub key_protection: KeyProtection, } impl MemoryConfig { @@ -23,10 +22,11 @@ impl MemoryConfig { MemoryConfig { port, interface: "127.0.0.1".to_string(), - seed: hex::decode("a32049da0ffde0ded92ce10a0230d35fe615ec8461c14986baa63fe3b3bac3db").unwrap(), + seed: hex::decode("a32049da0ffde0ded92ce10a0230d35fe615ec8461c14986baa63fe3b3bac3db") + .unwrap(), batch_size: DEFAULT_BATCH_SIZE, status_interval: DEFAULT_STATUS_INTERVAL, - key_protection: KeyProtection::Plaintext + key_protection: KeyProtection::Plaintext, } } } diff --git a/src/config/mod.rs b/src/config/mod.rs index 658669a..772e1ee 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -37,8 +37,8 @@ pub use self::environment::EnvironmentConfig; mod memory; pub use self::memory::MemoryConfig; -use Error; use key::KeyProtection; +use Error; /// Maximum number of requests to process in one batch and include the the Merkle tree. pub const DEFAULT_BATCH_SIZE: u8 = 64; @@ -98,7 +98,6 @@ pub trait ServerConfig { Ok(v) => Ok(v), Err(_) => Err(Error::InvalidConfiguration(addr)), } - } } @@ -145,14 +144,22 @@ pub fn is_valid_config(cfg: &Box<ServerConfig>) -> bool { is_valid = false; } if cfg.batch_size() < 1 || cfg.batch_size() > 64 { - error!("batch_size {} is invalid; valid range 1-64", cfg.batch_size()); + error!( + "batch_size {} is invalid; valid range 1-64", + cfg.batch_size() + ); is_valid = false; } if is_valid { match cfg.socket_addr() { Err(e) => { - error!("failed to create socket {}:{} {:?}", cfg.interface(), cfg.port(), e); + error!( + "failed to create socket {}:{} {:?}", + cfg.interface(), + cfg.port(), + e + ); is_valid = false; } _ => (), diff --git a/src/key/mod.rs b/src/key/mod.rs index 32ca241..6bb3eb5 100644 --- a/src/key/mod.rs +++ b/src/key/mod.rs @@ -66,4 +66,3 @@ impl FromStr for KeyProtection { } } } - diff --git a/src/kms/awskms.rs b/src/kms/awskms.rs index 96d4a38..14f0804 100644 --- a/src/kms/awskms.rs +++ b/src/kms/awskms.rs @@ -121,4 +121,3 @@ pub mod inner { } } } - diff --git a/src/kms/envelope.rs b/src/kms/envelope.rs index 1f6d615..da75961 100644 --- a/src/kms/envelope.rs +++ b/src/kms/envelope.rs @@ -73,7 +73,6 @@ fn vec_zero_filled(len: usize) -> Vec<u8> { pub struct EnvelopeEncryption; impl EnvelopeEncryption { - /// Decrypt a seed previously encrypted with `encrypt_seed()` pub fn decrypt_seed(kms: &KmsProvider, ciphertext_blob: &[u8]) -> Result<Vec<u8>, KmsError> { if ciphertext_blob.len() < MIN_PAYLOAD_SIZE { @@ -107,7 +106,13 @@ impl EnvelopeEncryption { // Decrypt the seed value using the DEK let dek_open_key = OpeningKey::new(&AES_256_GCM, &dek)?; - match open_in_place(&dek_open_key, &nonce, AD, IN_PREFIX_LEN, &mut encrypted_seed) { + match open_in_place( + &dek_open_key, + &nonce, + AD, + IN_PREFIX_LEN, + &mut encrypted_seed, + ) { Ok(plaintext_seed) => Ok(plaintext_seed.to_vec()), Err(_) => Err(KmsError::OperationFailed( "failed to decrypt plaintext seed".to_string(), diff --git a/src/kms/gcpkms.rs b/src/kms/gcpkms.rs index c0fbb5d..13303db 100644 --- a/src/kms/gcpkms.rs +++ b/src/kms/gcpkms.rs @@ -19,14 +19,16 @@ extern crate log; pub mod inner { extern crate base64; + extern crate google_cloudkms1 as cloudkms1; extern crate hyper; extern crate hyper_rustls; extern crate yup_oauth2 as oauth2; - extern crate google_cloudkms1 as cloudkms1; + use std::fmt; use std::env; use std::fmt::Formatter; + use std::result::Result; use std::str::FromStr; use std::result::Result; use std::default::Default; @@ -34,13 +36,15 @@ pub mod inner { use std::path::Path; use std::time::Duration; - use self::oauth2::{service_account_key_from_file, ServiceAccountAccess, ServiceAccountKey}; use self::cloudkms1::CloudKMS; - use self::cloudkms1::{Result as CloudKmsResult, Error as CloudKmsError, EncryptRequest, DecryptRequest}; + use self::cloudkms1::{ + DecryptRequest, EncryptRequest, Error as CloudKmsError, Result as CloudKmsResult, + }; use self::hyper::net::HttpsConnector; use self::hyper::header::Headers; use self::hyper::status::StatusCode; use self::hyper_rustls::TlsClient; + use self::oauth2::{service_account_key_from_file, ServiceAccountAccess, ServiceAccountKey}; use kms::{EncryptedDEK, KmsError, KmsProvider, PlaintextDEK}; @@ -156,5 +160,3 @@ pub mod inner { panic!("Failed to load service account credential. Is GOOGLE_APPLICATION_CREDENTIALS set?"); } } - - diff --git a/src/kms/mod.rs b/src/kms/mod.rs index 810623a..56e7631 100644 --- a/src/kms/mod.rs +++ b/src/kms/mod.rs @@ -52,9 +52,9 @@ mod envelope; use base64; +use ring; use std; use std::error::Error; -use ring; use config::ServerConfig; use error; @@ -59,14 +59,16 @@ extern crate base64; extern crate byteorder; -extern crate hex; extern crate core; extern crate time; extern crate yaml_rust; #[macro_use] extern crate hyper; +extern crate hex; extern crate mio; extern crate mio_extras; +extern crate time; +extern crate yaml_rust; #[macro_use] extern crate log; diff --git a/src/server.rs b/src/server.rs index e195d19..caf33af 100644 --- a/src/server.rs +++ b/src/server.rs @@ -1,25 +1,23 @@ +use hex; use std::io::ErrorKind; +use std::net::SocketAddr; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::Arc; use std::time::Duration; -use std::net::SocketAddr; -use hex; use time; use byteorder::{LittleEndian, WriteBytesExt}; - use mio::net::UdpSocket; use mio::{Events, Poll, PollOpt, Ready, Token}; use mio_extras::timer::Timer; use config::ServerConfig; -use kms; use key::{LongTermKey, OnlineKey}; +use kms; use merkle::MerkleTree; -use {Error, RtMessage, Tag}; use MIN_REQUEST_LENGTH; - +use {Error, RtMessage, Tag}; macro_rules! check_ctrlc { ($keep_running:expr) => { @@ -27,14 +25,12 @@ macro_rules! check_ctrlc { warn!("Ctrl-C caught, exiting..."); return true; } - } + }; } const MESSAGE: Token = Token(0); const STATUS: Token = Token(1); - - /// The main server instance. /// A Server is initialiezd from a Server Config /// and processes incoming messages in @@ -66,7 +62,6 @@ pub struct Server { impl Server { pub fn new(config: Box<ServerConfig>) -> Server { - let online_key = OnlineKey::new(); let public_key: String; @@ -98,7 +93,6 @@ impl Server { let merkle = MerkleTree::new(); let requests = Vec::with_capacity(config.batch_size() as usize); - Server { config, online_key, @@ -118,18 +112,15 @@ impl Server { public_key, - #[cfg(fuzzing)] - fake_client_socket: UdpSocket::bind(&"127.0.0.1:0".parse().unwrap()).unwrap() + fake_client_socket: UdpSocket::bind(&"127.0.0.1:0".parse().unwrap()).unwrap(), } - } pub fn get_keep_running(&self) -> Arc<AtomicBool> { - return self.keep_running.clone() + return self.keep_running.clone(); } - // extract the client's nonce from its request fn nonce_from_request<'a>(&self, buf: &'a [u8], num_bytes: usize) -> Result<&'a [u8], Error> { if num_bytes < MIN_REQUEST_LENGTH as usize { @@ -151,7 +142,13 @@ impl Server { } } - fn make_response(&self, srep: &RtMessage, cert_bytes: &[u8], path: &[u8], idx: u32) -> RtMessage { + fn make_response( + &self, + srep: &RtMessage, + cert_bytes: &[u8], + path: &[u8], + idx: u32, + ) -> RtMessage { let mut index = [0; 4]; (&mut index as &mut [u8]) .write_u32::<LittleEndian>(idx) @@ -175,7 +172,9 @@ impl Server { /// to process requests. It returns 'true' when the server /// has shutdown (due to keep_running being set to 'false') pub fn process_events(&mut self) -> bool { - self.poll.poll(&mut self.events, self.poll_duration).expect("poll failed"); + self.poll + .poll(&mut self.events, self.poll_duration) + .expect("poll failed"); for event in self.events.iter() { match event.token() { @@ -185,7 +184,6 @@ impl Server { 'process_batch: loop { check_ctrlc!(self.keep_running); - let resp_start = self.response_counter.load(Ordering::SeqCst); for i in 0..self.config.batch_size() { @@ -195,17 +193,17 @@ impl Server { Ok(nonce) => { self.requests.push((Vec::from(nonce), src_addr)); self.merkle.push_leaf(nonce); - }, + } Err(e) => { - self.num_bad_requests += 1; + self.num_bad_requests += 1; - info!( + info!( "Invalid request: '{:?}' ({} bytes) from {} (#{} in batch, resp #{})", e, num_bytes, src_addr, i, resp_start + i as usize ); } } - }, + } Err(e) => match e.kind() { ErrorKind::WouldBlock => { done = true; @@ -233,13 +231,16 @@ impl Server { for (i, &(ref nonce, ref src_addr)) in self.requests.iter().enumerate() { let paths = self.merkle.get_paths(i); - let resp = self.make_response(&srep, &self.cert_bytes, &paths, i as u32); + let resp = + self.make_response(&srep, &self.cert_bytes, &paths, i as u32); let resp_bytes = resp.encode().unwrap(); - let bytes_sent = self.socket + let bytes_sent = self + .socket .send_to(&resp_bytes, &src_addr) .expect("send_to failed"); - let num_responses = self.response_counter.fetch_add(1, Ordering::SeqCst); + let num_responses = + self.response_counter.fetch_add(1, Ordering::SeqCst); info!( "Responded {} bytes to {} for '{}..' (#{} in batch, resp #{})", @@ -278,21 +279,23 @@ impl Server { #[cfg(fuzzing)] pub fn send_to_self(&mut self, data: &[u8]) { - self.response_counter.store(0, Ordering::SeqCst);; + self.response_counter.store(0, Ordering::SeqCst);; self.num_bad_requests = 0; - let res = self.fake_client_socket.send_to(data, &self.socket.local_addr().unwrap()); + let res = self + .fake_client_socket + .send_to(data, &self.socket.local_addr().unwrap()); info!("Sent to self: {:?}", res); } pub fn get_public_key(&self) -> &str { - return &self.public_key + return &self.public_key; } pub fn get_online_key(&self) -> &OnlineKey { - return &self.online_key + return &self.online_key; } pub fn get_config(&self) -> &Box<ServerConfig> { - return &self.config + return &self.config; } } |