aev-vm 0.1.0

Manage QEMU virtual machines in Rust and open their consoles in Aen
Documentation
//! XDG-aware persistent and runtime paths.

use std::env;
use std::fs;
use std::os::unix::fs::{DirBuilderExt, MetadataExt, PermissionsExt};
use std::path::{Component, Path, PathBuf};

use anyhow::{Context, Result, bail};

use crate::config::validate_name;

/// All filesystem roots used by `KnottVM`.
#[derive(Debug, Clone)]
pub struct AppPaths {
    /// Directory containing VM definitions.
    pub config_root: PathBuf,
    /// Directory containing disk and firmware state.
    pub data_root: PathBuf,
    /// Directory containing ephemeral sockets and process state.
    pub runtime_root: PathBuf,
    runtime_base: Option<PathBuf>,
    fallback_runtime_base: bool,
}

impl AppPaths {
    /// Resolve roots from the XDG environment.
    pub fn discover() -> Result<Self> {
        let home = env::var_os("HOME")
            .map(PathBuf::from)
            .context("HOME is not set and XDG paths cannot be resolved")?;
        let config_default = home.join(".config");
        let data_default = home.join(".local/share");
        let config_home =
            resolve_xdg_home(env::var_os("XDG_CONFIG_HOME").as_deref(), &config_default);
        let data_home = resolve_xdg_home(env::var_os("XDG_DATA_HOME").as_deref(), &data_default);
        let (runtime_base, fallback_runtime_base) =
            if let Some(path) = env::var_os("XDG_RUNTIME_DIR") {
                let path = require_absolute_runtime_dir(PathBuf::from(path))?;
                (
                    fs::canonicalize(path)
                        .context("XDG_RUNTIME_DIR must name an existing directory")?,
                    false,
                )
            } else {
                // SAFETY: geteuid has no preconditions and does not access memory.
                let uid = unsafe { libc::geteuid() };
                (PathBuf::from(format!("/tmp/knottvm-{uid}")), true)
            };
        Ok(Self {
            config_root: config_home.join("knottvm/vms"),
            data_root: data_home.join("knottvm/vms"),
            runtime_root: runtime_base.join("knottvm"),
            runtime_base: Some(runtime_base),
            fallback_runtime_base,
        })
    }

    /// Construct explicit roots, primarily for isolated tests.
    #[must_use]
    pub const fn new(config_root: PathBuf, data_root: PathBuf, runtime_root: PathBuf) -> Self {
        Self {
            config_root,
            data_root,
            runtime_root,
            runtime_base: None,
            fallback_runtime_base: false,
        }
    }

    /// Create roots and enforce owner-only runtime access.
    pub fn ensure(&self) -> Result<()> {
        let runtime_base = self
            .runtime_base
            .as_deref()
            .or_else(|| self.runtime_root.parent())
            .context("runtime root must have a parent directory")?;
        if self.fallback_runtime_base {
            ensure_fallback_runtime_base(Path::new("/tmp"), runtime_base)?;
        } else {
            validate_runtime_base(runtime_base)?;
        }
        ensure_private_dir(&self.config_root)?;
        ensure_private_dir(&self.data_root)?;
        ensure_private_dir(&self.runtime_root)
    }

    /// Return a VM's TOML definition path.
    pub fn config(&self, name: &str) -> Result<PathBuf> {
        validate_name(name)?;
        Ok(self.config_root.join(format!("{name}.toml")))
    }

    /// Return a VM's persistent data directory.
    pub fn data(&self, name: &str) -> Result<PathBuf> {
        validate_name(name)?;
        Ok(self.data_root.join(name))
    }

    /// Return a VM's ephemeral runtime directory.
    pub fn runtime(&self, name: &str) -> Result<PathBuf> {
        validate_name(name)?;
        Ok(self.runtime_root.join(name))
    }
}

fn resolve_xdg_home(value: Option<&std::ffi::OsStr>, fallback: &Path) -> PathBuf {
    value
        .map(PathBuf::from)
        .filter(|path| path.is_absolute())
        .unwrap_or_else(|| fallback.to_path_buf())
}

fn require_absolute_runtime_dir(path: PathBuf) -> Result<PathBuf> {
    if !path.is_absolute() {
        bail!("XDG_RUNTIME_DIR must be an absolute path");
    }
    Ok(path)
}

