Skip to content
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,8 @@ jobs:
test -x "$bin"
sudo env "FCTL_TEST_FIRECRACKER_AGENT=$FCTL_TEST_FIRECRACKER_AGENT" "FCTL_TEST_FIRECRACKER_DATA=$RUNNER_TEMP/root" \
"$bin" driver::firecracker::tests::boots_a_sandbox --ignored --nocapture
# Jails lend disks to their users, which only root can.
sudo "$bin" driver::firecracker::vm::tests::stale_jails_go --exact --nocapture

# The Worker the deploy ships, built beside the checks. Its release build
# takes two minutes, so it is cached by what it is built from: a push that
Expand Down
6 changes: 6 additions & 0 deletions crates/fctl-host/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
//! firecracker = "/usr/local/bin/firecracker" # unset: the release fctl pins, downloaded
//! kernel = "/var/lib/fctl/vmlinux" # a file, or an image with /vmlinux (unset: the published one)
//! disk_gb = 64 # each sandbox's own disk, which takes only what it holds
//! jailer = true # as root: each VM as a user of its own, in a chroot and a cgroup
//! ```
//!
//! The runner token lives next to it in `host-token`, and the Claude token
Expand Down Expand Up @@ -157,6 +158,10 @@ pub struct FirecrackerConfig {
/// The disk each sandbox gets, in GiB: a sparse file, which takes only
/// what the session writes.
pub disk_gb: u32,
/// Whether a host that runs as root runs each VM through Firecracker's
/// jailer: as a user of its own, in a chroot with only its files, and
/// in a cgroup of its own. A host that doesn't run as root can't.
pub jailer: bool,
}

impl Default for FirecrackerConfig {
Expand All @@ -166,6 +171,7 @@ impl Default for FirecrackerConfig {
kernel: None,
passt: None,
disk_gb: 64,
jailer: true,
}
}
}
Expand Down
49 changes: 33 additions & 16 deletions crates/fctl-host/src/driver/firecracker/assets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,20 @@ pub fn pinned_firecracker(bin: &Path) -> PathBuf {
bin.join(format!("firecracker-v{FIRECRACKER_VERSION}"))
}

/// Downloads the pinned Firecracker into `bin`, checked against its
/// archive's SHA-256, unless it is there.
/// The jailer of the same release, which comes with it.
pub fn pinned_jailer(bin: &Path) -> PathBuf {
bin.join(format!("jailer-v{FIRECRACKER_VERSION}"))
}

/// Downloads the pinned Firecracker and its jailer into `bin`, checked
/// against their archive's SHA-256, unless they are there.
pub async fn download_firecracker(
bin: &Path,
log: &(dyn Fn(String) + Send + Sync),
) -> Result<PathBuf> {
let path = pinned_firecracker(bin);
if path.is_file() {
let jailer = pinned_jailer(bin);
if path.is_file() && jailer.is_file() {
return Ok(path);
}
let arch = std::env::consts::ARCH;
Expand All @@ -73,24 +79,35 @@ pub async fn download_firecracker(
if digest != format!("sha256:{sum}") {
bail!("{url} doesn't match the checksum fctl expects");
}
let inside = format!(
"release-v{FIRECRACKER_VERSION}-{arch}/firecracker-v{FIRECRACKER_VERSION}-{arch}"
);
let wanted = [("firecracker", &path), ("jailer", &jailer)].map(|(name, to)| {
(
format!(
"release-v{FIRECRACKER_VERSION}-{arch}/{name}-v{FIRECRACKER_VERSION}-{arch}"
),
to.clone(),
)
});
let file = std::fs::File::open(&archive)?;
let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(file));
let mut found = 0;
for entry in tar.entries()? {
let mut entry = entry?;
if entry.path()?.to_string_lossy() == inside {
let tmp = path.with_extension("tmp");
let mut out = std::fs::File::create(&tmp)?;
std::io::copy(&mut entry, &mut out)?;
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o755))?;
std::fs::rename(&tmp, &path)?;
return Ok(());
}
let name = entry.path()?.to_string_lossy().into_owned();
let Some((_, to)) = wanted.iter().find(|(inside, _)| *inside == name) else {
continue;
};
let tmp = to.with_extension("tmp");
let mut out = std::fs::File::create(&tmp)?;
std::io::copy(&mut entry, &mut out)?;
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o755))?;
std::fs::rename(&tmp, to)?;
found += 1;
}
if found < wanted.len() {
bail!("{url} has no Firecracker or no jailer");
}
bail!("{url} has no {inside}")
Ok(())
})();
let _ = std::fs::remove_file(&archive);
result.map(|()| path)
Expand Down
158 changes: 154 additions & 4 deletions crates/fctl-host/src/driver/firecracker/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,21 @@ pub struct FirecrackerDriver {
locks: Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
}

