aev-vm 0.1.0

Manage QEMU virtual machines in Rust and open their consoles in Aen
Documentation
//! Native Aen console for an existing, private developer QA guest endpoint.

use std::fs::{self, File, OpenOptions};
use std::os::fd::AsRawFd;
use std::os::unix::fs::{FileTypeExt, MetadataExt, OpenOptionsExt};
use std::path::{Component, Path, PathBuf};
use std::process::ExitCode;

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

#[derive(Debug, Parser)]
#[command(
    version,
    about = "Open a private guest RFB socket in a native Aen window"
)]
struct Arguments {
    /// Absolute Unix socket path inside a directory owned and accessible only by you.
    #[arg(long)]
    socket: PathBuf,
    /// Window title (at most 128 bytes, without control characters).
    #[arg(long, default_value = "KnottOS installation check", value_parser = title)]
    title: String,
}

fn title(value: &str) -> Result<String, String> {
    if value.is_empty() || value.len() > 128 || value.chars().any(char::is_control) {
        return Err("title must contain 1–128 bytes without control characters".into());
    }
    Ok(value.to_owned())
}

/// Keep the inspected private directory pinned throughout the console lifetime.
struct Endpoint {
    _directory: File,
    socket: PathBuf,
}

impl Endpoint {
    fn open(path: &Path) -> Result<Self> {
        if !path.is_absolute()
            || path
                .components()
                .any(|part| !matches!(part, Component::RootDir | Component::Normal(_)))
        {
            bail!("socket path must be absolute without parent components");
        }
        let name = path.file_name().context("socket path has no file name")?;
        let parent = path.parent().context("socket path has no directory")?;
        let directory = OpenOptions::new()
            .read(true)
            .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC)
            .open(parent)
            .context("cannot open the socket's private directory")?;
        let metadata = directory.metadata()?;
        // SAFETY: geteuid takes no arguments and has no preconditions.
        let uid = unsafe { libc::geteuid() };
        if metadata.uid() != uid || metadata.mode() & 0o077 != 0 {
            bail!("socket directory must belong to you and deny group/other access");
        }
        // Resolve the leaf through the descriptor, not the original directory path.
        // The directory cannot be replaced between this check and RFB connect.
        let socket = PathBuf::from(format!("/proc/self/fd/{}", directory.as_raw_fd())).join(name);
        let metadata = fs::symlink_metadata(&socket).context("cannot inspect guest socket")?;
        if !metadata.file_type().is_socket() || metadata.uid() != uid {
            bail!("guest endpoint must be a Unix socket owned by you, without a symlink");
        }
        Ok(Self {
            _directory: directory,
            socket,
        })
    }
}

fn main() -> ExitCode {
    let arguments = Arguments::parse();
    let result = Endpoint::open(&arguments.socket)
        .and_then(|endpoint| aev_vm::console::run(&arguments.title, &endpoint.socket));
    match result {
        Ok(()) => ExitCode::SUCCESS,
        Err(error) => {
            eprintln!("knottvm-console-socket: {error:#}");
            ExitCode::FAILURE
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::os::unix::fs::{PermissionsExt, symlink};
    use std::os::unix::net::{UnixListener, UnixStream};

    fn directory() -> tempfile::TempDir {
        let directory = tempfile::tempdir().unwrap();
        fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o700)).unwrap();
        directory
    }

    #[test]
    fn arguments_require_an_explicit_socket_and_a_bounded_title() {
        assert!(Arguments::try_parse_from(["console"]).is_err());
        assert!(
            Arguments::try_parse_from([
                "console",
                "--socket",
                "/tmp/guest",
                "--title",
                "bad\nname"
            ])
            .is_err()
        );
        assert!(title(&"a".repeat(129)).is_err());
        assert!(title("").is_err());
        let arguments = Arguments::try_parse_from(["console", "--socket", "/tmp/guest"]).unwrap();
        assert_eq!(arguments.socket, Path::new("/tmp/guest"));
    }

    #[test]
    fn rejects_relative_paths_and_parent_components() {
        assert!(Endpoint::open(Path::new("guest.sock")).is_err());
        assert!(Endpoint::open(Path::new("/tmp/../guest.sock")).is_err());
        assert!(Endpoint::open(Path::new("/")).is_err());
    }

    #[test]
    fn rejects_shared_directory() {
        let directory = directory();
        let socket = directory.path().join("guest.sock");
        let _listener = UnixListener::bind(&socket).unwrap();
        fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o750)).unwrap();
        assert!(Endpoint::open(&socket).is_err());
    }

    #[test]
    fn rejects_regular_files_missing_endpoints_and_symlink_leaves() {
        let directory = directory();
        let socket = directory.path().join("guest.sock");
        assert!(Endpoint::open(&socket).is_err());
        fs::write(&socket, b"not a socket").unwrap();
        assert!(Endpoint::open(&socket).is_err());
        fs::remove_file(&socket).unwrap();
        let actual = directory.path().join("actual.sock");
        let _listener = UnixListener::bind(&actual).unwrap();
        symlink(&actual, &socket).unwrap();
        assert!(Endpoint::open(&socket).is_err());
    }

    #[test]
    fn rejects_a_symlink_as_the_socket_directory() {
        let directory = directory();
        let actual = directory.path().join("actual");
        fs::create_dir(&actual).unwrap();
        fs::set_permissions(&actual, fs::Permissions::from_mode(0o700)).unwrap();
        let _listener = UnixListener::bind(actual.join("guest.sock")).unwrap();
        let alias = directory.path().join("alias");
        symlink(&actual, &alias).unwrap();
        assert!(Endpoint::open(&alias.join("guest.sock")).is_err());
    }

    #[test]
    fn directory_replacement_cannot_redirect_a_pinned_endpoint() {
        let directory = directory();
        let original = directory.path().join("original");
        fs::create_dir(&original).unwrap();
        fs::set_permissions(&original, fs::Permissions::from_mode(0o700)).unwrap();
        let original_listener = UnixListener::bind(original.join("guest.sock")).unwrap();
        let endpoint = Endpoint::open(&original.join("guest.sock")).unwrap();
        fs::rename(&original, directory.path().join("moved")).unwrap();
        fs::create_dir(&original).unwrap();
        fs::set_permissions(&original, fs::Permissions::from_mode(0o700)).unwrap();
        let replacement = UnixListener::bind(original.join("guest.sock")).unwrap();
        original_listener.set_nonblocking(true).unwrap();
        replacement.set_nonblocking(true).unwrap();
        let _connected = UnixStream::connect(&endpoint.socket).unwrap();
        assert!(original_listener.accept().is_ok());
        assert_eq!(
            replacement.accept().unwrap_err().kind(),
            std::io::ErrorKind::WouldBlock
        );
    }
}