feat(boot): gatekeeper gates boot (init→UI→gatekeeper→data); keystore disk + virtio-rng discovery; terminal READ_SECRET; storage SET_KEY; PageCount ≤8192, alloc cap gone; device window 0x01D0_0000; test-qemu types passcode over 2 boots

This commit is contained in:
2026-10-27 23:43:47 +01:00
parent b7ef67ffd8
commit 3b7d004285
36 changed files with 455 additions and 74 deletions

View File

@@ -6,3 +6,14 @@ edition = "2024"
[dependencies]
keystore = { workspace = true }
zeroize = { workspace = true }
types = { workspace = true }
libkos = { workspace = true }
port-block-device = { workspace = true }
port-entropy = { workspace = true }
driver-block-virtio = { workspace = true }
driver-rng-virtio = { workspace = true }
[[bin]]
name = "gatekeeper"
test = false
bench = false

View File

@@ -0,0 +1,55 @@
//! The flow's ports on real devices: the keystore disk, virtio-rng, and
//! the terminal.
use libkos::io::print_to;
use port_block_device::{BlockDevice, SectorId};
use port_entropy::Entropy;
use types::bounded::CapSlot;
use crate::flow::{Keystore, MAX_SECRET, Prompt, Secret};
use keystore::RECORD_SIZE;
/// The record's two copies are its first two sectors.
pub struct Disk<D: BlockDevice>(pub D);
impl<D: BlockDevice> Keystore for Disk<D> {
fn read(&mut self, copy: usize, out: &mut [u8; RECORD_SIZE]) -> bool {
self.0.sector_size() == RECORD_SIZE && self.0.read_sector(SectorId::new(copy as u32), out)
}
fn write(&mut self, copy: usize, data: &[u8; RECORD_SIZE]) -> bool {
self.0.sector_size() == RECORD_SIZE && self.0.write_sector(SectorId::new(copy as u32), data)
}
}
pub struct Hardware<E: Entropy>(pub E);
impl<E: Entropy> keystore::Random for Hardware<E> {
fn fill(&mut self, buf: &mut [u8]) -> bool {
self.0.fill(buf)
}
}
pub struct Terminal(pub CapSlot);
impl Prompt for Terminal {
fn say(&mut self, text: &str) {
print_to(self.0, format_args!("{}", text));
}
fn clear(&mut self) {
libkos::terminal::clear(self.0);
}
fn secret(&mut self, question: &str, out: &mut Secret) -> bool {
print_to(self.0, format_args!("{}", question));
let mut line = Secret::new();
let mut buf = [0u8; MAX_SECRET + 1];
let n = libkos::terminal::read_secret(self.0, &mut buf);
let typed = buf[..n].strip_suffix(b"\n").unwrap_or(&buf[..n]);
line.set(typed);
buf.fill(0);
out.set(line.as_bytes());
n > 0
}
}

View File

