diff --git a/ext/README.md b/ext/README.md index b8099cb..e47791e 100644 --- a/ext/README.md +++ b/ext/README.md @@ -904,9 +904,30 @@ The site is a read-only disk built from the app root with `mke2fs -d`, mounted a (or `--guest-root`, the root nginx sends in `SCRIPT_FILENAME`). The guest's root is read-only too, so core, plugins and themes can't be written. Its PID 1 is `securecore-fpm` again, as `/sbin/securecore-init`: it mounts the disks, forwards vsock and starts php-fpm, whose log comes -back to the launcher's stderr. Layers 2 and 3 run in the guest's php-fpm unchanged; layer 3's +back to the launcher's stderr, every line numbered and acknowledged, so a line that can't be +delivered is counted in the launcher's log, never silently dropped (#86). When php-fpm exits, +the guest sends its last lines and its exit status first, and the launcher's stop line quotes +them (#87). Layers 2 and 3 run in the guest's php-fpm unchanged; layer 3's isolated children need Landlock and seccomp in the guest kernel (mirab#89 adds them to mirab's). +**Editing `securecore.json` while the guest runs** (#90). The launcher follows the file, as the +extension does on a host (a look a second, the same parser), reading it as the pool user, never +through a link and at most 128 KiB (a link, a device or a larger file is refused and logged): an +invalid file is refused and +logged, and the guest keeps the last valid config; a valid one is also checked against what a +start would check (a config the microVM can't run is refused the same way), then put in place +of the guest's copy, where the extension reloads it within a second. As on a host, layers 2 and +3 change in place, and a change to `layer1` or the vault applies at the next start +(`restart_needed`); the host's egress takes layer 2's new hosts at once. + +**The site's php.ini settings** (#90). php.ini in the guest is the root image's, the same for +every site. `--guest-ini ` names a file of the extension's per-site debug settings +(`securecore.debug_* = …` lines with plain-word values, `[a-z0-9_.,:-]`, so no `${VAR}`; any +other setting is refused with the reason, which never quotes the file), delivered in +each start message and again whenever the file changes, with php-fpm started again gracefully, +as a php.ini change needs on a host. A value the extension refuses stops php-fpm, as it would +on a host, and the launcher's log says why. + **Snapshots.** A start restores a snapshot of a warmed-up VM when there is one for this key: the sha256s of Firecracker, the kernel, the root image, the site tree (every path, mode, owner, size and mtime, writable folders excepted) and `securecore.json`, plus the memory, vCPUs, boot diff --git a/ext/fpm/src/guest.rs b/ext/fpm/src/guest.rs index 844636e..9e54964 100644 --- a/ext/fpm/src/guest.rs +++ b/ext/fpm/src/guest.rs @@ -171,13 +171,78 @@ 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 }, + /// A new `securecore.json` (hex), after the start (#90): put in place of the site disk's + /// copy at `/securecore.json`, where the extension's own reload picks it up, as it does + /// on a host. The host validated it first. + Config { hex: String }, + /// The site's php.ini settings (hex, the whole file; empty: none), in the start message or + /// after it (#90): php-fpm is started again with them (a graceful stop first), as a php.ini + /// change needs on a host. The host allows only `securecore.debug_*` keys ([`site_ini`]). + Ini { hex: String }, /// 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 }, + /// A question, alone on its connection: the sha256 of the config the guest's extension reads + /// now, answered `sha ` (#90 review: a delivery whose reply was lost is decided by it). + ConfigSha, Done, } +/// The largest `securecore.json` the host delivers (bytes). +pub const MAX_CONFIG: usize = crate::sitefile::MAX_CONFIG; +/// Where the guest keeps delivered configs and the site's ini. +const LIVE_DIR: &str = "/run/securecore"; +/// php-fpm's extra ini folder, after the image's own: the site's settings ([`Ctl::Ini`]). +pub const SITE_INI_DIR: &str = "/run/securecore/conf.d"; +/// The image's ini folder (PHP's compiled-in scan dir in the official images). +pub const IMAGE_INI: &str = "/usr/local/etc/php/conf.d"; +/// At most this many configs are delivered into one running guest: each is a file mounted over +/// the one before it (the swap is atomic for the extension's readers), so they stack, each file +/// kept in the guest's memory: at most 200 × [`MAX_CONFIG`] (25 MiB), a few hundred KiB for +/// configs of the usual size. A restart starts the count again. +pub const MAX_CONFIG_SWAPS: usize = 200; + +/// A value a site's php.ini setting may have in the guest: `[a-z0-9_.,:-]{0,64}`. +pub fn site_ini_value_ok(value: &str) -> bool { + value.len() <= 64 && value.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"_.,:-".contains(&b)) +} + +/// The settings a site's php.ini may give the guest's php-fpm (#90): the extension's per-site +/// debug settings only, with plain-word values ([`site_ini_value_ok`]). Everything else in +/// php.ini is the image's (the same for every site); a line setting anything else, or that +/// isn't `key = value`, is refused with the reason, which never quotes the file. Returns the +/// file as the guest writes it. +pub fn site_ini(text: &str) -> Result { + let mut out = String::new(); + for (n, raw) in text.lines().enumerate() { + let line = raw.trim(); + if line.is_empty() || line.starts_with(';') || line.starts_with('#') { + continue; + } + // Nothing from the file is ever quoted back (#90 review): a refused line could hold + // anything, a secret among it, and the reason goes to the launcher's log. + let n = n + 1; + let Some((key, value)) = line.split_once('=') else { + return Err(format!("line {n}: not `key = value`")); + }; + let (key, value) = (key.trim(), value.trim()); + let ok = key.strip_prefix("securecore.debug_").is_some_and(|k| !k.is_empty() && k.bytes().all(|b| b.is_ascii_lowercase() || b == b'_')); + if !ok { + return Err(format!( + "line {n}: a site's php.ini may set only the extension's securecore.debug_* settings in the guest (the rest of php.ini is the guest image's)" + )); + } + // Plain words only: PHP's ini parser expands ${VAR} from php-fpm's environment, where the + // vault's secrets are, and quotes would let a value say more than a word (#90 review). + if !site_ini_value_ok(value) { + return Err(format!("line {n}: {key}: a value may hold only a-z, 0-9 and _ . , : - (at most 64)")); + } + out.push_str(&format!("{key} = {value}\n")); + } + Ok(out) +} + impl Ctl { pub fn line(&self) -> String { match self { @@ -190,7 +255,11 @@ impl Ctl { Ctl::Sync => "sync\n".into(), Ctl::Reload => "reload\n".into(), Ctl::Proto { version } => format!("proto {version}\n"), + Ctl::Config { hex } => format!("config {hex}\n"), + Ctl::Ini { hex } if hex.is_empty() => "ini\n".into(), + Ctl::Ini { hex } => format!("ini {hex}\n"), Ctl::LogKey { hex } => format!("logkey {hex}\n"), + Ctl::ConfigSha => "configsha\n".into(), Ctl::Done => "done\n".into(), } } @@ -213,9 +282,16 @@ impl Ctl { ["sync"] => Ok(Ctl::Sync), ["reload"] => Ok(Ctl::Reload), ["proto", v] => Ok(Ctl::Proto { version: v.parse().map_err(|_| format!("proto: {v}"))? }), + ["config", hex] if hex.len() % 2 == 0 && hex.len() <= 2 * MAX_CONFIG && hex.bytes().all(|b| b.is_ascii_hexdigit()) => { + Ok(Ctl::Config { hex: (*hex).into() }) + } + ["ini", hex] if hex.len() % 2 == 0 && hex.len() <= 2 * MAX_CONFIG && hex.bytes().all(|b| b.is_ascii_hexdigit()) => Ok(Ctl::Ini { hex: (*hex).into() }), + ["ini"] => Ok(Ctl::Ini { hex: String::new() }), + ["config" | "ini", ..] => Err(format!("a malformed {} line", words[0])), ["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()), + ["configsha"] => Ok(Ctl::ConfigSha), ["done"] => Ok(Ctl::Done), // Never echo an env line: it carries a secret. ["env", ..] => Err("a malformed env line".into()), @@ -243,11 +319,13 @@ pub fn allowed(lines: &[Ctl], started: bool) -> Result<(), String> { return Err("the handshake comes alone".into()); } let starts = lines.iter().any(Ctl::starts); - let others = lines.iter().any(|c| matches!(c, Ctl::Sync | Ctl::Reload)); + // (`ini` goes with either: at the start, or alone after it.) + let others = lines.iter().any(|c| matches!(c, Ctl::Sync | Ctl::Reload | Ctl::Config { .. })); match (started, starts, others) { (true, true, _) => Err("this boot's start message was already taken".into()), (false, false, true) => Err("nothing but the start message before the start message".into()), - (false, true, true) => Err("a start message carries no sync or reload".into()), + (false, false, false) if lines.iter().any(|c| matches!(c, Ctl::Ini { .. })) => Err("nothing but the start message before the start message".into()), + (false, true, true) => Err("a start message carries no sync, reload or config".into()), _ => Ok(()), } } @@ -445,6 +523,79 @@ pub fn reload(master: &AtomicI32, stop: impl FnOnce(i32), start: impl FnOnce() - Ok(()) } +/// Configs delivered into this guest so far ([`MAX_CONFIG_SWAPS`]). +static CONFIG_SWAPS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// Puts `bytes` in place of `/securecore.json` (#90): written to a new file on tmpfs, then +/// bind-mounted (read-only) over the path, on top of the one before. A reader opens either the +/// old file or the new one, never a half-written one, and the extension's stat sees a new inode. +fn put_config(bytes: &[u8]) -> io::Result<()> { + let boot = BOOT.get().ok_or_else(|| io::Error::other("no boot settings"))?; + if bytes.len() > MAX_CONFIG { + return Err(io::Error::other(format!("a config over {MAX_CONFIG} bytes"))); + } + let n = CONFIG_SWAPS.fetch_add(1, Ordering::SeqCst) + 1; + if n > MAX_CONFIG_SWAPS { + CONFIG_SWAPS.fetch_sub(1, Ordering::SeqCst); + return Err(io::Error::other(format!("{MAX_CONFIG_SWAPS} configs were already delivered to this guest; restart the launcher to apply more"))); + } + fs::create_dir_all(LIVE_DIR)?; + let file = format!("{LIVE_DIR}/securecore-{n}.json"); + { + use std::os::unix::fs::OpenOptionsExt as _; + let mut f = fs::OpenOptions::new().write(true).create_new(true).mode(0o644).open(&file)?; + f.write_all(bytes)?; + } + let target = format!("{}/securecore.json", boot.root); + // Mounted on the file itself, never through a link (#90 review): the site disk is the site's, + // and `/securecore.json` there could be a link to anywhere in the guest. Opened without + // following one, it must be a regular file, and the mount goes on that very file. + let at = regular_target(&target)?; + mount(&file, &fd_path(&at), "", libc::MS_BIND, "")?; + // A bind mount takes its flags only on a remount: on the new mount, again by its file. + let top = regular_target(&target)?; + mount("", &fd_path(&top), "", libc::MS_REMOUNT | libc::MS_BIND | libc::MS_RDONLY | libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC, "")?; + // The file stays: the next config is mounted on this one, and Linux refuses a mount on a + // file that has been unlinked. (Under /run, which php-fpm's pool user can't write.) + Ok(()) +} + +/// `path` opened `O_PATH | O_NOFOLLOW`: refused unless it is a regular file itself (a link is +/// not followed, and is refused). +pub fn regular_target(path: &str) -> io::Result { + let c = cstr(path)?; + // SAFETY: open(2) with a NUL-terminated path; the fd is owned below. + let fd = unsafe { libc::open(c.as_ptr(), libc::O_PATH | libc::O_NOFOLLOW | libc::O_CLOEXEC) }; + if fd < 0 { + let e = io::Error::last_os_error(); + return Err(io::Error::new(e.kind(), format!("{path}: {e}"))); + } + // SAFETY: fd was just returned by open(2). + let fd = unsafe { OwnedFd::from_raw_fd(fd) }; + let f = fs::File::from(fd); + let m = f.metadata().map_err(|e| io::Error::new(e.kind(), format!("{path}: {e}")))?; + if !m.file_type().is_file() { + return Err(io::Error::other(format!("{path} is not a regular file (a link, a folder or a device): not replaced"))); + } + Ok(OwnedFd::from(f)) +} + +/// `/proc/self/fd/`: the open file itself, for a call that takes a path. +fn fd_path(fd: &OwnedFd) -> String { + format!("/proc/self/fd/{}", fd.as_raw_fd()) +} + +/// The sha256 of the config the guest's extension reads now (`/securecore.json`), for the +/// host to ask after a delivery whose answer it didn't get (#90 review). +fn config_sha() -> io::Result { + use sha2::{Digest as _, Sha256}; + let boot = BOOT.get().ok_or_else(|| io::Error::other("no boot settings"))?; + // Never through a link, capped (#90 verification review, N5): the launcher's own reading. + let path = format!("{}/securecore.json", boot.root); + let bytes = crate::sitefile::read(Path::new(&path), MAX_CONFIG).map_err(io::Error::other)?.ok_or_else(|| io::Error::other(format!("{path}: missing")))?; + Ok(hex_of(&Sha256::digest(&bytes))) +} + /// Applies one control line. fn apply(ctl: &Ctl) -> io::Result<()> { match ctl { @@ -512,12 +663,25 @@ fn apply(ctl: &Ctl) -> io::Result<()> { // 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::Config { hex } => put_config(&unhex(hex)), + Ctl::Ini { hex } => { + let text = String::from_utf8(unhex(hex)).map_err(|_| io::Error::other("ini: not UTF-8"))?; + // Checked again here: the guest takes no php.ini line but the extension's debug ones. + let text = site_ini(&text).map_err(io::Error::other)?; + fs::create_dir_all(SITE_INI_DIR)?; + let path = format!("{SITE_INI_DIR}/zz-site.ini"); + fs::write(format!("{path}.new"), &text)?; + fs::rename(format!("{path}.new"), &path)?; + 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(()) } + // Answered by serve_ctl itself. + Ctl::ConfigSha => Ok(()), + // Checked before anything is applied ([`protocol_ok`]). Ctl::Proto { .. } | Ctl::Done => Ok(()), } } @@ -551,6 +715,12 @@ fn serve_ctl(conn: Vsock, peer_cid: u32) { if !done { return say("ctl: a control connection closed or timed out before `done`; nothing applied"); } + // The one question: which config the extension reads now. + if failed.is_none() && lines == [Ctl::ConfigSha] { + let reply = config_sha().map_or_else(|e| format!("error {e}\n"), |sha| format!("sha {sha}\n")); + let _ = out.write_all(reply.as_bytes()); + return; + } let started = STARTED.load(Ordering::SeqCst); if failed.is_none() { failed = allowed(&lines, started).err(); @@ -572,8 +742,9 @@ fn serve_ctl(conn: Vsock, peer_cid: u32) { } } // The delivered environment reaches php-fpm only through a fresh master: the one running - // now started at boot (before any start message, so a snapshot holds none of it). - if failed.is_none() && lines.iter().any(|c| matches!(c, Ctl::Env { .. })) { + // now started at boot (before any start message, so a snapshot holds none of it). The same + // for the site's php.ini settings, which PHP reads only at startup. + if failed.is_none() && lines.iter().any(|c| matches!(c, Ctl::Env { .. } | Ctl::Ini { .. })) { if let Err(e) = apply(&Ctl::Reload) { failed = Some(format!("starting php-fpm with the delivered environment: {e}")); } else if !fpm_listening(Duration::from_secs(10)) { @@ -851,7 +1022,11 @@ fn start_php_fpm(boot: &Boot) -> io::Result { cmd.env("SC_EGRESS_PORTS", list(&boot.egress)).env("SC_EGRESS_HOST_PORT", crate::egress::EGRESS_PORT.to_string()); } } - if !boot.ext { + // The image's ini folder, then the site's settings when it has any (#90). + let base = if boot.ext { IMAGE_INI } else { NOEXT_INI }; + if Path::new(&format!("{SITE_INI_DIR}/zz-site.ini")).exists() { + cmd.env("PHP_INI_SCAN_DIR", format!("{base}:{SITE_INI_DIR}")); + } else if !boot.ext { cmd.env("PHP_INI_SCAN_DIR", NOEXT_INI); } // php-fpm and every worker under no_new_privs (#80): no exec ever gains privileges (a setuid @@ -998,6 +1173,9 @@ mod tests { Ctl::Refresh, Ctl::Sync, Ctl::Reload, + Ctl::Config { hex: hex_of(br#"{"layer1":{}}"#) }, + Ctl::Ini { hex: hex_of(b"securecore.debug_attribution_log = both\n") }, + Ctl::Ini { hex: String::new() }, Ctl::Done, ] { assert_eq!(Ctl::parse(ctl.line().trim_end()), Ok(ctl.clone()), "{ctl:?}"); @@ -1077,5 +1255,63 @@ mod tests { 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()); + // #90: a config only after the start; the site's ini in the start message or after it. + let config = Ctl::Config { hex: hex_of(b"{}") }; + let ini = Ctl::Ini { hex: String::new() }; + assert_eq!(allowed(std::slice::from_ref(&config), true), Ok(())); + assert!(allowed(std::slice::from_ref(&config), false).is_err(), "no config before the start"); + assert!(allowed(&[Ctl::Time { secs: 1, nanos: 0 }, config], false).is_err(), "nor in the start message"); + assert_eq!(allowed(&[Ctl::Time { secs: 1, nanos: 0 }, ini.clone()], false), Ok(())); + assert_eq!(allowed(std::slice::from_ref(&ini), true), Ok(())); + assert!(allowed(&[ini], false).is_err(), "nothing but the start message before it"); + } + + /// A site's php.ini in the guest (#90): the extension's debug settings only. + #[test] + fn a_sites_ini_carries_only_the_debug_settings() { + assert_eq!( + site_ini("; comment\n\nsecurecore.debug_attribution_log=both\n securecore.debug_attribution_rule = frame \n").as_deref(), + Ok("securecore.debug_attribution_log = both\nsecurecore.debug_attribution_rule = frame\n") + ); + assert_eq!(site_ini("").as_deref(), Ok("")); + for bad in ["securecore.config = /etc/x.json", "extension = evil.so", "memory_limit = 1G", "securecore.debug_ = x", "securecore.debug_attribution_log"] { + assert!(site_ini(bad).is_err(), "{bad}"); + } + assert!(site_ini("securecore.debug_attribution_log = a\u{7}b").is_err()); + // #90 review: values are plain words (PHP expands ${VAR} from php-fpm's environment, + // where the vault's secrets are), and a refusal never quotes the file. + for bad in [ + "securecore.debug_attribution_log = ${WORDPRESS_DB_PASSWORD}", + "securecore.debug_attribution_log = \"both\"", + "securecore.debug_attribution_log = {x}", + "securecore.debug_attribution_log = Both", + "securecore.debug_attribution_log = $SECRET", + ] { + let e = site_ini(bad).expect_err(bad); + assert!(!e.contains("WORDPRESS") && !e.contains("SECRET") && !e.contains("both") && !e.contains("Both"), "{e}"); + } + for bad in ["sk_live_SECRET = 1", "SECRET-NO-EQUALS"] { + let e = site_ini(bad).expect_err(bad); + assert!(!e.contains("SECRET") && !e.contains("sk_live"), "a refused line is never quoted: {e}"); + } + assert_eq!(site_ini("securecore.debug_db_attribution = component").as_deref(), Ok("securecore.debug_db_attribution = component\n")); + } + + /// #90 review: the config is mounted on `/securecore.json` only when that is a regular + /// file itself, never through a link the site disk holds. + #[test] + fn a_mount_target_must_be_a_regular_file_not_a_link() { + let dir = std::env::temp_dir().join(format!("sc-guest-target-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).expect("dir"); + let file = dir.join("securecore.json"); + fs::write(&file, "{}").expect("write"); + let link = dir.join("link.json"); + std::os::unix::fs::symlink(&file, &link).expect("link"); + assert!(regular_target(file.to_str().expect("utf8")).is_ok()); + let e = regular_target(link.to_str().expect("utf8")).expect_err("a link"); + assert!(e.to_string().contains("not a regular file"), "{e}"); + assert!(regular_target(dir.to_str().expect("utf8")).is_err(), "a folder"); + let _ = fs::remove_dir_all(&dir); } } diff --git a/ext/fpm/src/main.rs b/ext/fpm/src/main.rs index 8f6a446..2ea66b4 100644 --- a/ext/fpm/src/main.rs +++ b/ext/fpm/src/main.rs @@ -28,7 +28,7 @@ const USAGE: &str = "usage: securecore-fpm --config [--php-fpm [--vm-dir ] [--vm-user |:] [--pool-user |:] [--kvm ] [--state-dir ] \ [--listen unix:|:] [--listen-owner ] [--listen-group ] [--listen-mode ] \ [--guest-root ] [--mem ] [--vcpus ] [--write-disk-mib ] [--no-snapshot] \ -[--guest-arg ]... [--guest-env ]... [--] [php-fpm args...] | securecore-fpm --migrate-config "; +[--guest-arg ]... [--guest-env ]... [--guest-ini ] [--] [php-fpm args...] | securecore-fpm --migrate-config "; struct Args { config: PathBuf, @@ -49,6 +49,7 @@ struct Args { snapshot: bool, guest_args: Vec, guest_env: Vec, + guest_ini: Option, rest: Vec, } @@ -75,6 +76,7 @@ fn parse(args: impl IntoIterator) -> Result, Strin snapshot: true, guest_args: Vec::new(), guest_env: Vec::new(), + guest_ini: None, rest: Vec::new(), }; let mut config = None; @@ -91,7 +93,7 @@ fn parse(args: impl IntoIterator) -> Result, Strin a.snapshot = false; } "--config" | "--php-fpm" | "--vm-dir" | "--vm-user" | "--pool-user" | "--kvm" | "--state-dir" | "--listen" | "--listen-owner" - | "--listen-group" | "--listen-mode" | "--guest-root" | "--mem" | "--vcpus" | "--write-disk-mib" | "--guest-arg" | "--guest-env" => { + | "--listen-group" | "--listen-mode" | "--guest-root" | "--mem" | "--vcpus" | "--write-disk-mib" | "--guest-arg" | "--guest-env" | "--guest-ini" => { args.next(); let value = args.next().ok_or_else(|| format!("{flag} needs a value"))?; let text = || value.to_str().map(str::to_owned).ok_or_else(|| format!("{flag}: not UTF-8")); @@ -118,6 +120,7 @@ fn parse(args: impl IntoIterator) -> Result, Strin "--vcpus" => a.vcpus = number()?, "--write-disk-mib" => a.write_disk_mib = u64::from(number()?), "--guest-env" => a.guest_env.push(text()?), + "--guest-ini" => a.guest_ini = Some(PathBuf::from(&value)), _ => a.guest_args.push(text()?), } } @@ -183,6 +186,7 @@ mod microvm { snapshot: a.snapshot, guest_args: a.guest_args.clone(), guest_env: a.guest_env.clone(), + guest_ini: a.guest_ini.clone(), }) } diff --git a/ext/fpm/src/vm.rs b/ext/fpm/src/vm.rs index fa3af2e..911c792 100644 --- a/ext/fpm/src/vm.rs +++ b/ext/fpm/src/vm.rs @@ -172,8 +172,32 @@ pub struct Options { /// Variables of the launcher's environment the guest's php-fpm gets, besides the vault's /// own (`layer2.vault.secrets[].env`), which it always gets ([`guest_env`]). pub guest_env: Vec, + /// The site's php.ini settings for the guest's php-fpm (#90): a file of `securecore.debug_*` + /// lines ([`crate::guest::site_ini`]), delivered at each start and again whenever it changes. + /// A missing file is no settings. + pub guest_ini: Option, } +/// The site's php.ini settings as the guest gets them: `None` without `--guest-ini` or while the +/// file is missing; refused with the reason when it sets anything else. The file is the +/// operator's (a launcher flag names it, as with `--config`), read the way `securecore.json` is +/// ([`crate::sitefile::read`]: no link anywhere in its path, as its folder's owner, regular +/// only), within [`MAX_SITE_INI`]. +pub fn read_site_ini(path: Option<&Path>) -> Result, String> { + let Some(path) = path else { return Ok(None) }; + match crate::sitefile::read(path, MAX_SITE_INI) { + Ok(None) => Ok(None), + Ok(Some(b)) => { + let text = String::from_utf8(b).map_err(|_| format!("{}: not UTF-8", path.display()))?; + crate::guest::site_ini(&text).map(Some).map_err(|e| format!("{}: {e}", path.display())) + } + Err(e) => Err(e), + } +} + +/// The largest `--guest-ini` file read. +pub const MAX_SITE_INI: usize = 16 * 1024; + /// php-fpm's environment in the guest: each name in `--guest-env` and each vault secret's `env`, /// with its value from the launcher's own environment (as php-fpm on the host would have it). /// Delivered in every start message, never in an image, a boot argument or a snapshot. A name @@ -1140,7 +1164,7 @@ struct Machine { /// The `connect[].socket` folders, checked and held ([`open_sockets`]). sockets: Vec<(u16, jail::SocketDir)>, /// What the guest may reach by name. - egress: crate::egress::Egress, + egress: &'static std::sync::RwLock, } /// What a jail holds for one spawn: the host ends of the guest's ports come with it. @@ -1410,10 +1434,12 @@ fn take_out(inside: &Path, out: &Path, user: User) -> Result<(), String> { /// The start message: the clock, fresh randomness, the workers' refresh after a restore, then /// the writable disks and tmpfs folders. -fn start_message(plan: &Plan, restored: bool, entropy: [u8; 64], env: &[(String, String)]) -> Vec { +fn start_message(plan: &Plan, restored: bool, entropy: [u8; 64], env: &[(String, String)], ini: Option<&str>) -> Vec { let (secs, nanos) = now(); let mut lines = vec![Ctl::Time { secs, nanos }, Ctl::Entropy { hex: hex(&entropy) }]; lines.extend(env.iter().map(|(name, value)| Ctl::Env { name: name.clone(), hex: hex(value.as_bytes()) })); + // The site's php.ini settings (#90): php-fpm starts again with them, as with `env`. + lines.extend(ini.map(|text| Ctl::Ini { hex: hex(text.as_bytes()) })); if restored { lines.push(Ctl::Refresh); } @@ -1480,6 +1506,220 @@ fn refused(lines: &[Ctl], reply: &str) -> Result<(), String> { Err(format!("the guest refused {kinds:?}: {reply}")) } +/// How often the launcher looks at the config and the site's php.ini settings: the extension's +/// own reload interval, so an edit reaches the guest's workers about as soon as a host's. +pub const WATCH_INTERVAL: Duration = Duration::from_millis(1000); + +/// How [`live_change`]'s refusal starts. +const VM_CANT_RUN: &str = "the microVM can't run it"; + +/// Whether a running guest can take `new` (#90), the config it started with being `started`: +/// `Err(why)` when the microVM can't express it (the same check a start makes, [`plan`]), so the +/// guest keeps what it has; else what the launcher says about it. As on a host, a change to +/// `layer1` or to the vault takes effect only at the next start (the extension in the guest +/// reports `restart_needed`); layers 2 and 3 reload in place. +pub fn live_change(started: &Loaded, new: &Loaded, opts: &Options) -> Result, String> { + plan(new, opts).map_err(|e| format!("{VM_CANT_RUN} ({e})"))?; + let mut notes = Vec::new(); + if new.config.layer1 != started.config.layer1 { + notes.push("layer1 differs from the one this VM started with: it applies at the next start (restart_needed)".to_owned()); + } + if securecore_config::started_vault(&new.config) != securecore_config::started_vault(&started.config) { + notes.push("layer2.vault differs from the one this VM started with: it applies at the next start (restart_needed)".to_owned()); + } + Ok(notes) +} + +/// Follows the config file and the site's php.ini settings for the running guest (#90), every +/// [`WATCH_INTERVAL`], with the extension's own [`securecore_config::Reloader`]: an invalid file +/// or one the microVM can't run is refused with the reason, and the guest keeps what it has; a +/// valid one is put in place in the guest, where the extension reloads it as on a host (and the +/// host's egress takes its layer 2 hosts). A changed php.ini is delivered and php-fpm started +/// again gracefully with it. +fn watch_live(started: &Loaded, opts: &Options, uds: &Path, egress: &std::sync::RwLock, ports: &[u16], mut ini: Option) { + let mut in_guest = started.sha256.clone(); + // The file's bytes last looked at (by sha256), and what was said about them: each version is + // judged once, as the extension's Reloader does. + let mut seen = started.sha256.clone(); + let mut refused: Option = None; + let mut read_error: Option = None; + let mut ini_refused: Option = None; + let mut unsure: Option<(Loaded, u8)> = None; + loop { + thread::sleep(WATCH_INTERVAL); + // The launcher's start reads it the same way (#90 review): no link anywhere in its path, + // as its folder's owner, regular only, at most MAX_CONFIG bytes. + let bytes = match crate::sitefile::read(&started.path, crate::guest::MAX_CONFIG) { + Ok(Some(b)) => { + read_error = None; + Some(b) + } + other => { + let e = other.err().unwrap_or_else(|| format!("{}: missing", started.path.display())); + if read_error.as_deref() != Some(&e) { + log(&format!("{e}; keeping the last valid config in the guest (sha256 {})", short_sha(&in_guest))); + read_error = Some(e); + } + None + } + }; + let live = match bytes { + Some(b) if securecore_config::sha256_hex(&b) != seen => { + let sha = securecore_config::sha256_hex(&b); + seen = sha.clone(); + match securecore_config::Config::from_slice(&b) { + Ok(config) => Some((Loaded { path: started.path.clone(), config, sha256: sha, root: started.root.clone() }, b)), + Err(problem) => { + // Never quoting the file (#90 review), as at the start. + let e = securecore_config::LoadError { path: started.path.clone(), problem }.without_contents(); + log(&format!("{e}; keeping the last valid config in the guest (sha256 {})", short_sha(&in_guest))); + None + } + } + } + _ => None, + }; + if let Some((live, b)) = live + && live.sha256 != in_guest + && refused.as_deref() != Some(&live.sha256) + { + let t = Instant::now(); + let result = live_change(started, &live, opts).and_then(|notes| deliver_config(uds, &b, &live.sha256).map(|how| (notes, how))); + match result { + Ok((mut notes, how)) => { + notes.extend(how); + log(&format!( + "delivered {} (sha256 {}) to the running guest in {:.0} ms; its extension reloads it", + live.path.display(), + short_sha(&live.sha256), + ms(t) + )); + for n in notes { + log(&n); + } + *egress.write().unwrap_or_else(|p| p.into_inner()) = crate::egress::Egress::new(&live, ports.to_vec()); + in_guest = live.sha256.clone(); + refused = None; + } + Err(e) => { + log(&format!( + "{}: refused for the running guest: {e}; keeping the last valid config in the guest (sha256 {})", + live.path.display(), + short_sha(&in_guest) + )); + // No answer from the guest (not its own refusal, not ours): it may still put + // it in place late, so its answer is asked for again on the next looks. + if !guest_answered(&e) && !e.starts_with(VM_CANT_RUN) { + unsure = Some((live.clone(), 0)); + } + refused = Some(live.sha256.clone()); + } + } + } else if let Some((live, tries)) = unsure.take() { + // N4 (#90 verification review): the guest's own answer decides a delivery whose + // reply was lost, on the next looks too. + match ask_config_sha(uds) { + Ok(now) if now == live.sha256 => { + log(&format!( + "the running guest reads {} (sha256 {}) after all (it answered late): delivered", + live.path.display(), + short_sha(&live.sha256) + )); + *egress.write().unwrap_or_else(|p| p.into_inner()) = crate::egress::Egress::new(&live, ports.to_vec()); + in_guest = live.sha256.clone(); + refused = None; + } + Ok(_) => {} + Err(_) if tries < 10 => unsure = Some((live, tries + 1)), + Err(e) => log(&format!("the guest never said which config it reads ({e}); it is taken to keep sha256 {}", short_sha(&in_guest))), + } + } + if let Some(path) = &opts.guest_ini { + // As the pool user, never through a link, capped; a refusal never quotes the file. + match read_site_ini(Some(path)) { + Ok(text) if text != ini => { + ini_refused = None; + let t = Instant::now(); + let body = text.clone().unwrap_or_default(); + match tell_guest(uds, &[Ctl::Ini { hex: hex(body.as_bytes()) }, Ctl::Done], crate::guest::RELOAD_TIMEOUT) { + Ok(()) => log(&format!( + "delivered the site's php.ini settings from {} ({} lines) to the running guest and started its php-fpm again gracefully in {:.0} ms", + path.display(), + body.lines().count(), + ms(t) + )), + // No answer at all (N4, #90 verification review): the next look delivers + // them again; the guest's own refusal stands. + Err(e) if !guest_answered(&e) => { + log(&format!("the site's php.ini settings from {}: no answer from the guest ({e}); sending them again", path.display())); + continue; + } + Err(e) => log(&format!("the site's php.ini settings from {}: the guest refused them: {e}", path.display())), + } + ini = text; + } + Ok(_) => {} + Err(e) => { + if ini_refused.as_deref() != Some(e.as_str()) { + log(&format!("{e}; the guest keeps its php.ini settings")); + } + ini_refused = Some(e); + } + } + } + } +} + +/// How long a live config delivery waits for the guest's `ok`. +const SYNC_TIMEOUT_LIVE: Duration = Duration::from_secs(10); + +/// Puts `bytes` (whose sha256 is `sha`) in the running guest. The guest's answer decides (#90 +/// review): an `error` reply is a refusal; when no answer came (a timeout, a broken connection) +/// the guest is asked which config it reads now, and if that is `sha` the delivery stands. `Ok` +/// carries a note when it was decided that way. +fn deliver_config(uds: &Path, bytes: &[u8], sha: &str) -> Result, String> { + let sent = tell_guest(uds, &[Ctl::Config { hex: hex(bytes) }, Ctl::Done], SYNC_TIMEOUT_LIVE); + let asked = match &sent { + Err(e) if !guest_answered(e) => Some(ask_config_sha(uds)), + _ => None, + }; + delivery_outcome(sent, asked, sha) +} + +/// Whether a [`tell_guest`] error is the guest's own `error` reply (as opposed to no reply). +fn guest_answered(e: &str) -> bool { + e.starts_with("the guest refused ") +} + +/// [`deliver_config`]'s decision, given the delivery's result and, when it had no answer, the +/// guest's answer to "which config do you read now". +pub fn delivery_outcome(sent: Result<(), String>, asked: Option>, sha: &str) -> Result, String> { + match (sent, asked) { + (Ok(()), _) => Ok(None), + (Err(e), Some(Ok(now))) if now == sha => Ok(Some(format!("its reply was lost ({e}), but it reads that config now: delivered"))), + (Err(e), Some(Ok(now))) => Err(format!("{e}; the guest reads sha256 {} now", short_sha(&now))), + (Err(e), Some(Err(q))) => Err(format!("{e}; asking the guest which config it reads failed too ({q})")), + (Err(e), None) => Err(e), + } +} + +/// The sha256 of the config the guest's extension reads now ([`Ctl::ConfigSha`]). +fn ask_config_sha(uds: &Path) -> Result { + let mut s = vsock::connect_through(uds, CTL_PORT, Duration::from_secs(2)).map_err(|e| format!("the guest's control port: {e}"))?; + let message: String = [Ctl::ConfigSha, Ctl::Done].iter().map(Ctl::line).collect(); + s.write_all(message.as_bytes()).map_err(|e| format!("the guest's control port: {e}"))?; + s.set_read_timeout(Some(SYNC_TIMEOUT_LIVE)).map_err(|e| e.to_string())?; + let reply = read_reply(s)?; + match reply.trim_end().split_once(' ') { + Some(("sha", sha)) if sha.len() == 64 && sha.bytes().all(|b| b.is_ascii_hexdigit()) => Ok(sha.to_owned()), + _ => Err(format!("the guest answered {:?}", reply.trim_end())), + } +} + +fn short_sha(sha: &str) -> &str { + &sha[..sha.len().min(16)] +} + /// The protocol handshake, alone on its connection before any start message: `proto `. The /// guest's init answers `ok` only when it speaks this launcher's protocol and was booted for it; /// an older init doesn't know the line. Either way nothing secret has been sent yet. @@ -1606,6 +1846,7 @@ struct Real<'a> { opts: &'a Options, m: &'a Machine, env: &'a [(String, String)], + ini: Option<&'a str>, } impl Lifecycle for Real<'_> { @@ -1652,7 +1893,7 @@ impl Lifecycle for Real<'_> { fn tell(&mut self, vm: &Vm, restored: bool) -> Result<(), String> { handshake(&vm.vsock)?; - tell_guest(&vm.vsock, &start_message(self.plan, restored, random64()?, self.env), START_TIMEOUT) + tell_guest(&vm.vsock, &start_message(self.plan, restored, random64()?, self.env, self.ini), START_TIMEOUT) } } @@ -1712,9 +1953,10 @@ fn wire(plan: &Plan, m: &Machine, j: &Jail, short: &Path, wiring: Wiring, keys: }); } // Named hosts on the egress ports (#72): each connection's request line is checked here. - if !m.egress.ports.is_empty() { + // The rules are read per connection: a delivered config changes layer 2's hosts (#90). + let egress = m.egress; + if !egress.read().unwrap_or_else(|p| p.into_inner()).ports.is_empty() { let l = bind_unix(&short.join(format!("v.sock_{}", crate::egress::EGRESS_PORT)), owned)?; - let egress: &'static crate::egress::Egress = Box::leak(Box::new(m.egress.clone())); let slots: &'static Slots = Box::leak(Box::new(Slots::new(FORWARD_SLOTS))); let pool = plan.pool; thread::spawn(move || { @@ -1728,7 +1970,8 @@ fn wire(plan: &Plan, m: &Machine, j: &Jail, short: &Path, wiring: Wiring, keys: // The host's addresses now (an interface may have come up since the start). let own = crate::egress::host_addresses(); let connect = |conn: UnixStream, addrs: &[std::net::SocketAddr]| egress_as_pool(conn, addrs, pool); - match crate::egress::serve(c, egress, &own, &connect) { + let rules = egress.read().unwrap_or_else(|p| p.into_inner()).clone(); + match crate::egress::serve(c, &rules, &own, &connect) { Ok(what) => log(&format!("egress: {what} closed")), Err(why) => log(&format!("egress refused: {why}")), } @@ -2281,8 +2524,13 @@ pub fn run(loaded: &Loaded, opts: &Options) -> Result<(), String> { sizes.join(",") ), }; + let egress: &'static std::sync::RwLock = Box::leak(Box::new(std::sync::RwLock::new(egress))); + let ini = read_site_ini(opts.guest_ini.as_deref())?; + if let (Some(path), Some(text)) = (&opts.guest_ini, &ini) { + log(&format!("the guest's php-fpm gets the site's php.ini settings from {} ({} lines), in each start message", path.display(), text.lines().count())); + } let m = Machine { site: site_path, disks, args, key: key.sha256(), user, sockets, egress }; - let (mut vm, how, ready) = bring_up(&mut Real { plan: &plan, opts, m: &m, env: &env }, opts.snapshot)?; + let (mut vm, how, ready) = bring_up(&mut Real { plan: &plan, opts, m: &m, env: &env, ini: ini.as_deref() }, opts.snapshot)?; let t_ready = ready.duration_since(t0).as_secs_f64() * 1000.0; let t_started = ms(t0); match how { @@ -2349,6 +2597,12 @@ pub fn run(loaded: &Loaded, opts: &Options) -> Result<(), String> { } } }); + // An edited securecore.json and php.ini settings reach the running guest (#90). + { + let (loaded, opts, uds) = (loaded.clone(), opts.clone(), vm.vsock.clone()); + let ports = plan.egress.clone(); + thread::spawn(move || watch_live(&loaded, &opts, &uds, egress, &ports, ini)); + } let sig = loop { let sig = wait_for_signal(&set); match sig { @@ -2416,6 +2670,7 @@ mod tests { snapshot: true, guest_args: vec![], guest_env: vec![], + guest_ini: None, } } @@ -2479,7 +2734,7 @@ mod tests { assert!(args.contains(" sc.sock=3306:/run/mysqld/mysqld.sock"), "{args}"); assert!(!args.contains("sc.time"), "the clock is in no key: {args}"); let env = [("WORDPRESS_DB_PASSWORD".to_owned(), "s3cret".to_owned())]; - let msg = start_message(&p, true, [7; 64], &env); + let msg = start_message(&p, true, [7; 64], &env, None); assert!(matches!(msg[0], Ctl::Time { .. }), "the clock first"); assert_eq!(msg[1], Ctl::Entropy { hex: "07".repeat(64) }, "then fresh randomness"); assert_eq!(msg[2], Ctl::Env { name: "WORDPRESS_DB_PASSWORD".into(), hex: hex(b"s3cret") }, "then php-fpm's environment"); @@ -2487,7 +2742,11 @@ mod tests { assert_eq!(msg[4], Ctl::Mount { device: "/dev/vdc".into(), path: "/var/www/html/wp-content/uploads".into() }); assert_eq!(msg[5], Ctl::Tmpfs { path: "/var/cache/sc".into() }); assert_eq!(msg.last(), Some(&Ctl::Done)); - assert!(!start_message(&p, false, [7; 64], &env).contains(&Ctl::Refresh), "a cold boot's workers are fresh"); + assert!(!start_message(&p, false, [7; 64], &env, None).contains(&Ctl::Refresh), "a cold boot's workers are fresh"); + // The site's php.ini settings (#90), after the environment. + let ini = "securecore.debug_attribution_log = both\n"; + let msg = start_message(&p, false, [7; 64], &env, Some(ini)); + assert_eq!(msg[3], Ctl::Ini { hex: hex(ini.as_bytes()) }); assert!(!args.contains("s3cret") && !args.contains(&hex(b"s3cret")), "never a boot argument"); assert_ne!(random64().expect("random"), random64().expect("random"), "every start message gets its own"); let _ = fs::remove_dir_all(&dir); @@ -2514,6 +2773,24 @@ mod tests { let _ = fs::remove_dir_all(&dir); } + /// A live edit (#90): refused when the microVM can't run it; else delivered, with layer1 and + /// vault changes flagged for the next start (restart_needed), as on a host. + #[test] + fn a_live_edit_is_refused_when_the_vm_cant_run_it_and_flags_what_needs_a_start() { + let dir = scratch("live"); + let base = r#"{"isolation":"microvm","network":{"bind":[{"port":9000}]}}"#; + let started = loaded(&dir, base); + let same_l1 = started.clone(); + assert_eq!(live_change(&started, &same_l1, &opts()), Ok(vec![]), "layers 2 and 3 only: delivered, nothing for the next start"); + let more = loaded(&dir, r#"{"isolation":"microvm","write":["wp-content/uploads"],"network":{"bind":[{"port":9000}]}}"#); + let notes = live_change(&started, &more, &opts()).expect("the VM can run it"); + assert!(notes.len() == 1 && notes[0].contains("restart_needed"), "{notes:?}"); + let socks = loaded(&dir, r#"{"isolation":"microvm","network":{"bind":[{"port":9000}],"unixSockets":["/run/x.sock"]}}"#); + let e = live_change(&started, &socks, &opts()).expect_err("unixSockets"); + assert!(e.starts_with("the microVM can't run it"), "{e}"); + let _ = fs::remove_dir_all(&dir); + } + #[test] fn the_site_key_changes_with_the_tree_but_not_with_uploads() { let dir = scratch("key"); @@ -3045,6 +3322,43 @@ mod tests { assert!(stop_sync_failed(&disk).starts_with("the guest did not sync its disks before the stop: "), "{}", stop_sync_failed(&disk)); } + /// #90 review: the config and the --guest-ini file are read as themselves (never through a + /// link: another site's config, /dev/zero), regular files only, within a cap, and an error + /// never quotes their bytes. + #[test] + fn a_site_file_is_read_as_itself_regular_and_capped() { + // The reading itself is sitefile::read's (its own tests); here the --guest-ini file's. + let dir = fs::canonicalize(scratch("regular")).expect("dir"); + let big = dir.join("big.ini"); + fs::write(&big, vec![b';'; MAX_SITE_INI + 1]).expect("write"); + assert!(read_site_ini(Some(&big)).expect_err("too big").contains("larger than")); + assert!(read_site_ini(Some(Path::new("/dev/zero"))).expect_err("a device").contains("not a regular file")); + let ini = dir.join("site.ini"); + fs::write(&ini, "securecore.debug_attribution_log = ${WORDPRESS_DB_PASSWORD}\n").expect("write"); + let e = read_site_ini(Some(&ini)).expect_err("a ${} value"); + assert!(!e.contains("WORDPRESS_DB_PASSWORD"), "{e}"); + let ini_link = dir.join("ini-link.ini"); + std::os::unix::fs::symlink(&ini, &ini_link).expect("link"); + assert!(read_site_ini(Some(&ini_link)).expect_err("a link").contains("a link is in its path")); + assert_eq!(read_site_ini(Some(&dir.join("absent.ini"))), Ok(None), "no file: no settings"); + let _ = fs::remove_dir_all(&dir); + } + + /// #90 review: the guest's answer decides a delivery. An `error` reply is a refusal; a lost + /// reply is settled by asking which config the guest reads now. + #[test] + fn a_delivery_whose_reply_was_lost_is_decided_by_the_guests_config() { + let sha = "ab".repeat(32); + assert_eq!(delivery_outcome(Ok(()), None, &sha), Ok(None)); + let timeout = Err("the guest's control port: timed out".to_owned()); + let ok = delivery_outcome(timeout.clone(), Some(Ok(sha.clone())), &sha).expect("it runs it"); + assert!(ok.is_some_and(|n| n.contains("delivered"))); + assert!(delivery_outcome(timeout.clone(), Some(Ok("cd".repeat(32))), &sha).is_err(), "it runs another one"); + assert!(delivery_outcome(timeout, Some(Err("no answer".into())), &sha).is_err()); + assert!(guest_answered("the guest refused [\"config\", \"done\"]: error mount …")); + assert!(!guest_answered("the guest's control port: timed out")); + } + /// 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] diff --git a/test/ext-attribution.sh b/test/ext-attribution.sh index 7b037d6..606e661 100755 --- a/test/ext-attribution.sh +++ b/test/ext-attribution.sh @@ -14,9 +14,8 @@ # 5. layer2 mode off records nothing; an invalid debug value refuses to start. # Exits non-zero on any failure. Writes .tmp/ext-attribution/. Leaves the stack as it found it # (examples/wordpress.json, no debug ini, fixtures removed). -# On the microVM target (SC_TARGET=microvm, test/lib/target.sh) 1 runs in the guest; 2–5 switch -# the debug settings in php.ini, which in the guest is on the read-only root image (php-fpm there -# takes no per-site ini), so each of their checks is n/a, with that reason. +# On the microVM target (SC_TARGET=microvm, test/lib/target.sh) everything runs in the guest: the +# debug settings are the launcher's --guest-ini file, delivered to the running guest (#90). # DOCKER_CONTEXT=colima test/ext-config.sh && DOCKER_CONTEXT=colima test/ext-attribution.sh set -u cd "$(dirname "$0")/.." || exit 1 @@ -45,12 +44,27 @@ field() { sed -n "s/^$1=//p" "$dir/status"; } attr() { phplog "$1" | sed -n 's/.*securecore: attribution //p'; } # has