fn ensure_fallback_runtime_base(tmp_root: &Path, runtime_base: &Path) -> Result<()> {
    ensure_fallback_runtime_base_owned_by(tmp_root, runtime_base, system_root_uid()?)
}

fn ensure_fallback_runtime_base_owned_by(
    tmp_root: &Path,
    runtime_base: &Path,
    trusted_tmp_owner: u32,
) -> Result<()> {
    // SAFETY: geteuid has no preconditions and does not access memory.
    let uid = unsafe { libc::geteuid() };
    let expected = tmp_root.join(format!("knottvm-{uid}"));
    if runtime_base != expected {
        bail!("fallback runtime path is not the expected per-user directory");
    }
    validate_sticky_tmp_root(tmp_root, trusted_tmp_owner)?;
    match fs::DirBuilder::new().mode(0o700).create(runtime_base) {
        Ok(()) => {}
        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
        Err(error) => {
            return Err(error).with_context(|| {
                format!("failed to create runtime base {}", runtime_base.display())
            });
        }
    }
    validate_runtime_base(runtime_base)
}

fn validate_sticky_tmp_root(path: &Path, trusted_owner: u32) -> Result<()> {
    let metadata = fs::symlink_metadata(path)
        .with_context(|| format!("failed to inspect temporary root {}", path.display()))?;
    let mode = metadata.mode() & 0o7777;
    if !metadata.is_dir()
        || metadata.file_type().is_symlink()
        || metadata.uid() != trusted_owner
        || mode & 0o1000 == 0
    {
        bail!(
            "temporary root {} is not a trusted sticky directory",
            path.display()
        );
    }
    Ok(())
}

fn system_root_uid() -> Result<u32> {
    fs::symlink_metadata("/")
        .map(|metadata| metadata.uid())
        .context("failed to inspect filesystem root owner")
}

/// Validate every directory in the runtime path so another UID cannot replace
/// a protected leaf through a writable ancestor. Shared sticky roots such as
/// `/tmp` are safe only when owned by root or this user.
fn validate_runtime_base(path: &Path) -> Result<()> {
    if !path.is_absolute() {
        bail!("runtime base must be an absolute path");
    }
    // SAFETY: geteuid has no preconditions and does not access memory.
    let uid = unsafe { libc::geteuid() };
    let root_uid = system_root_uid()?;
    let mut current = PathBuf::new();
    for component in path.components() {
        match component {
            Component::RootDir => current.push(component.as_os_str()),
            Component::Normal(name) => current.push(name),
            Component::CurDir | Component::ParentDir | Component::Prefix(_) => {
                bail!("runtime base must be canonical")
            }
        }
        let metadata = fs::symlink_metadata(&current)
            .with_context(|| format!("failed to inspect runtime ancestor {}", current.display()))?;
        let mode = metadata.mode() & 0o7777;
        if !metadata.is_dir() || metadata.file_type().is_symlink() {
            bail!("runtime ancestor {} is not a directory", current.display());
        }
        if current == path {
            if metadata.uid() != uid {
                bail!("runtime base {} is owned by another user", path.display());
            }
            if mode & 0o022 != 0 {
                bail!(
                    "runtime base {} is writable by another user",
                    path.display()
                );
            }
            continue;
        }
        if metadata.uid() != root_uid && metadata.uid() != uid {
            bail!(
                "runtime ancestor {} is owned by another user",
                current.display()
            );
        }
        if mode & 0o022 != 0
            && !(mode & 0o1000 != 0 && (metadata.uid() == root_uid || metadata.uid() == uid))
        {
            bail!(
                "runtime ancestor {} can be replaced by another user",
                current.display()
            );
        }
    }
    fs::set_permissions(path, fs::Permissions::from_mode(0o700))
        .with_context(|| format!("failed to secure runtime base {}", path.display()))?;
    Ok(())
}