@@ -57,6 +57,8 @@ impl Drop for Secret {
/// The owner, on the screen and keyboard.
pub trait Prompt {
fn say(&mut self, text: &str);
/// Blanks the screen.
fn clear(&mut self);
/// Shows `question` and reads a passcode without showing it; false if
/// nothing could be read.
fn secret(&mut self, question: &str, out: &mut Secret) -> bool;
@@ -128,6 +130,8 @@ fn choose(prompt: &mut impl Prompt, question: &str, optional: bool, out: &mut Se
/// A device never set up (or wiped): the owner chooses a passcode, and
/// may choose a duress one. Returns the new master key.
fn setup(ks: &mut impl Keystore, rng: &mut impl Random, prompt: &mut impl Prompt, params: KdfParams, memory: &mut [Block]) -> Result<Key, Failure> {
// After a wipe nothing earlier may show: it must look like a new device.
prompt.clear();
prompt.say("This device has no passcode yet. Choose one; it protects everything on it.\n");
let mut real = Secret::new();
choose(prompt, "New passcode: ", false, &mut real)?;

View File

@@ -7,8 +7,78 @@
extern crate alloc;
pub mod devices;
pub mod flow;
#[cfg(test)]
#[path = "tests/mod.rs"]
mod tests;
use alloc::vec;
use keystore::{Block, KdfParams};
use libkos::syscall::{self, Received};
use types::bounded::CapSlot;
use types::gatekeeper::{KEY, UNLOCK, reply};
/// Where init's manifest put them: its own endpoint (devices arrive on
/// it, then init's calls), then the terminal.
const EP: CapSlot = CapSlot::const_new(0);
const TERMINAL: CapSlot = CapSlot::const_new(1);
/// Answers init's next call, if it is `op`, with `words`.
fn answer(op: usize, words: [usize; 4]) -> bool {
loop {
match syscall::receive_msg(EP) {
Ok(Received::Call { badge: 0, words: [w, ..], .. }) if w == op => {
return syscall::reply(words, None).is_ok();
}
// Anyone else, or anything else: refused.
Ok(Received::Call { .. }) => {
let _ = syscall::reply([reply::FAILED, 0, 0, 0], None);
}
Ok(_) => {}
Err(_) => return false,
}
}
}
pub fn run() -> ! {
// Init hands over the keystore disk, then the randomness device.
let keystore = libkos::device::receive_device(EP).mmio.and_then(driver_block_virtio::VirtioBlockDevice::new);
let random = libkos::device::receive_device(EP).mmio.and_then(driver_rng_virtio::VirtioRng::new);
let (Some(keystore), Some(random)) = (keystore, random) else {
libkos::println!("gatekeeper: no keystore or no randomness, nothing to unlock with");
let _ = answer(UNLOCK, [reply::FAILED, 0, 0, 0]);
syscall::exit();
};
let mut memory = vec![Block::default(); KdfParams::DEFAULT.memory_kib as usize];
libkos::println!("gatekeeper: waiting for the owner");
let key = flow::run(
&mut devices::Disk(keystore),
&mut devices::Hardware(random),
&mut devices::Terminal(TERMINAL),
KdfParams::DEFAULT,
&mut memory,
);
// The guesses' working memory goes before anything else happens.
for b in memory.iter_mut() {
*b = Block::default();
}
drop(memory);
match key {
Ok(key) => {
libkos::println!("gatekeeper: unlocked");
libkos::terminal::clear(TERMINAL);
let word = |i: usize| usize::from_le_bytes(key.0[i * 8..i * 8 + 8].try_into().unwrap_or([0; 8]));
if answer(UNLOCK, [reply::OK, 0, 0, 0]) {
let _ = answer(KEY, [word(0), word(1), word(2), word(3)]);
}
}
Err(why) => {
libkos::println!("gatekeeper: cannot go on: {:?}", why);
let _ = answer(UNLOCK, [reply::FAILED, 0, 0, 0]);
}
}
// Its capabilities go with it.
syscall::exit()
}

View File

@@ -0,0 +1,11 @@
#![no_std]
#![forbid(unsafe_code)]
#![no_main]
extern crate libkos;
libkos::entry!(main);
fn main() {
gatekeeper::run();
}

View File

@@ -67,18 +67,26 @@ impl Random for Counter {
/// An owner typing from a script; what was shown is kept.
struct Owner {
typing: VecDeque<&'static str>,
/// On the screen now.
shown: String,
/// Ever shown, cleared or not.
said: String,
}
impl Owner {
fn types(lines: &[&'static str]) -> Self {
Self { typing: lines.iter().copied().collect(), shown: String::new() }
Self { typing: lines.iter().copied().collect(), shown: String::new(), said: String::new() }
}
}
impl Prompt for Owner {
fn say(&mut self, text: &str) {
self.shown.push_str(text);
self.said.push_str(text);
}
/// What a fresh screen shows: nothing that came before.
fn clear(&mut self) {
self.shown.clear();
}
fn secret(&mut self, question: &str, out: &mut Secret) -> bool {
self.shown.push_str(question);
@@ -158,7 +166,7 @@ fn too_many_wrong_passcodes_wipe_the_keys_and_the_device_starts_fresh() {
guesses.extend(["5678", "5678", "", ""]);
let mut owner = Owner::types(&guesses);
let new = run_with(&mut dev, &mut owner).unwrap();
assert!(owner.shown.contains("One try left"));
assert!(owner.said.contains("One try left"));
assert!(owner.shown.ends_with("This device has no passcode yet. Choose one; it protects everything on it.\nNew passcode: Again: A duress passcode wipes the device when it is entered instead. Leave it empty for none.\nDuress passcode: Again: "));
assert_ne!(new.0, key, "the old master key is gone");
let mut old = Owner::types(&["1234"]);
@@ -173,6 +181,7 @@ fn the_duress_passcode_wipes_silently_and_the_device_looks_fresh() {
let mut owner = Owner::types(&["0000", "4321", "4321", "", ""]);
let new = run_with(&mut dev, &mut owner).unwrap();
assert!(!owner.shown.contains("Wrong"), "nothing tells it was a duress passcode");
assert!(owner.shown.starts_with("This device has no passcode yet"), "nor is the passcode prompt left showing");
assert!(owner.shown.contains("no passcode yet"));
assert_ne!(new.0, key);
}

View File

@@ -25,6 +25,8 @@ pub enum StorageRequest {
Mkdir { path_len: usize },
/// Carries the endpoint to print to.
SetLog,
/// Half (`half`: 0 or 1) of the master key.
SetKey { half: usize, words: [usize; 2] },
/// A capability to the path (`path_len` bytes of the buffer), inside
/// the caller's scope.
Grant {
@@ -74,6 +76,7 @@ impl Encode for StorageRequest {
Delete { path_len } => [op::DELETE, path_len, 0, 0],
Mkdir { path_len } => [op::MKDIR, path_len, 0, 0],
SetLog => [op::SET_LOG, 0, 0, 0],
SetKey { half, words } => [op::SET_KEY, half, words[0], words[1]],
Grant { path_len, write } => [op::GRANT, path_len, usize::from(write), 0],
Release => [op::RELEASE, 0, 0, 0],
}
@@ -95,6 +98,7 @@ impl Decode for StorageRequest {
op::DELETE => Delete { path_len: w[1] },
op::MKDIR => Mkdir { path_len: w[1] },
op::SET_LOG => SetLog,
op::SET_KEY => SetKey { half: w[1], words: [w[2], w[3]] },
op::GRANT => Grant {
path_len: w[1],
write: w[2] != 0,

View File

@@ -50,6 +50,9 @@ pub struct StorageServer<F: FileSystem, H: Host> {
clients: [Option<Client>; MAX_CLIENTS],
owners: [Option<Owner>; MAX_HANDLES],
log: Option<CapSlot>,
/// The master key's halves, from the gatekeeper through init: what the
/// disk's encryption will be keyed with.
key: [Option<[usize; 2]>; 2],
}
impl<F: FileSystem, H: Host> StorageServer<F, H> {
@@ -61,6 +64,7 @@ impl<F: FileSystem, H: Host> StorageServer<F, H> {
clients: [const { None }; MAX_CLIENTS],
owners: [None; MAX_HANDLES],
log: None,
key: [None; 2],
}
}
@@ -83,6 +87,23 @@ impl<F: FileSystem, H: Host> StorageServer<F, H> {
}
}
/// Only the unbadged holder (init), each half only once: nobody can
/// replace the key later.
fn set_key(&mut self, badge: usize, half: usize, words: [usize; 2]) -> StorageResponse {
match (badge, self.key.get_mut(half)) {
(0, Some(slot @ None)) => {
*slot = Some(words);
StorageResponse::Ok
}
_ => StorageResponse::Error,
}
}
/// Whether the whole master key has arrived.
pub fn unlocked(&self) -> bool {
self.key.iter().all(Option::is_some)
}
pub fn filesystem(&self) -> &F {
&self.fs
}
@@ -265,7 +286,7 @@ impl<F: FileSystem, H: Host> StorageServer<F, H> {
None => R::NotFound,
};
let response = match request {
Attach | SetLog | Release => R::Error,
Attach | SetLog | SetKey { .. } | Release => R::Error,
Grant { path_len, write } => {
let narrower = scope.narrow(&buf[sent(path_len)], write);
return match narrower.and_then(|s| grants.add(badge, s, |b| host.mint(b))) {
@@ -368,6 +389,7 @@ impl<F: FileSystem, H: Host> Server for StorageServer<F, H> {
) -> ([usize; 4], Option<Give>) {
match StorageRequest::decode(words) {
Some(StorageRequest::SetLog) => (self.set_log(badge, cap).encode(), None),
Some(StorageRequest::SetKey { half, words }) => (self.set_key(badge, half, words).encode(), None),
// A badge storage never issued, or one it has taken back.
Some(request) => match self.grants.scope(badge) {
None => (StorageResponse::Denied.encode(), None),

View File

@@ -25,6 +25,7 @@ fn every_request_roundtrips() {
write: false,
},
StorageRequest::Release,
StorageRequest::SetKey { half: 1, words: [7, 9] },
] {
assert_eq!(StorageRequest::decode(req.encode()), Some(req));
}

View File

@@ -472,3 +472,16 @@ fn the_unbadged_holder_cannot_be_released() {
StorageResponse::Error
);
}
#[test]
fn only_init_sets_the_key_and_only_once() {
let mut s = server();
let set = |s: &mut Srv, badge, half| call(s, badge, StorageRequest::SetKey { half, words: [1, 2] }).0;
assert_eq!(set(&mut s, 5, 0), StorageResponse::Error, "a client cannot");
assert_eq!(set(&mut s, 0, 0), StorageResponse::Ok);
assert!(!s.unlocked());
assert_eq!(set(&mut s, 0, 0), StorageResponse::Error, "nor can it be replaced");
assert_eq!(set(&mut s, 0, 2), StorageResponse::Error, "two halves only");
assert_eq!(set(&mut s, 0, 1), StorageResponse::Ok);
assert!(s.unlocked());
}

View File

@@ -157,9 +157,9 @@ impl<C: Console> TerminalServer<C> {
}
}
/// Edits a line from the keyboard, echoing it, until Enter. Ctrl+C
/// drops it and reads as an empty line.
fn read_line(&mut self) {
/// Edits a line from the keyboard, echoing it (as `*` if `secret`),
/// until Enter. Ctrl+C drops it and reads as an empty line.
fn read_line(&mut self, secret: bool) {
self.console.flush();
// Flushed now; a flush timer still running is harmless.
self.flush_pending = false;
@@ -190,7 +190,7 @@ impl<C: Console> TerminalServer<C> {
b if self.line_len + 1 < MAX_LINE && (b' '..=b'~').contains(&b) => {
self.line[self.line_len] = b;
self.line_len += 1;
self.grid.put(b);
self.grid.put(if secret { b'*' } else { b });
}
_ => continue,
}
@@ -202,14 +202,18 @@ impl<C: Console> TerminalServer<C> {
}
/// The next chunk of the typed line, reading one first if none is left.
fn read(&mut self) -> [usize; 4] {
/// A secret line never reaches the screen, and is forgotten once read.
fn read(&mut self, secret: bool) -> [usize; 4] {
if self.line_read == self.line_len {
self.read_line();
self.read_line(secret);
}
let end = (self.line_read + TEXT_BYTES).min(self.line_len);
let chunk = &self.line[self.line_read..end];
let words = text_words(&self.line[self.line_read..end]);
self.line_read = end;
text_words(chunk)
if secret && self.line_read == self.line_len {
self.line.fill(0);
}
words
}
}
@@ -230,7 +234,8 @@ impl<C: Console> Server for TerminalServer<C> {
fn handle_call(&mut self, _badge: usize, words: [usize; 4], cap: Option<CapSlot>) -> ([usize; 4], Option<libkos::syscall::Give>) {
let reply = match words[0] {
types::terminal::READ => self.read(),
types::terminal::READ => self.read(false),
types::terminal::READ_SECRET => self.read(true),
types::terminal::REDRAW => {
// Taking focus back clears the screen.
self.console.take_focus();

View File

@@ -176,3 +176,13 @@ fn rows_are_drawn_only_as_wide_as_their_text_or_what_it_replaces() {
// Cleared: the old five cells and the cursor after them are erased.
assert!(t.console().rows_drawn.contains(&(0, 6)), "{:?}", t.console().rows_drawn);
}
#[test]
fn a_secret_line_shows_stars_and_is_forgotten() {
let mut t = term(b"hunter2\n");
let (words, _) = t.handle_call(1, [types::terminal::READ_SECRET, 0, 0, 0], None);
let (bytes, len) = text_of(words).unwrap();
assert_eq!(&bytes[..len], b"hunter2\n");
assert_eq!(&t.grid().row(0)[..8], b"*******\x20");
assert!(!t.grid().row(0).windows(7).any(|w| w == b"hunter2"));
}