/// The jailer beside the Firecracker `firecracker`: `jailer`, or the
/// release's name for it, which the archive gives both (`jailer-v1.17.0`
/// beside `firecracker-v1.17.0`, `jailer-v1.17.0-x86_64` beside
/// `firecracker-v1.17.0-x86_64`).
fn jailer_beside(firecracker: &Path) -> Option<PathBuf> {
let name = firecracker.file_name()?.to_string_lossy().into_owned();
let released = name
.strip_prefix("firecracker")
.map(|rest| firecracker.with_file_name(format!("jailer{rest}")));
[Some(firecracker.with_file_name("jailer")), released]
.into_iter()
.flatten()
.find(|p| p.is_file())
}

/// Finds `program` on the PATH, or in the directories where Linux keeps
/// what administrators run, which users' PATHs may lack.
pub fn find_program(program: &str) -> Option<PathBuf> {
Expand Down Expand Up @@ -205,7 +220,66 @@ impl FirecrackerDriver {
}

fn vm(&self, name: &str) -> Result<Vm> {
Vm::new(self.sandboxes().join(name))
self.with_jails(Vm::new(self.sandboxes().join(name))?)
}

/// Where the VMs' jails go, when they run through Firecracker's jailer:
/// on a host that runs as root, unless `host.toml` says otherwise.
fn jails(&self) -> Option<PathBuf> {
(self.cfg().jailer && nix::unistd::geteuid().is_root()).then(|| self.root.join("jail"))
}

fn with_jails(&self, vm: Vm) -> Result<Vm> {
Ok(match self.jails() {
Some(jails) => vm.with_jails(jails),
None => vm,
})
}

/// How `vm` runs: through Firecracker's jailer, on a host that runs as
/// root ([`jailer`](Self::jailer)); or without it, where the host
/// doesn't run as root.
fn jail_for(&self, vm: &Vm, firecracker: &Path) -> Result<Option<vm::Jail>> {
if vm.jails.is_none() {
return Ok(None);
}
let jailer = self.jailer(firecracker).with_context(|| {
format!(
"Firecracker's jailer isn't beside {} (as jailer, or named as the release names it) or on the PATH: install it there, or set jailer = false in host.toml's [firecracker]",
firecracker.display()
)
})?;
Ok(Some(vm::Jail { jailer }))
}

/// Firecracker's jailer for `firecracker`: the pinned release's, which
/// comes with it; else beside it, as `jailer` or as the release names it
/// (`jailer-v1.17.0-x86_64` beside `firecracker-v1.17.0-x86_64`); else
/// on the PATH.
fn jailer(&self, firecracker: &Path) -> Option<PathBuf> {
let pinned = assets::pinned_jailer(&self.root.join("bin"));
if self.cfg().firecracker.is_none() {
return Some(pinned);
}
jailer_beside(firecracker).or_else(|| find_program("jailer"))
}

/// Removes the jails of VMs that don't run, which a host that stopped
/// or crashed left ([`vm::remove_stale_jails`]).
fn remove_stale_jails(&self) {
let Some(jails) = self.jails() else {
return;
};
let running: std::collections::HashSet<String> =
[self.sandboxes(), self.root.join("unpacking")]
.iter()
.filter_map(|d| std::fs::read_dir(d).ok())
.flat_map(|entries| entries.flatten())
.filter_map(|e| Vm::new(e.path()).ok())
.filter(Vm::running)
.map(|vm| vm.key)
.collect();
vm::remove_stale_jails(&jails, &running, Duration::from_secs(10 * 60));
}

fn record(&self, name: &str) -> Option<Record> {
Expand Down Expand Up @@ -349,6 +423,24 @@ impl FirecrackerDriver {
}),
None => None,
};
if let Some(jails) = self.jails() {
if let Some(why) = vm::jails_problem(&jails) {
return info(false, why, version);
}
if let Some(b) = &binary
&& self.cfg().firecracker.is_some()
&& self.jailer(b).is_none()
{
return info(
false,
format!(
"Firecracker's jailer isn't beside {} (as jailer, or named as the release names it) or on the PATH: install it there, or set jailer = false in host.toml's [firecracker]",
b.display()
),
version,
);
}
}
let mut later = Vec::new();
if binary.is_none() {
later.push(format!("Firecracker {}", assets::FIRECRACKER_VERSION));
Expand Down Expand Up @@ -629,9 +721,12 @@ impl FirecrackerDriver {
hex::encode(fctl_domain::random_bytes::<6>())
);
remove_stale(&self.root.join("unpacking"));
let vm = Vm::new(self.root.join("unpacking").join(&name))?;
self.remove_stale_jails();
let vm = self.with_jails(Vm::new(self.root.join("unpacking").join(&name))?)?;
let spec = vm::unpack_spec(kernel, initrd, &name, rootfs);
vm.start(&spec, &firecracker).await?;
self.remove_stale_jails();
let jail = self.jail_for(&vm, &firecracker)?;
vm.start(&spec, &firecracker, jail.as_ref()).await?;
let result = async {
vm.wait_ready().await?;
let within =
Expand Down Expand Up @@ -776,7 +871,8 @@ impl FirecrackerDriver {
memory_mb: spec.memory_mb,
network: true,
};
vm.start(&boot, &firecracker).await?;
let jail = self.jail_for(&vm, &firecracker)?;
vm.start(&boot, &firecracker, jail.as_ref()).await?;
vm.wait_ready().await?;
if let Err(e) = vm.link_network(&passt).await {
vm.kill().await;
Expand Down Expand Up @@ -1061,6 +1157,24 @@ mod tests {
FirecrackerDriver::new(&host)
}

/// Beside a Firecracker that `host.toml` names, the jailer is `jailer`
/// or named as the release names it.
#[test]
fn finds_the_jailer_beside_firecracker() -> Result<()> {
let dir = tempfile::tempdir()?;
let firecracker = dir.path().join("firecracker-v1.17.0-x86_64");
std::fs::write(&firecracker, b"")?;
assert_eq!(jailer_beside(&firecracker), None);
let released = dir.path().join("jailer-v1.17.0-x86_64");
std::fs::write(&released, b"")?;
assert_eq!(jailer_beside(&firecracker), Some(released));
let plain = dir.path().join("jailer");
std::fs::write(&plain, b"")?;
assert_eq!(jailer_beside(&firecracker), Some(plain.clone()));
assert_eq!(jailer_beside(&dir.path().join("firecracker")), Some(plain));
Ok(())
}

#[tokio::test]
async fn names_and_sandboxes_keep_their_images() -> Result<()> {
let dir = tempfile::tempdir()?;
Expand Down Expand Up @@ -1261,6 +1375,25 @@ mod tests {
assert_eq!(out, format!("0\n{name}\n/root\n/\n"));
}
assert_eq!(out.lines().nth(1), Some(name.as_str()));
// As root, the VM runs in Firecracker's jailer, as a user of
// its own.
if nix::unistd::geteuid().is_root() {
let pid = std::fs::read_to_string(
cfg.data_dir()
.join("firecracker/sandboxes")
.join(&name)
.join("firecracker.pid"),
)?;
let status = std::fs::read_to_string(format!("/proc/{}/status", pid.trim()))?;
let uid: u32 = status
.lines()
.find_map(|l| l.strip_prefix("Uid:"))
.and_then(|l| l.split_whitespace().next())
.and_then(|u| u.parse().ok())
.context("Firecracker's uid")?;
assert!(uid >= vm::JAIL_ID_BASE, "Firecracker runs as {uid}");
eprintln!("jailed as {uid}");
}
if let Ok(command) = std::env::var("FCTL_TEST_FIRECRACKER_RUN") {
eprintln!("{command}: {}", d.exec(&sb, &command).await?.trim());
}
Expand Down Expand Up @@ -1304,6 +1437,23 @@ mod tests {
// A stopped sandbox keeps its disk, and starts again from it.
d.exec(&sb, "echo kept > \"$HOME/note\"").await?;
d.stop(&sb).await?;
// Its disk, which its jail had, is the host's again, as are the
// images' filesystems, which their unpacking VMs' jails had.
if nix::unistd::geteuid().is_root() {
use std::os::unix::fs::MetadataExt;
let firecracker = cfg.data_dir().join("firecracker");
let images = std::fs::read_dir(firecracker.join("images"))?
.flatten()
.map(|e| e.path().join("rootfs.ext4"))
.filter(|p| p.is_file());
let disks = std::fs::read_dir(firecracker.join("sandboxes").join(&name))?
.flatten()
.map(|e| e.path());
for path in images.chain(disks) {
let owner = std::fs::symlink_metadata(&path)?.uid();
assert!(owner < vm::JAIL_ID_BASE, "{path:?} is {owner}'s");
}
}
let listed = d.list().await?;
assert!(listed.iter().any(|s| s.name == name && !s.running), "{listed:?}");
d.ensure(&spec, &log).await?;
Expand Down
Loading
Loading