/// Create a directory and reject roots owned by another user.
pub fn ensure_private_dir(path: &Path) -> Result<()> {
    fs::create_dir_all(path)
        .with_context(|| format!("failed to create directory {}", path.display()))?;
    let metadata = fs::symlink_metadata(path)
        .with_context(|| format!("failed to inspect directory {}", path.display()))?;
    if !metadata.is_dir() {
        bail!("{} is not a directory", path.display());
    }
    // SAFETY: geteuid has no preconditions and does not access memory.
    let uid = unsafe { libc::geteuid() };
    if metadata.uid() != uid {
        bail!("directory {} is owned by another user", path.display());
    }
    fs::set_permissions(path, fs::Permissions::from_mode(0o700))
        .with_context(|| format!("failed to secure directory {}", path.display()))?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::ffi::OsStr;
    use std::os::unix::fs::symlink;
    use tempfile::tempdir;

    fn sticky_tmp(root: &Path) -> PathBuf {
        let path = root.join("tmp");
        fs::create_dir(&path).unwrap();
        fs::set_permissions(&path, fs::Permissions::from_mode(0o1777)).unwrap();
        path
    }

    #[test]
    fn relative_or_empty_persistent_xdg_homes_use_home_defaults() {
        let config_default = Path::new("/home/test/.config");
        let data_default = Path::new("/home/test/.local/share");
        for value in [
            None,
            Some(OsStr::new("")),
            Some(OsStr::new("relative/path")),
        ] {
            assert_eq!(resolve_xdg_home(value, config_default), config_default);
            assert_eq!(resolve_xdg_home(value, data_default), data_default);
        }
        assert_eq!(
            resolve_xdg_home(Some(OsStr::new("/tmp/config")), config_default),
            Path::new("/tmp/config")
        );
        assert_eq!(
            resolve_xdg_home(Some(OsStr::new("/tmp/data")), data_default),
            Path::new("/tmp/data")
        );
    }

    #[test]
    fn relative_runtime_dir_is_rejected_before_canonicalization() {
        let error =
            require_absolute_runtime_dir(PathBuf::from("missing-relative-runtime")).unwrap_err();
        assert!(
            error
                .to_string()
                .contains("XDG_RUNTIME_DIR must be an absolute path")
        );
    }

    #[test]
    fn fallback_runtime_base_is_created_atomically_and_private() {
        // SAFETY: geteuid has no preconditions and does not access memory.
        let uid = unsafe { libc::geteuid() };
        let root = tempdir().unwrap();
        let tmp = sticky_tmp(root.path());
        let base = tmp.join(format!("knottvm-{uid}"));

        if system_root_uid().unwrap() != uid {
            assert!(ensure_fallback_runtime_base(&tmp, &base).is_err());
            assert!(!base.exists());
        }
        ensure_fallback_runtime_base_owned_by(&tmp, &base, uid).unwrap();
        let metadata = fs::symlink_metadata(&base).unwrap();
        assert!(metadata.is_dir());
        assert!(!metadata.file_type().is_symlink());
        assert_eq!(metadata.uid(), uid);
        assert_eq!(metadata.mode() & 0o777, 0o700);
        assert!(!base.join("knottvm").exists());
    }

    #[test]
    fn fallback_rejects_preexisting_writable_or_symlinked_parents() {
        // SAFETY: geteuid has no preconditions and does not access memory.
        let uid = unsafe { libc::geteuid() };
        let root = tempdir().unwrap();
        let tmp = sticky_tmp(root.path());
        let writable = tmp.join(format!("knottvm-{uid}"));
        fs::create_dir(&writable).unwrap();
        fs::set_permissions(&writable, fs::Permissions::from_mode(0o777)).unwrap();
        assert!(ensure_fallback_runtime_base_owned_by(&tmp, &writable, uid).is_err());
        assert!(!writable.join("knottvm").exists());

        fs::remove_dir(&writable).unwrap();
        let target = root.path().join("attacker-owned");
        fs::create_dir(&target).unwrap();
        symlink(&target, &writable).unwrap();
        assert!(ensure_fallback_runtime_base_owned_by(&tmp, &writable, uid).is_err());
        assert!(!target.join("knottvm").exists());
    }

    #[test]
    fn runtime_base_rejects_a_replaceable_ancestor() {
        let root = tempdir().unwrap();
        let parent = root.path().join("writable-parent");
        fs::create_dir(&parent).unwrap();
        fs::set_permissions(&parent, fs::Permissions::from_mode(0o777)).unwrap();
        let base = parent.join("runtime");
        fs::create_dir(&base).unwrap();
        fs::set_permissions(&base, fs::Permissions::from_mode(0o700)).unwrap();

        assert!(validate_runtime_base(&base).is_err());

        let target = root.path().join("safe-target");
        fs::create_dir(&target).unwrap();
        fs::set_permissions(&target, fs::Permissions::from_mode(0o700)).unwrap();
        let link = root.path().join("linked-parent");
        symlink(&target, &link).unwrap();
        assert!(validate_runtime_base(&link.join("runtime")).is_err());
    }
}