add status bar extension to inform of security states

- inverted text indicates a trusted message. policy is enforced in the GAM.
- we don't have a way to lock the USB port yet; but at least now it's communicated.
This commit is contained in:
bunnie 2021-06-13 04:40:50 +08:00
parent d5c30fae00
commit 0db9ad9e6f
13 changed files with 233 additions and 17 deletions

1
Cargo.lock generated
View file

@ -686,6 +686,7 @@ dependencies = [
"num-traits",
"rkyv 0.4.3",
"susres",
"trng",
"utralib",
"xous",
"xous-ipc",

View file

@ -15,8 +15,15 @@ mod soft;
mod vex;
pub use soft::{Aes128Soft, Aes192, Aes256Soft};
#[cfg(target_os = "none")]
pub use vex::{Aes128, Aes256};
#[cfg(not(target_os = "none"))]
pub use soft::Aes128Soft as Aes128;
#[cfg(not(target_os = "none"))]
pub use soft::Aes256Soft as Aes256;
#[cfg(feature = "ctr")]
pub use soft::{Aes128Ctr, Aes192Ctr, Aes256Ctr};

View file

@ -29,6 +29,7 @@ macro_rules! define_aes_impl {
(
$name:ident,
$key_size:ty,
$key_bits:expr,
$fixslice_keys:ty,
$fixslice_key_schedule:path,
$fixslice_decrypt:path,
@ -40,6 +41,11 @@ macro_rules! define_aes_impl {
pub struct $name {
keys: $fixslice_keys,
}
impl $name {
pub fn key_size(&self) -> usize {
$key_bits as usize
}
}
impl NewBlockCipher for $name {
type KeySize = $key_size;
@ -97,6 +103,7 @@ macro_rules! define_aes_impl {
define_aes_impl!(
Aes128Soft,
U16,
128,
FixsliceKeys128,
fixslice::aes128_key_schedule,
fixslice::aes128_decrypt,
@ -107,6 +114,7 @@ define_aes_impl!(
define_aes_impl!(
Aes192,
U24,
192,
FixsliceKeys192,
fixslice::aes192_key_schedule,
fixslice::aes192_decrypt,
@ -117,6 +125,7 @@ define_aes_impl!(
define_aes_impl!(
Aes256Soft,
U32,
256,
FixsliceKeys256,
fixslice::aes256_key_schedule,
fixslice::aes256_decrypt,

View file

@ -65,6 +65,14 @@ pub(crate) enum Opcode {
// Request blank screen for ship mode
ShipModeBlankRequest,
/// claims an authentication token out of a fixed name space
/// this is first-come, first-serve basis. Once the system is initialized, no more tokens can be handed out.
ClaimToken,
/// system-level API that can be called by the Xous process launcher to check if we're at a state where less trusted code could be run
/// it basically checks that all tokens have been claimed by trusted OS procesess, thus blocking any further token creation
AllowLessTrustedCode,
/////// planned
// hides a canvas with a given GID
@ -72,6 +80,8 @@ pub(crate) enum Opcode {
// indicates if the current UI layout requires an input field
//HasInput(bool),
Quit,
}
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]

View file

@ -5,7 +5,7 @@ use api::*;
use graphics_server::api::{TextOp, TextView};
use graphics_server::api::{Point, Gid, Line, Rectangle, Circle, RoundedRectangle};
use graphics_server::api::{Point, Gid, Line, Rectangle, Circle, RoundedRectangle, TokenClaim};
use api::Opcode; // if you prefer to map the api into your local namespace
use xous::{send_message, CID, Message};
@ -160,6 +160,32 @@ impl Gam {
}
}
}
pub fn claim_token(&self, name: &str) -> Result<Option<[u32; 4]>, xous::Error> {
let tokenclaim = TokenClaim {
token: None,
name: String::<128>::from_str(name),
};
let mut buf = Buffer::into_buf(tokenclaim).or(Err(xous::Error::InternalError))?;
buf.lend_mut(self.conn, Opcode::ClaimToken.to_u32().unwrap()).or(Err(xous::Error::InternalError))?;
let returned_claim = buf.to_original::<TokenClaim, _>().unwrap();
Ok(returned_claim.token)
}
pub fn allow_less_trusted_code(&self) -> Result<bool, xous::Error> {
let response = send_message(self.conn,
Message::new_blocking_scalar(Opcode::AllowLessTrustedCode.to_usize().unwrap(), 0, 0, 0, 0)
).expect("couldn't run allow trusted code check");
if let xous::Result::Scalar1(result) = response {
if result == 1 {
Ok(true)
} else {
Ok(false)
}
} else {
Err(xous::Error::InternalError)
}
}
}
use core::sync::atomic::{AtomicU32, Ordering};

View file

@ -20,7 +20,7 @@ use log::info;
use heapless::FnvIndexMap;
use num_traits::FromPrimitive;
use xous_ipc::Buffer;
use xous_ipc::{Buffer, String};
use api::Opcode;
use xous::{msg_scalar_unpack, msg_blocking_scalar_unpack};
@ -49,7 +49,7 @@ impl ChatLayout {
// allocate canvases in structures, and record their GID for future reference
let status_canvas = Canvas::new(
Rectangle::new_coords(0, 0, screensize.x, small_height),
Rectangle::new_coords(0, 0, screensize.x, small_height * 2),
255, &trng, None
).expect("couldn't create status canvas");
canvases.insert(status_canvas.gid(), status_canvas).expect("can't store status canvus");
@ -176,6 +176,96 @@ impl ModalCanvases {
}
/*
Authentication tokens to the GAM are created on a first-come, first-serve basis,
under the following assumptions:
- the boot set is fully trusted (signature checked, just-my-own-code running)
- the boot set will grab all the token slots availble before allowing any less-trusted code to run
This scheme thus effectively locks out less-trusted code, while simplifying the
registration of interprocess comms between trusted elements, only relying on ephemeral,
dynamically generated 128-bit tokens.
*/
const TOKEN_SLOTS: usize = 3;
#[derive(Copy, Clone, Debug)]
pub struct NamedToken {
token: [u32; 4],
name: String::<128>,
}
pub struct TokenManager {
tokens: [Option<NamedToken>; TOKEN_SLOTS],
slot_names: [&'static str; TOKEN_SLOTS],
trng: trng::Trng,
}
impl<'a> TokenManager {
pub fn new(xns: &xous_names::XousNames) -> TokenManager {
TokenManager {
tokens: [None; TOKEN_SLOTS],
slot_names: ["status", "menu", "passwords"],
trng: trng::Trng::new(&xns).unwrap(),
}
}
/// checks to see if all the slots have been occupied. We can't allow untrusted code to run until all slots have checked in
pub fn allow_untrusted_code(&self) -> bool {
let mut allow = true;
for t in self.tokens.iter() {
if t.is_none() {
allow = false
}
}
allow
}
pub fn claim_token(&mut self, name: &str) -> Option<[u32; 4]> {
// first check if the name is valid
let mut valid = false;
for &valid_name in self.slot_names.iter() {
if name.eq(valid_name) {
valid = true;
}
}
if !valid { return None }
// now check if it hasn't already been registered
let mut registered = false;
for maybe_token in self.tokens.iter() {
match maybe_token {
Some(token) => {
if name.eq(token.name.as_str().unwrap()) {
registered = true;
}
}
_ => ()
}
}
if registered { return None }
// now do the registration
let token = [self.trng.get_u32().unwrap(), self.trng.get_u32().unwrap(), self.trng.get_u32().unwrap(), self.trng.get_u32().unwrap(),];
for maybe_token in self.tokens.iter_mut() {
if maybe_token.is_none() {
*maybe_token = Some(NamedToken {
token,
name: String::<128>::from_str(name),
});
}
return Some(token)
}
// somehow, we didn't have space -- but with all the previous checks, we really should have
None
}
pub fn is_token_valid(&self, token: [u32; 4]) -> bool {
for maybe_token in self.tokens.iter() {
match maybe_token {
Some(found_token) => {
if found_token.token == token {
return true
}
}
_ => ()
}
}
false
}
}
#[xous::xous_main]
fn xmain() -> ! {
let debugc = true;
@ -192,6 +282,8 @@ fn xmain() -> ! {
let gfx = graphics_server::Gfx::new(&xns).expect("can't connect to GFX");
let trng = trng::Trng::new(&xns).expect("can't connect to TRNG");
let mut tm = TokenManager::new(&xns);
let screensize = gfx.screen_size().expect("Couldn't get screen size");
// a map of canvases accessable by Gid
@ -307,6 +399,14 @@ fn xmain() -> ! {
match tv.get_op() {
TextOp::Nop => (),
TextOp::Render | TextOp::ComputeBounds => {
if tv.invert & tv.token.is_some() {
// an inverted text can only be made by secure processes. check that it has a valid token.
if !tm.is_token_valid(tv.token.unwrap()) {
log::error!("Attempt to draw inverted text without valid credentials. Aborting.");
continue;
}
}
log::trace!("render request for {:?}", tv);
if tv.get_op() == TextOp::ComputeBounds {
tv.dry_run = true;
@ -435,7 +535,21 @@ fn xmain() -> ! {
}
log::trace!("leaving RenderObject");
}
None => {log::error!("unhandled message {:?}", msg); break}
Some(Opcode::ClaimToken) => {
let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) };
let mut tokenclaim = buffer.to_original::<TokenClaim, _>().unwrap();
tokenclaim.token = tm.claim_token(tokenclaim.name.as_str().unwrap());
buffer.replace(tokenclaim).unwrap();
},
Some(Opcode::AllowLessTrustedCode) => xous::msg_blocking_scalar_unpack!(msg, _, _, _, _, {
if tm.allow_untrusted_code() {
xous::return_scalar(msg.sender, 1).unwrap();
} else {
xous::return_scalar(msg.sender, 0).unwrap();
}
}),
Some(Opcode::Quit) => break,
None => {log::error!("unhandled message {:?}", msg);}
}
}
// clean up our program

View file

@ -81,7 +81,7 @@ pub fn status_thread(canvas_gid_0: usize, canvas_gid_1: usize, canvas_gid_2: usi
// build uptime text view: left half of status bar
let mut uptime_tv = TextView::new(status_gid,
TextBounds::BoundingBox(Rectangle::new(Point::new(0,0),
Point::new(screensize.x / 2, screensize.y - 1))));
Point::new(screensize.x / 2, screensize.y / 2 - 1))));
uptime_tv.untrusted = false;
uptime_tv.style = blitstr::GlyphStyle::Small;
uptime_tv.draw_border = false;
@ -93,7 +93,7 @@ pub fn status_thread(canvas_gid_0: usize, canvas_gid_1: usize, canvas_gid_2: usi
// build battstats text view: right half of status bar
let mut battstats_tv = TextView::new(status_gid,
TextBounds::BoundingBox(Rectangle::new(Point::new(screensize.x / 2, 0),
Point::new(screensize.x, screensize.y - 1))));
Point::new(screensize.x, screensize.y / 2 - 1))));
battstats_tv.style = blitstr::GlyphStyle::Small;
battstats_tv.draw_border = false;
battstats_tv.margin = Point::new(0, 0);
@ -132,6 +132,20 @@ pub fn status_thread(canvas_gid_0: usize, canvas_gid_1: usize, canvas_gid_2: usi
let mut charger_pump_modulus = 0;
let llio = llio::Llio::new(&xns).unwrap();
let mut debug_unlocked = llio.debug_usb_unlocked().unwrap();
// build security status textview
let mut security_tv = TextView::new(status_gid,
TextBounds::BoundingBox(Rectangle::new(Point::new(0,screensize.y / 2),
Point::new(screensize.x, screensize.y - 1))));
security_tv.style = blitstr::GlyphStyle::Small;
security_tv.draw_border = false;
security_tv.margin = Point::new(0, 0);
security_tv.token = gam.claim_token("status").expect("couldn't request token"); // this is a shared magic word to identify this process
security_tv.clear_area = true;
security_tv.invert = true;
write!(&mut security_tv, " USB unlocked").unwrap();
gam.post_textview(&mut security_tv).unwrap();
let secs_interval;
let batt_interval;
if cfg!(feature = "slowstatus") {
@ -161,6 +175,15 @@ pub fn status_thread(canvas_gid_0: usize, canvas_gid_1: usize, canvas_gid_2: usi
}
}),
Some(StatusOpcode::Pump) => {
if debug_unlocked != llio.debug_usb_unlocked().unwrap() {
debug_unlocked = llio.debug_usb_unlocked().unwrap();
security_tv.clear_str();
if debug_unlocked {
write!(&mut security_tv, " USB unlocked").unwrap();
} else {
write!(&mut security_tv, " USB secured").unwrap();
}
}
let elapsed_time = ticktimer.elapsed_ms();
let now_seconds: usize = ((elapsed_time / 1000) % 60) as usize;
if (now_seconds / secs_interval) != (last_seconds / secs_interval) {
@ -234,6 +257,7 @@ pub fn status_thread(canvas_gid_0: usize, canvas_gid_1: usize, canvas_gid_2: usi
log::trace!("|status: requesting draw of '{}'", uptime_tv);
gam.post_textview(&mut uptime_tv).expect("|status: can't draw uptime");
gam.post_textview(&mut battstats_tv).expect("|status: can't draw battery stats");
gam.post_textview(&mut security_tv).unwrap();
gam.redraw().expect("|status: couldn't redraw");
stats_phase = (stats_phase + 1) % 8;
}

View file

@ -14,6 +14,7 @@ log = "0.4"
log-server = {path = "../log-server"}
xous = {path = "../../xous-rs"}
susres = {path = "../susres"}
trng = {path = "../trng"}
xous-ipc = {path = "../../xous-ipc"}
xous-names = {path = "../xous-names"}

View file

@ -86,6 +86,8 @@ pub(crate) enum Opcode {
/// SuspendResume callback
SuspendResume,
Quit,
}
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)]
@ -101,3 +103,9 @@ pub struct ClipObject {
pub clip: Rectangle,
pub obj: ClipObjectType,
}
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)]
pub struct TokenClaim {
pub token: Option<[u32; 4]>,
pub name: xous_ipc::String::<128>,
}

View file

@ -2,7 +2,7 @@
// pub mod size;
pub mod api;
pub use api::{Circle, DrawStyle, Line, PixelColor, Point, Rectangle, TextView, TextBounds, Gid, TextOp, RoundedRectangle, ClipObject, ClipObjectType};
pub use api::{Circle, DrawStyle, Line, PixelColor, Point, Rectangle, TextView, TextBounds, Gid, TextOp, RoundedRectangle, ClipObject, ClipObjectType, TokenClaim};
use blitstr_ref as blitstr;
pub use blitstr::{ClipRect, Cursor, GlyphStyle};
pub mod op;

View file

@ -288,8 +288,12 @@ fn xmain() -> ! {
} else {
0
};
let fillcolor = if tv.clear_area {
Some(PixelColor::Light)
let fillcolor = if tv.clear_area || tv.invert {
if tv.invert {
Some(PixelColor::Dark)
} else {
Some(PixelColor::Light)
}
} else {
None
};
@ -318,13 +322,14 @@ fn xmain() -> ! {
let mut ref_cursor = blitstr::Cursor::from_top_left_of(cr.into());
if debugtv { log::trace!("(TV): paint_str with {:?} | {:?} | {:?} | {:?} len: {}", cr, ref_cursor, tv.style, tv.text, tv.text.as_str().unwrap().len()); }
log::debug!("{}", tv);
let do_xor = tv.invert;
blitstr::paint_str(
display.native_buffer(),
cr.into(),
&mut ref_cursor,
tv.style.into(),
tv.text.as_str().unwrap(),
false,
do_xor,
tv.insertion,
tv.ellipsis,
paintfn
@ -386,7 +391,8 @@ fn xmain() -> ! {
display.update();
display.redraw();
}),
None => {log::error!("received opcode scalar that is not handled"); break}
Some(Opcode::Quit) => break,
None => {log::error!("received opcode scalar that is not handled");}
}
display.update();
}

View file

@ -523,6 +523,9 @@ impl Llio {
Err(xous::Error::InternalError)
}
}
pub fn debug_usb_unlocked(&self) -> Result<bool, xous::Error> {
Ok(true) // for now, always return true, because we don't have the hardware yet to lock out debug USB
}
}

View file

@ -406,13 +406,15 @@ mod implementation {
// a stub to try to avoid breaking hosted mode for as long as possible.
#[cfg(not(target_os = "none"))]
mod implementation {
use crate::api::{TrngBuf, HealthTests, TrngErrors};
pub struct Trng {
seed: u32,
msgcount: u16, // re-print the message every time we rollover
}
impl Trng {
pub fn new() -> Trng {
pub fn new(_xns: &xous_names::XousNames) -> Trng {
Trng {
seed: 0x1afe_cafe,
msgcount: 0,
@ -429,8 +431,8 @@ mod implementation {
#[allow(dead_code)]
pub fn wait_full(&self) { }
pub fn get_buf(&self, len: u16) -> TrngBuf {
if msgcount < 10 {
pub fn get_buf(&mut self, len: u16) -> TrngBuf {
if self.msgcount < 10 {
log::info!("hosted mode TRNG is *not* random, it is an LFSR");
}
self.msgcount += 1;
@ -443,7 +445,7 @@ mod implementation {
}
pub fn get_trng(&mut self, _count: usize) -> [u32; 2] {
if msgcount < 10 {
if self.msgcount < 10 {
log::info!("hosted mode TRNG is *not* random, it is an LFSR");
}
self.msgcount += 1;
@ -469,10 +471,15 @@ mod implementation {
av_adaptive_errs: None,
ro_repcount_errs: None,
ro_adaptive_errs: None,
kernel_underruns: None,
server_underruns: None,
kernel_underruns: 0,
server_underruns: 0,
nist_errs: 0,
pending_mask: 0,
}
}
pub fn get_err_stats(&self) -> HealthTests {
HealthTests::default()
}
}
}