diff --git a/api/xous-names/Cargo.toml b/api/xous-names/Cargo.toml new file mode 100644 index 000000000..33e767075 --- /dev/null +++ b/api/xous-names/Cargo.toml @@ -0,0 +1,23 @@ +[package] +authors = ["bunnie "] +description = "Xous microkernel OS inter-process name resolution server" +edition = "2018" +name = "xous-api-names" +version = "0.9.7" +license = "MIT OR Apache-2.0" +repository = "https://github.com/betrusted-io/xous-core/" +homepage = "https://betrusted.io/" + +# Dependency versions enforced by Cargo.lock. +[dependencies] +num-derive = {version = "0.3.3", default-features = false} +num-traits = {version = "0.2.14", default-features = false} +log = "0.4.14" +log-server = {version = "0.1.3", package = "xous-api-log"} +xous = "0.9.9" +xous-ipc = "0.9.9" +rkyv = {version = "0.4.3", default-features = false, features = ["const_generics"]} + +[features] +debugprint = [] +default = [] # "debugprint" diff --git a/api/xous-names/README.md b/api/xous-names/README.md new file mode 100644 index 000000000..8f6dfec4b --- /dev/null +++ b/api/xous-names/README.md @@ -0,0 +1,143 @@ +# Xous API: xous-names + +`xous-names` resolves plaintext server names to 128-bit randomly +assigned server IDs. It is also the front-line gatekeeper for +restricting access to services by preventing connections or +discoverability (or more accurately, discoverability is inherently +hard because it requires brute-forcing the server ID in a 128-bit +space of randomly assigned numbers). + +See the [Xous Book](https://betrusted.io/xous-book/ch07-01-xous-names.html) for +more details. The Xous Book should be considered normative; the specification +below is historical. + +## Specification +Server IDs (SIDs) are used by processes to send messages to +servers. It is thus an attack surface. Furthermore, if a process can +forge an SID before a server can claim it, it can “become” the +server. Thus, it’s helpful to keep the SID a secret. + +In Xous, an SID is a 128-bit number that, with two exceptions, is only +known to the server itself, and an oracle known as `xous-name-server`. + +SIDs are never revealed to a process. Processes establish connections +to servers using a descriptive, human-readable string name. Since the +SIDs are random numbers, there is no way to turn the descriptive +string into the SID except by resolving it with `xous-name-server`. + +On boot, a trusted set of processes are started which form the +operating system. These must all claim names in the name space before +any further processes are started, to prevent later processes from +claiming their names. Servers can also optionally limit the total +number of connections allowed, which effectively makes them unreachable +by less trusted code that is run after the core trusted set of processes +have started up. The `trusted_init_done()` libary call on the name +server will return true if all the servers that have a connection +limit have fully populated all of their connections. + +The exception to random SIDs are the `xous-name-server`, +`xous-log-server ` (note the trailing space), and `ticktimer-server`. +These are three well known names that have a defined, +fixed SID so that all processes can talk to them; `xous-name-server` is +necessarily well-known as it is the mechanism to resolve further +names, `xous-log-server ` is necessary for debugging, so that bugs upstream +of name resolution can be logged. `xous-name-server` was picked because +`name-server` already has a meaning in the context of DNS. `ticktimer-server` +is necessary for implementing deterministic timing delays in +`xous-name-server` upon failure, and also for other processes to +wait a fixed period of time on initialization while the initial set +of name registrations occur. + +A new process that intends to receive messages uses the `register_name` convenience +function in the `xous-names/src/lib.rs` file, with the following procedure. + +1. It calls `register_name` with a preferred ASCII name string, +limited to 64 characters. It also specifies how many connections the server +will allow. `None` on the specifier means no limit. + +1. `xous-name-server` returns the borrowed memory to the server, where the +buffer has been replaced with a response field. In the case that the registration +is affirmed, the SID field in `Registration` contains the assigned SID +of calling process. In the case that the name is determined to be invalid +(perhaps because it is already reserved or registered), it will return +an error code. + +3. If the registration is denied, the server can attempt to +re-register its SID with a different ASCII name string by repeating +steps 2-3. + + +A process that would like to send a server a message must first request the +name server to broker a connection to the target process. It does this by +typically calling the `request_conneciton_blocking` convenience function +with the registered name of the server. + +1. `request_connection_blocking` is called with the maximum 64-character +ASCII name string. + +2. The convencience function creates a `Lookup` message which is lent to +the name server. + +4. `xous-name-server` can respond with one of three results: + A. affirm the connection by returning a connection ID + B. a flat denial of the connection; or + C. a slot containing a request to authenticate. + +Here are the cases worked out: + +A. affirming the connection: `xous-name-server` would use +`MessageSender.pid()` to extract the sender’s PID, and call +`ConnectForProcess(PID,SID)` on behalf of the sender. The sender can +then use the CID as the first argument to `send_message()`. This is +the common case, and many servers follow this path, such as those +asking for access to the `ticktimer` or other public services. + +B. flat denial: `xous-name-server` simply returns a message saying the +request was denied. This is also the case when the request is malformed or incorrect. +No information shall be leaked about the +nature of the denial. Denials are also delayed to the nearest 0.1 second interval since boot +to eliminate side channels and to rate limit fuzzing requests. Some +services (such as the key server) are restricted to only a set of +trusted process loaded at boot, and therefore it should not be +discoverable. + +C. request to authenticate: `xous-name-server` responds with `success` set +to `false`, but `authenticate_request` to `true`. The `pubkey_id` field +is populated with the ID of an acceptable Ed25519 public key for authentication, and +a 256-bit challenge nonce is provided in the `challenge` field. Authentication +consists of the requesting server proving that it has knowledge of a shared +secret, namely, an Ed25519 private key. + +Upon generating the request to authenticate, `xous-name-server` computes +the correct response to the challenge and stores it in a table with +a timestamp. + +The sending process must then sign the `challenge` and return an +`Authenticate` message, constructed similarly to the `Lookup` +message but with the `response_to_challenge` field filled out. It must +do this before `AUTHENTICATE_TIMEOUT` milliseconds have passed. +The server, upon receipt of an `Authenticate` message, merely checks +if the `response_to_challenge` matches any response stored in its +table, and if it does, it accepts the process as authenticated. It is +cryptographically unlikely for there to be a collision in the table; +however, this implementation is weak to an attacker potentially +stealing the response and using it. That being said, if an attacker +already has that level of control in the calling process, there +are bigger problems. + +The `AUTHENTICATE_TIMEOUT` field is used to give `xous-name-server` +a chance to depopulate the response table over time, so that it +does not "leak" memory. + +## Current Implementation + +The current implementation is a hash map that matches randomly generated +names with a list of names each server selects for itself. Currently, any +request to lookup and connect to a server will succeed up to the limit +of connections (if any) specified by a server, but the hooks +are there to enforce permissions and deny connections, and/or request +authentication for connection. + +Server names are crate-local, and are bound through library functions +called during the creation of server access objects. In other words, +there is no global name space for servers. diff --git a/api/xous-names/src/api.rs b/api/xous-names/src/api.rs new file mode 100644 index 000000000..5acff89da --- /dev/null +++ b/api/xous-names/src/api.rs @@ -0,0 +1,239 @@ +#[allow(dead_code)] +pub const AUTHENTICATE_TIMEOUT: u32 = 10_000; // time in ms that a process has to respond to an authentication request + +#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive)] +#[non_exhaustive] +#[repr(C)] +pub(crate) enum Opcode { + /// Create a new server with the given name and return its SID. + Register = 0, + + /// Create a connection to the target server. + Lookup = 1, + + /// Create an authenticated connection to the target server. + AuthenticatedLookup = 2, + + /// unregister a server, given its cryptographically unique SID. + Unregister = 3, + + /// disconnect, given a server name and a cryptographically unique, one-time use token + Disconnect = 4, + + /// indicates if all inherentely trusted slots have been occupied. Should not run untrusted code until this is the case. + TrustedInitDone = 5, + + /// Connect to a Server, blocking if the Server does not exist. When the Server is started, + /// return with either the CID or an AuthenticationRequest + /// + /// # Message Types + /// + /// * MutableLend + /// + /// # Arguments + /// + /// The memory being pointed to should be a &str, and the length of the string should + /// be specified in the `valid` field. + /// + /// # Return Values + /// + /// Memory is overwritten to contain a return value. This return value can be defined + /// as the following enum: + /// + /// ```rust + /// #[repr(C)] + /// #[non_exhaustive] + /// enum ConnectResult { + /// Success(xous::CID /* connection ID */, [u32; 4] /* Disconnection token */), + /// Error(u32 /* error code */), + /// Unhandled, /* Catchall for future Results */ + /// } + /// ``` + BlockingConnect = 6, +} + +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] +#[non_exhaustive] +#[repr(C)] +pub(crate) enum Return { + /// The caller must perform an AuthenticatedLookup using this challenge + AuthenticateRequest(AuthenticateRequest), + + /// The connection failed for some reason + Failure, + + /// A server was successfully created with the given SID + SID([u32; 4]), + + /// A connection was successfully made with the given CID; an optional "disconnect token" is provided + CID((xous::CID, Option<[u32; 4]>)), + + /// Operation requested was otherwise successful (currently only used by disconnect to ack the disconnect) + Success, +} + +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] +pub(crate) struct Registration { + pub name: xous_ipc::String<64>, + pub conn_limit: Option, +} + +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] +pub(crate) struct Disconnect { + pub name: xous_ipc::String<64>, + pub token: [u32; 4], +} + +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] +pub(crate) struct AuthenticatedLookup { + pub name: xous_ipc::String<64>, + pub pubkey_id: [u8; 20], // 160-bit pubkey ID encoded in network order (big endian) + pub response: [u32; 8], +} + +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] +#[repr(C)] +pub(crate) struct AuthenticateRequest { + pub name: xous_ipc::String<64>, // a copy of the originally requested lookup + pub pubkey_id: [u8; 20], // 160-bit pubkey ID encoded in network order (big endian) + pub challenge: [u32; 4], +} + +////////////////////////////////////////////////////////////////////////////////////////////// +// We keep XousServerName around because want to be able to index off the server name, without +// burdening the Kernel String type with the Hash32 methods +////////////////////////////////////////////////////////////////////////////////////////////// + +// --------------------- Taken from rkyv docs https://docs.rs/rkyv/0.3.0/rkyv/trait.Archive.html // +#[derive(Debug, Copy, Clone)] +pub struct XousServerName { + value: [u8; 64], + length: usize, +} + +impl Default for XousServerName { + fn default() -> Self { + XousServerName { + value: [0u8; 64], + length: 0, + } + } +} + +#[allow(dead_code)] +impl XousServerName { + pub fn to_str(&self) -> &str { + core::str::from_utf8(unsafe { + core::slice::from_raw_parts(self.value.as_ptr(), self.length as usize) + }) + .unwrap() + } + pub fn new() -> XousServerName { + XousServerName { + value: [0; 64], + length: 0, + } + } + + pub fn from_str(src: &str) -> XousServerName { + let mut s = Self::new(); + // Copy the string into our backing store. + for (&src_byte, dest_byte) in src.as_bytes().iter().zip(&mut s.value) { + *dest_byte = src_byte; + } + // Set the string length to the length of the passed-in String, + // or the maximum possible length. Which ever is smaller. + s.length = s.value.len().min(src.as_bytes().len()); + + // If the string is not valid, set its length to 0. + if s.as_str().is_err() { + s.length = 0; + } + assert!(s.length < s.value.len(), "incorrect length derivation!"); + + s + } + + pub fn as_bytes(&self) -> [u8; 64] { + self.value + } + + pub fn as_str(&self) -> core::result::Result<&str, core::str::Utf8Error> { + core::str::from_utf8(&self.value[0..self.length as usize]) + } + + pub fn len(&self) -> usize { + self.length as usize + } + + pub fn is_empty(&self) -> bool { + self.length == 0 + } + + /// Clear the contents and set the length to 0 + pub fn clear(&mut self) { + self.length = 0; + self.value = [0; 64]; + } +} + +// Allow using the `write!()` macro to write into a `&XousServerName` +impl core::fmt::Write for XousServerName { + fn write_str(&mut self, s: &str) -> core::result::Result<(), core::fmt::Error> { + self.length = 0; + let b = s.bytes(); + + // Ensure the length is acceptable + if b.len() > self.value.len() { + Err(core::fmt::Error)?; + } + self.length = b.len(); + assert!( + self.length < self.value.len(), + "incorrect length derivation!" + ); + + // Copy the string into this variable + for (dest, src) in self.value.iter_mut().zip(s.bytes()) { + *dest = src; + } + + // Attempt to convert the string to UTF-8 to validate it's correct UTF-8 + core::str::from_utf8(unsafe { + core::slice::from_raw_parts(self.value.as_ptr(), self.length as usize) + }) + .map_err(|_| core::fmt::Error)?; + Ok(()) + } +} + +impl std::hash::Hash for XousServerName { + fn hash(&self, state: &mut H) + where + H: std::hash::Hasher, + { + assert!(self.length < self.value.len(), "incorret length on hash!"); + std::hash::Hash::hash(&self.value[..self.length as usize], state); + std::hash::Hash::hash(&self.length, state) + } +} + +impl PartialEq for XousServerName { + fn eq(&self, other: &Self) -> bool { + assert!(self.length < self.value.len(), "incorret length on Eq!"); + assert!( + other.length < other.value.len(), + "incorrect length on Eq (other)!" + ); + self.value[..self.length as usize] == other.value[..other.length as usize] + && self.length == other.length + } +} + +impl Eq for XousServerName {} + +impl core::fmt::Display for XousServerName { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "{}", self.to_str()) + } +} diff --git a/api/xous-names/src/lib.rs b/api/xous-names/src/lib.rs new file mode 100644 index 000000000..9d4af65cf --- /dev/null +++ b/api/xous-names/src/lib.rs @@ -0,0 +1,184 @@ +#![cfg_attr(target_os = "none", no_std)] + +//! Detailed docs are parked under Structs/XousNames down below + +pub mod api; + +use api::Disconnect; +use core::fmt::Write; +use num_traits::ToPrimitive; +use xous_ipc::{Buffer, String}; + +#[doc = include_str!("../README.md")] +#[derive(Debug)] +pub struct XousNames { + conn: xous::CID, +} +impl XousNames { + pub fn new() -> Result { + REFCOUNT.fetch_add(1, Ordering::Relaxed); + let conn = xous::connect(xous::SID::from_bytes(b"xous-name-server").unwrap()) + .expect("Couldn't connect to XousNames"); + Ok(XousNames { conn }) + } + + pub fn unregister_server(&self, sid: xous::SID) -> Result<(), xous::Error> { + // searches the name table and removes a given SID from the table. + // It's considered "secure" because you'd have to guess a random 128-bit SID + // to destroy someone else's SID. + + // note that with the current implementation, the destroy call will have to be an O(N) search through + // the server table, but this is OK as we expect <100 servers on a device + let s = sid.to_array(); + let response = xous::send_message( + self.conn, + xous::Message::new_blocking_scalar( + api::Opcode::Unregister.to_usize().unwrap(), + s[0] as usize, + s[1] as usize, + s[2] as usize, + s[3] as usize, + ), + ) + .expect("unregistration failed"); + if let xous::Result::Scalar1(result) = response { + if result != 0 { + Ok(()) + } else { + Err(xous::Error::ServerNotFound) + } + } else { + Err(xous::Error::InternalError) + } + } + + pub fn register_name( + &self, + name: &str, + max_conns: Option, + ) -> Result { + let mut registration = api::Registration { + name: String::<64>::new(), + conn_limit: max_conns, + }; + // could also do String::from_str() but in this case we want things to fail if the string is too long. + write!(registration.name, "{}", name).expect("name probably too long"); + + let mut buf = Buffer::into_buf(registration).or(Err(xous::Error::InternalError))?; + + buf.lend_mut(self.conn, api::Opcode::Register.to_u32().unwrap()) + .or(Err(xous::Error::InternalError))?; + + match buf.to_original().unwrap() { + api::Return::SID(sid_raw) => { + let sid = sid_raw.into(); + xous::create_server_with_sid(sid).expect("can't auto-register server"); + Ok(sid) + } + api::Return::Failure => Err(xous::Error::InternalError), + _ => unimplemented!("unimplemented return codes"), + } + } + + pub fn request_connection_with_token( + &self, + name: &str, + ) -> Result<(xous::CID, Option<[u32; 4]>), xous::Error> { + let mut lookup_name = xous_ipc::String::<64>::new(); + write!(lookup_name, "{}", name).expect("name problably too long"); + let mut buf = Buffer::into_buf(lookup_name).or(Err(xous::Error::InternalError))?; + + buf.lend_mut(self.conn, api::Opcode::Lookup.to_u32().unwrap()) + .or(Err(xous::Error::InternalError))?; + + match buf.to_original().unwrap() { + api::Return::CID((cid, token)) => Ok((cid, token)), + // api::Return::AuthenticateRequest(_) => Err(xous::Error::AccessDenied), + _ => Err(xous::Error::ServerNotFound), + } + } + pub fn disconnect_with_token(&self, name: &str, token: [u32; 4]) -> Result<(), xous::Error> { + let disconnect = Disconnect { + name: String::<64>::from_str(name), + token, + }; + let mut buf = Buffer::into_buf(disconnect).or(Err(xous::Error::InternalError))?; + buf.lend_mut(self.conn, api::Opcode::Disconnect.to_u32().unwrap()) + .or(Err(xous::Error::InternalError))?; + + match buf.to_original().unwrap() { + api::Return::Success => Ok(()), + _ => Err(xous::Error::ServerNotFound), + } + } + + pub fn request_connection(&self, name: &str) -> Result { + let mut lookup_name = xous_ipc::String::<64>::new(); + write!(lookup_name, "{}", name).expect("name problably too long"); + + let mut buf = Buffer::into_buf(lookup_name).or(Err(xous::Error::InternalError))?; + + buf.lend_mut(self.conn, api::Opcode::Lookup.to_u32().unwrap()) + .or(Err(xous::Error::InternalError))?; + + match buf.to_original().unwrap() { + api::Return::CID((cid, _)) => Ok(cid), + // api::Return::AuthenticateRequest(_) => Err(xous::Error::AccessDenied), + _ => Err(xous::Error::ServerNotFound), + } + } + + /// note: you probably want to use this one, to avoid synchronization issues on startup as servers register asynhcronously + pub fn request_connection_blocking(&self, name: &str) -> Result { + loop { + match self.request_connection(name) { + Ok(val) => return Ok(val), + Err(xous::Error::AccessDenied) => return Err(xous::Error::AccessDenied), + _ => (), + } + log::info!("connection to {} could not be established, retrying", name); + xous::yield_slice(); + } + } + + pub fn trusted_init_done(&self) -> Result { + let response = xous::send_message( + self.conn, + xous::Message::new_blocking_scalar( + api::Opcode::TrustedInitDone.to_usize().unwrap(), + 0, + 0, + 0, + 0, + ), + ) + .expect("couldn't query trusted_init_done"); + if let xous::Result::Scalar1(result) = response { + if result == 1 { + Ok(true) + } else { + Ok(false) + } + } else { + Err(xous::Error::InternalError) + } + } + + // todo: + // pub fn authenticated_connection(&self, name: &str, key: Authkey) + // this function will create an authenticated connection, if such are allowed + // it's intended for use by dynamically-loaded third-party apps. As of Xous 0.8 this isn't supported, so it's just a "todo" +} + +use core::sync::atomic::{AtomicU32, Ordering}; +static REFCOUNT: AtomicU32 = AtomicU32::new(0); +impl Drop for XousNames { + fn drop(&mut self) { + // de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the connection. + if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { + unsafe { + xous::disconnect(self.conn).unwrap(); + } + } + } +}