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/docs/layer1-microvm.md b/docs/layer1-microvm.md index d483ad2..63dfa1f 100644 --- a/docs/layer1-microvm.md +++ b/docs/layer1-microvm.md @@ -822,6 +822,35 @@ site's settings (`WORDPRESS_DB_HOST`, …). Until #72 the test image baked them the snapshot's `vm.mem` (as text or hex) and `vm.snap`, `console.log`, the launcher's log. It also checks that a restored guest still reaches the database. +## The guest's log: what it guarantees, and against whom (#86) + +php-fpm's lines (layer 2's audit lines among them) and the init's own come to the launcher on +vsock 1514, numbered and acknowledged. A line that can't be delivered is counted in the +launcher's own log ("N guest log lines lost"), never dropped in silence. + +- **Only the init writes the log.** The launcher makes a fresh 32-byte log key for every boot + and every restore, and gives it to the init over the control port, which only the host can + reach. A connection to 1514 that doesn't present that key first, within a second, is refused, + and the refusals are counted in the launcher's log. A restored init's old key (the + snapshot's) is refused too. It is never let in, and is only counted apart. +- **Labels.** php-fpm's output (master and workers) is logged as `guest: …`. The init's own lines + go in a frame of their own and are logged as `guest-init: …`, which nothing php-fpm writes can + produce. +- **Reserved room for the init.** The init's lines have the last 256 KiB of the guest's 4 MiB + buffer to themselves, so php-fpm's lines can't crowd them out. +- **Escaping.** Control characters and the Unicode line separators in a guest line are escaped, + so one guest line is one launcher line. + +**This holds against code that isn't root in the guest: PHP, plugins, and anything they run as +the pool user. It does not hold against root in the guest.** The lines are produced inside the +guest, by php-fpm's master and the init, and the key is in the init's memory. Code that becomes +root in the guest (a kernel exploit, say) can forge lines, drop them before they are numbered, +or send nothing at all. What the launcher still guarantees then is that such lines are marked +as the guest's (`guest:`/`guest-init:`) and never read as its own (`securecore-fpm:`), and +that a key learned in one restored guest is worthless in the next. An audit trail that must +survive a compromised guest has to be kept outside it: the host's egress, sync and database +logs are the launcher's own. + ## Follow-up issues (not filed) 1. **mirab: Landlock and seccomp in the x86_64 guest kernel.** Add `SECURITY`, diff --git a/ext/config/src/lib.rs b/ext/config/src/lib.rs index 7b28020..eeec413 100644 --- a/ext/config/src/lib.rs +++ b/ext/config/src/lib.rs @@ -627,10 +627,36 @@ fn root_of(path: &Path) -> PathBuf { /// Reads, parses and validates the file at `path`. pub fn load(path: &Path) -> Result { - let err = |problem| LoadError { path: path.to_owned(), problem }; - let bytes = fs::read(path).map_err(|e| err(Problem::Read(e)))?; - let config = Config::from_slice(&bytes).map_err(err)?; - Ok(Loaded { path: path.to_owned(), config, sha256: sha256_hex(&bytes), root: root_of(path) }) + let bytes = fs::read(path).map_err(|e| LoadError { path: path.to_owned(), problem: Problem::Read(e) })?; + load_bytes(path, &bytes) +} + +/// Parses and validates `bytes`, read from `path` by the caller (the launcher reads the file its +/// own careful way, addiscorp/securecore#90 review). +pub fn load_bytes(path: &Path, bytes: &[u8]) -> Result { + let config = Config::from_slice(bytes).map_err(|problem| LoadError { path: path.to_owned(), problem })?; + Ok(Loaded { path: path.to_owned(), config, sha256: sha256_hex(bytes), root: root_of(path) }) +} + +impl LoadError { + /// The message without anything of the file's bytes in it: a JSON or schema error says + /// where (line and column) and what kind, never the token it met (serde's messages quote + /// it, and a file in the wrong place could hold anything). The rules the types can't + /// express ([`Problem::Invalid`]) are this crate's own words. + pub fn without_contents(&self) -> String { + match &self.problem { + Problem::Parse(e) => { + let kind = match e.classify() { + serde_json::error::Category::Syntax => "not valid JSON", + serde_json::error::Category::Eof => "the file ends too early", + serde_json::error::Category::Data => "a key or value securecore.schema.json doesn't take", + serde_json::error::Category::Io => "it could not be read", + }; + format!("{}: invalid at line {} column {}: {kind}", self.path.display(), e.line(), e.column()) + } + _ => self.to_string(), + } + } } pub fn sha256_hex(bytes: &[u8]) -> String { 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 6bd27ab..5899fea 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; @@ -169,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, } @@ -184,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(), } } @@ -206,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()), @@ -229,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); @@ -476,7 +486,8 @@ fn apply(ctl: &Ctl) -> io::Result<()> { return Err(io::Error::new(e.kind(), format!("{device}: BLKFLSBUF: {e}"))); } drop(dev); - mount(device, path, "ext4", libc::MS_NOSUID | libc::MS_NODEV, WRITABLE_MOUNT_DATA)?; + // noexec (#86 verification review): nothing written to a writable folder runs. + mount(device, path, "ext4", libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC, WRITABLE_MOUNT_DATA)?; WRITABLE.lock().unwrap_or_else(|p| p.into_inner()).push(path.clone()); // Every file closed after writing is made durable at once, whatever the host's sync // is doing (it may be stuck behind a host that doesn't answer). @@ -488,18 +499,25 @@ fn apply(ctl: &Ctl) -> io::Result<()> { }); Ok(()) } - Ctl::Tmpfs { path } => mount("tmpfs", path, "tmpfs", libc::MS_NOSUID | libc::MS_NODEV, "mode=1777"), + Ctl::Tmpfs { path } => mount("tmpfs", path, "tmpfs", libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC, "mode=1777"), Ctl::Sync => { // 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, 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(()), } } @@ -561,6 +579,11 @@ fn serve_ctl(conn: Vsock, peer_cid: u32) { } else if !fpm_listening(Duration::from_secs(10)) { failed = Some(format!("php-fpm with the delivered environment isn't listening on 127.0.0.1:{FPM_PORT}")); } + } else if failed.is_none() && lines.contains(&Ctl::Reload) && !fpm_listening(Duration::from_secs(10)) { + // A reload is done once the fresh php-fpm takes requests, not once it is started: the + // host says "reloaded" on this answer, and sends requests on (found by #86's stress on + // GitHub's runners, where requests right after a reload met no listener). + failed = Some(format!("the reloaded php-fpm isn't listening on 127.0.0.1:{FPM_PORT}")); } // The host never shows a reply to a message that carried secrets, so the reason is logged // here too (no message here ever holds a value: refused env lines are never echoed). @@ -569,15 +592,30 @@ 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()); - } + // Its own kind of frame: the launcher logs it as `guest-init: `, which php-fpm's lines can't + // be (#86 verification review). + LOG.init_line(message.as_bytes()); } /// Warns once a writable disk passes 90 % (and again past 98 %): beyond it, php-fpm's writes @@ -608,28 +646,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); } } @@ -802,13 +828,15 @@ 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 { set_clock(t, 0)?; } - mount("/dev/vdb", &boot.root, "ext4", libc::MS_RDONLY | flags, "noload")?; + // noexec too: php-fpm reads the site's PHP, nothing on the site disk ever runs as a program. + mount("/dev/vdb", &boot.root, "ext4", libc::MS_RDONLY | flags | libc::MS_NOEXEC, "noload")?; loopback_up()?; // The folder sync watches every folder of the writable disks (8192 by default here). let _ = fs::write("/proc/sys/fs/inotify/max_user_watches", "65536"); @@ -818,6 +846,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); @@ -957,6 +986,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 new file mode 100644 index 0000000..a4d7bed --- /dev/null +++ b/ext/fpm/src/guestlog.rs @@ -0,0 +1,1100 @@ +//! 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 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; 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: `, 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}; + +/// 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); +/// 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; + +/// The part of the guest's buffer only the init's own lines may use. +pub const INIT_RESERVE: usize = 256 << 10; +/// 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)] +pub enum Frame { + /// php-fpm's output (its master's and every worker's stderr). + Line { seq: u64, text: Vec }, + /// The init's own line: tagged apart on the wire, so nothing php-fpm writes can read as it. + Init { seq: u64, text: Vec }, + Lost { seq: u64, count: u64 }, +} + +impl Frame { + pub fn seq(&self) -> u64 { + match self { + Frame::Line { seq, .. } | Frame::Init { seq, .. } | Frame::Lost { seq, .. } => *seq, + } + } + + pub fn encode(&self) -> Vec { + match self { + Frame::Line { seq, text } | Frame::Init { seq, text } => { + let kind = if matches!(self, Frame::Init { .. }) { "I" } else { "L" }; + let mut out = format!("{kind} {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'I' if sp.is_some() => Some(Frame::Init { 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() +} + +/// 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") +} + +/// A key line's length, its newline included. +const HELLO_LEN: usize = 2 + 2 * KEY_LEN + 1; + +/// Bytes waiting to be read on `c` (0 if it can't say). +fn waiting(c: &UnixStream) -> usize { + use std::os::fd::AsRawFd as _; + let mut n: libc::c_int = 0; + // SAFETY: FIONREAD writes one int, on a socket we hold. + if unsafe { libc::ioctl(c.as_raw_fd(), libc::FIONREAD, &mut n) } < 0 { 0 } else { n.max(0) as usize } +} + +/// The first line of a connection, read a byte at a time (so nothing after it is taken), by +/// `deadline` at the latest, however slowly the bytes come: `None` when none came in time, or +/// the connection ended first, or it is longer than a key line. +fn read_hello(mut c: &UnixStream, deadline: Instant) -> Option> { + let mut line = Vec::with_capacity(HELLO_LEN); + let mut b = [0u8; 1]; + loop { + let left = deadline.checked_duration_since(Instant::now()).filter(|d| !d.is_zero())?; + c.set_read_timeout(Some(left)).ok()?; + match c.read(&mut b) { + Ok(1) if b[0] == b'\n' => return Some(line), + Ok(1) if line.len() < HELLO_LEN => line.push(b[0]), + _ => return None, + } + } +} + +/// 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`. +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, + /// 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 { + 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, acks: 0, key: None }), + cv: Condvar::new(), + cap, + } + } + + fn lock(&self) -> std::sync::MutexGuard<'_, Queue> { + 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. + pub fn line(&self, text: &[u8]) { + self.queue(text, false); + } + + /// The init's own line ([`Frame::Init`]): it may use the last [`INIT_RESERVE`] bytes of the + /// buffer, which php-fpm's lines never take, so a flood on php-fpm's stderr can't crowd it + /// out (#86 verification review). + pub fn init_line(&self, text: &[u8]) { + self.queue(text, true); + } + + fn queue(&self, text: &[u8], init: bool) { + 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; + let room = if init { self.cap } else { self.cap.saturating_sub(INIT_RESERVE.min(self.cap / 2)) }; + if q.bytes + need > room { + q.lost += 1; + return; + } + q.push_lost(); + q.push(|seq| if init { Frame::Init { seq, text } } else { 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()); + q.acks += 1; + } + 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 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); + } +} + +/// 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 = BACKOFF.0; + loop { + // Nothing to send, or no key yet: wait before connecting. + let (key, acks) = { + let mut q = outbox.lock(); + while q.frames.is_empty() || q.key.is_none() { + q = outbox.cv.wait(q).unwrap_or_else(|p| p.into_inner()); + } + (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, + }; + if moved_on { + backoff = BACKOFF.0; + } else { + thread::sleep(backoff); + backoff = (backoff * 2).min(BACKOFF.1); + } + } +} + +/// 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); + 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. + /// 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 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")); + } + } + self.last = Some(seq); + match frame { + Frame::Line { text, .. } => out.push(guest_line(text, cut)), + Frame::Init { text, .. } => out.push(init_line(text, cut)), + Frame::Lost { count, .. } => out.push(lost_line(*count, "the guest's log buffer was full")), + } + Ok(out) + } + + pub fn last(&self) -> Option { + self.last + } +} + +/// 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)) +} + +/// `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: {}{}", escaped(text), if cut { " …[cut]" } else { "" }) +} + +/// The init's own line as the launcher logs it: a label of its own, which nothing php-fpm writes +/// can produce (its lines are always `guest: `). +pub fn init_line(text: &[u8], cut: bool) -> String { + format!("guest-init: {}{}", escaped(text), if cut { " …[cut]" } else { "" }) +} + +/// A guest's text with every control character but the tab, and the Unicode line separators +/// (U+0085, U+2028, U+2029), written as `\u{…}` (#86 verification review): one guest line stays +/// one log line, whatever a terminal or a log viewer makes of its bytes. (A tab can't end a line +/// or move the cursor back, and SQL in PHP's lines is full of them.) +pub fn escaped(text: &[u8]) -> String { + let mut out = String::with_capacity(text.len()); + for c in String::from_utf8_lossy(text).chars() { + if (c.is_control() && c != '\t') || matches!(c, '\u{85}' | '\u{2028}' | '\u{2029}') { + out.extend(c.escape_unicode()); + } else { + out.push(c); + } + } + out +} + +/// The longest frame line the host reads whole: a line, its number and its kind. +const MAX_FRAME: usize = MAX_LINE + 64; + +/// 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) { + { + // 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() { + 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 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)>, + /// A restored VM's snapshot key: the restored init presents it until it gets this VM's own + /// (a moment later), so it is refused quietly, counted apart, and never let in. + stale: Option, + stale_refused: AtomicU64, +} + +impl LogServer { + pub fn new(key: Key, stale: Option, 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)), + stale, + stale_refused: AtomicU64::new(0), + } + } + + /// Says what hasn't been said yet (the last second's refusals, the stale key's), when the VM + /// stops (#86 verification review). + pub fn flush(&self) { + let n = self.refused(); + let mut said = self.said.lock().unwrap_or_else(|p| p.into_inner()); + if n > said.1 { + let _ = (self.emit)(&format!( + "securecore-fpm: refused {} more guest log connection{} without this VM's log key before the stop ({n} in all)\n", + n - said.1, + if n - said.1 == 1 { "" } else { "s" } + )); + *said = (Some(Instant::now()), n); + } + let stale = self.stale_refused.swap(0, Ordering::SeqCst); + if stale > 0 { + let _ = (self.emit)(&format!( + "securecore-fpm: refused {stale} guest log connection{} with the snapshot's old log key (the restored init's, until this VM's own reached it)\n", + if stale == 1 { "" } else { "s" } + )); + } + } + + /// 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 one out to make room: the oldest that + /// hasn't a whole key line waiting to be read. One that has (the init's, its hello written the + /// moment it connected) is spared, so a churn of keyless connections can't keep evicting it + /// (#86 verification review). 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 { + let victim = s.iter().position(|(_, c)| waiting(c) < HELLO_LEN).unwrap_or(0); + if let Some((_, old)) = s.remove(victim) { + 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 hello = read_hello(&conn, Instant::now() + HELLO_TIMEOUT); + self.release(&self.pending, id); + match hello { + Some(h) if hello_ok(&h, &self.key) => {} + Some(h) if self.stale.is_some_and(|k| hello_ok(&h, &k)) => { + let _ = conn.shutdown(std::net::Shutdown::Both); + self.stale_refused.fetch_add(1, Ordering::SeqCst); + return; + } + None => { + let _ = conn.shutdown(std::net::Shutdown::Both); + return self.refuse("it sent no key line within a second"); + } + Some(_) => { + let _ = conn.shutdown(std::net::Shutdown::Both); + return self.refuse("it sent something else first"); + } + } + let r = BufReader::with_capacity(64 << 10, conn); + 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; + use std::sync::Arc; + 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 }] { + 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)); + 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; 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).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] + 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 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, &*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 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, server: 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 server = server.clone(); + thread::spawn(move || server.take(c)); + } + } + + /// 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 path = scratch("stall"); + let l = UnixListener::bind(&path).expect("bind"); + let key = [3u8; KEY_LEN]; + let log = Log::default(); + let server = Arc::new(LogServer::new(key, None, log.emit())); + let conns = Arc::new(AtomicUsize::new(0)); + { + 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) + .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 = 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(); + 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(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, None, 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")); + } + + /// K4: the init's lines have a label of their own, which a php-fpm line can't produce, and a + /// part of the buffer php-fpm's lines can't fill. + #[test] + fn the_inits_lines_are_labelled_apart_and_never_crowded_out() { + let ob = leak(OUTBOX_BYTES); + let flood = "w".repeat(1000); + for _ in 0..(OUTBOX_BYTES / 1000) { + ob.line(flood.as_bytes()); + } + assert!(ob.pending().1 > 0, "php-fpm's flood filled its part and was counted"); + ob.line(format!("securecore-init: php-fpm exited (forged by a worker) {flood}").as_bytes()); + ob.init_line(b"php-fpm exited at boot (exit code 78)"); + let log = Log::default(); + let frames: Vec = ob.lock().frames.iter().flat_map(|(_, b)| b.clone()).collect(); + serve(&frames[..], io::sink(), &Mutex::new(Inbox::default()), &*log.emit()).expect("serves"); + let text = log.text(); + assert!(text.lines().any(|l| l == "guest-init: php-fpm exited at boot (exit code 78)"), "the init's line is there, under its label"); + assert!(!text.contains("forged by a worker"), "the worker's line was counted as lost, not queued"); + assert_eq!(guest_line(b"securecore-init: forged", false), "guest: securecore-init: forged", "a worker's line is always guest:"); + assert!(text.lines().filter(|l| l.starts_with("guest-init: ")).count() == 1); + } + + /// N1: control characters and the Unicode line separators are escaped; a tab is kept. + #[test] + fn a_guest_line_stays_one_line() { + let s = escaped("a\rb\u{1b}[2Jc\u{85}d\u{2028}e\u{2029}f\tg\u{7f}".as_bytes()); + assert_eq!(s, "a\\u{d}b\\u{1b}[2Jc\\u{85}d\\u{2028}e\\u{2029}f\tg\\u{7f}"); + assert!(!s.chars().any(|c| (c.is_control() && c != '\t') || matches!(c, '\u{85}' | '\u{2028}' | '\u{2029}'))); + assert_eq!(init_line(b"x\x08y", false), "guest-init: x\\u{8}y"); + } + + /// K2 and K3: a restored init's old key is refused quietly and counted apart; a key line + /// dripped a byte at a time past the deadline is refused; the refusals not yet said are said + /// by `flush` (N3). + #[test] + fn an_old_key_and_a_slow_hello_are_refused_and_said_at_the_stop() { + let path = scratch("stale"); + let l = UnixListener::bind(&path).expect("bind"); + let (key, old) = ([5u8; KEY_LEN], [6u8; KEY_LEN]); + let log = Log::default(); + let server = Arc::new(LogServer::new(key, Some(old), 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)); + } + }); + } + let mut c = UnixStream::connect(&path).expect("connect"); + c.write_all(format!("{}L 1 from the snapshot's key\n", hello_line(&old)).as_bytes()).expect("write"); + let mut sink = Vec::new(); + let _ = c.set_read_timeout(Some(Duration::from_secs(3))); + let _ = c.read_to_end(&mut sink); + assert!(sink.is_empty(), "nothing acknowledged"); + // The right key line, dripped a byte every 60 ms (4 s in all): each byte comes well within + // a second of the last, but the whole line doesn't come within the one second a + // connection has, so it is cut then and refused (K3). + let t = Instant::now(); + let d = UnixStream::connect(&path).expect("connect"); + let mut cut = None; + for b in hello_line(&key).bytes() { + if (&d).write_all(&[b]).is_err() { + cut = Some(t.elapsed()); + break; + } + thread::sleep(Duration::from_millis(60)); + } + let cut = cut.unwrap_or_else(|| t.elapsed()); + assert!(cut < Duration::from_millis(2500), "cut at the deadline, not after the whole line ({cut:?})"); + thread::sleep(Duration::from_millis(200)); + server.flush(); + let text = log.text(); + assert!(!text.contains("from the snapshot's key"), "{text}"); + assert!(text.contains("refused 1 guest log connection with the snapshot's old log key"), "{text}"); + assert!(text.contains("guest log connection") && server.refused() == 1, "the slow one: {text}"); + let _ = std::fs::remove_dir_all(path.parent().expect("dir")); + } +} diff --git a/ext/fpm/src/lib.rs b/ext/fpm/src/lib.rs index 46b3f4f..d96d1b8 100644 --- a/ext/fpm/src/lib.rs +++ b/ext/fpm/src/lib.rs @@ -22,6 +22,8 @@ pub mod egress; pub mod fcgi; #[cfg(target_os = "linux")] pub mod guest; +pub mod guestlog; +pub mod sitefile; #[cfg(target_os = "linux")] pub mod jail; #[cfg(target_os = "linux")] diff --git a/ext/fpm/src/main.rs b/ext/fpm/src/main.rs index 7595e36..8f6a446 100644 --- a/ext/fpm/src/main.rs +++ b/ext/fpm/src/main.rs @@ -286,9 +286,11 @@ fn main() -> ExitCode { } Err(problem) => return failed(&format!("{problem} ({USAGE})")), }; - let loaded = match securecore_config::load(&args.config) { + // Never through a link, as the folder's owner, capped, and no error quotes the file + // (#90 review): the same reading the microVM's config watcher does. + let loaded = match securecore_fpm::sitefile::load(&args.config) { Ok(loaded) => loaded, - Err(err) => return failed(&err.to_string()), + Err(err) => return failed(&err), }; let path = loaded.path.display(); let layer1 = &loaded.config.layer1; diff --git a/ext/fpm/src/sitefile.rs b/ext/fpm/src/sitefile.rs new file mode 100644 index 0000000..82f03b8 --- /dev/null +++ b/ext/fpm/src/sitefile.rs @@ -0,0 +1,217 @@ +//! Reading `securecore.json` the careful way (addiscorp/securecore#90 review, S1): at launch and +//! in the microVM's config watcher, with one function. The file is the site's, and the site's +//! owner controls it, so the launcher (root) never lets it point anywhere else: +//! +//! - the root (the folder holding `securecore.json`, which the operator names with `--config`) +//! is the operator's: resolved once with `canonicalize`, so a deployment's link +//! (`/var/www/current -> releases/7`) works; +//! - below it everything is the site owner's: the file is opened from an fd on that root with +//! `openat2` `RESOLVE_BENEATH | RESOLVE_NO_SYMLINKS`, so no link (the file itself, a folder on +//! the way) and no `..` out of the root is followed; +//! - the file is opened as the owner of the root (this thread's filesystem ids, +//! `setfsuid`/`setfsgid`), so a file that owner can't read (another site's, root's own) isn't; +//! - it must be a regular file, opened `O_NONBLOCK` (a FIFO or a device is refused at once, +//! never read), and at most [`MAX_CONFIG`] bytes are read; +//! - no error quotes the file's bytes ([`securecore_config::LoadError::without_contents`]). + +use std::io::{self, Read as _}; +use std::path::Path; + +use securecore_config::{LoadError, Loaded}; + +/// The largest `securecore.json` read (and the largest a microVM guest takes). +pub const MAX_CONFIG: usize = 128 * 1024; + +/// Reads `path` as described in the module header, its folder being the root: `Ok(None)` when +/// it doesn't exist. +pub fn read(path: &Path, cap: usize) -> Result>, String> { + let (root, name) = match (path.parent(), path.file_name()) { + (Some(d), Some(n)) if !d.as_os_str().is_empty() => (d, Path::new(n)), + (_, Some(n)) => (Path::new("."), Path::new(n)), + _ => return Err(format!("{}: not a file path", path.display())), + }; + read_beneath(root, name, cap) +} + +/// Reads `rel` beneath `root` as described in the module header: `root` resolved once (the +/// operator's), nothing below it a link. `Ok(None)` when it doesn't exist. +pub fn read_beneath(root: &Path, rel: &Path, cap: usize) -> Result>, String> { + let path = root.join(rel); + let shown = path.display(); + let f = match open(root, rel) { + Ok(f) => f, + Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(e) if matches!(e.raw_os_error(), Some(libc::ELOOP | libc::EXDEV)) => { + return Err(format!("{shown}: a link is in its path below {}: refused (the file is read only as itself)", root.display())); + } + Err(e) => return Err(format!("{shown}: {e}")), + }; + let m = f.metadata().map_err(|e| format!("{shown}: {e}"))?; + if !m.file_type().is_file() { + return Err(format!("{shown} is not a regular file: refused")); + } + if m.len() > cap as u64 { + return Err(format!("{shown} is larger than {cap} bytes: refused")); + } + let mut b = Vec::new(); + f.take(cap as u64 + 1).read_to_end(&mut b).map_err(|e| format!("{shown}: {e}"))?; + if b.len() > cap { + return Err(format!("{shown} is larger than {cap} bytes: refused")); + } + Ok(Some(b)) +} + +/// [`read`], then the config crate's own parser: the launcher's start and the microVM's +/// watcher see the same file the same way. Errors never quote the file. +pub fn load(path: &Path) -> Result { + match read(path, MAX_CONFIG)? { + None => Err(format!("{}: cannot read it: No such file or directory", path.display())), + Some(b) => securecore_config::load_bytes(path, &b).map_err(|e: LoadError| e.without_contents()), + } +} + +#[cfg(target_os = "linux")] +fn open(root: &Path, rel: &Path) -> io::Result { + use std::os::fd::{AsRawFd as _, FromRawFd as _, OwnedFd}; + use std::os::unix::ffi::OsStrExt as _; + use std::os::unix::fs::MetadataExt as _; + let c = |p: &Path| std::ffi::CString::new(p.as_os_str().as_bytes()).map_err(|_| io::Error::other("a path with a NUL")); + // The root is the operator's (`/var/www/current -> releases/7` is a deployment, not an + // attack): resolved once, as the launcher. + let root = std::fs::canonicalize(root)?; + let (d, n) = (c(&root)?, c(rel)?); + // SAFETY: open(2) with a NUL-terminated path; the fd is owned below. + let dfd = unsafe { libc::open(d.as_ptr(), libc::O_PATH | libc::O_DIRECTORY | libc::O_CLOEXEC) }; + if dfd < 0 { + return Err(io::Error::last_os_error()); + } + // SAFETY: dfd was just returned by openat2(2). + let dfd = unsafe { OwnedFd::from_raw_fd(dfd) }; + let owner = std::fs::File::from(dfd.try_clone()?).metadata()?; + // As the folder's owner, when that isn't who runs this (root reading a site's file). + // SAFETY: getuid only reads this process's id. + let swap = (unsafe { libc::geteuid() } == 0 && owner.uid() != 0).then_some((owner.uid(), owner.gid())); + // SAFETY: setfsuid(2)/setfsgid(2) change only this thread's filesystem ids; put back below. + let old = swap.map(|(u, g)| unsafe { (libc::setfsgid(g), libc::setfsuid(u)) }); + // Below the root everything is the site owner's: no link, no `..` out of it. + let fd = crate::jail::openat2_raw(dfd.as_raw_fd(), &n, libc::O_RDONLY | libc::O_NONBLOCK | libc::O_CLOEXEC, crate::jail::BENEATH); + let err = io::Error::last_os_error(); + if let Some((g, u)) = old { + // SAFETY: as above. + unsafe { + libc::setfsuid(u as libc::uid_t); + libc::setfsgid(g as libc::gid_t); + } + } + if fd < 0 { + return Err(err); + } + // SAFETY: fd was just returned by openat2(2). + Ok(unsafe { std::fs::File::from_raw_fd(fd) }) +} + +/// Elsewhere (the launcher runs on Linux; this keeps the crate's tests building): no link as the +/// last component. +#[cfg(not(target_os = "linux"))] +fn open(root: &Path, rel: &Path) -> io::Result { + use std::os::unix::fs::OpenOptionsExt as _; + std::fs::OpenOptions::new().read(true).custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK).open(root.join(rel)) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + use std::time::{Duration, Instant}; + + fn scratch(name: &str) -> std::path::PathBuf { + // A folder whose path holds no link (macOS's /var is one; /private/var isn't). + let base = fs::canonicalize(std::env::temp_dir()).expect("tmp"); + let dir = base.join(format!("sc-sitefile-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).expect("dir"); + dir + } + + /// S1: at launch as in the watcher, a link to another site's config, root's own file, a + /// device and a FIFO are refused at once, and no error quotes the file. + #[test] + fn the_config_is_read_as_itself_by_its_folders_owner() { + let dir = scratch("read"); + let good = dir.join("securecore.json"); + fs::write(&good, r#"{"layer1":{"isolation":"off"},"layer2":{"enabled":false},"layer3":{"enabled":false}}"#).expect("write"); + assert!(load(&good).is_ok(), "a plain file loads"); + let other = dir.join("other-site.json"); + fs::write(&other, r#"{"layer1":{"isolation":"off"},"layer2":{"enabled":false},"layer3":{"enabled":false}}"#).expect("write"); + let link = dir.join("link.json"); + std::os::unix::fs::symlink(&other, &link).expect("link"); + assert!(load(&link).expect_err("a link").contains("link"), "a link to another site's config"); + let zero = dir.join("zero.json"); + std::os::unix::fs::symlink("/dev/zero", &zero).expect("link"); + let t = Instant::now(); + assert!(load(&zero).is_err(), "/dev/zero through a link"); + assert!(read(Path::new("/dev/zero"), MAX_CONFIG).expect_err("a device").contains("not a regular file")); + let fifo = dir.join("fifo.json"); + let cf = std::ffi::CString::new(fifo.to_str().expect("utf8")).expect("cstr"); + // SAFETY: mkfifo(3) with a NUL-terminated path. + assert_eq!(unsafe { libc::mkfifo(cf.as_ptr(), 0o644) }, 0); + assert!(read(&fifo, MAX_CONFIG).expect_err("a FIFO").contains("not a regular file")); + assert!(t.elapsed() < Duration::from_secs(1), "refused at once, never read"); + let big = dir.join("big.json"); + fs::write(&big, vec![b' '; MAX_CONFIG + 1]).expect("write"); + assert!(read(&big, MAX_CONFIG).expect_err("too big").contains("larger than")); + // serde's messages quote what they met; these never do. + fs::write(&good, r#"{"layer1":{"isolation":"sk_live_SECRET"},"layer2":{"enabled":false},"layer3":{"enabled":false}}"#).expect("write"); + let e = load(&good).expect_err("an unknown value"); + assert!(e.contains("invalid at line 1 column") && !e.contains("SECRET"), "{e}"); + fs::write(&good, "{\"layer1\": \"sk_live_SECRET").expect("write"); + assert!(!load(&good).expect_err("not JSON").contains("SECRET")); + // As root: the file is opened as the folder's owner, so root's own file isn't read. + // SAFETY: geteuid only reads this process's id. + #[cfg(target_os = "linux")] + if unsafe { libc::geteuid() } == 0 { + use std::os::unix::fs::PermissionsExt as _; + let site = dir.join("site"); + fs::create_dir_all(&site).expect("site"); + std::os::unix::fs::chown(&site, Some(65534), Some(65534)).expect("chown"); + let root_only = site.join("securecore.json"); + fs::write(&root_only, "{}").expect("write"); + fs::set_permissions(&root_only, fs::Permissions::from_mode(0o600)).expect("chmod"); + assert!(read(&root_only, MAX_CONFIG).expect_err("root's alone").contains("Permission denied")); + fs::set_permissions(&root_only, fs::Permissions::from_mode(0o644)).expect("chmod"); + assert!(read(&root_only, MAX_CONFIG).expect("readable").is_some()); + // A link anywhere in the path, not only the last component. + } + let _ = fs::remove_dir_all(&dir); + } + + /// The site root may be reached through the operator's link (a deployment's + /// `/var/www/current -> releases/1`); below it, a link (the file, a folder on the way) or a + /// `..` out of it is refused. + #[test] + fn the_root_may_be_a_deployments_link_but_nothing_below_it() { + let dir = scratch("deploy"); + let release = dir.join("releases/1"); + fs::create_dir_all(release.join("conf")).expect("release"); + let json = r#"{"layer1":{"isolation":"off"},"layer2":{"enabled":false},"layer3":{"enabled":false}}"#; + fs::write(release.join("securecore.json"), json).expect("write"); + fs::write(release.join("conf/site.ini"), "x").expect("write"); + let current = dir.join("current"); + std::os::unix::fs::symlink("releases/1", ¤t).expect("link"); + let loaded = load(¤t.join("securecore.json")).expect("through the deployment's link"); + assert_eq!(loaded.config, securecore_config::Config::from_slice(json.as_bytes()).expect("valid")); + // Below the root: the file a link, a folder a link, and `..` out of the root. + fs::write(dir.join("elsewhere.json"), json).expect("write"); + let inside = release.join("linked.json"); + std::os::unix::fs::symlink(dir.join("elsewhere.json"), &inside).expect("link"); + assert!(read(¤t.join("linked.json"), MAX_CONFIG).expect_err("a linked file").contains("a link is in its path")); + std::os::unix::fs::symlink(release.join("conf"), release.join("conflink")).expect("link"); + // (openat2 is Linux's; the fallback elsewhere checks the last component only.) + #[cfg(target_os = "linux")] + assert!(read_beneath(¤t, Path::new("conflink/site.ini"), 1024).expect_err("a linked folder").contains("a link is in its path")); + assert_eq!(read_beneath(¤t, Path::new("conf/site.ini"), 1024), Ok(Some(b"x".to_vec())), "a real folder is fine"); + #[cfg(target_os = "linux")] + assert!(read_beneath(¤t, Path::new("../../elsewhere.json"), 1024).is_err(), "never out of the root"); + let _ = fs::remove_dir_all(&dir); + } +} diff --git a/ext/fpm/src/vm.rs b/ext/fpm/src/vm.rs index 921968a..cefb1ba 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 @@ -52,6 +53,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 +68,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; @@ -1080,6 +1083,17 @@ 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, + /// Its log port's server: what it hasn't said yet is said when the VM goes ([`Drop`]). + log_server: &'static guestlog::LogServer, +} + +/// A VM's log key, and the old one a restored snapshot's init still holds for a moment. +#[derive(Clone, Copy)] +struct LogKeys { + key: guestlog::Key, + stale: Option, } /// An `O_PATH` handle on `dir` and the short path prefix that reaches into it. @@ -1096,6 +1110,8 @@ fn short_dir(dir: &Path) -> Result<(fs::File, PathBuf), String> { impl Drop for Vm { fn drop(&mut self) { + // The last second's refusals on its log port (#86 verification review). + self.log_server.flush(); if let Some(mut c) = self.child.take() { let _ = c.kill(); let _ = c.wait(); @@ -1136,14 +1152,16 @@ 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 { + /// `keys`: this VM's log key, and a restored snapshot's old one, which is refused quietly. + fn spawn(plan: &Plan, opts: &Options, m: &Machine, wiring: Wiring, snap: Option<&Path>, keys: LogKeys) -> 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, keys).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>, keys: LogKeys) -> Result { + let key = keys.key; j.prepare()?; j.place(&opts.assets.kernel, IN_KERNEL)?; j.place(&opts.assets.rootfs, IN_ROOTFS)?; @@ -1162,7 +1180,7 @@ impl Vm { j.user_dir(IN_SNAP_NEW)?; } let (root, short) = short_dir(&j.root)?; - wire(plan, m, j, &short, wiring)?; + let log_server = wire(plan, m, j, &short, wiring, keys)?; 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}"))?; @@ -1175,7 +1193,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, log_server }; let t = Instant::now(); while UnixStream::connect(&vm.api).is_err() { if let Some(st) = vm.exited() { @@ -1229,8 +1247,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, LogKeys { key: random_key()?, stale: None })?; 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)))?; @@ -1251,11 +1290,27 @@ 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())) +} + +/// A restore's log keys: a fresh one of its own, and the snapshot's as the stale one. +fn restore_keys(snap: &Path) -> Result { + Ok(LogKeys { key: random_key()?, stale: Some(snap_key(snap)?) }) +} + +/// A restore: a fresh log key of its own, given to the restored init at once (#86 verification +/// review, K2). The snapshot's key, which every restore of it starts with, is only ever refused +/// (quietly): whoever learned it in one restored guest has nothing in the next. 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), restore_keys(snap)?)?; vm.api( "PUT", "/snapshot/load", @@ -1265,6 +1320,7 @@ fn restore(plan: &Plan, opts: &Options, m: &Machine, snap: &Path) -> Result 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())) } @@ -1370,6 +1434,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). @@ -1378,7 +1452,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}")) @@ -1580,7 +1654,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, keys: LogKeys) -> Result<&'static guestlog::LogServer, String> { let user = m.user; let owned = SocketMode { owner: Some(user.uid), group: Some(user.gid), mode: 0o600 }; if wiring == Wiring::Full { @@ -1641,71 +1715,23 @@ 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): 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)?; + // 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(keys.key, keys.stale, emit))); thread::spawn(move || { for c in l.incoming().flatten() { - let Some(slot) = LOG_SLOTS.take() else { continue }; - thread::spawn(move || { - let _slot = slot; - let _ = c.shutdown(std::net::Shutdown::Write); - mark_guest_lines(c, &mut io::stderr()); - }); + thread::spawn(move || server.take(c)); } }); - Ok(()) + Ok(server) } -/// 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 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 +1794,6 @@ 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); /// Connections through one `address` forward at once. const FORWARD_SLOTS: usize = 64; @@ -2320,7 +2344,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); @@ -2334,6 +2358,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 { @@ -2720,14 +2745,20 @@ mod tests { #[test] fn guest_lines_are_capped_and_connections_counted() { - let long = format!("{}\nnext\n", "x".repeat(MAX_LINE * 3)); - let mut out = Vec::new(); - mark_guest_lines(long.as_bytes(), &mut out); - let text = String::from_utf8(out).expect("utf8"); + let long = format!("L 1 {}\nL 2 next\n", "x".repeat(guestlog::MAX_LINE * 3)); + let out = Mutex::new(String::new()); + let mut acks = Vec::new(); + 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() < 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"); @@ -2944,13 +2975,49 @@ 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 text = String::from_utf8(out).expect("utf8"); - assert_eq!(text, "guest: NOTICE: ready\nguest: securecore-fpm: microVM restored from snapshot forged\nguest: partial\n"); + 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()), &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" + ); 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)); + } + + /// K2: every restore of a snapshot takes the log with a key of its own, never the snapshot's, + /// which it only knows as the one to refuse. + #[test] + fn each_restore_gets_a_log_key_of_its_own() { + let dir = scratch("keys"); + fs::write(dir.join(SNAP_LOG_KEY), [4u8; guestlog::KEY_LEN]).expect("write"); + let (a, b) = (restore_keys(&dir).expect("keys"), restore_keys(&dir).expect("keys")); + assert_eq!(a.stale, Some([4u8; guestlog::KEY_LEN]), "the snapshot's key is the stale one"); + assert!(a.key != [4u8; guestlog::KEY_LEN] && b.key != a.key, "each restore's own, fresh"); + fs::write(dir.join(SNAP_LOG_KEY), b"short").expect("write"); + assert!(restore_keys(&dir).is_err(), "a broken key file fails the restore (it cold-boots)"); + let _ = fs::remove_dir_all(&dir); + } + #[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/ext/fpm/tests/launch.rs b/ext/fpm/tests/launch.rs index 2eebe43..3f93100 100644 --- a/ext/fpm/tests/launch.rs +++ b/ext/fpm/tests/launch.rs @@ -55,7 +55,9 @@ fn an_invalid_config_exits_125_without_running_php_fpm() { let out = launch(&path, &format!("touch {}", marker.display())); assert_eq!(out.status.code(), Some(125), "{}", stderr(&out)); assert!(!marker.exists(), "php-fpm must not run on an invalid config"); - assert!(stderr(&out).contains(&format!("securecore-fpm: {}: invalid:", path.display())), "{}", stderr(&out)); + // Where and what kind, never the file's token (#90 review: serde quotes what it met). + assert!(stderr(&out).contains(&format!("securecore-fpm: {}: invalid at line 1 column ", path.display())), "{}", stderr(&out)); + assert!(!stderr(&out).contains("`0`"), "{}", stderr(&out)); assert!(stderr(&out).contains("refusing to start php-fpm"), "{}", stderr(&out)); // A missing file, and no --config at all, fail the same way. diff --git a/test/ext-config.sh b/test/ext-config.sh index 7788104..19f0a45 100755 --- a/test/ext-config.sh +++ b/test/ext-config.sh @@ -171,7 +171,9 @@ refuses() { problem=$2 if on_microvm; then is "$(php_state)" "exited 125" "$1: the launcher exits 125" - if grep -qF "securecore-fpm: $(site_dir)/securecore.json: ${problem#\$conf: }" "$dir/refuse.log"; then + # The launcher's words, when they differ (, a third argument): it + # never quotes the file, so a JSON or schema error says where and what kind (#90 review). + if grep -qF "securecore-fpm: $(site_dir)/securecore.json: ${3:-${problem#\$conf: }}" "$dir/refuse.log"; then pass "$1: the log says why: $(grep -F 'securecore-fpm' "$dir/refuse.log" | head -1 | cut -c1-200)" else fail "$1: the log names the file and the problem" "$(tr '\n' ' ' < "$dir/refuse.log" | cut -c1-400)" @@ -187,11 +189,12 @@ refuses() { } # (Single quotes: '$conf' is the literal placeholder refuses() fills in.) put "$dir/bad-mode.json" -refuses "invalid mode" '$conf: invalid: unknown variant `block`' +refuses "invalid mode" '$conf: invalid: unknown variant `block`' "invalid at line " +! on_microvm || is "$(grep -c 'block' "$dir/refuse.log")" 0 "invalid mode: the launcher's log doesn't quote the file's value" printf '{"layer1":{"isolation":"off"},"layer2":{"enabled":false},"layer3":{"enabled":false},"layer4":{}}\n' > "$dir/unknown-key.json" put "$dir/unknown-key.json" -refuses "unknown key" '$conf: invalid: unknown field `layer4`' +refuses "unknown key" '$conf: invalid: unknown field `layer4`' "invalid at line " # layer1.enabled is retired: the extension refuses a file that still sets it, saying why. printf '{"layer1":{"enabled":false},"layer2":{"enabled":false},"layer3":{"enabled":false}}\n' > "$dir/retired.json" diff --git a/test/ext-layer1.sh b/test/ext-layer1.sh index 4ae78da..9a405cf 100755 --- a/test/ext-layer1.sh +++ b/test/ext-layer1.sh @@ -193,8 +193,9 @@ else fi refused "unixSockets + TCP ports" "$dir/unix-and-ports.json" "$why" sed 's|{ "port": 9000 }|{ "port": 0 }|' ext/examples/wordpress.json > "$dir/invalid.json" +# The launcher never quotes the file (#90 review): where, and what kind. refused "invalid config (port 0)" "$dir/invalid.json" \ - "securecore-fpm: $conf: invalid: invalid value: integer \`0\`, expected a nonzero u16" + "securecore-fpm: $conf: invalid at line " # layer1.enabled is retired: a file that still sets it is refused, with what to write instead. sed 's|"isolation": "auto",|"enabled": true, "isolation": "auto",|' ext/examples/wordpress.json > "$dir/retired.json" grep -q '"enabled": true, "isolation"' "$dir/retired.json" || fail "the retired-enabled fixture was made" diff --git a/test/ext-microvm.sh b/test/ext-microvm.sh index 4439912..7831385 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, @@ -161,6 +164,9 @@ vmuser=${SC_VM_USER:-64000:64000} # The site's files the VM sees: the probe, the status page, writable folders owned by www-data. cp test/ext/microvm/probe.php "$site/sc-mvm-probe.php" +# An executable script on the site disk: the guest mounts it noexec, so it never runs (#86 review). +printf '#!/bin/sh\necho ran\n' > "$site/sc-mvm-exec.sh" +chmod 755 "$site/sc-mvm-exec.sh" cp test/ext/securecore-status.php "$site/sc-status.php" mkdir -p "$site/wp-content/uploads" "$site/wp-content/cache" chown 33:33 "$site/wp-content/plugins" "$site" @@ -248,6 +254,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 @@ -461,6 +523,12 @@ 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 uploads_exec)" BLOCKED "an uploads disk is noexec in the guest" + is "$(val first site_exec)/$(val first site_sh_exec)" "BLOCKED/ran" "the site disk is noexec in the guest (its script runs only through /bin/sh)" 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)" @@ -574,8 +642,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 +839,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 @@ -889,7 +957,7 @@ has "$dir/moved.log" "holds the writable disks (uploads) of the site that was at has "$dir/moved.log" "--state-dir $moved/old" "and how to keep it" find "$moved" -mindepth 1 -delete -for f in sc-mvm-probe.php sc-status.php sc-mvm-changed.txt wp-content/uploads/sc-big.bin; do rm -f "$site/$f"; done +for f in sc-mvm-probe.php sc-mvm-exec.sh sc-status.php sc-mvm-changed.txt wp-content/uploads/sc-big.bin; do rm -f "$site/$f"; done cp ext/examples/wordpress.json "$site/securecore.json" echo if [ "$fails" -eq 0 ]; then echo "all ext-microvm checks passed"; else echo "$fails check(s) failed"; fi diff --git a/test/ext/microvm/probe.php b/test/ext/microvm/probe.php index 8185d5c..a159564 100644 --- a/test/ext/microvm/probe.php +++ b/test/ext/microvm/probe.php @@ -12,7 +12,30 @@ 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"; +// 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"; +// The same on an uploads disk, and from the site disk (the test put an executable script there). +@file_put_contents("$root/wp-content/uploads/sc-mvm-exec.sh", "#!/bin/sh\necho ran\n"); +@chmod("$root/wp-content/uploads/sc-mvm-exec.sh", 0755); +echo 'uploads_exec=', trim((string) @shell_exec(escapeshellarg("$root/wp-content/uploads/sc-mvm-exec.sh") . ' 2>/dev/null')) === 'ran' ? 'RAN' : 'BLOCKED', "\n"; +echo 'site_exec=', trim((string) @shell_exec(escapeshellarg("$root/sc-mvm-exec.sh") . ' 2>/dev/null')) === 'ran' ? 'RAN' : 'BLOCKED', "\n"; +echo 'site_sh_exec=', trim((string) @shell_exec('/bin/sh ' . escapeshellarg("$root/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..624cf0b 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