From e45e77e5922a42d16b2c3ce173e72937896b933b Mon Sep 17 00:00:00 2001 From: Sami Fouad Date: Wed, 11 Nov 2026 12:52:35 -0600 Subject: [PATCH 1/8] Layer 1 microVM: deliver every guest log line, numbered and acknowledged (#86) The launcher shut its side of each log connection for writing. Firecracker turns a host's half-close into a full close of the connection and drops whatever the guest sends after it, while the guest's write() has already returned: lines vanished at random, and pump_log's reconnects and report()'s connection per line filled LOG_SLOTS, so more were refused. The guest now numbers every line (php-fpm's output and the init's own) and holds it until the host acknowledges it, on one connection, sending again what wasn't acknowledged after a broken or stalled connection or a restore. The host logs each frame once and acknowledges it. A full guest buffer, a gap in the numbers or lines unacknowledged at a stop become the launcher's own counted line. PROTOCOL 5. ext-pr.yml runs all eight ext-* suites on the microVM target. --- .github/workflows/ext-pr.yml | 7 +- ext/fpm/src/guest.rs | 66 ++-- ext/fpm/src/guestlog.rs | 602 +++++++++++++++++++++++++++++++++++ ext/fpm/src/lib.rs | 1 + ext/fpm/src/vm.rs | 102 +++--- test/ext-microvm.sh | 63 +++- test/ext/microvm/probe.php | 8 + 7 files changed, 753 insertions(+), 96 deletions(-) create mode 100644 ext/fpm/src/guestlog.rs diff --git a/.github/workflows/ext-pr.yml b/.github/workflows/ext-pr.yml index a8943f0..ae9db52 100644 --- a/.github/workflows/ext-pr.yml +++ b/.github/workflows/ext-pr.yml @@ -144,14 +144,13 @@ jobs: - name: test/ext-microvm.sh run: sudo -E env PATH="$PATH" TMPDIR="$PWD/.tmp" test/ext-microvm.sh # The ext-* suites on the microVM target (#72, test/lib/target.sh): php-fpm in the guest, - # behind the stack's nginx. Each check that can't apply in a guest says n/a and why. Not - # here yet: ext-enforce, ext-db and ext-vault, whose audit-line checks intermittently miss - # lines the guest's php-fpm logged (#86); they run on this target by hand until it's fixed. + # behind the stack's nginx. Each check that can't apply in a guest says n/a and why. All + # eight suites: the guest's log lines reach the launcher's log, every one (#86). - name: The ext-* suites on the microVM target (SC_TARGET=microvm) run: | set -u rc=0 - for s in config attribution layer3 layer1 hosts; do + for s in config attribution layer3 layer1 hosts enforce db vault; do echo "::group::test/ext-$s.sh (microvm)" sudo -E env PATH="$PATH" TMPDIR="$PWD/.tmp" SC_TARGET=microvm "test/ext-$s.sh" || { echo "::error::test/ext-$s.sh failed on the microVM target"; rc=1; } echo "::endgroup::" diff --git a/ext/fpm/src/guest.rs b/ext/fpm/src/guest.rs index 6bd27ab..07f44b8 100644 --- a/ext/fpm/src/guest.rs +++ b/ext/fpm/src/guest.rs @@ -7,7 +7,9 @@ //! out php-fpm's connect to 127.0.0.1: is a vsock connect to the host on that port //! (libsc-vsock-connect.so, #70), for each port the host forwards (sc.ports); a unix //! socket under /run (sc.sock) reaches the same port through a forwarder here -//! log php-fpm's stdout and stderr → vsock host:1514 (the serial console is too slow) +//! log php-fpm's stdout and stderr, and this init's own lines → vsock host:1514 (the serial +//! console is too slow), numbered and held until the host acknowledges them (#86, +//! [`crate::guestlog`]) //! ctl vsock 1515: the host's start message, sent after every cold boot and every restore: //! the clock, then the writable disks to mount; and `sync` before it stops the VM //! (see [`Ctl`]) @@ -21,7 +23,7 @@ use std::ffi::CString; use std::fs; -use std::io::{self, BufRead, BufReader, Read, Write}; +use std::io::{self, BufRead, BufReader, Write}; use std::net::TcpStream; use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; use std::os::unix::net::UnixListener; @@ -493,11 +495,13 @@ fn apply(ctl: &Ctl) -> io::Result<()> { // SAFETY: sync(2) takes nothing and can't fail. unsafe { libc::sync() }; // And every change to a writable folder is on the host's copy of it (#72). - if WRITABLE.lock().unwrap_or_else(|p| p.into_inner()).is_empty() { - return Ok(()); + if !WRITABLE.lock().unwrap_or_else(|p| p.into_inner()).is_empty() { + let drain = DRAIN.get().ok_or_else(|| io::Error::other("the folder sync never started"))?; + drain.wait(SYNC_DRAIN).map_err(|e| io::Error::other(format!("the writable folders did not sync to the host: {e}")))?; } - let drain = DRAIN.get().ok_or_else(|| io::Error::other("the folder sync never started"))?; - drain.wait(SYNC_DRAIN).map_err(|e| io::Error::other(format!("the writable folders did not sync to the host: {e}"))) + // The host stops the VM after a sync: every log line must be in its log by then, or + // counted there as lost (the reply is the launcher's to log). + LOG.drain(LOG_DRAIN).map_err(|n| io::Error::other(crate::guestlog::lost(n as u64, "not acknowledged by the host before the stop"))) } // Checked before anything is applied ([`protocol_ok`]). Ctl::Proto { .. } | Ctl::Done => Ok(()), @@ -569,15 +573,28 @@ fn serve_ctl(conn: Vsock, peer_cid: u32) { { report(&format!("ctl: the start message was refused: {e}")); } + // A refusal may end the launcher: the lines that explain it reach its log first. + if failed.is_some() { + let _ = LOG.drain(LOG_DRAIN); + } let reply = failed.map_or_else(|| "ok\n".to_owned(), |e| format!("error {e}\n")); let _ = out.write_all(reply.as_bytes()); } +/// Every line for the host's log (php-fpm's output and this init's own), held until the host +/// acknowledges it (#86): one numbered stream on one connection ([`crate::guestlog`]). +static LOG: crate::guestlog::Outbox = crate::guestlog::Outbox::new(crate::guestlog::OUTBOX_BYTES); +/// How long a `sync` waits for the host to have every log line (inside [`SYNC_TIMEOUT`]). +const LOG_DRAIN: Duration = Duration::from_secs(1); + +/// The log's sender, once per boot (a restore resumes it with the snapshot). +fn start_log() { + thread::spawn(|| crate::guestlog::send(&LOG, || Vsock::connect(HOST_CID, LOG_PORT))); +} + /// One line to the host's log, from this init (the host marks every guest line as the guest's). fn report(message: &str) { - if let Ok(mut c) = Vsock::connect(HOST_CID, LOG_PORT) { - let _ = c.write_all(format!("securecore-init: {message}\n").as_bytes()); - } + LOG.line(format!("securecore-init: {message}").as_bytes()); } /// Warns once a writable disk passes 90 % (and again past 98 %): beyond it, php-fpm's writes @@ -608,28 +625,16 @@ fn watch_space() { } } -/// php-fpm's output to the host, reconnecting when the connection breaks (every restore -/// resets the guest's vsock connections). -fn pump_log(mut from: fs::File) { - let mut conn: Option = None; - let mut buf = vec![0u8; 64 * 1024]; - loop { - let n = match from.read(&mut buf) { - Ok(0) | Err(_) => return, - Ok(n) => n, - }; - for _ in 0..50 { - if conn.is_none() { - conn = Vsock::connect(HOST_CID, LOG_PORT).ok(); - } - match conn.as_mut().map(|c| c.write_all(&buf[..n])) { - Some(Ok(())) => break, - _ => { - conn = None; - thread::sleep(Duration::from_millis(20)); - } - } +/// php-fpm's output to the host's log, a line at a time ([`LOG`] delivers it). Never blocks on +/// the host: php-fpm's master writes every worker's lines to this pipe. +fn pump_log(from: fs::File) { + let mut r = BufReader::with_capacity(64 << 10, from); + let mut line = Vec::with_capacity(256); + while let Some(cut) = crate::guestlog::read_capped(&mut r, &mut line, crate::guestlog::MAX_LINE) { + if cut { + line.extend_from_slice(" …[cut]".as_bytes()); } + LOG.line(&line); } } @@ -818,6 +823,7 @@ fn boot_guest() -> io::Result { // (`commit=1` on the mount). The defaults are 30 s and 5 s. fs::write("/proc/sys/vm/dirty_expire_centisecs", "100")?; fs::write("/proc/sys/vm/dirty_writeback_centisecs", "50")?; + start_log(); listen_forwards(&boot)?; let pid = start_php_fpm(&boot)?; FPM_MASTER.store(pid as i32, Ordering::SeqCst); diff --git a/ext/fpm/src/guestlog.rs b/ext/fpm/src/guestlog.rs new file mode 100644 index 0000000..f0bc93c --- /dev/null +++ b/ext/fpm/src/guestlog.rs @@ -0,0 +1,602 @@ +//! The guest's log channel to the host (vsock 1514, addiscorp/securecore#86): php-fpm's output +//! and the init's own lines, delivered so that no line is ever lost without the launcher saying so. +//! +//! A `write()` that returns in the guest only means the guest's kernel took the bytes: a restore +//! resets every vsock connection, and Firecracker drops what a guest sends on a connection whose +//! host side is closing. So the guest keeps every line until the host has acknowledged it: +//! +//! ```text +//! guest → host L \n one line (text holds no newline) +//! X \n lines dropped here (the guest's buffer was full) +//! host → guest A \n every frame up to is in the launcher's log +//! ``` +//! +//! - **The guest** ([`Outbox`], [`send`]) numbers each line, queues it (up to [`OUTBOX_BYTES`]), +//! sends it on one connection and drops it once acknowledged. A broken connection, or one on +//! which nothing is acknowledged for [`ACK_STALL`], is replaced, and every unacknowledged frame +//! is sent again. A line that doesn't fit in the buffer is counted, and the count goes out as a +//! frame of its own, in order, before the next line. +//! - **The host** ([`Inbox`], [`serve`]) logs each frame once (a frame sent again is skipped by +//! its number), every line marked `guest: ` so the guest can't write the launcher's own lines, +//! and acknowledges. A count frame, or a gap in the numbers, becomes the launcher's own line +//! `securecore-fpm: N guest log lines lost (…)`. +//! +//! Plain Rust over any connection ([`Conn`]), so the tests drive it over unix sockets. + +use std::collections::VecDeque; +use std::io::{self, BufRead, BufReader, Read, Write}; +use std::sync::{Condvar, Mutex}; +use std::thread; +use std::time::{Duration, Instant}; + +/// The longest guest log line kept whole; a longer one is cut there and marked. +pub const MAX_LINE: usize = 8 * 1024; +/// What the guest holds for the host before it starts counting lines as lost. +pub const OUTBOX_BYTES: usize = 4 << 20; +/// A connection on which unacknowledged frames wait this long without an acknowledgement is +/// replaced (the host may be gone without the guest's kernel knowing). +pub const ACK_STALL: Duration = Duration::from_secs(2); + +/// One frame from the guest. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Frame { + Line { seq: u64, text: Vec }, + Lost { seq: u64, count: u64 }, +} + +impl Frame { + pub fn seq(&self) -> u64 { + match self { + Frame::Line { seq, .. } | Frame::Lost { seq, .. } => *seq, + } + } + + pub fn encode(&self) -> Vec { + match self { + Frame::Line { seq, text } => { + let mut out = format!("L {seq} ").into_bytes(); + out.extend_from_slice(text); + out.push(b'\n'); + out + } + Frame::Lost { seq, count } => format!("X {seq} {count}\n").into_bytes(), + } + } + + /// One received line, without its newline. `None`: not a frame. + pub fn parse(line: &[u8]) -> Option { + let (kind, rest) = (line.first()?, line.get(1..)?); + let rest = rest.strip_prefix(b" ")?; + let sp = rest.iter().position(|&b| b == b' '); + let (num, tail) = match sp { + Some(i) => (&rest[..i], &rest[i + 1..]), + None => (rest, &b""[..]), + }; + let seq = std::str::from_utf8(num).ok()?.parse::().ok().filter(|s| *s > 0)?; + match kind { + b'L' if sp.is_some() => Some(Frame::Line { seq, text: tail.to_vec() }), + b'X' => Some(Frame::Lost { seq, count: std::str::from_utf8(tail).ok()?.parse().ok()? }), + _ => None, + } + } +} + +/// The host's acknowledgement of every frame up to `seq`. +pub fn ack_line(seq: u64) -> String { + format!("A {seq}\n") +} + +fn parse_ack(line: &str) -> Option { + line.strip_prefix("A ")?.trim_end().parse().ok() +} + +/// Reads one line of at most `cap` bytes into `line` (without its newline, a trailing `\r` +/// dropped): `Some(cut)` when a line was read (`cut`: it was longer, and the rest was skipped), +/// `None` at the end of the stream with nothing read. Never buffers more than `cap`. +pub fn read_capped(r: &mut impl BufRead, line: &mut Vec, cap: usize) -> Option { + line.clear(); + let mut cut = false; + loop { + let buf = match r.fill_buf() { + Ok([]) | Err(_) => { + return if line.is_empty() && !cut { None } else { Some(cut) }; + } + Ok(b) => b, + }; + let (take, done) = match buf.iter().position(|&b| b == b'\n') { + Some(i) => (i, true), + None => (buf.len(), false), + }; + let room = cap.saturating_sub(line.len()); + line.extend_from_slice(&buf[..take.min(room)]); + cut |= take > room; + r.consume(if done { take + 1 } else { take }); + if done { + if line.last() == Some(&b'\r') { + line.pop(); + } + return Some(cut); + } + } +} + +#[derive(Debug, Default)] +struct Queue { + /// Unacknowledged frames, oldest first, each with its encoding. + frames: VecDeque<(u64, Vec)>, + bytes: usize, + /// The last number given out. + seq: u64, + /// Lines dropped since the last count frame. + lost: u64, + /// Bumped each time the connection in use is given up. + conn: u64, + /// When an acknowledgement last arrived (or the connection was made). + acked_at: Option, +} + +impl Queue { + fn push(&mut self, frame: impl FnOnce(u64) -> Frame) { + self.seq += 1; + let bytes = frame(self.seq).encode(); + self.bytes += bytes.len(); + self.frames.push_back((self.seq, bytes)); + } + + fn push_lost(&mut self) { + if self.lost > 0 { + let count = std::mem::take(&mut self.lost); + self.push(|seq| Frame::Lost { seq, count }); + } + } +} + +/// The guest's lines for the host, held until acknowledged ([`send`] delivers them). +pub struct Outbox { + q: Mutex, + cv: Condvar, + cap: usize, +} + +impl Outbox { + pub const fn new(cap: usize) -> Outbox { + Outbox { + q: Mutex::new(Queue { frames: VecDeque::new(), bytes: 0, seq: 0, lost: 0, conn: 0, acked_at: None }), + cv: Condvar::new(), + cap, + } + } + + fn lock(&self) -> std::sync::MutexGuard<'_, Queue> { + self.q.lock().unwrap_or_else(|p| p.into_inner()) + } + + /// Queues one line (cut at [`MAX_LINE`]); it is never written to the caller's stream, so a + /// slow host never blocks php-fpm. When the buffer is full the line is counted as lost, and + /// the count is sent, in order, before the next line that fits. + pub fn line(&self, text: &[u8]) { + let mut text = text.to_vec(); + if text.len() > MAX_LINE { + text.truncate(MAX_LINE); + text.extend_from_slice(" …[cut]".as_bytes()); + } + let mut q = self.lock(); + // A count frame is small; the line must fit beside it. + let need = text.len() + 64; + if q.bytes + need > self.cap { + q.lost += 1; + return; + } + q.push_lost(); + q.push(|seq| Frame::Line { seq, text }); + self.cv.notify_all(); + } + + /// The host has every frame up to `seq`. + pub fn ack(&self, seq: u64) { + let mut q = self.lock(); + let mut progressed = false; + while q.frames.front().is_some_and(|(s, _)| *s <= seq) { + let (_, b) = q.frames.pop_front().unwrap_or_default(); + q.bytes -= b.len(); + progressed = true; + } + if progressed { + q.acked_at = Some(Instant::now()); + } + self.cv.notify_all(); + } + + /// Frames not yet acknowledged (and lines counted but not yet sent as a count). + pub fn pending(&self) -> (usize, u64) { + let q = self.lock(); + (q.frames.len(), q.lost) + } + + /// Waits up to `timeout` for the host to have every line; the count still pending if not. + /// A count of lost lines is queued first, so the host hears of them too. + pub fn drain(&self, timeout: Duration) -> Result<(), usize> { + let t = Instant::now(); + let mut q = self.lock(); + if q.lost > 0 { + q.push_lost(); + self.cv.notify_all(); + } + while !q.frames.is_empty() { + let left = timeout.saturating_sub(t.elapsed()); + if left.is_zero() { + return Err(q.frames.len()); + } + q = self.cv.wait_timeout(q, left).unwrap_or_else(|p| p.into_inner()).0; + } + Ok(()) + } + + /// Gives up connection `conn` (if it is still the one in use). + fn broken(&self, conn: u64) { + let mut q = self.lock(); + if q.conn == conn { + q.conn += 1; + } + self.cv.notify_all(); + } +} + +/// A connection the log goes over: duplicated for the acknowledgement reader, and shut to end it. +pub trait Conn: Read + Write + Send + Sized + 'static { + fn dup(&self) -> io::Result; + fn shut(&self); +} + +impl Conn for std::os::unix::net::UnixStream { + fn dup(&self) -> io::Result { + self.try_clone() + } + fn shut(&self) { + let _ = self.shutdown(std::net::Shutdown::Both); + } +} + +#[cfg(target_os = "linux")] +impl Conn for crate::vsock::Vsock { + fn dup(&self) -> io::Result { + crate::vsock::Half::dup(self) + } + fn shut(&self) { + crate::vsock::Half::shut(self, std::net::Shutdown::Both); + } +} + +/// Delivers `outbox` for ever over connections from `connect`: one at a time; each new one starts +/// with every unacknowledged frame again. +pub fn send(outbox: &'static Outbox, connect: impl Fn() -> io::Result) -> ! { + let mut backoff = Duration::from_millis(10); + loop { + // Nothing to send: wait for a line before connecting. + { + let mut q = outbox.lock(); + while q.frames.is_empty() { + q = outbox.cv.wait(q).unwrap_or_else(|p| p.into_inner()); + } + } + let conn = match connect() { + Ok(c) => c, + Err(_) => { + thread::sleep(backoff); + backoff = (backoff * 2).min(Duration::from_millis(500)); + continue; + } + }; + backoff = Duration::from_millis(10); + let _ = deliver(outbox, conn); + } +} + +/// One connection's life: its acknowledgements read on a thread of their own, frames written +/// from the oldest unacknowledged one on, until it breaks or stalls. Every way out shuts it. +fn deliver(outbox: &'static Outbox, mut conn: C) -> io::Result<()> { + let id = { + let mut q = outbox.lock(); + q.acked_at = Some(Instant::now()); + q.conn + }; + let reader = conn.dup()?; + let acks = thread::spawn(move || { + let mut r = BufReader::new(reader); + let mut line = Vec::new(); + while let Some(false) = read_capped(&mut r, &mut line, 64) { + match std::str::from_utf8(&line).ok().and_then(parse_ack) { + Some(seq) => outbox.ack(seq), + None => break, + } + } + outbox.broken(id); + }); + let mut sent = 0u64; + let result = loop { + let batch: Vec = { + let mut q = outbox.lock(); + loop { + if q.conn != id { + break; + } + let stalled = !q.frames.is_empty() && q.acked_at.is_some_and(|t| t.elapsed() > ACK_STALL); + if stalled { + q.conn += 1; + break; + } + if q.frames.back().is_some_and(|(s, _)| *s > sent) { + break; + } + q = outbox.cv.wait_timeout(q, Duration::from_millis(250)).unwrap_or_else(|p| p.into_inner()).0; + } + if q.conn != id { + break Ok(()); + } + // Nothing sent before is still waiting: the wait for an acknowledgement starts now. + if q.frames.front().is_some_and(|(s, _)| *s > sent) { + q.acked_at = Some(Instant::now()); + } + let mut batch = Vec::new(); + let from = sent; + for (s, b) in q.frames.iter().filter(|(s, _)| *s > from) { + if batch.len() + b.len() > 256 << 10 && !batch.is_empty() { + break; + } + batch.extend_from_slice(b); + sent = *s; + } + batch + }; + if let Err(e) = conn.write_all(&batch) { + outbox.broken(id); + break Err(e); + } + }; + conn.shut(); + let _ = acks.join(); + result +} + +/// The host's view of one guest's log: the last frame logged. +#[derive(Debug, Default)] +pub struct Inbox { + last: Option, +} + +impl Inbox { + /// What `frame` adds to the launcher's log: nothing for a frame already logged; a count of + /// the lines lost for a gap before it or a count frame; the guest's line marked as the guest's. + pub fn take(&mut self, frame: &Frame, cut: bool) -> Vec { + let seq = frame.seq(); + let mut out = Vec::new(); + if let Some(last) = self.last { + if seq <= last { + return out; + } + if seq > last + 1 { + out.push(lost_line(seq - last - 1, "missing from the guest's numbered stream")); + } + } + self.last = Some(seq); + match frame { + Frame::Line { text, .. } => out.push(guest_line(text, cut)), + Frame::Lost { count, .. } => out.push(lost_line(*count, "the guest's log buffer was full")), + } + out + } + + pub fn last(&self) -> Option { + self.last + } +} + +/// The launcher's own line for lines that never arrived. +pub fn lost_line(count: u64, why: &str) -> String { + format!("securecore-fpm: {}", lost(count, why)) +} + +/// `N guest log lines lost (why)`: the count the launcher logs, whichever side found it. +pub fn lost(count: u64, why: &str) -> String { + format!("{count} guest log line{} lost ({why})", if count == 1 { "" } else { "s" }) +} + +/// A guest's line as the launcher logs it: marked, so it never reads as the launcher's own. +pub fn guest_line(text: &[u8], cut: bool) -> String { + format!("guest: {}{}", String::from_utf8_lossy(text), if cut { " …[cut]" } else { "" }) +} + +/// The longest frame line the host reads whole: a line, its number and its kind. +const MAX_FRAME: usize = MAX_LINE + 64; + +/// One log connection on the host: frames from `from`, logged to `to` through `inbox` (shared by +/// every connection of one guest), each batch acknowledged on `ack`. A line that isn't a frame +/// is logged as the guest's, unnumbered. +pub fn serve(from: impl Read, mut ack: impl Write, inbox: &Mutex, to: &mut impl Write) { + let mut r = BufReader::with_capacity(64 << 10, from); + let mut line = Vec::with_capacity(256); + while let Some(cut) = read_capped(&mut r, &mut line, MAX_FRAME) { + let out = match Frame::parse(&line) { + Some(frame) => inbox.lock().unwrap_or_else(|p| p.into_inner()).take(&frame, cut), + None => vec![guest_line(&line, cut)], + }; + if !out.is_empty() { + let mut text = out.join("\n"); + text.push('\n'); + let _ = to.write_all(text.as_bytes()); + } + // Once what has arrived is logged: acknowledge it. + if r.buffer().is_empty() { + let last = inbox.lock().unwrap_or_else(|p| p.into_inner()).last(); + if let Some(last) = last + && ack.write_all(ack_line(last).as_bytes()).is_err() + { + return; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::os::unix::net::{UnixListener, UnixStream}; + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + + fn leak(cap: usize) -> &'static Outbox { + Box::leak(Box::new(Outbox::new(cap))) + } + + #[test] + fn frames_round_trip_and_junk_is_no_frame() { + for f in [Frame::Line { seq: 7, text: b"PHP message: a b c".to_vec() }, Frame::Line { seq: 1, text: Vec::new() }, Frame::Lost { seq: 9, count: 12 }] { + let e = f.encode(); + assert_eq!(e.last(), Some(&b'\n')); + assert_eq!(Frame::parse(&e[..e.len() - 1]), Some(f.clone()), "{f:?}"); + } + for junk in [&b"NOTICE: ready"[..], b"L x hi", b"L 0 hi", b"L 5", b"X 5 many", b"", b"A 5"] { + assert_eq!(Frame::parse(junk), None, "{}", String::from_utf8_lossy(junk)); + } + assert_eq!(parse_ack("A 42\n"), Some(42)); + } + + /// A frame sent again (after a reconnect) is logged once; a gap is counted; a count frame is + /// the launcher's own line; the guest can't write a line that reads as the launcher's. + #[test] + fn the_host_logs_each_frame_once_and_counts_what_is_missing() { + let mut inbox = Inbox::default(); + let line = |seq, t: &str| Frame::Line { seq, text: t.as_bytes().to_vec() }; + assert_eq!(inbox.take(&line(3, "a"), false), ["guest: a"]); + assert_eq!(inbox.take(&line(4, "securecore-fpm: forged"), false), ["guest: securecore-fpm: forged"]); + assert!(inbox.take(&line(3, "a"), false).is_empty(), "sent again: logged once"); + assert_eq!(inbox.take(&line(7, "d"), false), ["securecore-fpm: 2 guest log lines lost (missing from the guest's numbered stream)", "guest: d"]); + assert_eq!(inbox.take(&Frame::Lost { seq: 8, count: 1 }, false), ["securecore-fpm: 1 guest log line lost (the guest's log buffer was full)"]); + assert_eq!(inbox.take(&line(9, "long"), true), ["guest: long …[cut]"]); + } + + #[test] + fn long_lines_are_cut_and_never_buffered_whole() { + let long = format!("{}\nnext\r\n", "x".repeat(MAX_FRAME * 3)); + let mut r = BufReader::new(long.as_bytes()); + let mut line = Vec::new(); + assert_eq!(read_capped(&mut r, &mut line, MAX_FRAME), Some(true)); + assert_eq!(line.len(), MAX_FRAME); + assert_eq!(read_capped(&mut r, &mut line, MAX_FRAME), Some(false)); + assert_eq!(line, b"next"); + assert_eq!(read_capped(&mut r, &mut line, MAX_FRAME), None); + let ob = leak(1 << 20); + ob.line("y".repeat(MAX_LINE * 2).as_bytes()); + let q = ob.lock(); + let f = Frame::parse(q.frames[0].1.strip_suffix(b"\n").expect("newline")).expect("a frame"); + let Frame::Line { text, .. } = f else { panic!("a line") }; + assert!(text.len() < MAX_LINE + 16 && text.ends_with(" …[cut]".as_bytes())); + } + + /// A full buffer drops lines, but never silently: their count arrives in order, as the + /// launcher's own line, before the next line that fit. + #[test] + fn a_full_buffer_is_counted_and_the_count_is_delivered() { + let ob = leak(400); + for i in 0..20 { + ob.line(format!("line {i:02} {}", "z".repeat(40)).as_bytes()); + } + let (queued, lost) = ob.pending(); + assert!(queued > 0 && lost > 0 && queued as u64 + lost == 20, "queued {queued} lost {lost}"); + ob.ack(u64::MAX); + ob.line(b"after"); + let mut log = Vec::new(); + let inbox = Mutex::new(Inbox { last: Some(queued as u64) }); + let frames: Vec = ob.lock().frames.iter().flat_map(|(_, b)| b.clone()).collect(); + serve(&frames[..], io::sink(), &inbox, &mut log); + let log = String::from_utf8(log).expect("utf8"); + assert_eq!(log, format!("securecore-fpm: {lost} guest log lines lost (the guest's log buffer was full)\nguest: after\n")); + } + + /// The host's side of the stress below: a log listener that, for its first `drops` + /// connections, reads a few frames and then closes without a word (a restore's reset, a dying + /// connection) or keeps silent (Firecracker dropping a closing connection's data); then + /// serves for real. + fn flaky_host(l: UnixListener, drops: usize, inbox: Arc>, log: Arc>>, conns: Arc) { + for (n, c) in l.incoming().flatten().enumerate() { + conns.fetch_add(1, Ordering::SeqCst); + if n < drops { + let mut r = BufReader::new(c); + let mut line = Vec::new(); + for _ in 0..(n * 7 % 50) { + if read_capped(&mut r, &mut line, MAX_FRAME).is_none() { + break; + } + } + if n % 2 == 1 { + // Silent: holds the connection, reads and never acknowledges. + let mut sink = Vec::new(); + let _ = r.get_mut().set_read_timeout(Some(Duration::from_secs(3))); + let _ = r.read_to_end(&mut sink); + } + continue; + } + let (inbox, log) = (inbox.clone(), log.clone()); + thread::spawn(move || { + let ack = c.try_clone().expect("dup"); + serve(c, ack, &inbox, &mut Writer(log)); + }); + } + } + + #[derive(Clone)] + struct Writer(Arc>>); + impl Write for Writer { + fn write(&mut self, b: &[u8]) -> io::Result { + self.0.lock().expect("log").extend_from_slice(b); + Ok(b.len()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + } + + /// Every line arrives exactly once, in order, through connections that die mid-stream or + /// swallow what they get: the guest sends again whatever the host hasn't acknowledged. + #[test] + fn every_line_arrives_once_through_connections_that_die_or_stall() { + let dir = std::env::temp_dir().join(format!("sc-guestlog-{}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("log.sock"); + let _ = std::fs::remove_file(&path); + let l = UnixListener::bind(&path).expect("bind"); + let (inbox, log, conns) = (Arc::new(Mutex::new(Inbox::default())), Arc::new(Mutex::new(Vec::new())), Arc::new(AtomicUsize::new(0))); + { + let (inbox, log, conns) = (inbox.clone(), log.clone(), conns.clone()); + thread::spawn(move || flaky_host(l, 4, inbox, log, conns)); + } + let ob = leak(OUTBOX_BYTES); + let p = path.clone(); + thread::spawn(move || send(ob, move || UnixStream::connect(&p))); + let writers: Vec<_> = (0..4) + .map(|w| { + thread::spawn(move || { + for i in 0..500 { + ob.line(format!("w{w} line {i:03}").as_bytes()); + if i % 100 == 0 { + thread::sleep(Duration::from_millis(20)); + } + } + }) + }) + .collect(); + for w in writers { + w.join().expect("writer"); + } + ob.drain(Duration::from_secs(30)).expect("the host acknowledged every line"); + let log = String::from_utf8(log.lock().expect("log").clone()).expect("utf8"); + assert!(!log.contains("lost"), "nothing lost: {}", &log[..log.len().min(400)]); + for w in 0..4 { + let mine: Vec<&str> = log.lines().filter(|l| l.starts_with(&format!("guest: w{w} "))).collect(); + let want: Vec = (0..500).map(|i| format!("guest: w{w} line {i:03}")).collect(); + assert_eq!(mine, want, "writer {w}: every line once, in order"); + } + assert!(conns.load(Ordering::SeqCst) > 4, "the dead and the silent connections were replaced"); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/ext/fpm/src/lib.rs b/ext/fpm/src/lib.rs index 46b3f4f..3f3f35b 100644 --- a/ext/fpm/src/lib.rs +++ b/ext/fpm/src/lib.rs @@ -22,6 +22,7 @@ pub mod egress; pub mod fcgi; #[cfg(target_os = "linux")] pub mod guest; +pub mod guestlog; #[cfg(target_os = "linux")] pub mod jail; #[cfg(target_os = "linux")] diff --git a/ext/fpm/src/vm.rs b/ext/fpm/src/vm.rs index 921968a..499e53a 100644 --- a/ext/fpm/src/vm.rs +++ b/ext/fpm/src/vm.rs @@ -9,7 +9,8 @@ //! folder bind-mounted into the jail (Firecracker connects as the jailed user), or a //! thread that connects to its TCP `address`. A port with neither is an egress port: //! the guest reaches named hosts on it through `/v.sock_1517` ([`crate::egress`]). -//! log guest port 1514 → this process's stderr, each line marked `guest: ` (read only) +//! log guest port 1514 → this process's stderr, each line marked `guest: `: numbered frames, +//! each logged once and acknowledged; a lost line is counted ([`crate::guestlog`], #86) //! ctl guest port 1515 ← one start message after each boot or restore (clock, fresh //! randomness, the workers' refresh after a restore, then the disks); later `sync` //! before a stop and `reload` on SIGUSR2/SIGHUP @@ -44,6 +45,7 @@ use std::os::unix::net::{UnixDatagram, UnixListener, UnixStream}; use std::os::unix::process::CommandExt as _; use std::path::{Path, PathBuf}; use std::process::{Child, Command, Stdio}; +use std::sync::Mutex; use std::sync::atomic::{AtomicBool, Ordering}; use std::thread; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; @@ -52,6 +54,7 @@ use securecore_config::Loaded; use sha2::{Digest as _, Sha256}; use crate::fcgi; +use crate::guestlog; use crate::guest::{CTL_PORT, Ctl, FPM_PORT, LOG_PORT}; use crate::jail::{self, Jail, User}; use crate::vsock; @@ -66,7 +69,8 @@ pub const DEFAULT_VM_USER: &str = "securecore-vm"; /// message, the sync), so old snapshots are never restored into a new driver. The guest's init /// is the same binary: it boots with `sc.proto=`, answers the handshake only when it is /// its own, and takes no start message otherwise ([`handshake`]). -pub const PROTOCOL: u32 = 4; +/// 5: the log port's numbered, acknowledged frames ([`guestlog`], #86). +pub const PROTOCOL: u32 = 5; /// KVM_GET_API_VERSION, and the only value every KVM since Linux 2.6.22 returns. const KVM_GET_API_VERSION: libc::c_ulong = 0xAE00; const KVM_API_VERSION: i32 = 12; @@ -1641,71 +1645,42 @@ fn wire(plan: &Plan, m: &Machine, j: &Jail, short: &Path, wiring: Wiring) -> Res }); } } - // php-fpm's log, to this process's stderr: read only, and every line marked as the guest's, - // so nothing the guest writes can pass for the launcher's own lines. + // php-fpm's log, to this process's stderr (#86): numbered frames, each logged once and + // acknowledged, every line marked as the guest's, so nothing the guest writes can pass for + // the launcher's own lines ([`crate::guestlog`]). Never shut for writing: Firecracker turns a + // host's half-close into a full close and drops whatever the guest sends after it. let l = bind_unix(&short.join(format!("v.sock_{LOG_PORT}")), owned)?; + let inbox: &'static Mutex = Box::leak(Box::new(Mutex::new(guestlog::Inbox::default()))); thread::spawn(move || { for c in l.incoming().flatten() { - let Some(slot) = LOG_SLOTS.take() else { continue }; + // The guest keeps one connection; more means old ones are dying. A refused one loses + // nothing (the guest sends again what isn't acknowledged), but it is said. + let Some(slot) = LOG_SLOTS.take() else { + log(&format!("the guest's log: {LOG_SLOTS_N} connections already open; refusing another (the guest sends its lines again)")); + continue; + }; thread::spawn(move || { let _slot = slot; - let _ = c.shutdown(std::net::Shutdown::Write); - mark_guest_lines(c, &mut io::stderr()); + let Ok(ack) = c.try_clone() else { return }; + guestlog::serve(c, ack, inbox, &mut Stderr); }); } }); Ok(()) } -/// Copies the guest's log to `to`, every line marked `guest: `, so no line the guest writes -/// reads as the launcher's own (`securecore-fpm: …`). -/// A line longer than [`MAX_LINE`] bytes is cut there (and marked), so the guest can't make the -/// launcher buffer without bound. -pub fn mark_guest_lines(from: impl Read, to: &mut impl Write) { - let mut r = BufReader::new(from); - let mut line: Vec = Vec::with_capacity(256); - loop { - line.clear(); - let mut cut = false; - let mut eof = false; - loop { - let buf = match r.fill_buf() { - Ok([]) => { - eof = true; - break; - } - Ok(b) => b, - Err(_) => { - eof = true; - break; - } - }; - let (take, done) = match buf.iter().position(|&b| b == b'\n') { - Some(i) => (i, true), - None => (buf.len(), false), - }; - let room = MAX_LINE.saturating_sub(line.len()); - line.extend_from_slice(&buf[..take.min(room)]); - cut |= take > room; - r.consume(if done { take + 1 } else { take }); - if done { - break; - } - } - if eof && line.is_empty() { - return; - } - let text = String::from_utf8_lossy(&line); - let _ = writeln!(to, "guest: {}{}", text.trim_end_matches('\r'), if cut { " …[cut]" } else { "" }); - if eof { - return; - } +/// The launcher's stderr, each write whole (a guest line never interleaves with another thread's). +struct Stderr; + +impl Write for Stderr { + fn write(&mut self, b: &[u8]) -> io::Result { + io::stderr().lock().write_all(b).map(|()| b.len()) + } + fn flush(&mut self) -> io::Result<()> { + io::stderr().flush() } } -/// The longest guest log line kept whole. -pub const MAX_LINE: usize = 8 * 1024; - /// A fixed number of slots: a connection takes one or is turned away. pub struct Slots(std::sync::atomic::AtomicUsize, usize); @@ -1768,8 +1743,9 @@ impl Default for Coalesce { } } -/// The guest's log connections at once (its php-fpm stream, and the init's short reports). -static LOG_SLOTS: Slots = Slots::new(4); +/// The guest's log connections at once: its one stream, and ones it is giving up. +const LOG_SLOTS_N: usize = 4; +static LOG_SLOTS: Slots = Slots::new(LOG_SLOTS_N); /// Connections through one `address` forward at once. const FORWARD_SLOTS: usize = 64; @@ -2720,14 +2696,16 @@ mod tests { #[test] fn guest_lines_are_capped_and_connections_counted() { - let long = format!("{}\nnext\n", "x".repeat(MAX_LINE * 3)); + let long = format!("L 1 {}\nL 2 next\n", "x".repeat(guestlog::MAX_LINE * 3)); let mut out = Vec::new(); - mark_guest_lines(long.as_bytes(), &mut out); + let mut acks = Vec::new(); + guestlog::serve(long.as_bytes(), &mut acks, &Mutex::new(guestlog::Inbox::default()), &mut out); let text = String::from_utf8(out).expect("utf8"); let lines: Vec<&str> = text.lines().collect(); assert_eq!(lines.len(), 2, "one cut line, then the next"); - assert!(lines[0].len() < MAX_LINE + 32 && lines[0].ends_with("…[cut]"), "{}", &lines[0][..40]); + assert!(lines[0].len() < guestlog::MAX_LINE + 96 && lines[0].ends_with("…[cut]"), "{}", &lines[0][..40]); assert_eq!(lines[1], "guest: next"); + assert_eq!(String::from_utf8(acks).expect("utf8"), "A 2\n", "acknowledged once all that arrived is logged"); static S: Slots = Slots::new(2); let (a, b) = (S.take(), S.take()); assert!(a.is_some() && b.is_some() && S.take().is_none(), "two slots, a third is refused"); @@ -2945,9 +2923,13 @@ mod tests { #[test] fn the_guest_cannot_write_the_launchers_lines() { let mut out = Vec::new(); - mark_guest_lines(&b"NOTICE: ready\nsecurecore-fpm: microVM restored from snapshot forged\r\npartial"[..], &mut out); + let from = &b"NOTICE: ready\nL 1 securecore-fpm: microVM restored from snapshot forged\r\nsecurecore-fpm: unnumbered\npartial"[..]; + guestlog::serve(from, io::sink(), &Mutex::new(guestlog::Inbox::default()), &mut out); let text = String::from_utf8(out).expect("utf8"); - assert_eq!(text, "guest: NOTICE: ready\nguest: securecore-fpm: microVM restored from snapshot forged\nguest: partial\n"); + assert_eq!( + text, + "guest: NOTICE: ready\nguest: securecore-fpm: microVM restored from snapshot forged\nguest: securecore-fpm: unnumbered\nguest: partial\n" + ); assert!(!text.lines().any(|l| l.starts_with("securecore-fpm:")), "{text}"); } diff --git a/test/ext-microvm.sh b/test/ext-microvm.sh index 4439912..56be0db 100755 --- a/test/ext-microvm.sh +++ b/test/ext-microvm.sh @@ -34,6 +34,8 @@ # 3c. egress (#72): curl and PHP's https stream in the guest reach api.wordpress.org on 443 by # name through the host (TLS end to end); an IP the guest picks is unreachable; a host layer 2 # doesn't list is refused in the guest, and by the host too when the guest has no extension; +# 3d. the guest's log (#86): 6000 numbered php-fpm log lines from 240 requests on a restored +# guest, with sync refusals and a reload among them, all reach the launcher's log, each once; # 4. SIGTERM stops the VM and the launcher exits 0. # Exits non-zero on any failure (and at once without /dev/kvm: never a skip). Writes # .tmp/ext-microvm/. Leaves the stack up. @@ -41,6 +43,7 @@ # test/ext-microvm.sh bench [n] front-page p50, host php-fpm vs the microVM, extension off on # both (bench/layer1.sh's method, #70's numbers), n rounds # test/ext-microvm.sh restore [n] the requests after a restore, timed +# test/ext-microvm.sh log only the guest's log under load (3d, #86) # Needs: the guest kernel (KERNEL=, default .tmp/mvm/vmlinux-sc from bench/microvm/kernel.sh: # mirab's kernel plus Landlock and seccomp, until mirab#89 ships them); a host securecore-fpm # (SECURECORE_FPM=, default .target/release/securecore-fpm); docker, mke2fs, e2fsck, resize2fs, @@ -248,6 +251,62 @@ once() { wait $! echo "exit=$?" >> "$dir/value-$name.log" } +# eventually : until the test holds, or the time is up. +eventually() { n=0; until eval "$2"; do n=$((n + 1)); [ "$n" -lt "$1" ] || return 1; sleep 0.1; done; } + +# The guest's log under load (#86): a restored guest; 240 requests, 8 at a time, each writing 25 +# numbered lines to php-fpm's log (6000 lines, as layer 2's audit lines go); 20 of them write an +# upload over a link the owner put in the host's folder, which the host's sync refuses (each +# refusal is a line the guest's init logs); a graceful reload between the two halves. Every line +# must be in the launcher's log, once. (`test/ext-microvm.sh log` runs only this.) +log_stress() { + echo "# the guest's log under load: every line php-fpm writes reaches the launcher's log (#86)" + # A folder of this run's own: the uploads disk keeps what an earlier run's guest wrote, and the + # next start syncs that back to the host. + ln86=sc86-$(date +%s) + lg=$site/wp-content/uploads/$ln86 + mkdir -p "$lg" + find "$lg" -mindepth 1 -delete + chown "$pool" "$lg" + if start log86 "$dir/microvm.json"; then + has "$dir/log86.log" "microVM restored from snapshot" "the stress runs on a restored guest (a restore resets the guest's vsock connections)" + # The links appear on the host after the start: the guest never sees them, the sync refuses them. + for i in $(seq 0 19); do ln -s /nonexistent "$lg/r-$i"; done + burst() { + seq "$1" "$2" | xargs -P 8 -I{} sh -c ' + i={}; q="?log=25&id=r$i"; [ "$i" -lt 20 ] && q="$q&put=$3/r-$i&size=10" + curl -s -o /dev/null -w "%{http_code}\n" -H "Host: 127.0.0.1:$1" "http://127.0.0.1:$2/sc-mvm-probe.php$q"' sh "$port" "$vport" "$ln86" + } + burst 0 119 > "$dir/log86.codes" + # The second half from the php-fpm a graceful reload started (its own log pipe). + kill -USR2 "$PID" + eventually 400 "grep -q \"reloaded the guest's php-fpm gracefully\" \"$dir/log86.log\"" || true + burst 120 239 >> "$dir/log86.codes" + is "$(grep -c '^200$' "$dir/log86.codes")" 240 "240 requests answered 200" + # The lines reach the log after the answers: wait for the last ones, then stop (its sync + # drains what the guest still holds). + got() { grep -oE 'sc86 r[0-9]+ [0-9]{3}' "$dir/log86.log" | sort -u | wc -l; } + eventually 300 '[ "$(got)" -ge 6000 ]' || true + eventually 300 '[ "$(grep -c "the host refused \"$ln86/r-" "$dir/log86.log")" -ge 20 ]' || true + stop + is "$(got)" 6000 "all 6000 numbered lines are in the launcher's log" + is "$(grep -oE 'sc86 r[0-9]+ [0-9]{3}' "$dir/log86.log" | sort | uniq -d | wc -l)" 0 "and each once" + is "$(grep -oE "the host refused \"$ln86/r-[0-9]+\"" "$dir/log86.log" | sort -u | wc -l)" 20 "all 20 sync refusals are in the launcher's log" + has "$dir/log86.log" "reloaded the guest's php-fpm gracefully" "a reload ran during the stress" + lacks "$dir/log86.log" "guest log line" "no line was lost or counted as lost" + is "$(find "$lg" -maxdepth 1 -name 'r-*' -type l | wc -l)" 20 "the owner's 20 links are still links" + else + fail "the guest's log under load: the start serves" + fi + find "$lg" -mindepth 1 -delete + rmdir "$lg" +} +if [ "$what" = log ]; then + log_stress + if [ "$fails" -eq 0 ]; then echo "all log checks passed"; else echo "$fails check(s) failed"; fi + [ "$fails" -eq 0 ] + exit +fi if [ "$what" = restore ]; then # Where the first page after a restore spends its time (#71's snapshot question): n restores of @@ -574,8 +633,6 @@ chown "$pool" "$outside" # A link the site owner put in the host's folder while the VM was stopped: the host's, so the # listing keeps it (never follows, removes or pushes it). ln -sfn "$outside" "$up/sc-evil2" -# eventually : until the test holds, or the time is up. -eventually() { n=0; until eval "$2"; do n=$((n + 1)); [ "$n" -lt "$1" ] || return 1; sleep 0.1; done; } # synced : waits (60 s at most) for the host's copy, then prints the ms. synced() { t0=$(date +%s%N) @@ -773,6 +830,8 @@ else fail "egress in log mode: the start serves" fi +log_stress + echo "# a guest booted for another protocol gets no start message, so no secret (#72)" # What an older root image's init is to this launcher: the handshake fails before any env line. if start oldproto "$dir/microvm.json" --guest-arg sc.proto=3 --no-snapshot; then diff --git a/test/ext/microvm/probe.php b/test/ext/microvm/probe.php index 8185d5c..b65803b 100644 --- a/test/ext/microvm/probe.php +++ b/test/ext/microvm/probe.php @@ -12,6 +12,14 @@ usleep(0); } } +// The guest's log (#86): ?log=&id= writes n numbered lines to php-fpm's log, as layer 2's +// audit lines go; the test finds every one in the launcher's log. +if (isset($_GET['log'])) { + $id = preg_replace('/[^a-z0-9-]/', '', (string) ($_GET['id'] ?? 'x')); + for ($i = 0, $n = min(1000, (int) $_GET['log']); $i < $n; $i++) { + error_log(sprintf('sc86 %s %03d %s', $id, $i, str_repeat('.', 80))); + } +} echo 'kernel=', php_uname('r'), "\n"; // The worker's effective uid, from the kernel (no posix extension needed). echo 'euid=', preg_match('/^Uid:\s+\d+\s+(\d+)/m', (string) @file_get_contents('/proc/self/status'), $u) ? $u[1] : '?', "\n"; From 6411aeca381dff7649abf02616c6e0fecace5b75 Mon Sep 17 00:00:00 2001 From: Sami Fouad Date: Wed, 11 Nov 2026 15:01:40 -0600 Subject: [PATCH 2/8] Layer 1 microVM: only the guest's init writes the log; a line is acknowledged only once written (#86 review) Any process in the guest could connect to host port 1514 and forge or suppress the log: one Inbox was shared by every connection, so a frame numbered u64::MAX made every later init line look already logged, and X frames or jumps wrote launcher-prefixed loss lines. - The launcher makes a log key per VM (kept beside a snapshot, whose init holds it) and gives it to the init over the control port, which only the host can reach. A log connection must present it first, within a second; others are refused and counted in a launcher line at most once a second. At most 16 connections wait for their key (the oldest goes), and keyed ones have their own places, so nothing can squat the port. - A jump larger than the guest's buffer can make closes the stream. - The init's reconnects back off (to 1 s) while no connection gets an acknowledgement. - A line is acknowledged only once it is written: a failed write stops the connection and leaves the line unlogged, so the guest sends it again. - The vsock preload takes LD_PRELOAD and SC_* out of the environment once read, so programs PHP starts don't inherit them; /tmp in the guest is noexec. - A stop whose sync reply is only unacknowledged log lines says so, not that the disks didn't sync. - The microVM target gates each suite's n/a count on test/lib/na-expected.txt. --- ext/fpm/guest/vsock-connect.c | 14 +- ext/fpm/src/guest.rs | 28 +- ext/fpm/src/guestlog.rs | 476 ++++++++++++++++++++++++++++------ ext/fpm/src/vm.rs | 145 +++++++---- test/ext-microvm.sh | 4 + test/ext/microvm/probe.php | 9 + test/lib/na-expected.txt | 10 + test/lib/target.sh | 19 +- 8 files changed, 566 insertions(+), 139 deletions(-) create mode 100644 test/lib/na-expected.txt diff --git a/ext/fpm/guest/vsock-connect.c b/ext/fpm/guest/vsock-connect.c index 3f060e4..f4bb146 100644 --- a/ext/fpm/guest/vsock-connect.c +++ b/ext/fpm/guest/vsock-connect.c @@ -61,9 +61,17 @@ static void load_ports(void) { if (!egress_host_port) negress = 0; } -/* Read once, in php-fpm's master at load time: its workers are forks with clear_env, so the - * variable is gone by the time a worker connects. */ -__attribute__((constructor)) static void init(void) { load_ports(); } +/* Read once, in php-fpm's master at load time, then taken out of the environment: the workers are + * forks of the master (the library and what it read stay mapped), and the image's pool has + * clear_env = no, so without this every program a PHP script starts would inherit the preload + * and the list of ports it forwards (#86 review). */ +__attribute__((constructor)) static void init(void) { + load_ports(); + unsetenv("LD_PRELOAD"); + unsetenv("SC_VSOCK_PORTS"); + unsetenv("SC_EGRESS_PORTS"); + unsetenv("SC_EGRESS_HOST_PORT"); +} static int listed(unsigned short p) { if (nports < 0) load_ports(); diff --git a/ext/fpm/src/guest.rs b/ext/fpm/src/guest.rs index 07f44b8..8117da1 100644 --- a/ext/fpm/src/guest.rs +++ b/ext/fpm/src/guest.rs @@ -171,6 +171,10 @@ pub enum Ctl { /// The handshake, alone on its connection before the start message: the host's protocol. /// `ok` only when it is this init's own and the one it booted with (`sc.proto`). Proto { version: u32 }, + /// This VM's log key (hex, [`crate::guestlog::KEY_LEN`] bytes): the host takes the log only + /// from connections that present it (#86). Alone on its connection, at any time; only the + /// host can reach this port, and no other process in the guest learns the key. + LogKey { hex: String }, Done, } @@ -186,6 +190,7 @@ impl Ctl { Ctl::Sync => "sync\n".into(), Ctl::Reload => "reload\n".into(), Ctl::Proto { version } => format!("proto {version}\n"), + Ctl::LogKey { hex } => format!("logkey {hex}\n"), Ctl::Done => "done\n".into(), } } @@ -208,6 +213,9 @@ impl Ctl { ["sync"] => Ok(Ctl::Sync), ["reload"] => Ok(Ctl::Reload), ["proto", v] => Ok(Ctl::Proto { version: v.parse().map_err(|_| format!("proto: {v}"))? }), + ["logkey", hex] if hex.len() == 2 * crate::guestlog::KEY_LEN && hex.bytes().all(|b| b.is_ascii_hexdigit()) => Ok(Ctl::LogKey { hex: (*hex).into() }), + // Never echo it: it is a secret. + ["logkey", ..] => Err("a malformed logkey line".into()), ["done"] => Ok(Ctl::Done), // Never echo an env line: it carries a secret. ["env", ..] => Err("a malformed env line".into()), @@ -231,7 +239,7 @@ pub fn env_name_ok(name: &str) -> bool { /// Exactly one start message per boot (a snapshot is taken before it, so each restore takes its /// own); after it only `sync` and `reload`, and nothing at all before it but a start. pub fn allowed(lines: &[Ctl], started: bool) -> Result<(), String> { - if lines.iter().any(|c| matches!(c, Ctl::Proto { .. })) && lines.len() > 1 { + if lines.iter().any(|c| matches!(c, Ctl::Proto { .. } | Ctl::LogKey { .. })) && lines.len() > 1 { return Err("the handshake comes alone".into()); } let starts = lines.iter().any(Ctl::starts); @@ -501,9 +509,14 @@ fn apply(ctl: &Ctl) -> io::Result<()> { } // The host stops the VM after a sync: every log line must be in its log by then, or // counted there as lost (the reply is the launcher's to log). - LOG.drain(LOG_DRAIN).map_err(|n| io::Error::other(crate::guestlog::lost(n as u64, "not acknowledged by the host before the stop"))) + LOG.drain(LOG_DRAIN).map_err(|n| io::Error::other(crate::guestlog::lost(n as u64, crate::guestlog::UNACKED_AT_STOP))) } // Checked before anything is applied ([`protocol_ok`]). + Ctl::LogKey { hex } => { + let key: crate::guestlog::Key = unhex(hex).try_into().map_err(|_| io::Error::other("logkey: not a key"))?; + LOG.set_key(key); + Ok(()) + } Ctl::Proto { .. } | Ctl::Done => Ok(()), } } @@ -807,7 +820,8 @@ fn boot_guest() -> io::Result { mount("proc", "/proc", "proc", flags | libc::MS_NOEXEC, "")?; mount("sysfs", "/sys", "sysfs", flags | libc::MS_NOEXEC, "")?; mount("devtmpfs", "/dev", "devtmpfs", libc::MS_NOSUID, "")?; - mount("tmpfs", "/tmp", "tmpfs", flags, "mode=1777")?; + // noexec: nothing a site writes there runs (#86 review). + mount("tmpfs", "/tmp", "tmpfs", flags | libc::MS_NOEXEC, "mode=1777")?; mount("tmpfs", "/run", "tmpfs", flags, "mode=755")?; let boot = parse_cmdline(&fs::read_to_string("/proc/cmdline")?).map_err(io::Error::other)?; if let Some(t) = boot.time { @@ -963,6 +977,14 @@ mod tests { assert_eq!(allowed(&[Ctl::Sync], true), Ok(())); assert_eq!(allowed(&[Ctl::Reload], true), Ok(())); assert!(allowed(&[Ctl::Sync], false).is_err(), "nothing before the start"); + // The log key (#86 review): at any time, alone, and never echoed when malformed. + let key = Ctl::LogKey { hex: "ab".repeat(crate::guestlog::KEY_LEN) }; + assert_eq!(Ctl::parse(key.line().trim_end()), Ok(key.clone())); + assert_eq!(allowed(std::slice::from_ref(&key), false), Ok(())); + assert_eq!(allowed(std::slice::from_ref(&key), true), Ok(())); + assert!(allowed(&[key, Ctl::Sync], true).is_err(), "alone on its connection"); + let e = Ctl::parse(&format!("logkey {}", "5ec7".repeat(8))).expect_err("short"); + assert!(!e.contains("5ec7"), "{e}"); assert!(allowed(&[Ctl::Time { secs: 1, nanos: 0 }, Ctl::Reload], false).is_err()); } } diff --git a/ext/fpm/src/guestlog.rs b/ext/fpm/src/guestlog.rs index f0bc93c..c1e2eb0 100644 --- a/ext/fpm/src/guestlog.rs +++ b/ext/fpm/src/guestlog.rs @@ -6,25 +6,37 @@ //! host side is closing. So the guest keeps every line until the host has acknowledged it: //! //! ```text -//! guest → host L \n one line (text holds no newline) +//! guest → host K \n first, on every connection: this VM's log key +//! L \n one line (text holds no newline) //! X \n lines dropped here (the guest's buffer was full) //! host → guest A \n every frame up to is in the launcher's log //! ``` //! +//! - **Only the init writes the log.** Any process in the guest can open a vsock connection to +//! host port 1514, so the host takes frames only from a connection that first presents this +//! VM's log key: [`KEY_LEN`] random bytes the launcher makes per VM (kept with a snapshot, which +//! holds it in the init's memory) and gives the init over the control port, which only the host +//! can reach. A connection without it is refused, and the refusals are counted in the +//! launcher's own log ([`LogServer`]). It gets [`HELLO_TIMEOUT`] to present the key; at most +//! [`MAX_PENDING`] connections wait at once (the oldest is dropped for a new one), so nothing in +//! the guest can hold the port, and keyed connections have places of their own. //! - **The guest** ([`Outbox`], [`send`]) numbers each line, queues it (up to [`OUTBOX_BYTES`]), //! sends it on one connection and drops it once acknowledged. A broken connection, or one on //! which nothing is acknowledged for [`ACK_STALL`], is replaced, and every unacknowledged frame -//! is sent again. A line that doesn't fit in the buffer is counted, and the count goes out as a -//! frame of its own, in order, before the next line. +//! is sent again; reconnects back off while no connection gets an acknowledgement. A line that +//! doesn't fit in the buffer is counted, and the count goes out as a frame of its own, in order, +//! before the next line. //! - **The host** ([`Inbox`], [`serve`]) logs each frame once (a frame sent again is skipped by -//! its number), every line marked `guest: ` so the guest can't write the launcher's own lines, -//! and acknowledges. A count frame, or a gap in the numbers, becomes the launcher's own line -//! `securecore-fpm: N guest log lines lost (…)`. +//! its number), every line marked `guest: `, and acknowledges only what it has written. A count +//! frame, or a gap in the numbers, becomes the launcher's own line `securecore-fpm: N guest log +//! lines lost (…)`; a gap larger than the guest's buffer could ever make ends the connection. //! //! Plain Rust over any connection ([`Conn`]), so the tests drive it over unix sockets. use std::collections::VecDeque; use std::io::{self, BufRead, BufReader, Read, Write}; +use std::os::unix::net::UnixStream; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Condvar, Mutex}; use std::thread; use std::time::{Duration, Instant}; @@ -36,6 +48,23 @@ pub const OUTBOX_BYTES: usize = 4 << 20; /// A connection on which unacknowledged frames wait this long without an acknowledgement is /// replaced (the host may be gone without the guest's kernel knowing). pub const ACK_STALL: Duration = Duration::from_secs(2); +/// The log key's length in bytes (sent as hex). +pub const KEY_LEN: usize = 32; +/// How long a connection has to present the key. +pub const HELLO_TIMEOUT: Duration = Duration::from_secs(1); +/// Connections waiting to present the key at once: a new one replaces the oldest. +pub const MAX_PENDING: usize = 16; +/// Keyed connections at once (the init's current one, and one it is giving up): a new one +/// replaces the oldest. +pub const MAX_STREAMS: usize = 2; +/// The most frames the guest's buffer can hold (each line counts at least 64 bytes against +/// [`OUTBOX_BYTES`]): a jump in the numbers larger than this is no loss but a broken stream. +pub const MAX_JUMP: u64 = (OUTBOX_BYTES / 64) as u64; + +/// A log key: [`KEY_LEN`] random bytes. +pub type Key = [u8; KEY_LEN]; +/// Where the host's log lines go (whole lines, each call one write). +pub type Emit = Box io::Result<()> + Send + Sync>; /// One frame from the guest. #[derive(Debug, Clone, PartialEq, Eq)] @@ -90,6 +119,22 @@ fn parse_ack(line: &str) -> Option { line.strip_prefix("A ")?.trim_end().parse().ok() } +/// The first line of every log connection. +pub fn hello_line(key: &Key) -> String { + let hex: String = key.iter().map(|b| format!("{b:02x}")).collect(); + format!("K {hex}\n") +} + +/// Whether `line` (without its newline) presents `key`. Compared in constant time. +pub fn hello_ok(line: &[u8], key: &Key) -> bool { + let want = hello_line(key); + let want = want.trim_end().as_bytes(); + if line.len() != want.len() { + return false; + } + line.iter().zip(want).fold(0u8, |acc, (a, b)| acc | (a ^ b)) == 0 +} + /// Reads one line of at most `cap` bytes into `line` (without its newline, a trailing `\r` /// dropped): `Some(cut)` when a line was read (`cut`: it was longer, and the rest was skipped), /// `None` at the end of the stream with nothing read. Never buffers more than `cap`. @@ -133,6 +178,11 @@ struct Queue { conn: u64, /// When an acknowledgement last arrived (or the connection was made). acked_at: Option, + /// Acknowledgements that moved the queue on, ever: a connection that adds none counts as a + /// failed one, and the next waits longer. + acks: u64, + /// This VM's log key, once the host has given it. + key: Option, } impl Queue { @@ -161,7 +211,7 @@ pub struct Outbox { impl Outbox { pub const fn new(cap: usize) -> Outbox { Outbox { - q: Mutex::new(Queue { frames: VecDeque::new(), bytes: 0, seq: 0, lost: 0, conn: 0, acked_at: None }), + q: Mutex::new(Queue { frames: VecDeque::new(), bytes: 0, seq: 0, lost: 0, conn: 0, acked_at: None, acks: 0, key: None }), cv: Condvar::new(), cap, } @@ -171,6 +221,17 @@ impl Outbox { self.q.lock().unwrap_or_else(|p| p.into_inner()) } + /// The key the host takes this VM's lines with. A new one ends the connection in use (the + /// next one presents the new key). + pub fn set_key(&self, key: Key) { + let mut q = self.lock(); + if q.key != Some(key) { + q.key = Some(key); + q.conn += 1; + } + self.cv.notify_all(); + } + /// Queues one line (cut at [`MAX_LINE`]); it is never written to the caller's stream, so a /// slow host never blocks php-fpm. When the buffer is full the line is counted as lost, and /// the count is sent, in order, before the next line that fits. @@ -203,6 +264,7 @@ impl Outbox { } if progressed { q.acked_at = Some(Instant::now()); + q.acks += 1; } self.cv.notify_all(); } @@ -248,7 +310,7 @@ pub trait Conn: Read + Write + Send + Sized + 'static { fn shut(&self); } -impl Conn for std::os::unix::net::UnixStream { +impl Conn for UnixStream { fn dup(&self) -> io::Result { self.try_clone() } @@ -267,39 +329,53 @@ impl Conn for crate::vsock::Vsock { } } -/// Delivers `outbox` for ever over connections from `connect`: one at a time; each new one starts -/// with every unacknowledged frame again. +/// The first wait between two connections that got nothing acknowledged, and the longest. +const BACKOFF: (Duration, Duration) = (Duration::from_millis(10), Duration::from_secs(1)); + +/// Delivers `outbox` for ever over connections from `connect`: one at a time, once the host has +/// given the key; each new one presents the key, then every unacknowledged frame again. A +/// connection that fails, or ends without moving the queue on (the host refused it), makes the +/// next wait longer, up to a second. pub fn send(outbox: &'static Outbox, connect: impl Fn() -> io::Result) -> ! { - let mut backoff = Duration::from_millis(10); + let mut backoff = BACKOFF.0; loop { - // Nothing to send: wait for a line before connecting. - { + // Nothing to send, or no key yet: wait before connecting. + let (key, acks) = { let mut q = outbox.lock(); - while q.frames.is_empty() { + while q.frames.is_empty() || q.key.is_none() { q = outbox.cv.wait(q).unwrap_or_else(|p| p.into_inner()); } - } - let conn = match connect() { - Ok(c) => c, - Err(_) => { - thread::sleep(backoff); - backoff = (backoff * 2).min(Duration::from_millis(500)); - continue; + (q.key.unwrap_or_default(), q.acks) + }; + let moved_on = match connect() { + Ok(conn) => { + let _ = deliver(outbox, conn, &key); + outbox.lock().acks != acks } + Err(_) => false, }; - backoff = Duration::from_millis(10); - let _ = deliver(outbox, conn); + if moved_on { + backoff = BACKOFF.0; + } else { + thread::sleep(backoff); + backoff = (backoff * 2).min(BACKOFF.1); + } } } -/// One connection's life: its acknowledgements read on a thread of their own, frames written -/// from the oldest unacknowledged one on, until it breaks or stalls. Every way out shuts it. -fn deliver(outbox: &'static Outbox, mut conn: C) -> io::Result<()> { +/// One connection's life: the key, then its acknowledgements read on a thread of their own and +/// frames written from the oldest unacknowledged one on, until it breaks or stalls. Every way out +/// shuts it. +fn deliver(outbox: &'static Outbox, mut conn: C, key: &Key) -> io::Result<()> { let id = { let mut q = outbox.lock(); q.acked_at = Some(Instant::now()); q.conn }; + if let Err(e) = conn.write_all(hello_line(key).as_bytes()) { + conn.shut(); + return Err(e); + } let reader = conn.dup()?; let acks = thread::spawn(move || { let mut r = BufReader::new(reader); @@ -367,12 +443,16 @@ pub struct Inbox { impl Inbox { /// What `frame` adds to the launcher's log: nothing for a frame already logged; a count of /// the lines lost for a gap before it or a count frame; the guest's line marked as the guest's. - pub fn take(&mut self, frame: &Frame, cut: bool) -> Vec { + /// A jump larger than [`MAX_JUMP`] is refused: no buffer of the guest's could make it. + pub fn take(&mut self, frame: &Frame, cut: bool) -> Result, String> { let seq = frame.seq(); let mut out = Vec::new(); if let Some(last) = self.last { if seq <= last { - return out; + return Ok(out); + } + if seq - last > MAX_JUMP { + return Err(format!("frame {seq} after frame {last}: a jump no guest buffer can make")); } if seq > last + 1 { out.push(lost_line(seq - last - 1, "missing from the guest's numbered stream")); @@ -383,7 +463,7 @@ impl Inbox { Frame::Line { text, .. } => out.push(guest_line(text, cut)), Frame::Lost { count, .. } => out.push(lost_line(*count, "the guest's log buffer was full")), } - out + Ok(out) } pub fn last(&self) -> Option { @@ -391,6 +471,9 @@ impl Inbox { } } +/// Why lines still in the guest's buffer when it stops are lost (the guest's `sync` reply). +pub const UNACKED_AT_STOP: &str = "not acknowledged by the host before the stop"; + /// The launcher's own line for lines that never arrived. pub fn lost_line(count: u64, why: &str) -> String { format!("securecore-fpm: {}", lost(count, why)) @@ -409,21 +492,40 @@ pub fn guest_line(text: &[u8], cut: bool) -> String { /// The longest frame line the host reads whole: a line, its number and its kind. const MAX_FRAME: usize = MAX_LINE + 64; -/// One log connection on the host: frames from `from`, logged to `to` through `inbox` (shared by -/// every connection of one guest), each batch acknowledged on `ack`. A line that isn't a frame -/// is logged as the guest's, unnumbered. -pub fn serve(from: impl Read, mut ack: impl Write, inbox: &Mutex, to: &mut impl Write) { +/// Why [`serve`] stopped before the end of its stream. +#[derive(Debug, PartialEq, Eq)] +pub enum Stop { + /// The launcher's log couldn't be written: nothing more is acknowledged, so the guest keeps + /// the lines and sends them again. + Log(String), + /// The stream broke the protocol. + Protocol(String), +} + +/// One keyed log connection on the host: frames from `from`, written with `emit` through `inbox` +/// (the guest's one stream state, shared by its connections), each batch acknowledged on `ack` +/// once it is written, never before. A line that isn't a frame is logged as the guest's, +/// unnumbered. +pub fn serve(from: impl Read, mut ack: impl Write, inbox: &Mutex, emit: &dyn Fn(&str) -> io::Result<()>) -> Result<(), Stop> { let mut r = BufReader::with_capacity(64 << 10, from); let mut line = Vec::with_capacity(256); while let Some(cut) = read_capped(&mut r, &mut line, MAX_FRAME) { - let out = match Frame::parse(&line) { - Some(frame) => inbox.lock().unwrap_or_else(|p| p.into_inner()).take(&frame, cut), - None => vec![guest_line(&line, cut)], - }; - if !out.is_empty() { - let mut text = out.join("\n"); - text.push('\n'); - let _ = to.write_all(text.as_bytes()); + { + // Held while the lines are written: a frame counts as logged only once it is. + let mut inbox = inbox.lock().unwrap_or_else(|p| p.into_inner()); + let before = inbox.last; + let out = match Frame::parse(&line) { + Some(frame) => inbox.take(&frame, cut).map_err(Stop::Protocol)?, + None => vec![guest_line(&line, cut)], + }; + if !out.is_empty() { + let mut text = out.join("\n"); + text.push('\n'); + if let Err(e) = emit(&text) { + inbox.last = before; + return Err(Stop::Log(e.to_string())); + } + } } // Once what has arrived is logged: acknowledge it. if r.buffer().is_empty() { @@ -431,23 +533,157 @@ pub fn serve(from: impl Read, mut ack: impl Write, inbox: &Mutex, to: &mu if let Some(last) = last && ack.write_all(ack_line(last).as_bytes()).is_err() { - return; + return Ok(()); } } } + Ok(()) +} + +/// The host's end of one guest's log port: every connection to it goes through [`LogServer::take`], +/// which lets in only those that present `key`, and logs everything with `emit` (the launcher's +/// stderr). Refused connections are counted, and said at most once a second. +pub struct LogServer { + key: Key, + inbox: Mutex, + emit: Emit, + pending: Mutex>, + streams: Mutex>, + next: AtomicU64, + refused: AtomicU64, + said: Mutex<(Option, u64)>, +} + +impl LogServer { + pub fn new(key: Key, emit: Emit) -> LogServer { + LogServer { + key, + inbox: Mutex::new(Inbox::default()), + emit, + pending: Mutex::new(VecDeque::new()), + streams: Mutex::new(VecDeque::new()), + next: AtomicU64::new(0), + refused: AtomicU64::new(0), + said: Mutex::new((None, 0)), + } + } + + /// The guest's stream state (for the launcher to quote, #87). + pub fn inbox(&self) -> &Mutex { + &self.inbox + } + + /// Connections refused so far (no key, a wrong one, or none in time). + pub fn refused(&self) -> u64 { + self.refused.load(Ordering::SeqCst) + } + + /// Keeps `conn` among at most `max` in `set`, shutting the oldest out; its id. + fn hold(&self, set: &Mutex>, conn: &UnixStream, max: usize) -> u64 { + let id = self.next.fetch_add(1, Ordering::SeqCst); + let mut s = set.lock().unwrap_or_else(|p| p.into_inner()); + while s.len() >= max { + if let Some((_, old)) = s.pop_front() { + let _ = old.shutdown(std::net::Shutdown::Both); + } + } + if let Ok(c) = conn.try_clone() { + s.push_back((id, c)); + } + id + } + + fn release(&self, set: &Mutex>, id: u64) { + set.lock().unwrap_or_else(|p| p.into_inner()).retain(|(i, _)| *i != id); + } + + fn refuse(&self, why: &str) { + let n = self.refused.fetch_add(1, Ordering::SeqCst) + 1; + let mut said = self.said.lock().unwrap_or_else(|p| p.into_inner()); + if said.0.is_none_or(|t| t.elapsed() >= Duration::from_secs(1)) { + let _ = (self.emit)(&format!( + "securecore-fpm: refused {} guest log connection{} without this VM's log key ({why}; {n} so far): only the guest's init writes the log\n", + n - said.1, + if n - said.1 == 1 { "" } else { "s" } + )); + *said = (Some(Instant::now()), n); + } + } + + /// Serves one connection to the log port, to its end. + pub fn take(&self, conn: UnixStream) { + let id = self.hold(&self.pending, &conn, MAX_PENDING); + let _ = conn.set_read_timeout(Some(HELLO_TIMEOUT)); + let mut r = BufReader::with_capacity(64 << 10, conn); + let mut hello = Vec::new(); + let got = read_capped(&mut r, &mut hello, 2 * KEY_LEN + 8); + self.release(&self.pending, id); + match got { + Some(false) if hello_ok(&hello, &self.key) => {} + None => return self.refuse("it closed or sent nothing in time"), + _ => { + let _ = r.get_ref().shutdown(std::net::Shutdown::Both); + return self.refuse("it sent something else first"); + } + } + let conn = r.get_ref(); + let _ = conn.set_read_timeout(None); + let id = self.hold(&self.streams, conn, MAX_STREAMS); + let Ok(ack) = conn.try_clone() else { + self.release(&self.streams, id); + return; + }; + let result = serve(r, &ack, &self.inbox, &*self.emit); + self.release(&self.streams, id); + match result { + Ok(()) => {} + Err(Stop::Log(e)) => { + // Most likely unwritable too, but the guest keeps the lines either way. + eprintln!("securecore-fpm: the launcher's log can't be written ({e}); the guest keeps its lines until it can"); + } + Err(Stop::Protocol(e)) => { + let _ = (self.emit)(&format!("securecore-fpm: closed a guest log connection: {e}\n")); + } + } + let _ = ack.shutdown(std::net::Shutdown::Both); + } } #[cfg(test)] mod tests { use super::*; - use std::os::unix::net::{UnixListener, UnixStream}; + use std::os::unix::net::UnixListener; use std::sync::Arc; - use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::atomic::AtomicUsize; fn leak(cap: usize) -> &'static Outbox { Box::leak(Box::new(Outbox::new(cap))) } + /// A log in memory, written as the launcher's stderr is. + #[derive(Clone, Default)] + struct Log(Arc>>); + impl Log { + fn emit(&self) -> Emit { + let l = self.0.clone(); + Box::new(move |s| { + l.lock().expect("log").extend_from_slice(s.as_bytes()); + Ok(()) + }) + } + fn text(&self) -> String { + String::from_utf8(self.0.lock().expect("log").clone()).expect("utf8") + } + } + + fn scratch(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("sc-guestlog-{name}-{}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + let path = dir.join("log.sock"); + let _ = std::fs::remove_file(&path); + path + } + #[test] fn frames_round_trip_and_junk_is_no_frame() { for f in [Frame::Line { seq: 7, text: b"PHP message: a b c".to_vec() }, Frame::Line { seq: 1, text: Vec::new() }, Frame::Lost { seq: 9, count: 12 }] { @@ -459,20 +695,48 @@ mod tests { assert_eq!(Frame::parse(junk), None, "{}", String::from_utf8_lossy(junk)); } assert_eq!(parse_ack("A 42\n"), Some(42)); + let key = [7u8; KEY_LEN]; + let hello = hello_line(&key); + assert!(hello_ok(hello.trim_end().as_bytes(), &key)); + assert!(!hello_ok(hello_line(&[8u8; KEY_LEN]).trim_end().as_bytes(), &key), "another key"); + assert!(!hello_ok(b"K 0707", &key), "a short one"); } /// A frame sent again (after a reconnect) is logged once; a gap is counted; a count frame is - /// the launcher's own line; the guest can't write a line that reads as the launcher's. + /// the launcher's own line; the guest can't write a line that reads as the launcher's; a jump + /// no buffer can make is refused. #[test] fn the_host_logs_each_frame_once_and_counts_what_is_missing() { let mut inbox = Inbox::default(); let line = |seq, t: &str| Frame::Line { seq, text: t.as_bytes().to_vec() }; - assert_eq!(inbox.take(&line(3, "a"), false), ["guest: a"]); - assert_eq!(inbox.take(&line(4, "securecore-fpm: forged"), false), ["guest: securecore-fpm: forged"]); - assert!(inbox.take(&line(3, "a"), false).is_empty(), "sent again: logged once"); - assert_eq!(inbox.take(&line(7, "d"), false), ["securecore-fpm: 2 guest log lines lost (missing from the guest's numbered stream)", "guest: d"]); - assert_eq!(inbox.take(&Frame::Lost { seq: 8, count: 1 }, false), ["securecore-fpm: 1 guest log line lost (the guest's log buffer was full)"]); - assert_eq!(inbox.take(&line(9, "long"), true), ["guest: long …[cut]"]); + assert_eq!(inbox.take(&line(3, "a"), false).expect("ok"), ["guest: a"]); + assert_eq!(inbox.take(&line(4, "securecore-fpm: forged"), false).expect("ok"), ["guest: securecore-fpm: forged"]); + assert!(inbox.take(&line(3, "a"), false).expect("ok").is_empty(), "sent again: logged once"); + assert_eq!(inbox.take(&line(7, "d"), false).expect("ok"), ["securecore-fpm: 2 guest log lines lost (missing from the guest's numbered stream)", "guest: d"]); + assert_eq!(inbox.take(&Frame::Lost { seq: 8, count: 1 }, false).expect("ok"), ["securecore-fpm: 1 guest log line lost (the guest's log buffer was full)"]); + assert_eq!(inbox.take(&line(9, "long"), true).expect("ok"), ["guest: long …[cut]"]); + assert!(inbox.take(&line(u64::MAX, "x"), false).is_err(), "a jump to the end of the numbers"); + assert_eq!(inbox.last(), Some(9), "and it moved nothing"); + assert_eq!(inbox.take(&line(10, "next"), false).expect("ok"), ["guest: next"]); + } + + /// A line is acknowledged only once it is in the launcher's log (#86 review): a write that + /// fails stops the connection, acknowledges nothing, and leaves the frame unlogged, so the + /// guest's copy is sent again and logged then. + #[test] + fn a_line_the_log_could_not_take_is_never_acknowledged() { + let inbox = Mutex::new(Inbox::default()); + let mut acks = Vec::new(); + let broken = |_: &str| -> io::Result<()> { Err(io::Error::other("disk full")) }; + let r = serve(&b"L 1 audit\n"[..], &mut acks, &inbox, &broken); + assert_eq!(r, Err(Stop::Log("disk full".into()))); + assert!(acks.is_empty(), "nothing acknowledged: {:?}", String::from_utf8_lossy(&acks)); + assert_eq!(inbox.lock().expect("inbox").last(), None, "not counted as logged"); + let log = Log::default(); + let mut acks = Vec::new(); + serve(&b"L 1 audit\n"[..], &mut acks, &inbox, &*log.emit()).expect("serves"); + assert_eq!(log.text(), "guest: audit\n", "sent again, logged then"); + assert_eq!(acks, b"A 1\n"); } #[test] @@ -505,19 +769,18 @@ mod tests { assert!(queued > 0 && lost > 0 && queued as u64 + lost == 20, "queued {queued} lost {lost}"); ob.ack(u64::MAX); ob.line(b"after"); - let mut log = Vec::new(); + let log = Log::default(); let inbox = Mutex::new(Inbox { last: Some(queued as u64) }); let frames: Vec = ob.lock().frames.iter().flat_map(|(_, b)| b.clone()).collect(); - serve(&frames[..], io::sink(), &inbox, &mut log); - let log = String::from_utf8(log).expect("utf8"); - assert_eq!(log, format!("securecore-fpm: {lost} guest log lines lost (the guest's log buffer was full)\nguest: after\n")); + serve(&frames[..], io::sink(), &inbox, &*log.emit()).expect("serves"); + assert_eq!(log.text(), format!("securecore-fpm: {lost} guest log lines lost (the guest's log buffer was full)\nguest: after\n")); } - /// The host's side of the stress below: a log listener that, for its first `drops` + /// The host's side of the stress below: a keyed log server that, for its first `drops` /// connections, reads a few frames and then closes without a word (a restore's reset, a dying /// connection) or keeps silent (Firecracker dropping a closing connection's data); then /// serves for real. - fn flaky_host(l: UnixListener, drops: usize, inbox: Arc>, log: Arc>>, conns: Arc) { + fn flaky_host(l: UnixListener, drops: usize, server: Arc, conns: Arc) { for (n, c) in l.incoming().flatten().enumerate() { conns.fetch_add(1, Ordering::SeqCst); if n < drops { @@ -536,23 +799,8 @@ mod tests { } continue; } - let (inbox, log) = (inbox.clone(), log.clone()); - thread::spawn(move || { - let ack = c.try_clone().expect("dup"); - serve(c, ack, &inbox, &mut Writer(log)); - }); - } - } - - #[derive(Clone)] - struct Writer(Arc>>); - impl Write for Writer { - fn write(&mut self, b: &[u8]) -> io::Result { - self.0.lock().expect("log").extend_from_slice(b); - Ok(b.len()) - } - fn flush(&mut self) -> io::Result<()> { - Ok(()) + let server = server.clone(); + thread::spawn(move || server.take(c)); } } @@ -560,17 +808,18 @@ mod tests { /// swallow what they get: the guest sends again whatever the host hasn't acknowledged. #[test] fn every_line_arrives_once_through_connections_that_die_or_stall() { - let dir = std::env::temp_dir().join(format!("sc-guestlog-{}", std::process::id())); - let _ = std::fs::create_dir_all(&dir); - let path = dir.join("log.sock"); - let _ = std::fs::remove_file(&path); + let path = scratch("stall"); let l = UnixListener::bind(&path).expect("bind"); - let (inbox, log, conns) = (Arc::new(Mutex::new(Inbox::default())), Arc::new(Mutex::new(Vec::new())), Arc::new(AtomicUsize::new(0))); + let key = [3u8; KEY_LEN]; + let log = Log::default(); + let server = Arc::new(LogServer::new(key, log.emit())); + let conns = Arc::new(AtomicUsize::new(0)); { - let (inbox, log, conns) = (inbox.clone(), log.clone(), conns.clone()); - thread::spawn(move || flaky_host(l, 4, inbox, log, conns)); + let (server, conns) = (server.clone(), conns.clone()); + thread::spawn(move || flaky_host(l, 4, server, conns)); } let ob = leak(OUTBOX_BYTES); + ob.set_key(key); let p = path.clone(); thread::spawn(move || send(ob, move || UnixStream::connect(&p))); let writers: Vec<_> = (0..4) @@ -589,7 +838,7 @@ mod tests { w.join().expect("writer"); } ob.drain(Duration::from_secs(30)).expect("the host acknowledged every line"); - let log = String::from_utf8(log.lock().expect("log").clone()).expect("utf8"); + let log = log.text(); assert!(!log.contains("lost"), "nothing lost: {}", &log[..log.len().min(400)]); for w in 0..4 { let mine: Vec<&str> = log.lines().filter(|l| l.starts_with(&format!("guest: w{w} "))).collect(); @@ -597,6 +846,67 @@ mod tests { assert_eq!(mine, want, "writer {w}: every line once, in order"); } assert!(conns.load(Ordering::SeqCst) > 4, "the dead and the silent connections were replaced"); - let _ = std::fs::remove_dir_all(&dir); + let _ = std::fs::remove_dir_all(path.parent().expect("dir")); + } + + /// A hostile process in the guest (#86 review) opens its own connections to the log port: it + /// forges a frame numbered at the end of the numbers (which would make every later init line + /// look already logged), count frames and launcher-looking lines, presents a wrong key, and + /// squats connections that never say anything. None of it reaches the log; the init's lines + /// all do, once; the refusals are the launcher's own counted line. + #[test] + fn a_hostile_connection_can_neither_hide_the_inits_lines_nor_write_the_launchers() { + let path = scratch("hostile"); + let l = UnixListener::bind(&path).expect("bind"); + let key = [9u8; KEY_LEN]; + let log = Log::default(); + let server = Arc::new(LogServer::new(key, log.emit())); + { + let server = server.clone(); + thread::spawn(move || { + for c in l.incoming().flatten() { + let server = server.clone(); + thread::spawn(move || server.take(c)); + } + }); + } + // Squatters first: more than every waiting place, holding them open, silent. + let squatters: Vec = (0..3 * MAX_PENDING).map(|_| UnixStream::connect(&path).expect("connect")).collect(); + let forge = |hello: Option| { + let mut c = UnixStream::connect(&path).expect("connect"); + if let Some(h) = hello { + let _ = c.write_all(h.as_bytes()); + } + let _ = c.write_all(format!("L {} x\nX 5 999\nL 6 securecore-fpm: 999 guest log lines lost (forged)\n", u64::MAX).as_bytes()); + let mut sink = Vec::new(); + let _ = c.set_read_timeout(Some(Duration::from_secs(3))); + let _ = c.read_to_end(&mut sink); + sink + }; + let no_key = forge(None); + let wrong_key = forge(Some(hello_line(&[1u8; KEY_LEN]))); + assert!(no_key.is_empty() && wrong_key.is_empty(), "a refused connection gets no acknowledgement"); + let ob = leak(OUTBOX_BYTES); + ob.set_key(key); + let p = path.clone(); + thread::spawn(move || send(ob, move || UnixStream::connect(&p))); + for i in 0..300 { + ob.line(format!("init line {i:03}").as_bytes()); + if i == 150 { + // More forgeries while the init's stream runs. + let _ = forge(None); + } + } + ob.drain(Duration::from_secs(30)).expect("the host acknowledged every init line"); + drop(squatters); + let text = log.text(); + let mine: Vec<&str> = text.lines().filter(|l| l.starts_with("guest: init line ")).collect(); + let want: Vec = (0..300).map(|i| format!("guest: init line {i:03}")).collect(); + assert_eq!(mine, want, "every init line, once, in order"); + assert!(!text.contains("guest: x") && !text.contains("forged") && !text.contains("lines lost"), "nothing forged: {text}"); + let launcher: Vec<&str> = text.lines().filter(|l| l.starts_with("securecore-fpm: ")).collect(); + assert!(!launcher.is_empty() && launcher.iter().all(|l| l.starts_with("securecore-fpm: refused ")), "only refusal counts: {launcher:?}"); + assert!(server.refused() >= 3, "the forgers were counted: {}", server.refused()); + let _ = std::fs::remove_dir_all(path.parent().expect("dir")); } } diff --git a/ext/fpm/src/vm.rs b/ext/fpm/src/vm.rs index 499e53a..da7762d 100644 --- a/ext/fpm/src/vm.rs +++ b/ext/fpm/src/vm.rs @@ -45,7 +45,6 @@ use std::os::unix::net::{UnixDatagram, UnixListener, UnixStream}; use std::os::unix::process::CommandExt as _; use std::path::{Path, PathBuf}; use std::process::{Child, Command, Stdio}; -use std::sync::Mutex; use std::sync::atomic::{AtomicBool, Ordering}; use std::thread; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; @@ -1084,6 +1083,8 @@ struct Vm { _root: fs::File, /// Emptied (bind mounts unmounted first) when the VM is dropped, on every path out. jail: Jail, + /// The key only its init's log connections present ([`guestlog`]). + log_key: guestlog::Key, } /// An `O_PATH` handle on `dir` and the short path prefix that reaches into it. @@ -1140,14 +1141,14 @@ enum Wiring { impl Vm { /// A fresh jail with this machine's files (and `snap`'s, to restore it), then the jailer. /// A spawn that fails leaves no jail behind (nothing stays mounted). - fn spawn(plan: &Plan, opts: &Options, m: &Machine, wiring: Wiring, snap: Option<&Path>) -> Result { + fn spawn(plan: &Plan, opts: &Options, m: &Machine, wiring: Wiring, snap: Option<&Path>, key: guestlog::Key) -> Result { let j = Jail::new(&plan.state, &plan.id, m.user); - Vm::spawn_in(&j, plan, opts, m, wiring, snap).inspect_err(|_| { + Vm::spawn_in(&j, plan, opts, m, wiring, snap, key).inspect_err(|_| { let _ = j.clear(); }) } - fn spawn_in(j: &Jail, plan: &Plan, opts: &Options, m: &Machine, wiring: Wiring, snap: Option<&Path>) -> Result { + fn spawn_in(j: &Jail, plan: &Plan, opts: &Options, m: &Machine, wiring: Wiring, snap: Option<&Path>, key: guestlog::Key) -> Result { j.prepare()?; j.place(&opts.assets.kernel, IN_KERNEL)?; j.place(&opts.assets.rootfs, IN_ROOTFS)?; @@ -1166,7 +1167,7 @@ impl Vm { j.user_dir(IN_SNAP_NEW)?; } let (root, short) = short_dir(&j.root)?; - wire(plan, m, j, &short, wiring)?; + wire(plan, m, j, &short, wiring, key)?; let mut cmd = j.command(&opts.assets.jailer, &opts.assets.firecracker, opts.vcpus, opts.mem_mib, &["--api-sock", IN_API]); // stdout and stderr together, through a pipe, into a capped console.log. let (rd, wr) = std::io::pipe().map_err(|e| format!("pipe: {e}"))?; @@ -1179,7 +1180,7 @@ impl Vm { let pid = child.id() as i32; let _ = fs::write(j.base.join("firecracker.pid"), pid.to_string()); let inside = |p: &str| short.join(p.trim_start_matches('/')); - let mut vm = Vm { child: Some(child), pid, api: inside(IN_API), vsock: inside(IN_VSOCK), _root: root, jail: j.clone() }; + let mut vm = Vm { child: Some(child), pid, api: inside(IN_API), vsock: inside(IN_VSOCK), _root: root, jail: j.clone(), log_key: key }; let t = Instant::now(); while UnixStream::connect(&vm.api).is_err() { if let Some(st) = vm.exited() { @@ -1233,8 +1234,29 @@ fn now() -> (i64, u32) { (d.as_secs() as i64, d.subsec_nanos()) } +/// The file beside a snapshot that holds its VM's log key (the init in the snapshot has it). +const SNAP_LOG_KEY: &str = "log.key"; + +fn random_key() -> Result { + let r = random64()?; + let mut k = [0u8; guestlog::KEY_LEN]; + k.copy_from_slice(&r[..guestlog::KEY_LEN]); + Ok(k) +} + +/// Gives a booting guest's init its log key, on a thread of its own (the boot goes on meanwhile): +/// the init sends its log, its boot's own lines included, only once it has it. +fn give_log_key(vm: &Vm) { + let (uds, hex) = (vm.vsock.clone(), hex(&vm.log_key)); + thread::spawn(move || { + if let Err(e) = tell_guest(&uds, &[Ctl::LogKey { hex }, Ctl::Done], START_TIMEOUT) { + log(&format!("could not give the guest's init its log key ({e}): the guest's log is refused")); + } + }); +} + fn cold_boot(plan: &Plan, opts: &Options, m: &Machine, wiring: Wiring) -> Result { - let vm = Vm::spawn(plan, opts, m, wiring, None)?; + let vm = Vm::spawn(plan, opts, m, wiring, None, random_key()?)?; vm.api("PUT", "/machine-config", &format!(r#"{{"vcpu_count":{},"mem_size_mib":{},"smt":false}}"#, opts.vcpus, opts.mem_mib))?; let args = format!("{} sc.time={}", m.args, now().0); vm.api("PUT", "/boot-source", &format!(r#"{{"kernel_image_path":{},"boot_args":{}}}"#, json_str(IN_KERNEL), json_str(&args)))?; @@ -1255,11 +1277,19 @@ fn cold_boot(plan: &Plan, opts: &Options, m: &Machine, wiring: Wiring) -> Result } vm.api("PUT", "/vsock", &format!(r#"{{"guest_cid":3,"uds_path":{}}}"#, json_str(IN_VSOCK)))?; vm.api("PUT", "/actions", r#"{"action_type":"InstanceStart"}"#)?; + give_log_key(&vm); Ok(vm) } +/// A snapshot's log key: its init already holds it, so a restore's log is taken with it. +fn snap_key(snap: &Path) -> Result { + let path = snap.join(SNAP_LOG_KEY); + let b = fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?; + b.try_into().map_err(|_| format!("{}: not a log key", path.display())) +} + fn restore(plan: &Plan, opts: &Options, m: &Machine, snap: &Path) -> Result { - let vm = Vm::spawn(plan, opts, m, Wiring::Full, Some(snap))?; + let vm = Vm::spawn(plan, opts, m, Wiring::Full, Some(snap), snap_key(snap)?)?; vm.api( "PUT", "/snapshot/load", @@ -1296,6 +1326,14 @@ fn snapshot(vm: &Vm, plan: &Plan, user: User, snap: &Path) -> Result<(), String> for f in ["vm.snap", "vm.mem"] { take_out(&inside.join(f), &tmp.join(f), user).map_err(|e| format!("{f}: {e}"))?; } + // The init in the snapshot has this VM's log key: every restore's log is taken with it. + // Root's alone (the state folder is root's, 0700). + { + use std::os::unix::fs::OpenOptionsExt as _; + let p = tmp.join(SNAP_LOG_KEY); + let mut f = OpenOptions::new().write(true).create_new(true).mode(0o600).open(&p).map_err(|e| format!("{}: {e}", p.display()))?; + f.write_all(&vm.log_key).map_err(|e| format!("{}: {e}", p.display()))?; + } fs::rename(&tmp, snap).map_err(|e| format!("{}: {e}", snap.display())) } @@ -1374,6 +1412,16 @@ fn tell_guest(uds: &Path, lines: &[Ctl], timeout: Duration) -> Result<(), String refused(lines, reply.trim_end()) } +/// What the launcher says when the guest's sync before a stop fails: the guest syncs its disks +/// first and reports log lines it couldn't get acknowledged after, so a reply naming those is a +/// count of lost log lines, not a failed disk sync. +pub fn stop_sync_failed(e: &str) -> String { + match e.split_once("error ") { + Some((_, why)) if why.contains(guestlog::UNACKED_AT_STOP) => format!("the guest synced its disks before the stop, but {why}"), + _ => format!("the guest did not sync its disks before the stop: {e}"), + } +} + /// The guest's reply to `lines` as a result. Its text is shown only when `lines` carried no /// `env` line: an older init echoes a line it doesn't know, and that line could be a secret /// (a current init never echoes one, and logs its reason on the log port). @@ -1382,7 +1430,7 @@ fn refused(lines: &[Ctl], reply: &str) -> Result<(), String> { return Ok(()); } let kinds: Vec = lines.iter().map(|c| c.line().trim_end().split(' ').next().unwrap_or("").to_owned()).collect(); - if lines.iter().any(|c| matches!(c, Ctl::Env { .. })) { + if lines.iter().any(|c| matches!(c, Ctl::Env { .. } | Ctl::LogKey { .. })) { return Err(format!("the guest refused {kinds:?} (its reply isn't shown: the message carried secrets; the guest's own log line says why)")); } Err(format!("the guest refused {kinds:?}: {reply}")) @@ -1584,7 +1632,7 @@ fn bind_unix(path: &Path, mode: SocketMode) -> Result { /// The host ends of the guest's ports, in the jail: each `connect[].socket` as a link into its /// folder bind-mounted read-only, each `address` as a listener here, and the log listener. The /// jail was emptied first, so nothing from an earlier config is left. -fn wire(plan: &Plan, m: &Machine, j: &Jail, short: &Path, wiring: Wiring) -> Result<(), String> { +fn wire(plan: &Plan, m: &Machine, j: &Jail, short: &Path, wiring: Wiring, key: guestlog::Key) -> Result<(), String> { let user = m.user; let owned = SocketMode { owner: Some(user.uid), group: Some(user.gid), mode: 0o600 }; if wiring == Wiring::Full { @@ -1645,42 +1693,23 @@ fn wire(plan: &Plan, m: &Machine, j: &Jail, short: &Path, wiring: Wiring) -> Res }); } } - // php-fpm's log, to this process's stderr (#86): numbered frames, each logged once and - // acknowledged, every line marked as the guest's, so nothing the guest writes can pass for - // the launcher's own lines ([`crate::guestlog`]). Never shut for writing: Firecracker turns a - // host's half-close into a full close and drops whatever the guest sends after it. + // php-fpm's log, to this process's stderr (#86): only connections that present this VM's log + // key, numbered frames, each logged once and acknowledged once written, every line marked as + // the guest's, so nothing the guest writes can pass for the launcher's own lines + // ([`crate::guestlog`]). Never shut for writing: Firecracker turns a host's half-close into a + // full close and drops whatever the guest sends after it. let l = bind_unix(&short.join(format!("v.sock_{LOG_PORT}")), owned)?; - let inbox: &'static Mutex = Box::leak(Box::new(Mutex::new(guestlog::Inbox::default()))); + // Each write whole: a guest line never interleaves with another thread's. + let emit = Box::new(|s: &str| io::stderr().lock().write_all(s.as_bytes())); + let server: &'static guestlog::LogServer = Box::leak(Box::new(guestlog::LogServer::new(key, emit))); thread::spawn(move || { for c in l.incoming().flatten() { - // The guest keeps one connection; more means old ones are dying. A refused one loses - // nothing (the guest sends again what isn't acknowledged), but it is said. - let Some(slot) = LOG_SLOTS.take() else { - log(&format!("the guest's log: {LOG_SLOTS_N} connections already open; refusing another (the guest sends its lines again)")); - continue; - }; - thread::spawn(move || { - let _slot = slot; - let Ok(ack) = c.try_clone() else { return }; - guestlog::serve(c, ack, inbox, &mut Stderr); - }); + thread::spawn(move || server.take(c)); } }); Ok(()) } -/// The launcher's stderr, each write whole (a guest line never interleaves with another thread's). -struct Stderr; - -impl Write for Stderr { - fn write(&mut self, b: &[u8]) -> io::Result { - io::stderr().lock().write_all(b).map(|()| b.len()) - } - fn flush(&mut self) -> io::Result<()> { - io::stderr().flush() - } -} - /// A fixed number of slots: a connection takes one or is turned away. pub struct Slots(std::sync::atomic::AtomicUsize, usize); @@ -1743,9 +1772,6 @@ impl Default for Coalesce { } } -/// The guest's log connections at once: its one stream, and ones it is giving up. -const LOG_SLOTS_N: usize = 4; -static LOG_SLOTS: Slots = Slots::new(LOG_SLOTS_N); /// Connections through one `address` forward at once. const FORWARD_SLOTS: usize = 64; @@ -2296,7 +2322,7 @@ pub fn run(loaded: &Loaded, opts: &Options) -> Result<(), String> { } // The guest's writes to the writable disks reach the host's images before the VM stops. if let Err(e) = tell_guest(&vm.vsock, &[Ctl::Sync, Ctl::Done], crate::guest::SYNC_TIMEOUT) { - log(&format!("the guest did not sync its disks before the stop: {e}")); + log(&stop_sync_failed(&e)); } // Stops Firecracker (still unreaped, so its pid is still its own) and empties the jail. drop(vm); @@ -2310,6 +2336,7 @@ pub fn run(loaded: &Loaded, opts: &Options) -> Result<(), String> { #[cfg(test)] mod tests { use super::*; + use std::sync::Mutex; use securecore_config::Config; fn loaded(dir: &Path, layer1: &str) -> Loaded { @@ -2697,10 +2724,14 @@ mod tests { #[test] fn guest_lines_are_capped_and_connections_counted() { let long = format!("L 1 {}\nL 2 next\n", "x".repeat(guestlog::MAX_LINE * 3)); - let mut out = Vec::new(); + let out = Mutex::new(String::new()); let mut acks = Vec::new(); - guestlog::serve(long.as_bytes(), &mut acks, &Mutex::new(guestlog::Inbox::default()), &mut out); - let text = String::from_utf8(out).expect("utf8"); + let emit = |s: &str| -> io::Result<()> { + out.lock().expect("out").push_str(s); + Ok(()) + }; + guestlog::serve(long.as_bytes(), &mut acks, &Mutex::new(guestlog::Inbox::default()), &emit).expect("serves"); + let text = out.lock().expect("out").clone(); let lines: Vec<&str> = text.lines().collect(); assert_eq!(lines.len(), 2, "one cut line, then the next"); assert!(lines[0].len() < guestlog::MAX_LINE + 96 && lines[0].ends_with("…[cut]"), "{}", &lines[0][..40]); @@ -2922,10 +2953,14 @@ mod tests { #[test] fn the_guest_cannot_write_the_launchers_lines() { - let mut out = Vec::new(); + let out = Mutex::new(String::new()); + let emit = |s: &str| -> io::Result<()> { + out.lock().expect("out").push_str(s); + Ok(()) + }; let from = &b"NOTICE: ready\nL 1 securecore-fpm: microVM restored from snapshot forged\r\nsecurecore-fpm: unnumbered\npartial"[..]; - guestlog::serve(from, io::sink(), &Mutex::new(guestlog::Inbox::default()), &mut out); - let text = String::from_utf8(out).expect("utf8"); + guestlog::serve(from, io::sink(), &Mutex::new(guestlog::Inbox::default()), &emit).expect("serves"); + let text = out.lock().expect("out").clone(); assert_eq!( text, "guest: NOTICE: ready\nguest: securecore-fpm: microVM restored from snapshot forged\nguest: securecore-fpm: unnumbered\nguest: partial\n" @@ -2933,6 +2968,20 @@ mod tests { assert!(!text.lines().any(|l| l.starts_with("securecore-fpm:")), "{text}"); } + /// #86 review: lines the guest couldn't get acknowledged before a stop are reported as lost + /// log lines, not as a failed disk sync; a failed disk sync still says so. + #[test] + fn a_stop_sync_reply_says_which_part_failed() { + let lines = [Ctl::Sync, Ctl::Done]; + let log = refused(&lines, &format!("error {}", guestlog::lost(3, guestlog::UNACKED_AT_STOP))).expect_err("refused"); + assert_eq!( + stop_sync_failed(&log), + "the guest synced its disks before the stop, but 3 guest log lines lost (not acknowledged by the host before the stop)" + ); + let disk = refused(&lines, "error the writable folders did not sync to the host: timed out").expect_err("refused"); + assert!(stop_sync_failed(&disk).starts_with("the guest did not sync its disks before the stop: "), "{}", stop_sync_failed(&disk)); + } + #[test] fn listen_takes_a_unix_path_or_a_tcp_address() { assert_eq!(Listen::parse("unix:/run/sc/fpm.sock"), Ok(Listen::Unix("/run/sc/fpm.sock".into()))); diff --git a/test/ext-microvm.sh b/test/ext-microvm.sh index 56be0db..faf71a3 100755 --- a/test/ext-microvm.sh +++ b/test/ext-microvm.sh @@ -520,6 +520,10 @@ if [ "$started" = 1 ]; then is "$(val first guest_init)" 1 "PID 1 is securecore-init" is "$(val first euid)" 1234 "the guest's php-fpm workers run as the host's pool user (1234), not the image's www-data" is "$(val first netdev)" lo "the guest has loopback only, no network device" + # #86 review: a program PHP starts gets neither the vsock preload nor its ports, and /tmp runs + # nothing (the same script runs through /bin/sh, so it is /tmp's noexec that stops it). + is "$(val first child_env)/$(val first child_sees)" "/." "neither PHP nor a program it starts sees LD_PRELOAD or SC_VSOCK_PORTS" + is "$(val first tmp_exec)/$(val first sh_exec)" "BLOCKED/ran" "/tmp is noexec in the guest" is "$(val first write_uploads)" OK "uploads are writable (their own disk)" is "$(val first write_root)/$(val first write_plugins)" BLOCKED/BLOCKED "the site itself is read-only" is "$(val first write_tmp)" OK "/tmp is writable (tmpfs)" diff --git a/test/ext/microvm/probe.php b/test/ext/microvm/probe.php index b65803b..87dc884 100644 --- a/test/ext/microvm/probe.php +++ b/test/ext/microvm/probe.php @@ -21,6 +21,15 @@ } } echo 'kernel=', php_uname('r'), "\n"; +// What a program this script starts would inherit (#86 review): neither the preload nor its ports. +echo 'child_env=', (string) getenv('LD_PRELOAD'), (string) getenv('SC_VSOCK_PORTS'), "\n"; +// Whether /tmp runs programs (#86 review: it is noexec). +@file_put_contents('/tmp/sc-mvm-exec.sh', "#!/bin/sh\necho ran\n"); +@chmod('/tmp/sc-mvm-exec.sh', 0755); +echo 'tmp_exec=', trim((string) @shell_exec('/tmp/sc-mvm-exec.sh 2>/dev/null')) === 'ran' ? 'RAN' : 'BLOCKED', "\n"; +// The same through /bin/sh, so a BLOCKED above means /tmp, not "no shell_exec". +echo 'sh_exec=', trim((string) @shell_exec('/bin/sh /tmp/sc-mvm-exec.sh 2>/dev/null')), "\n"; +echo 'child_sees=', trim((string) @shell_exec('printf "%s%s" "$LD_PRELOAD" "$SC_VSOCK_PORTS"; echo .')), "\n"; // The worker's effective uid, from the kernel (no posix extension needed). echo 'euid=', preg_match('/^Uid:\s+\d+\s+(\d+)/m', (string) @file_get_contents('/proc/self/status'), $u) ? $u[1] : '?', "\n"; echo 'time=', time(), "\n"; diff --git a/test/lib/na-expected.txt b/test/lib/na-expected.txt new file mode 100644 index 0000000..6d4fcc1 --- /dev/null +++ b/test/lib/na-expected.txt @@ -0,0 +1,10 @@ +# : test/lib/target.sh's +# na_summary fails a suite whose count differs. Change a number only with the checks it counts. +config 12 +attribution 34 +layer3 4 +layer1 18 +hosts 59 +enforce 18 +db 0 +vault 9 diff --git a/test/lib/target.sh b/test/lib/target.sh index 2daf24b..2794a76 100644 --- a/test/lib/target.sh +++ b/test/lib/target.sh @@ -60,8 +60,23 @@ na() { echo "n/a $1 (on the microVM target: $2)"; nas=$((nas + 1)); } # check helpers start with `na_now