diff --git a/Cargo.lock b/Cargo.lock index ee5ccbe3d..acd31e324 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -994,6 +994,21 @@ dependencies = [ "xous-names", ] +[[package]] +name = "keys" +version = "0.1.0" +dependencies = [ + "log", + "log-server", + "num-derive", + "num-traits", + "susres", + "ticktimer-server", + "utralib", + "xous", + "xous-names", +] + [[package]] name = "lazy_static" version = "1.4.0" diff --git a/Cargo.toml b/Cargo.toml index 5b7bb434e..bc2805235 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,6 +29,7 @@ default-members = [ "services/aes", "services/test-stub", "services/spinor", + "services/keys", ] members = [ "xous-ipc", @@ -71,6 +72,7 @@ members = [ "services/aes", "services/test-stub", "services/spinor", + "services/keys", ] resolver = "2" diff --git a/services/keys/Cargo.toml b/services/keys/Cargo.toml new file mode 100644 index 000000000..4447c1f3c --- /dev/null +++ b/services/keys/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "keys" +version = "0.1.0" +authors = ["bunnie "] +edition = "2018" +description = "Xous keys server" + +[dependencies] +xous = { path = "../../xous-rs" } +log-server = { path = "../log-server" } +ticktimer-server = { path = "../ticktimer-server" } +xous-names = { path = "../xous-names" } +log = "0.4" +num-derive = {version = "0.3", default-features = false} +num-traits = {version = "0.2", default-features = false} +susres = {path = "../susres"} + +[target.'cfg(not(any(windows,unix)))'.dependencies] +utralib = { path = "../../utralib"} + +[features] +default = [] diff --git a/services/keys/README.md b/services/keys/README.md index 6e3e783ca..345f29df8 100644 --- a/services/keys/README.md +++ b/services/keys/README.md @@ -33,10 +33,12 @@ This server, `keys`, has the following responsibilities: - decrypt requested data - sign a data block - It communicates with the TRNG to provision and create keys if the KEYROM is initially blank + - It communicates with `xous_names` to confirm that the system has fully booted and that all servers with limited connection slots have their connections filled prior to allowing any sensitive operations. - Manages the state of the two unlock passwords for the KEYROM - Boot PIN code: secures the root application keys - Update passphrase: secures updates - The passwords are prompted automatically by `keys` as a result of third-party API calls requesting services of `keys` that would require their entry. + - Passwords are hashed with `bcrypt` prior to use. In line with [OWASP](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html) reccommendations, we opt to use the older, battle-tested `bcrypt` algorithm because the limited memory of Precursor does not allow us to use other algorithms with parameters that impart substial security advantages. - The passwords are entered via simple pop-up modal dialog boxes that plug directly into the `keys` memory space - Listens to the susres server to enforce password retirement policies - Plaintext copies of the password are mapped into a deliberate page of memory that is zero-ized on `Drop`, `suspend`, or other system states depending upon user policy. @@ -53,3 +55,9 @@ This server, `keys`, has the following responsibilities: - Validates the staged gateware for integrity (decrypt & HMAC check) - Copies the prepared gateware to the "live" location, once validated - Generates & writes self-signing loader and xous signatures + +Shortcomings: + - Anyone can attempt to initiate an update by calling the library API on `keys`. However, the update can not proceed without user consent via password. + - Fonts are mapped into the `gfx-server` memory space, which complicates loader.bin verification and validation. It also creates a potential for exploits that swap out fonts to create false messagse to users. + - There's a lot of complexity in this server, which makes it harder to analyze; see "Background" section above, for a discussion of the trade-offs that lead to this decision. + diff --git a/services/keys/src/api.rs b/services/keys/src/api.rs new file mode 100644 index 000000000..e8491722a --- /dev/null +++ b/services/keys/src/api.rs @@ -0,0 +1,10 @@ +pub(crate) const SERVER_NAME_KEYS: &str = "_Root key server and update manager_"; + +#[allow(dead_code)] +#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)] +pub(crate) enum Opcode { + + + /// Suspend/resume callback + SuspendResume, +} diff --git a/services/keys/src/lib.rs b/services/keys/src/lib.rs new file mode 100644 index 000000000..412f296b6 --- /dev/null +++ b/services/keys/src/lib.rs @@ -0,0 +1,33 @@ +#![cfg_attr(target_os = "none", no_std)] + +pub mod api; +use xous::{CID, send_message}; +use num_traits::ToPrimitive; + +pub struct Keys { + conn: CID, +} +impl Keys { + pub fn new(xns: &xous_names::XousNames) -> Result { + REFCOUNT.store(REFCOUNT.load(Ordering::Relaxed) + 1, Ordering::Relaxed); + let conn = xns.request_connection_blocking(api::SERVER_NAME_KEYS).expect("Can't connect to Keys server"); + Ok(Keys { + conn + }) + } +} + +use core::sync::atomic::{AtomicU32, Ordering}; +static REFCOUNT: AtomicU32 = AtomicU32::new(0); +impl Drop for Keys { + fn drop(&mut self) { + // the connection to the server side must be reference counted, so that multiple instances of this object within + // a single process do not end up de-allocating the CID on other threads before they go out of scope. + // Note to future me: you want this. Don't get rid of it because you think, "nah, nobody will ever make more than one copy of this object". + if REFCOUNT.load(Ordering::Relaxed) == 0 { + unsafe{xous::disconnect(self.conn).unwrap();} + } + // if there was object-specific state (such as a one-time use server for async callbacks, specific to the object instance), + // de-allocate those items here. They don't need a reference count because they are object-specific + } +} \ No newline at end of file diff --git a/services/keys/src/main.rs b/services/keys/src/main.rs new file mode 100644 index 000000000..9afb2dfd5 --- /dev/null +++ b/services/keys/src/main.rs @@ -0,0 +1,125 @@ +#![cfg_attr(target_os = "none", no_std)] +#![cfg_attr(target_os = "none", no_main)] + +mod api; + +use num_traits::FromPrimitive; + +use log::info; + + +#[cfg(target_os = "none")] +mod implementation { + use utralib::generated::*; + // use crate::api::*; + use log::info; + use susres::{RegManager, RegOrField, SuspendResume}; + + pub struct Keys { + csr: utralib::CSR, + fifo: xous::MemoryRange, + susres_manager: RegManager::<{utra::audio::AUDIO_NUMREGS}>, + } + + impl Keys { + pub fn new() -> Keys { + let csr = xous::syscall::map_memory( + xous::MemoryAddress::new(utra::audio::HW_AUDIO_BASE), + None, + 4096, + xous::MemoryFlags::R | xous::MemoryFlags::W, + ) + .expect("couldn't map Audio CSR range"); + let fifo = xous::syscall::map_memory( + xous::MemoryAddress::new(utralib::HW_AUDIO_MEM), + None, + utralib::HW_AUDIO_MEM_LEN, + xous::MemoryFlags::R | xous::MemoryFlags::W, + ) + .expect("couldn't map Audio CSR range"); + + let mut keys = Keys { + csr: CSR::new(csr.as_mut_ptr() as *mut u32), + susres_manager: RegManager::new(csr.as_mut_ptr() as *mut u32), + fifo, + }; + + keys + } + + pub fn suspend(&mut self) { + self.susres_manager.suspend(); + } + pub fn resume(&mut self) { + self.susres_manager.resume(); + } + } +} + +// a stub to try to avoid breaking hosted mode for as long as possible. +#[cfg(not(target_os = "none"))] +mod implementation { + use log::info; + + pub struct Keys { + } + + impl Keys { + pub fn new() -> Keys { + Keys { + } + } + pub fn suspend(&self) { + } + pub fn resume(&self) { + } + } +} + + +#[xous::xous_main] +fn xmain() -> ! { + use crate::implementation::Keys; + + log_server::init_wait().unwrap(); + log::set_max_level(log::LevelFilter::Info); + info!("my PID is {}", xous::process::id()); + + let xns = xous_names::XousNames::new().unwrap(); + /* + Connections allowed to the keys server: + 1. Shellchat (to originate update test requests) + 2. (future) PDDB + */ + let keys_sid = xns.register_name(api::SERVER_NAME_KEYS, Some(1)).expect("can't register server"); + log::trace!("registered with NS -- {:?}", keys_sid); + + let mut keys = Keys::new(); + + log::trace!("ready to accept requests"); + + // register a suspend/resume listener + let sr_cid = xous::connect(keys_sid).expect("couldn't create suspend callback connection"); + let mut susres = susres::Susres::new(&xns, api::Opcode::SuspendResume as u32, sr_cid).expect("couldn't create suspend/resume object"); + + loop { + let msg = xous::receive_message(keys_sid).unwrap(); + match FromPrimitive::from_usize(msg.body.id()) { + Some(api::Opcode::SuspendResume) => xous::msg_scalar_unpack!(msg, token, _, _, _, { + keys.suspend(); + susres.suspend_until_resume(token).expect("couldn't execute suspend/resume"); + keys.resume(); + }), + None => { + log::error!("couldn't convert opcode"); + break + } + } + } + // clean up our program + log::trace!("main loop exit, destroying servers"); + xns.unregister_server(keys_sid).unwrap(); + xous::destroy_server(keys_sid).unwrap(); + log::trace!("quitting"); + xous::terminate_process(0) +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs index bba80c7a9..2f259fa26 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -55,6 +55,7 @@ fn try_main() -> Result<(), DynError> { "engine-sha512", "engine-25519", "spinor", + "keys", ]; let benchmark_pkgs = [ "benchmark",