From 333793e00c17926762023cb1b4ee24efc6061070 Mon Sep 17 00:00:00 2001 From: Sami Fouad Date: Wed, 11 Nov 2026 13:03:52 -0600 Subject: [PATCH 1/6] Layer 1 microVM: a securecore.json edit reaches the running guest (#90) The launcher follows the config with the extension's own Reloader, once a second. An invalid file, or one the microVM can't run (the check a start makes), is refused with the reason and the guest keeps its config. A valid one goes to the guest over the control channel (config line), which mounts it over /securecore.json from tmpfs; the extension there reloads it as on a host. layer1 and vault changes apply at the next start and the guest's extension reports restart_needed, as on a host; the host's egress takes layer 2's new hosts at once. --guest-ini carries the site's securecore.debug_* php.ini settings into the guest (any other key is refused): in each start message, and again on every change, with php-fpm started again gracefully. ext-config and ext-attribution check these on the microVM target instead of n/a. --- ext/README.md | 20 +++- ext/fpm/src/guest.rs | 147 ++++++++++++++++++++++++++++- ext/fpm/src/main.rs | 8 +- ext/fpm/src/vm.rs | 201 ++++++++++++++++++++++++++++++++++++++-- test/ext-attribution.sh | 33 +++++-- test/ext-config.sh | 79 +++++++++++----- test/lib/target.sh | 34 ++++++- 7 files changed, 469 insertions(+), 53 deletions(-) diff --git a/ext/README.md b/ext/README.md index b8099cb..b256528 100644 --- a/ext/README.md +++ b/ext/README.md @@ -904,9 +904,27 @@ 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 `stat` a second, the same loader): 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; any other setting is refused with the reason), 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 8b4dce2..8a45a80 100644 --- a/ext/fpm/src/guest.rs +++ b/ext/fpm/src/guest.rs @@ -171,9 +171,61 @@ 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 }, Done, } +/// The largest `securecore.json` the host delivers (bytes). +pub const MAX_CONFIG: usize = 128 * 1024; +/// 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; + +/// The settings a site's php.ini may give the guest's php-fpm (#90): the extension's per-site +/// debug settings only. 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. 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; + } + let Some((key, value)) = line.split_once('=') else { + return Err(format!("line {}: want `key = value`, got {line:?}", n + 1)); + }; + 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 {}: {key:?}: 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)", + n + 1 + )); + } + if value.bytes().any(|b| b.is_ascii_control()) || value.len() > 256 { + return Err(format!("line {}: {key}: the value holds a control character or is too long", n + 1)); + } + out.push_str(&format!("{key} = {value}\n")); + } + Ok(out) +} + impl Ctl { pub fn line(&self) -> String { match self { @@ -186,6 +238,9 @@ 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::Done => "done\n".into(), } } @@ -208,6 +263,12 @@ 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])), ["done"] => Ok(Ctl::Done), // Never echo an env line: it carries a secret. ["env", ..] => Err("a malformed env line".into()), @@ -235,11 +296,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(()), } } @@ -437,6 +500,38 @@ 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); + mount(&file, &target, "", libc::MS_BIND, "")?; + // A bind mount takes its flags only on a remount. + mount("", &target, "", 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(()) +} + /// Applies one control line. fn apply(ctl: &Ctl) -> io::Result<()> { match ctl { @@ -503,6 +598,17 @@ 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, "not acknowledged by the host before the stop"))) } + 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(()) + } // Checked before anything is applied ([`protocol_ok`]). Ctl::Proto { .. } | Ctl::Done => Ok(()), } @@ -558,8 +664,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)) { @@ -830,7 +937,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 @@ -975,6 +1086,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:?}"); @@ -1046,5 +1160,28 @@ mod tests { assert_eq!(allowed(&[Ctl::Reload], true), Ok(())); assert!(allowed(&[Ctl::Sync], false).is_err(), "nothing before the start"); 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()); } } diff --git a/ext/fpm/src/main.rs b/ext/fpm/src/main.rs index 7595e36..3699c8a 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 defee91..34b0782 100644 --- a/ext/fpm/src/vm.rs +++ b/ext/fpm/src/vm.rs @@ -172,6 +172,21 @@ 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. +pub fn read_site_ini(path: Option<&Path>) -> Result, String> { + let Some(path) = path else { return Ok(None) }; + match fs::read_to_string(path) { + Ok(text) => crate::guest::site_ini(&text).map(Some).map_err(|e| format!("{}: {e}", path.display())), + Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(format!("{}: {e}", path.display())), + } } /// php-fpm's environment in the guest: each name in `--guest-env` and each vault secret's `env`, @@ -1127,7 +1142,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. @@ -1342,10 +1357,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); } @@ -1402,6 +1419,135 @@ 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); + +/// 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!("the microVM can't run it ({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 reloader: Option = None; + let mut in_guest = started.sha256.clone(); + let mut refused: Option = None; + let mut start_error: Option = None; + let mut ini_refused: Option = None; + loop { + thread::sleep(WATCH_INTERVAL); + let r = match &mut reloader { + Some(r) => r, + None => match securecore_config::Reloader::start(&started.path, Duration::ZERO, Instant::now()) { + Ok(r) => reloader.insert(r), + Err(e) => { + let e = e.to_string(); + if start_error.as_deref() != Some(&e) { + log(&format!("{e}; keeping the last valid config in the guest (sha256 {})", short_sha(&in_guest))); + start_error = Some(e); + } + continue; + } + }, + }; + if let securecore_config::Poll::Rejected(e) = r.poll(Instant::now()) { + log(&format!("{e}; keeping the last valid config in the guest (sha256 {})", short_sha(&in_guest))); + } + let live = r.live().clone(); + if live.sha256 != in_guest && refused.as_deref() != Some(&live.sha256) { + let t = Instant::now(); + let bytes = fs::read(&live.path).ok().filter(|b| securecore_config::sha256_hex(b) == live.sha256); + let result = match (bytes, live_change(started, &live, opts)) { + // Changed again since it was read: the next look takes the newer one. + (None, _) => continue, + (_, Err(e)) => Err(e), + (Some(b), Ok(notes)) => tell_guest(uds, &[Ctl::Config { hex: hex(&b) }, Ctl::Done], SYNC_TIMEOUT_LIVE).map(|()| notes), + }; + match result { + Ok(notes) => { + 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) + )); + refused = Some(live.sha256.clone()); + } + } + } + if let Some(path) = &opts.guest_ini { + let now = match fs::read_to_string(path) { + Ok(text) => Some(text), + Err(e) if e.kind() == io::ErrorKind::NotFound => None, + Err(_) => continue, + }; + let checked = now.as_deref().map(crate::guest::site_ini).transpose(); + match checked { + 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) + )), + 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", path.display())); + } + 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); + +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. @@ -1528,6 +1674,7 @@ struct Real<'a> { opts: &'a Options, m: &'a Machine, env: &'a [(String, String)], + ini: Option<&'a str>, } impl Lifecycle for Real<'_> { @@ -1574,7 +1721,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) } } @@ -1634,9 +1781,10 @@ fn wire(plan: &Plan, m: &Machine, j: &Jail, short: &Path, wiring: Wiring) -> Res }); } // 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 || { @@ -1650,7 +1798,8 @@ fn wire(plan: &Plan, m: &Machine, j: &Jail, short: &Path, wiring: Wiring) -> Res // 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}")), } @@ -2225,8 +2374,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 { @@ -2293,6 +2447,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 { @@ -2360,6 +2520,7 @@ mod tests { snapshot: true, guest_args: vec![], guest_env: vec![], + guest_ini: None, } } @@ -2423,7 +2584,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"); @@ -2431,7 +2592,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); @@ -2458,6 +2623,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"); 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