diff --git a/Guide/src/reference/devices/virtio/virtio-fs.md b/Guide/src/reference/devices/virtio/virtio-fs.md index 8a7dd80baaa..fb6fb1bc2d2 100644 --- a/Guide/src/reference/devices/virtio/virtio-fs.md +++ b/Guide/src/reference/devices/virtio/virtio-fs.md @@ -53,7 +53,8 @@ fixes the remaining guest-visible configuration: | File policy | Direct I/O | | Maximum write | 1 MiB payload plus protocol headers | | Symbolic links | `rw`: created with the exact target; `ro`: `EROFS` | -| Rename flags | Linux host: passed to `renameat2`, so `RENAME_EXCHANGE` swaps two names; Windows host: `EINVAL` | +| Device nodes | `rw`: `mknod` of a character or block device fails with `EPERM`; `ro`: `EROFS` | +| Rename flags | `RENAME_NOREPLACE` or `RENAME_EXCHANGE`: passed to `renameat2` on a Linux host, so `RENAME_EXCHANGE` swaps two names, and `EINVAL` on a Windows host; other flags, such as `RENAME_WHITEOUT`: `EINVAL` | ### Several host directories @@ -290,12 +291,15 @@ other than OpenVMM's own, or dropping OpenVMM's other supplementary groups, needs `CAP_SETUID` and `CAP_SETGID`, for example as ambient capabilities of an unprivileged OpenVMM process. Without them, only a caller whose UID and GID match OpenVMM's filesystem UID and GID can run, and only if OpenVMM has -no other supplementary groups. A request that cannot run as its caller, -because a credential switch fails or the capabilities are missing, fails -with `EPERM`; HostFs never falls back to OpenVMM's identity, groups, or -capabilities. `caller` mode requires a Linux host. Windows has no -per-request POSIX identity to switch to, so OpenVMM rejects -`--mount-owner caller` there. +no other supplementary groups. In a user namespace that does not map every +group, Linux reports each unmapped group as its overflow GID, 65534 by +default, so there OpenVMM counts a supplementary group that reads as the +overflow GID as another group, even for a caller with that GID. A request +that cannot run as its caller, because a credential switch fails or the +capabilities are missing, fails with `EPERM`; HostFs never falls back to +OpenVMM's identity, groups, or capabilities. `caller` mode requires a Linux +host. Windows has no per-request POSIX identity to switch to, so OpenVMM +rejects `--mount-owner caller` there. ```admonish warning The guest kernel reports each caller's identity, and guest root may assume @@ -418,6 +422,14 @@ absolute and parent-relative aliases, does not follow symbolic links or Windows reparse points while resolving guest or saved objects, and enforces read-only mode before invoking a host mutation. +The guest cannot make a device node in a microVM share. Linux lets even an +unprivileged process make a whiteout, character device 0:0, which host +overlay mounts and tools treat as a deleted file, and a privileged OpenVMM +could make any device node. HostFs therefore refuses `mknod` of a character +or block device with `EPERM`, and a rename with `RENAME_WHITEOUT`, which +leaves a whiteout at the old name, with `EINVAL`, before it asks the host. +The standard machine's HostFs passes both to the host. + On Linux, every host operation opens the parent directory of its path with `openat2(RESOLVE_BENEATH | RESOLVE_NO_SYMLINKS)` and applies the operation to the final component without following it, so a share fails to open on a host diff --git a/vm/devices/support/fs/lxutil/src/unix/credentials.rs b/vm/devices/support/fs/lxutil/src/unix/credentials.rs index 3cd9cee0d94..e04d16f912f 100644 --- a/vm/devices/support/fs/lxutil/src/unix/credentials.rs +++ b/vm/devices/support/fs/lxutil/src/unix/credentials.rs @@ -63,7 +63,9 @@ impl FsIdentity { /// than the GID of `identity`, so that it gains no access through the privileges or groups of /// the thread's original identity. Assuming a different identity, or dropping supplementary /// groups, requires `CAP_SETUID` and `CAP_SETGID`. A thread that already has `identity` and no -/// other supplementary groups needs no privilege. +/// other supplementary groups needs no privilege. In a user namespace that does not map every +/// group, the kernel reports each unmapped group as its overflow GID, so there a supplementary +/// group with the overflow GID counts as another group even if `identity` has that GID. /// /// # Errors /// @@ -111,7 +113,9 @@ impl SwitchedCredentials { }; // On an error below, dropping `credentials` restores whatever was already changed. let groups = groups()?; - if groups.iter().any(|&group| group != identity.gid) { + if groups.iter().any(|&group| group != identity.gid) + || (!groups.is_empty() && may_report_other_groups_as(identity.gid)) + { set_groups(&[])?; credentials.groups = Some(groups); } @@ -193,6 +197,44 @@ fn groups() -> lx::Result> { Ok(groups) } +/// Returns whether `getgroups` may report a supplementary group other than `gid` as `gid`. +/// +/// `getgroups` reports each group that the calling thread's user namespace does not map as the +/// kernel's overflow GID. A namespace maps only IDs that its parent maps, so one that maps every +/// ID, as the initial user namespace does, leaves no group unmapped. +fn may_report_other_groups_as(gid: lx::gid_t) -> bool { + // A map that cannot be read may leave groups unmapped, and an overflow GID that cannot be + // read may be any GID. + !std::fs::read_to_string("/proc/self/gid_map").is_ok_and(|map| maps_every_id(&map)) + && overflow_gid().is_none_or(|overflow| overflow == gid) +} + +/// Returns the kernel's overflow GID, from `/proc/sys/kernel/overflowgid`, if it can be read. +fn overflow_gid() -> Option { + std::fs::read_to_string("/proc/sys/kernel/overflowgid") + .ok()? + .trim() + .parse() + .ok() +} + +/// Returns whether `map`, an ID map in the format of `/proc/PID/gid_map`, maps every ID. +/// +/// Each line maps a range of IDs, given by its first ID inside the namespace, its first ID +/// outside, and its length. The kernel refuses overlapping ranges, so they cover every ID +/// exactly when their lengths add up to the number of IDs, `u32::MAX`, since `u32::MAX` itself +/// is not an ID. +fn maps_every_id(map: &str) -> bool { + let mut mapped = 0u64; + for range in map.lines() { + let Some(Ok(length)) = range.split_whitespace().nth(2).map(str::parse::) else { + return false; + }; + mapped += u64::from(length); + } + mapped == u64::from(u32::MAX) +} + /// Sets the calling thread's supplementary groups. fn set_groups(groups: &[lx::gid_t]) -> lx::Result<()> { let count = libc::c_long::try_from(groups.len()).map_err(|_| lx::Error::EINVAL)?; @@ -232,10 +274,16 @@ fn set_capabilities(data: &Capabilities) -> lx::Result<()> { #[cfg(test)] mod tests { use super::*; + use std::io::Read; use std::os::unix::fs::MetadataExt; use std::os::unix::fs::PermissionsExt; + use std::os::unix::process::CommandExt; + use std::path::Path; + use std::process::Command; + use std::process::Stdio; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; + use test_with_tracing::test; const CAP_SETGID: u32 = 6; const CAP_SETUID: u32 = 7; @@ -419,6 +467,129 @@ mod tests { } } + #[test] + fn only_complete_id_maps_map_every_id() { + // The initial user namespace maps every ID, and a nested one may too, in several ranges. + assert!(maps_every_id(" 0 0 4294967295\n")); + assert!(maps_every_id("0 0 1000\n1000 1000 4294966295\n")); + // Namespaces that map some IDs, or none yet. + assert!(!maps_every_id(" 65534 1003 1\n")); + assert!(!maps_every_id("0 1000 1\n1 100000 65536\n")); + assert!(!maps_every_id("")); + // A map that cannot be parsed may leave IDs unmapped. + assert!(!maps_every_id("0 0\n")); + } + + /// In a user namespace that maps the overflow GID to the test's GID and leaves its other + /// groups unmapped, every supplementary group reads as the overflow GID. A switch to that GID + /// cannot tell these groups apart, so without privilege it must fail rather than run the + /// operation with groups that it cannot drop. + #[test] + fn overflow_gid_groups_fail_closed_without_privilege() { + const DIRECTORY: &str = "LXUTIL_TEST_OVERFLOW_GID_DIRECTORY"; + if let Some(directory) = std::env::var_os(DIRECTORY) { + // Wait until the parent has mapped this process's user namespace. + std::io::stdin().read_to_end(&mut Vec::new()).unwrap(); + switch_to_overflow_gid(Path::new(&directory)); + return; + } + + let groups = groups().unwrap(); + if groups.is_empty() { + eprintln!("skipped: the test has no supplementary groups"); + return; + } + let Some(overflow) = overflow_gid() else { + eprintln!("skipped: cannot read the overflow GID"); + return; + }; + // SAFETY: These calls have no preconditions. + let (uid, gid) = unsafe { (libc::geteuid(), libc::getegid()) }; + // A file of another of the test's groups shows whether the operation kept that group. + let directory = tempfile::tempdir().unwrap(); + let probe = directory.path().join("probe"); + std::fs::write(&probe, b"").unwrap(); + let other_group = groups.iter().copied().find(|&group| group != gid); + if other_group + .is_none_or(|group| std::os::unix::fs::chown(&probe, None, Some(group)).is_err()) + { + std::fs::remove_file(&probe).unwrap(); + } + + let mut command = Command::new(std::env::current_exe().unwrap()); + command + .args([ + "--exact", + "unix::credentials::tests::overflow_gid_groups_fail_closed_without_privilege", + "--no-capture", + ]) + .env(DIRECTORY, directory.path()) + .stdin(Stdio::piped()); + // SAFETY: Between fork and exec, the child calls only unshare, which takes only flags and + // is async-signal-safe. + unsafe { + command.pre_exec(|| { + if libc::unshare(libc::CLONE_NEWUSER) == 0 { + Ok(()) + } else { + Err(std::io::Error::last_os_error()) + } + }); + } + let mut child = match command.spawn() { + Ok(child) => child, + Err(err) => { + eprintln!("skipped: cannot create a user namespace: {err}"); + return; + } + }; + // Map the overflow GID to the test's own GID, which leaves its other groups unmapped. + // An unprivileged process must deny setgroups first. + let pid = child.id(); + let mapped = [ + ("setgroups", "deny".to_owned()), + ("uid_map", format!("{uid} {uid} 1")), + ("gid_map", format!("{overflow} {gid} 1")), + ] + .into_iter() + .try_for_each(|(file, map)| std::fs::write(format!("/proc/{pid}/{file}"), map)); + if let Err(err) = mapped { + child.kill().unwrap(); + child.wait().unwrap(); + eprintln!("skipped: cannot map the user namespace: {err}"); + return; + } + drop(child.stdin.take()); + let status = child.wait().unwrap(); + assert!(status.success(), "{status}"); + // The child leaves this file, so that a name that matches no test fails. + assert!(directory.path().join("ran").exists()); + } + + /// Switches to the overflow GID, the thread's own GID in the user namespace of + /// [`overflow_gid_groups_fail_closed_without_privilege`], after recording in `directory` that + /// it ran. `chmod` keeps the `S_ISGID` bit of the probe file there, which belongs to another + /// of the test's groups, only for a member of that group. + fn switch_to_overflow_gid(directory: &Path) { + std::fs::write(directory.join("ran"), b"").unwrap(); + let probe = Some(directory.join("probe")).filter(|probe| probe.exists()); + let identity = FsIdentity::current(); + let groups = groups().unwrap(); + assert_eq!(Some(identity.gid), overflow_gid()); + assert!( + groups.iter().all(|&group| group == identity.gid), + "{groups:?}" + ); + // `Ok(Some(true))` would show that the operation kept another group. + let kept_other_group = with_fs_identity(identity, || { + probe.map(|probe| { + std::fs::set_permissions(&probe, std::fs::Permissions::from_mode(0o2755)).unwrap(); + std::fs::metadata(&probe).unwrap().mode() & libc::S_ISGID != 0 + }) + }); + assert_eq!(kept_other_group, Err(lx::Error::EPERM)); + } + /// Run with `CAP_SETUID` and `CAP_SETGID`, for example as root. #[test] #[ignore = "requires CAP_SETUID and CAP_SETGID"] diff --git a/vm/devices/virtio/virtiofs/src/lib.rs b/vm/devices/virtio/virtiofs/src/lib.rs index e8da5312f1b..a0e65f8eb54 100644 --- a/vm/devices/virtio/virtiofs/src/lib.rs +++ b/vm/devices/virtio/virtiofs/src/lib.rs @@ -186,7 +186,7 @@ impl Fuse for VirtioFs { // Windows and works if the file was deleted. The synthetic root's directory handle has no // backing file, so fall through to the node-based branch for it. let attr = if flags & FUSE_GETATTR_FH != 0 && !self.is_synthetic_root_handle(node_id, fh) { - let file = self.get_file(fh)?; + let file = self.get_file(node_id, fh)?; file.get_attr()? } else if self.is_synthetic_root(node_id) { self.synthetic_root_attr() @@ -213,7 +213,7 @@ impl Fuse for VirtioFs { let statx = if getattr_flags & FUSE_GETATTR_FH != 0 && !self.is_synthetic_root_handle(node_id, fh) { - let file = self.get_file(fh)?; + let file = self.get_file(node_id, fh)?; file.get_statx()? } else if self.is_synthetic_root(node_id) { self.synthetic_root_statx(mask) @@ -235,7 +235,7 @@ impl Fuse for VirtioFs { // If a file handle is specified, set the attributes on the open file. This is faster on // Windows and works if the file was deleted. let attr = if arg.valid & FATTR_FH != 0 { - let file = self.get_file(arg.fh)?; + let file = self.get_file(node_id, arg.fh)?; // Block truncation and other modifications on readonly filesystems if arg.valid & !(FATTR_FH | FATTR_LOCKOWNER) != 0 { self.check_writable(file.inode())?; @@ -366,6 +366,7 @@ impl Fuse for VirtioFs { self.check_writable(&inode)?; let path = inode.child_path(name)?; self.check_writable_entry(&inode, &path)?; + microvm::fs::validate_mknod_type(self, arg.mode)?; self.preflight_new_inode_path(&path)?; let reservation = self.reserve_inode()?; let (new_inode, attr) = @@ -450,8 +451,8 @@ impl Fuse for VirtioFs { inode.read_link() } - fn read(&self, _request: &Request, arg: &fuse_read_in) -> lx::Result> { - let file = self.get_file(arg.fh)?; + fn read(&self, request: &Request, arg: &fuse_read_in) -> lx::Result> { + let file = self.get_file(request.node_id(), arg.fh)?; let mut buffer = guest_buffer(arg.size)?; let size = file.read(&mut buffer, arg.offset)?; buffer.truncate(size); @@ -462,12 +463,14 @@ impl Fuse for VirtioFs { if data.len() > MAX_GUEST_BUFFER_SIZE { return Err(lx::Error::E2BIG); } - let file = self.get_file(arg.fh)?; + let file = self.get_file(request.node_id(), arg.fh)?; self.check_writable(file.inode())?; file.write(data, arg.offset, request.uid()) } fn release(&self, _request: &Request, arg: &fuse_release_in) -> lx::Result<()> { + // Unlike other requests through a handle, this accepts one whose node + // the guest has forgotten (see `get_file`). self.remove_file(arg.fh); Ok(()) } @@ -487,7 +490,7 @@ impl Fuse for VirtioFs { if self.is_synthetic_root_handle(request.node_id(), arg.fh) { return self.read_synthetic_root_dir(arg.offset, arg.size, false); } - let file = self.get_file(arg.fh)?; + let file = self.get_file(request.node_id(), arg.fh)?; file.read_dir(self, arg.offset, arg.size, false) } @@ -495,7 +498,7 @@ impl Fuse for VirtioFs { if self.is_synthetic_root_handle(request.node_id(), arg.fh) { return self.read_synthetic_root_dir(arg.offset, arg.size, true); } - let file = self.get_file(arg.fh)?; + let file = self.get_file(request.node_id(), arg.fh)?; file.read_dir(self, arg.offset, arg.size, true) } @@ -537,6 +540,7 @@ impl Fuse for VirtioFs { let new_path = new_inode.child_path(new_name)?; self.check_writable_entry(&inode, &old_path)?; self.check_writable_entry(&new_inode, &new_path)?; + microvm::fs::validate_rename_flags(self, flags)?; // Renaming a name onto itself changes nothing on the host, which still // fails it as it fails any other rename, such as with ENOENT for a // missing name. Every node keeps its names: the bookkeeping of a move @@ -566,14 +570,14 @@ impl Fuse for VirtioFs { inode.stat_fs() } - fn fsync(&self, _request: &Request, fh: u64, flags: u32) -> lx::Result<()> { - let file = self.get_file(fh)?; + fn fsync(&self, request: &Request, fh: u64, flags: u32) -> lx::Result<()> { + let file = self.get_file(request.node_id(), fh)?; let data_only = flags & FUSE_FSYNC_FDATASYNC != 0; file.fsync(data_only) } - fn fsync_dir(&self, _request: &Request, fh: u64, flags: u32) -> lx::Result<()> { - let file = self.get_file(fh)?; + fn fsync_dir(&self, request: &Request, fh: u64, flags: u32) -> lx::Result<()> { + let file = self.get_file(request.node_id(), fh)?; let data_only = flags & FUSE_FSYNC_FDATASYNC != 0; file.fsync_dir(data_only) } @@ -865,15 +869,34 @@ impl VirtioFs { }) } - /// Retrieve the file object with the specified file handle. - fn get_file(&self, fh: u64) -> lx::Result> { - let files = self.inner.files.read(); - let file = files.get(fh).ok_or_else(|| { + /// Retrieves the open file `fh` of a request about the node `node_id`. + /// + /// The handle must have been opened on that node, and the guest must still + /// hold the node. The inode table keeps the paths and aliases of the nodes + /// that it holds current through renames and removals, and they decide + /// what a request through one of a node's handles may do, such as whether + /// it may write (see [`Self::check_writable`]) and where `READDIRPLUS` + /// looks up the entries that it lists. The names of a forgotten node, + /// which leaves the table, go stale, and another node's names are not the + /// handle's. Unlike [`Self::get_inode`], this does not revalidate the + /// node's paths, since the handle reaches its file without them, even once + /// the file is unlinked. `RELEASE` does not call this: closing a handle + /// uses neither the node nor its names, and refusing it would leak the + /// handle. + fn get_file(&self, node_id: u64, fh: u64) -> lx::Result> { + let file = self.inner.files.read().get(fh).cloned().ok_or_else(|| { tracelimit::warn_ratelimited!(fh, "Request for unknown file"); lx::Error::EBADF })?; - - Ok(Arc::clone(file)) + let inode = self.inner.inodes.read().get(node_id).ok_or_else(|| { + tracelimit::warn_ratelimited!(node_id, fh, "request for a file of an unknown inode"); + lx::Error::EINVAL + })?; + if !Arc::ptr_eq(&inode, &file.inode) { + tracelimit::warn_ratelimited!(node_id, fh, "request for a file of another inode"); + return Err(lx::Error::EBADF); + } + Ok(file) } /// Reserve a file handle before opening or creating a host file. diff --git a/vm/devices/virtio/virtiofs/src/microvm/device_node_tests.rs b/vm/devices/virtio/virtiofs/src/microvm/device_node_tests.rs new file mode 100644 index 00000000000..6b7f0c7b972 --- /dev/null +++ b/vm/devices/virtio/virtiofs/src/microvm/device_node_tests.rs @@ -0,0 +1,198 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Tests that the guest makes no device node on a microVM share: `mknod` +//! makes only regular files, FIFOs, and sockets, and a rename leaves no +//! whiteout behind. + +use super::policy_tests::name; +use super::policy_tests::request; +use super::profile::MICROVM_ATTACHMENT_ID; +use super::profile::MicroVmVirtioFsProfile; +use super::profile::microvm_root_identity; +use crate::RENAME_EXCHANGE; +use crate::VirtioFs; +use fuse::Fuse; +use fuse::protocol::FUSE_ROOT_ID; +use fuse::protocol::fuse_mknod_in; +use std::fs::FileType; +use std::path::PathBuf; +use tempfile::TempDir; +use tempfile::tempdir; +use test_with_tracing::test; + +/// Linux's `RENAME_NOREPLACE` flag for `renameat2`, which refuses to replace +/// an existing name. +const RENAME_NOREPLACE: u32 = 1; + +/// Linux's `RENAME_WHITEOUT` flag for `renameat2`, which leaves a whiteout, +/// character device 0:0, at the old name. +const RENAME_WHITEOUT: u32 = 4; + +/// Linux's `/dev/null`, character device 1:3, as the guest kernel encodes it +/// in `FUSE_MKNOD`. +const DEV_NULL: u32 = (1 << 8) | 3; + +/// Linux's `/dev/loop0`, block device 7:0, as the guest kernel encodes it in +/// `FUSE_MKNOD`. +const DEV_LOOP0: u32 = 7 << 8; + +/// A read-write microVM share without an access policy, which holds the file +/// `existing`. +struct Share { + _directory: TempDir, + root: PathBuf, + fs: VirtioFs, +} + +impl Share { + fn new() -> Self { + let directory = tempdir().unwrap(); + let root = directory.path().join("share"); + std::fs::create_dir(&root).unwrap(); + std::fs::write(root.join("existing"), "existing").unwrap(); + let profile = MicroVmVirtioFsProfile::from_attachment( + MICROVM_ATTACHMENT_ID.to_owned(), + microvm_root_identity(&root).unwrap(), + false, + Vec::new(), + ) + .unwrap(); + let fs = VirtioFs::new_microvm(&root, profile).unwrap(); + Self { + _directory: directory, + root, + fs, + } + } + + /// Makes the node `node` of type and mode `mode` and device `rdev` in the + /// share's root with `FUSE_MKNOD`. + fn mknod(&self, node: &str, mode: u32, rdev: u32) -> lx::Result<()> { + let arg = fuse_mknod_in { + mode, + rdev, + umask: 0, + padding: 0, + }; + self.fs.mknod(&request(FUSE_ROOT_ID), name(node), &arg)?; + Ok(()) + } + + /// Renames `from` to `to` in the share's root with `FUSE_RENAME2`. + fn rename(&self, from: &str, to: &str, flags: u32) -> lx::Result<()> { + self.fs.rename( + &request(FUSE_ROOT_ID), + name(from), + FUSE_ROOT_ID, + name(to), + flags, + ) + } + + /// Returns the names in the share's host directory, sorted. + fn entries(&self) -> Vec { + let mut names = std::fs::read_dir(&self.root) + .unwrap() + .map(|entry| entry.unwrap().file_name().into_string().unwrap()) + .collect::>(); + names.sort(); + names + } + + fn read(&self, file: &str) -> String { + std::fs::read_to_string(self.root.join(file)).unwrap() + } + + /// Returns the host file type of `node`, without following a link. + fn file_type(&self, node: &str) -> FileType { + std::fs::symlink_metadata(self.root.join(node)) + .unwrap() + .file_type() + } +} + +/// Linux lets a caller without `CAP_MKNOD` make a whiteout, character device +/// 0:0, and a privileged one any device, so HostFs refuses every character +/// and block device with `EPERM`, as Linux does where it denies a device, +/// before it asks the host: an existing name fails with `EPERM`, not the +/// host's `EEXIST`. Other types fail as `mknod(2)` fails them: a directory +/// with `EPERM`, and a symbolic link or an invalid type with `EINVAL`. +#[test] +fn mknod_makes_no_device_node() { + let share = Share::new(); + for (kind, rdev, expected) in [ + (lx::S_IFCHR, 0, lx::Error::EPERM), + (lx::S_IFCHR, DEV_NULL, lx::Error::EPERM), + (lx::S_IFBLK, DEV_LOOP0, lx::Error::EPERM), + (lx::S_IFDIR, 0, lx::Error::EPERM), + (lx::S_IFLNK, 0, lx::Error::EINVAL), + (0o030000, 0, lx::Error::EINVAL), + ] { + for node in ["node", "existing"] { + assert_eq!( + share.mknod(node, kind | 0o600, rdev), + Err(expected), + "{node}: mode {kind:#o}, device {rdev:#x}" + ); + } + } + assert_eq!(share.entries(), ["existing"]); + assert_eq!(share.read("existing"), "existing"); + + // Regular files remain, and on Linux FIFOs and sockets, with a type of 0 + // making a regular file, as for `mknod(2)`. Windows hosts make only + // regular files. + share.mknod("regular", lx::S_IFREG | 0o600, 0).unwrap(); + assert!(share.file_type("regular").is_file()); + #[cfg(unix)] + { + use std::os::unix::fs::FileTypeExt; + share.mknod("untyped", 0o600, 0).unwrap(); + assert!(share.file_type("untyped").is_file()); + share.mknod("fifo", lx::S_IFIFO | 0o600, 0).unwrap(); + assert!(share.file_type("fifo").is_fifo()); + share.mknod("socket", lx::S_IFSOCK | 0o600, 0).unwrap(); + assert!(share.file_type("socket").is_socket()); + } +} + +/// `RENAME_WHITEOUT` leaves a whiteout, character device 0:0, at the old +/// name, which Linux lets a caller without `CAP_MKNOD` make, so HostFs passes +/// the host only `RENAME_NOREPLACE` or `RENAME_EXCHANGE`, and fails any other +/// flags with `EINVAL`, as Linux fails a flag that a filesystem does not +/// support or those two flags together, changing neither name, even for a +/// rename of a name onto itself. +#[test] +fn rename_leaves_no_whiteout() { + let share = Share::new(); + for flags in [ + RENAME_WHITEOUT, + RENAME_WHITEOUT | RENAME_NOREPLACE, + RENAME_NOREPLACE | RENAME_EXCHANGE, + 1 << 3, + ] { + for to in ["moved", "existing"] { + assert_eq!( + share.rename("existing", to, flags), + Err(lx::Error::EINVAL), + "{to}: flags {flags:#x}" + ); + } + } + assert_eq!(share.entries(), ["existing"]); + assert_eq!(share.read("existing"), "existing"); + + // RENAME_NOREPLACE still reaches the host, which refuses to replace a + // name. Windows hosts reject every rename flag with EINVAL. + std::fs::write(share.root.join("other"), "other").unwrap(); + let replace = share.rename("existing", "other", RENAME_NOREPLACE); + if cfg!(windows) { + assert_eq!(replace, Err(lx::Error::EINVAL)); + } else { + assert_eq!(replace, Err(lx::Error::EEXIST)); + share.rename("existing", "moved", RENAME_NOREPLACE).unwrap(); + assert_eq!(share.entries(), ["moved", "other"]); + assert_eq!(share.read("moved"), "existing"); + } +} diff --git a/vm/devices/virtio/virtiofs/src/microvm/file.rs b/vm/devices/virtio/virtiofs/src/microvm/file.rs index 009ec858217..67c0503e918 100644 --- a/vm/devices/virtio/virtiofs/src/microvm/file.rs +++ b/vm/devices/virtio/virtiofs/src/microvm/file.rs @@ -13,6 +13,7 @@ use crate::VirtioFs; use crate::file::DirectorySnapshot; use crate::file::VirtioFsFile; use fuse::DirEntryWriter; +use fuse::Fuse; use fuse::protocol::fuse_entry_out; use parking_lot::Mutex; use std::sync::Arc; @@ -138,26 +139,17 @@ impl VirtioFsFile { break; } } else { - // This check must happen before insert_lookup, because a - // readdirplus lookup creates a guest lookup reference. - if !buffer.check_dir_entry_plus(name) { - break; - } - let (child, attr) = self.inode.lookup_child(name)?; - // The snapshot numbers each entry as an object of this - // directory's host device. The host lists a mount point or - // a btrfs subvolume, whose lookup reaches another device, - // by the number of another object, so only an entry on - // this directory's device shows whether the name still - // reaches the listed object. - if child.device_nr() == self.inode.device_nr() - && attr.ino != entry.guest_inode_id - { - return Err(lx::Error::EIO); - } - let fuse_entry = fs.insert_lookup(child, attr)?; - if !buffer.dir_entry_plus(name, entry.next_cookie, fuse_entry) { - return Err(lx::Error::EIO); + match self.write_microvm_entry_plus(fs, &mut buffer, entry) { + Ok(true) => {} + Ok(false) => break, + // Each entry in the reply hands the guest a lookup + // reference, which the guest can release only if it + // receives the entry. So, as in `read_dir_with`, return + // the entries read so far, and report the error only if + // there are none; the guest's next read starts at the + // failing entry. + Err(error) if buffer.is_empty() => return Err(error), + Err(_) => break, } } } else if !buffer.dir_entry(name, entry.guest_inode_id, entry.next_cookie, entry.kind) { @@ -171,6 +163,44 @@ impl VirtioFsFile { Ok(buffer) } + /// Writes the readdirplus entry of `entry`, an entry of this directory's + /// snapshot other than `.` and `..`, to `buffer`, and returns whether it + /// fit. + /// + /// The entry's lookup takes the lookup reference that the entry hands to + /// the guest, so the reference is held only if the entry is written: an + /// entry that does not fit, or that fails, holds none. + fn write_microvm_entry_plus( + &self, + fs: &VirtioFs, + buffer: &mut Vec, + entry: &SavedDirectoryEntry, + ) -> lx::Result { + let name = lx::LxStr::from_bytes(&entry.name); + // This check must happen before insert_lookup, because a + // readdirplus lookup creates a guest lookup reference. + if !buffer.check_dir_entry_plus(name) { + return Ok(false); + } + let (child, attr) = self.inode.lookup_child(name)?; + // The snapshot numbers each entry as an object of this directory's + // host device. The host lists a mount point or a btrfs subvolume, + // whose lookup reaches another device, by the number of another + // object, so only an entry on this directory's device shows whether + // the name still reaches the listed object. + if child.device_nr() == self.inode.device_nr() && attr.ino != entry.guest_inode_id { + return Err(lx::Error::EIO); + } + let fuse_entry = fs.insert_lookup(child, attr)?; + let node_id = fuse_entry.nodeid; + if !buffer.dir_entry_plus(name, entry.next_cookie, fuse_entry) { + // The guest never receives the entry, so release its reference. + fs.forget(node_id, 1); + return Err(lx::Error::EIO); + } + Ok(true) + } + fn build_microvm_directory_snapshot(&self) -> lx::Result> { let stat = self.object_stat()?; if stat.mode & lx::S_IFMT != lx::S_IFDIR { diff --git a/vm/devices/virtio/virtiofs/src/microvm/fs.rs b/vm/devices/virtio/virtiofs/src/microvm/fs.rs index a9690f5ae1b..e5210633d27 100644 --- a/vm/devices/virtio/virtiofs/src/microvm/fs.rs +++ b/vm/devices/virtio/virtiofs/src/microvm/fs.rs @@ -38,6 +38,7 @@ use crate::ENTRY_TIMEOUT; use crate::FuseNegotiation; use crate::HandleMap; use crate::InodeMap; +use crate::RENAME_EXCHANGE; use crate::VirtioFs; use crate::VirtioFsInner; use crate::VirtioFsMode; @@ -95,6 +96,10 @@ pub(crate) fn configure_session(fs: &VirtioFs, info: &mut SessionInfo) { /// The longest symbolic link target, in bytes, that Linux accepts. const MAX_SYMLINK_TARGET_BYTES: usize = 4095; +/// Linux's `RENAME_NOREPLACE` flag for `renameat2`, which refuses to replace +/// an existing name. +const RENAME_NOREPLACE: u32 = 1; + /// Validates a guest symbolic link target without rewriting it. pub(crate) fn validate_symlink_target(fs: &VirtioFs, target: &lx::LxStr) -> lx::Result<()> { // The microVM volume never follows a symbolic link while resolving a host @@ -113,6 +118,39 @@ pub(crate) fn validate_symlink_target(fs: &VirtioFs, target: &lx::LxStr) -> lx:: Ok(()) } +/// Validates the file type of a node that the guest makes with `mknod`. +/// +/// A microVM guest makes only regular files, which a type of 0 also makes, +/// FIFOs, and sockets. Linux lets a caller without `CAP_MKNOD` make a +/// whiteout, character device 0:0, and a privileged OpenVMM could make any +/// device node, so character and block devices fail with `EPERM`, as Linux +/// fails a device that it denies, before the host is asked. The other types +/// fail as `mknod(2)` fails them, so that every host reports the same errors. +pub(crate) fn validate_mknod_type(fs: &VirtioFs, mode: u32) -> lx::Result<()> { + if !fs.is_microvm() { + return Ok(()); + } + match mode & lx::S_IFMT { + 0 | lx::S_IFREG | lx::S_IFIFO | lx::S_IFSOCK => Ok(()), + lx::S_IFCHR | lx::S_IFBLK | lx::S_IFDIR => Err(lx::Error::EPERM), + _ => Err(lx::Error::EINVAL), + } +} + +/// Validates the flags of a guest rename. +/// +/// `RENAME_WHITEOUT` leaves a whiteout, character device 0:0, at the old +/// name, which [`validate_mknod_type`] refuses to make, so a microVM rename +/// passes the host no flag, `RENAME_NOREPLACE`, or `RENAME_EXCHANGE`, and +/// fails with `EINVAL` otherwise, as Linux fails a flag that a filesystem +/// does not support, or those two flags together. +pub(crate) fn validate_rename_flags(fs: &VirtioFs, flags: u32) -> lx::Result<()> { + if fs.is_microvm() && !matches!(flags, 0 | RENAME_NOREPLACE | RENAME_EXCHANGE) { + return Err(lx::Error::EINVAL); + } + Ok(()) +} + pub(crate) fn insert_inode( fs: &VirtioFs, inodes: &mut InodeMap, diff --git a/vm/devices/virtio/virtiofs/src/microvm/fs_tests.rs b/vm/devices/virtio/virtiofs/src/microvm/fs_tests.rs index acf3947d606..08d7a557a53 100644 --- a/vm/devices/virtio/virtiofs/src/microvm/fs_tests.rs +++ b/vm/devices/virtio/virtiofs/src/microvm/fs_tests.rs @@ -22,7 +22,9 @@ use super::state::validate_microvm_state; use super::state::validate_relative_path; use crate::InodeMap; use crate::VirtioFs; +use crate::file::VirtioFsFile; use crate::inode::VirtioFsInode; +use crate::test_helpers::decode_dir_entries; use fuse::Fuse; use fuse::Session; use fuse::SessionInfoState; @@ -386,6 +388,110 @@ fn retyped_object_is_not_bound_by_the_alias_limit_of_the_tracked_inode() { } } +/// Returns a microVM filesystem of `root_path`, whose root holds the regular +/// files `names`, with an open handle of the root. +fn microvm_with_an_open_root(root_path: &Path, names: &[&str]) -> (VirtioFs, Arc) { + for name in names { + std::fs::write(root_path.join(name), name).unwrap(); + } + let fs = VirtioFs::new_microvm(root_path, profile(root_path)).unwrap(); + let root = fs.get_inode(FUSE_ROOT_ID).unwrap(); + let handle = fs.insert_file(root.open(lx::O_RDONLY).unwrap()).unwrap(); + let directory = fs.get_file(FUSE_ROOT_ID, handle).unwrap(); + (fs, directory) +} + +/// Each READDIRPLUS entry other than `.` and `..` hands the guest a lookup +/// reference, which the guest can release only if it receives the entry. A +/// READDIRPLUS that fails at an entry, here because the inode limit refuses +/// the entry's node, must therefore return the entries that it has looked up, +/// and fail only the next read, which starts at the failing entry. Once the +/// guest forgets those entries, the listing goes on. +#[test] +fn readdirplus_stopped_by_the_inode_limit_returns_the_entries_it_looked_up() { + let temporary_directory = tempdir().unwrap(); + let names = ["first", "second"]; + let (fs, directory) = microvm_with_an_open_root(temporary_directory.path(), &names); + // Leave room for one more node. + track_inodes_up_to_the_limit(&fs, directory.inode()); + let filler = *fs + .inner + .inodes + .read() + .inodes_by_node_id + .values + .keys() + .max() + .unwrap(); + fs.forget(filler, 1); + + let entries = decode_dir_entries(&directory.read_dir(&fs, 0, 4096, true).unwrap()); + let children: Vec<_> = entries + .iter() + .filter(|entry| entry.name != "." && entry.name != "..") + .collect(); + assert_eq!(children.len(), 1); + let child = children[0]; + assert_ne!(child.node_id, 0); + let offset = entries.last().unwrap().offset; + assert_eq!( + directory.read_dir(&fs, offset, 4096, true).unwrap_err(), + lx::Error::ENOSPC + ); + + fs.forget(child.node_id, 1); + let rest = decode_dir_entries(&directory.read_dir(&fs, offset, 4096, true).unwrap()); + let rest: Vec<_> = rest + .iter() + .map(|entry| entry.name.as_str()) + .filter(|name| *name != "." && *name != "..") + .collect(); + let other = names.into_iter().find(|name| *name != child.name).unwrap(); + assert_eq!(rest, [other]); +} + +/// A READDIRPLUS that fails at a listed name that no longer reaches the +/// listed object, here because a new file replaced it, must leave the guest +/// every lookup reference that it took: once the guest forgets each entry that +/// it received, only the root's node remains. +#[test] +fn readdirplus_of_a_replaced_entry_keeps_no_reference_the_guest_lacks() { + let temporary_directory = tempdir().unwrap(); + let root_path = temporary_directory.path(); + let (fs, directory) = microvm_with_an_open_root(root_path, &["first", "second", "third"]); + // A plain READDIR lists the directory without looking its entries up. + directory.read_dir(&fs, 0, 4096, false).unwrap(); + // Replace the last listed entry, which READDIRPLUS reaches after it looks + // the others up, with a file that exists alongside it until the rename, + // so that the host numbers the two differently. + let replaced = directory + .directory_entries() + .into_iter() + .map(|entry| entry.name) + .rfind(|name| name != b"." && name != b"..") + .unwrap(); + let replaced = root_path.join(String::from_utf8(replaced).unwrap()); + std::fs::write(root_path.join("replacement"), "replacement").unwrap(); + std::fs::rename(root_path.join("replacement"), replaced).unwrap(); + + // Read on as the guest does, until the listing ends or fails, and forget + // each entry received. + let mut offset = 0; + while let Ok(reply) = directory.read_dir(&fs, offset, 4096, true) { + let entries = decode_dir_entries(&reply); + let Some(last) = entries.last() else { + break; + }; + offset = last.offset; + for entry in entries { + if entry.node_id != 0 { + fs.forget(entry.node_id, 1); + } + } + } + assert_eq!(fs.inner.inodes.read().inodes_by_node_id.values.len(), 1); +} + #[test] fn saved_negotiation_must_match_the_exact_microvm_policy() { let temporary_directory = tempdir().unwrap(); @@ -487,7 +593,7 @@ fn directory_snapshot_survives_host_mutation_after_restore() { let handle = source .insert_file(Arc::clone(&root).open(lx::O_RDONLY).unwrap()) .unwrap(); - let file = source.get_file(handle).unwrap(); + let file = source.get_file(FUSE_ROOT_ID, handle).unwrap(); let first_page = file.read_dir(&source, 0, 32, false).unwrap(); assert!(!first_page.is_empty()); @@ -511,7 +617,7 @@ fn directory_snapshot_survives_host_mutation_after_restore() { .restore_microvm_state(&profile, state, &session) .unwrap(); let continuation = destination - .get_file(handle) + .get_file(FUSE_ROOT_ID, handle) .unwrap() .read_dir(&destination, continuation_offset, 4096, false) .unwrap(); @@ -820,7 +926,7 @@ fn snapshot_without_device_keys_restores_its_numbers() { .insert_file(sys_inode.open(lx::O_RDONLY | lx::O_DIRECTORY).unwrap()) .unwrap(); source - .get_file(handle) + .get_file(sys.nodeid, handle) .unwrap() .read_dir(&source, 0, 4096, false) .unwrap(); @@ -881,7 +987,7 @@ fn snapshot_without_device_keys_restores_its_numbers() { // except for a mount point, whose lookup reaches another device. let entries = crate::tests::read_directory( &destination, - &destination.get_file(handle).unwrap(), + &destination.get_file(sys.nodeid, handle).unwrap(), 0, 4096, true, @@ -938,7 +1044,13 @@ fn readdirplus_lists_mount_points() { .unwrap(), ) .unwrap(); - let entries = crate::tests::read_directory(&fs, &fs.get_file(handle).unwrap(), 0, 4096, true); + let entries = crate::tests::read_directory( + &fs, + &fs.get_file(FUSE_ROOT_ID, handle).unwrap(), + 0, + 4096, + true, + ); for name in ["proc", "sys"] { let lookup = fs .lookup_helper(&root, lx::LxStr::from_bytes(name.as_bytes())) diff --git a/vm/devices/virtio/virtiofs/src/microvm/mod.rs b/vm/devices/virtio/virtiofs/src/microvm/mod.rs index 9006c2edf96..fc2820ab503 100644 --- a/vm/devices/virtio/virtiofs/src/microvm/mod.rs +++ b/vm/devices/virtio/virtiofs/src/microvm/mod.rs @@ -7,6 +7,8 @@ mod aggregate_fs_tests; pub(crate) mod device; #[cfg(test)] +mod device_node_tests; +#[cfg(test)] mod exchange_tests; pub(crate) mod file; pub(crate) mod fs; diff --git a/vm/devices/virtio/virtiofs/src/microvm/policy_tests.rs b/vm/devices/virtio/virtiofs/src/microvm/policy_tests.rs index 142e7461079..bf6bf31262d 100644 --- a/vm/devices/virtio/virtiofs/src/microvm/policy_tests.rs +++ b/vm/devices/virtio/virtiofs/src/microvm/policy_tests.rs @@ -17,10 +17,13 @@ use fuse::Fuse; use fuse::Request; use fuse::Session; use fuse::SessionState; +use fuse::protocol::FATTR_FH; use fuse::protocol::FATTR_MODE; use fuse::protocol::FATTR_SIZE; +use fuse::protocol::FUSE_GETATTR_FH; use fuse::protocol::FUSE_LOOKUP; use fuse::protocol::FUSE_ROOT_ID; +use fuse::protocol::StatxFlags; use fuse::protocol::fuse_create_in; use fuse::protocol::fuse_in_header; use fuse::protocol::fuse_mkdir_in; @@ -433,6 +436,148 @@ fn a_create_of_an_existing_name_opens_it_as_open_does() { share.assert_protected_paths_unchanged(); } +/// Sends each request that names an open file's handle, `fh`, as a request +/// about the node `node_id`, and returns each request's name and result. +fn file_handle_requests( + fs: &VirtioFs, + node_id: u64, + fh: u64, +) -> Vec<(&'static str, lx::Result<()>)> { + let node = request(node_id); + let mut read = fuse_read_in::new_zeroed(); + read.fh = fh; + read.size = 64; + let truncate = setattr(FATTR_FH | FATTR_SIZE, |arg| { + arg.fh = fh; + arg.size = 1; + }); + vec![ + ("GETATTR", fs.get_attr(&node, FUSE_GETATTR_FH, fh).map(drop)), + ( + "STATX", + fs.get_statx( + &node, + fh, + FUSE_GETATTR_FH, + StatxFlags::new(), + lx::StatExMask::new(), + ) + .map(drop), + ), + ("SETATTR", fs.set_attr(&node, &truncate).map(drop)), + ("READ", fs.read(&node, &read).map(drop)), + ("WRITE", write(fs, node_id, fh, b"x").map(drop)), + ("FSYNC", fs.fsync(&node, fh, 0)), + ] +} + +/// Sends each request that names an open directory's handle, `fh`, as a +/// request about the node `node_id`, and returns each request's name and +/// result. +fn directory_handle_requests( + fs: &VirtioFs, + node_id: u64, + fh: u64, +) -> Vec<(&'static str, lx::Result<()>)> { + let node = request(node_id); + let mut read = fuse_read_in::new_zeroed(); + read.fh = fh; + read.size = 4096; + vec![ + ("READDIR", fs.read_dir(&node, &read).map(drop)), + ("READDIRPLUS", fs.read_dir_plus(&node, &read).map(drop)), + ("FSYNCDIR", fs.fsync_dir(&node, fh, 0)), + ] +} + +/// A request through a handle must name the node that the handle was opened +/// on, and the guest must still hold that node: HostFs keeps the names of the +/// nodes that the guest holds current, and they decide what a request through +/// the handle may do, such as whether it may write. So a request with another +/// node fails with `EBADF`, and one with a node that the guest forgot fails +/// with `EINVAL`, as other requests about a forgotten node do. The guest can +/// still release such a handle, which uses no name, so that it does not leak. +#[test] +fn a_handle_serves_only_its_node_while_the_guest_holds_it() { + let share = Share::new(); + std::fs::create_dir(share.path("out/directory")).unwrap(); + let fs = share.fs(&[], &[], &["out"]); + let out = lookup(&fs, "out").unwrap(); + let file = lookup(&fs, "out/existing").unwrap(); + let directory = lookup(&fs, "out/directory").unwrap(); + let marker = lookup(&fs, "marker").unwrap(); + let file_handle = open(&fs, file, lx::O_RDWR).unwrap(); + let directory_handle = fs + .open_dir(&request(directory), lx::O_RDONLY as u32) + .unwrap() + .fh; + let requests = |file_node, directory_node| { + let mut sent = file_handle_requests(&fs, file_node, file_handle); + sent.extend(directory_handle_requests( + &fs, + directory_node, + directory_handle, + )); + sent + }; + + // Each request that names the handle's node succeeds, even once the file + // is unlinked, since the handle reaches its file without a name. + fs.unlink(&request(out), name("existing")).unwrap(); + for (operation, result) in requests(file, directory) { + assert!(result.is_ok(), "{operation}: {result:?}"); + } + + // Another node's ID. + for (operation, result) in requests(marker, marker) { + assert_eq!(error(result), lx::Error::EBADF, "{operation}"); + } + + // The IDs of the handles' nodes, once the guest forgets them. + fs.forget(file, 1); + fs.forget(directory, 1); + for (operation, result) in requests(file, directory) { + assert_eq!(error(result), lx::Error::EINVAL, "{operation}"); + } + + release(&fs, file, file_handle); + let mut arg = fuse_release_in::new_zeroed(); + arg.fh = directory_handle; + fs.release_dir(&request(directory), &arg).unwrap(); + assert_eq!(error(write(&fs, file, file_handle, b"x")), lx::Error::EBADF); + share.assert_protected_paths_unchanged(); +} + +/// An object is writable only while every name that the guest has used for it +/// is. A guest that forgets the node of an open handle and looks the object up +/// again at a read-only name gets a new node, whose names the forgotten node +/// never learns, so the handle must write through neither node. +#[test] +fn a_handle_of_a_forgotten_node_cannot_write_a_read_only_file() { + let share = Share::new(); + // A host hard link puts the read-only `marker` inside the writable path. + std::fs::hard_link(share.path("marker"), share.path("out/link")).unwrap(); + let fs = share.fs(&[], &[], &["out"]); + let link = lookup(&fs, "out/link").unwrap(); + let fh = open(&fs, link, lx::O_RDWR).unwrap(); + + fs.forget(link, 1); + let marker = lookup(&fs, "marker").unwrap(); + assert_ne!(marker, link); + assert_eq!(error(open(&fs, marker, lx::O_RDWR)), lx::Error::EROFS); + for (node_id, expected) in [(link, lx::Error::EINVAL), (marker, lx::Error::EBADF)] { + assert_eq!(error(write(&fs, node_id, fh, b"guest")), expected); + let truncate = setattr(FATTR_FH | FATTR_SIZE, |arg| { + arg.fh = fh; + arg.size = 0; + }); + assert_eq!(error(fs.set_attr(&request(node_id), &truncate)), expected); + } + + release(&fs, link, fh); + assert_eq!(share.read("marker"), "host"); +} + #[test] fn allowed_paths_stay_readable_inside_a_hidden_subtree() { let share = Share::new(); diff --git a/vm/devices/virtio/virtiofs/src/microvm/symlink_tests.rs b/vm/devices/virtio/virtiofs/src/microvm/symlink_tests.rs index d22d5874079..f063c5617e4 100644 --- a/vm/devices/virtio/virtiofs/src/microvm/symlink_tests.rs +++ b/vm/devices/virtio/virtiofs/src/microvm/symlink_tests.rs @@ -431,7 +431,7 @@ fn readdirplus_returns_usable_symlink_nodes() { .unwrap(); let entries = fs - .get_file(handle) + .get_file(FUSE_ROOT_ID, handle) .unwrap() .read_dir(&fs, 0, 4096, true) .unwrap();