diff --git a/vm/devices/support/fs/lxutil/src/lib.rs b/vm/devices/support/fs/lxutil/src/lib.rs index 835e8356f84..66387b2c345 100644 --- a/vm/devices/support/fs/lxutil/src/lib.rs +++ b/vm/devices/support/fs/lxutil/src/lib.rs @@ -500,10 +500,10 @@ impl LxVolume { /// Extended attribute names are not case sensitive. They are stored as upper case in NTFS but /// `list_xattr` will report them as lower case for greater compatibility with Linux. /// - /// Extended attribute names are prefixed with "LX.", and have a slightly shorter maximum length - /// limit than Linux. Attribute values are prefixed with a 4-byte header to allow for "empty" - /// values, which NTFS does not normally allow. `get_xattr` and `list_xattr` will strip these - /// prefixes. + /// Extended attribute names are prefixed with "LX.", so they can be at most 251 bytes long + /// rather than 255 as on Linux; longer names fail with `ERANGE`. Attribute values are prefixed + /// with a 4-byte header to allow for "empty" values, which NTFS does not normally allow. + /// `get_xattr` and `list_xattr` will strip these prefixes. /// /// Security for accessing the various attribute namespaces is not enforced. /// @@ -531,10 +531,10 @@ impl LxVolume { /// Extended attribute names are not case sensitive. They are stored as upper case in NTFS but /// `list_xattr` will report them as lower case for greater compatibility with Linux. /// - /// Extended attribute names are prefixed with "LX.", and have a slightly shorter maximum length - /// limit than Linux. Attribute values are prefixed with a 4-byte header to allow for "empty" - /// values, which NTFS does not normally allow. `get_xattr` and `list_xattr` will strip these - /// prefixes. + /// Extended attribute names are prefixed with "LX.", so they can be at most 251 bytes long + /// rather than 255 as on Linux; longer names fail with `ERANGE`. Attribute values are prefixed + /// with a 4-byte header to allow for "empty" values, which NTFS does not normally allow. + /// `get_xattr` and `list_xattr` will strip these prefixes. /// /// Security for accessing the various attribute namespaces is not enforced. pub fn get_xattr( @@ -557,10 +557,10 @@ impl LxVolume { /// Extended attribute names are not case sensitive. They are stored as upper case in NTFS but /// `list_xattr` will report them as lower case for greater compatibility with Linux. /// - /// Extended attribute names are prefixed with "LX.", and have a slightly shorter maximum length - /// limit than Linux. Attribute values are prefixed with a 4-byte header to allow for "empty" - /// values, which NTFS does not normally allow. `get_xattr` and `list_xattr` will strip these - /// prefixes. + /// Extended attribute names are prefixed with "LX.", so they can be at most 251 bytes long + /// rather than 255 as on Linux; longer names fail with `ERANGE`. Attribute values are prefixed + /// with a 4-byte header to allow for "empty" values, which NTFS does not normally allow. + /// `get_xattr` and `list_xattr` will strip these prefixes. /// /// Security for accessing the various attribute namespaces is not enforced. pub fn list_xattr(&self, path: impl AsRef, list: Option<&mut [u8]>) -> lx::Result { @@ -574,10 +574,10 @@ impl LxVolume { /// Extended attribute names are not case sensitive. They are stored as upper case in NTFS but /// `list_xattr` will report them as lower case for greater compatibility with Linux. /// - /// Extended attribute names are prefixed with "LX.", and have a slightly shorter maximum length - /// limit than Linux. Attribute values are prefixed with a 4-byte header to allow for "empty" - /// values, which NTFS does not normally allow. `get_xattr` and `list_xattr` will strip these - /// prefixes. + /// Extended attribute names are prefixed with "LX.", so they can be at most 251 bytes long + /// rather than 255 as on Linux; longer names fail with `ERANGE`. Attribute values are prefixed + /// with a 4-byte header to allow for "empty" values, which NTFS does not normally allow. + /// `get_xattr` and `list_xattr` will strip these prefixes. /// /// Security for accessing the various attribute namespaces is not enforced. pub fn remove_xattr( @@ -1835,6 +1835,39 @@ mod tests { ); } + /// Like Linux's `symlink(2)`, creating a symbolic link to an empty target + /// fails with `ENOENT` and creates nothing. On Windows, the empty target, + /// which names the link's own directory, would otherwise get an NT link + /// from a volume that does not confine paths, and a WSL-style link from + /// one that does. + #[test] + fn symlink_rejects_an_empty_target() { + for confine_paths in [false, true] { + let env = TestEnv::with_options(LxVolumeOptions::new().confine_paths(confine_paths)); + env.create_file("testdir/testfile", "test"); + let link = Path::from_lx("testdir/link").unwrap(); + assert_eq!( + env.volume + .symlink(&link, "", LxCreateOptions::new(0, 0, 0)) + .unwrap_err(), + lx::Error::ENOENT, + "confine_paths={confine_paths}" + ); + assert_eq!( + env.volume + .symlink_stat(&link, "", LxCreateOptions::new(0, 0, 0)) + .unwrap_err(), + lx::Error::ENOENT, + "confine_paths={confine_paths}" + ); + assert_eq!( + env.volume.lstat(&link).unwrap_err(), + lx::Error::ENOENT, + "confine_paths={confine_paths}" + ); + } + } + #[test] fn symlink_ancestors_are_not_walked() { fn expect_traversal_error(result: lx::Result) { @@ -2365,6 +2398,25 @@ mod tests { assert_eq!(stat2.link_count, 3); } + #[test] + fn link_to_a_one_character_name() { + let env = TestEnv::new(); + env.create_file("testfile", "test"); + let stat = env.volume.lstat("testfile").unwrap(); + + // On Windows, a name of one UTF-16 unit makes the shortest + // FILE_LINK_INFORMATION buffer. + env.volume.link("testfile", "a").unwrap(); + let stat2 = env.volume.lstat("a").unwrap(); + assert_eq!(stat2.inode_nr, stat.inode_nr); + assert_eq!(stat2.link_count, 2); + + let stat2 = env.volume.link_stat("testfile", "b").unwrap(); + assert_eq!(stat2.inode_nr, stat.inode_nr); + assert_eq!(stat2.link_count, 3); + assert_eq!(fs::read(env.root_dir.path().join("b")).unwrap(), b"test"); + } + #[test] fn stat_fs() { let env = TestEnv::new(); @@ -2550,6 +2602,91 @@ mod tests { assert_eq!(&buffer[..3], b"baz"); } + #[test] + fn xattr_name_length() { + // Linux allows names of up to 255 bytes. On Windows, an attribute is an NTFS extended + // attribute named "LX." and the attribute's name, and NTFS allows EA names of up to 254 + // bytes. + const NAME_MAX: usize = if cfg!(windows) { 251 } else { 255 }; + + fn name(len: usize) -> Vec { + let mut name = b"user.a".to_vec(); + name.resize(len, b'x'); + name + } + + let env = TestEnv::new(); + env.create_file("testfile", "test"); + env.volume + .set_xattr("testfile", "user.a", b"secret", 0) + .unwrap(); + + // An attribute with the longest name can be set, read, and removed. + let longest = name(NAME_MAX); + let longest = lx::LxStr::from_bytes(&longest); + env.volume + .set_xattr("testfile", longest, b"long", 0) + .unwrap(); + + let mut value = [0u8; 16]; + let size = env + .volume + .get_xattr("testfile", longest, Some(&mut value)) + .unwrap(); + + assert_eq!(&value[..size], b"long"); + env.volume.remove_xattr("testfile", longest).unwrap(); + let err = env.volume.get_xattr("testfile", longest, None).unwrap_err(); + + assert_eq!(err.value(), lx::ENODATA); + + // A longer name fails with ERANGE, rather than reaching an attribute whose name it starts + // with. + for len in NAME_MAX + 1..=262 { + let long = name(len); + let long = lx::LxStr::from_bytes(&long); + let results = [ + ( + "get", + env.volume + .get_xattr("testfile", long, Some(&mut value)) + .map(drop), + ), + ( + "get size", + env.volume.get_xattr("testfile", long, None).map(drop), + ), + ("set", env.volume.set_xattr("testfile", long, b"long", 0)), + ( + "create", + env.volume + .set_xattr("testfile", long, b"long", lx::XATTR_CREATE), + ), + ( + "replace", + env.volume + .set_xattr("testfile", long, b"long", lx::XATTR_REPLACE), + ), + ("remove", env.volume.remove_xattr("testfile", long)), + ]; + + for (operation, result) in results { + assert_eq!( + result.map_err(|err| err.value()), + Err(lx::ERANGE), + "{operation} of a {len}-byte name" + ); + } + } + + let size = env + .volume + .get_xattr("testfile", "user.a", Some(&mut value)) + .unwrap(); + + assert_eq!(&value[..size], b"secret"); + } + // This test is disabled in CI on Windows only, because it requires NTFS support for setting // the case sensitive directory attribute, which is only enabled if the WSL optional component // is installed. diff --git a/vm/devices/support/fs/lxutil/src/windows/mod.rs b/vm/devices/support/fs/lxutil/src/windows/mod.rs index 1e2bd19ed4d..6ded3682a73 100644 --- a/vm/devices/support/fs/lxutil/src/windows/mod.rs +++ b/vm/devices/support/fs/lxutil/src/windows/mod.rs @@ -848,6 +848,13 @@ impl LxVolume { mut options: super::LxCreateOptions, ) -> lx::Result { assert!(path.is_relative() && !path.as_os_str().is_empty()); + + // Linux has no symbolic link with an empty target: symlink(2) fails one with ENOENT, + // before it looks at the link's path, so do the same before creating anything. + if target.is_empty() { + return Err(lx::Error::ENOENT); + } + self.check_sandbox_enforcement(path)?; // Handle filesystems that do not support reparse points. @@ -2026,6 +2033,18 @@ mod tests { assert_eq!(volume.read_link(path).unwrap(), target); } + /// An NT link's reparse buffer starts with a whole `REPARSE_DATA_BUFFER`, + /// which extends past the start of the link's names, so the buffer of an + /// empty target could not hold it, and is refused with `ENOENT`, as Linux + /// refuses the target. + #[test] + fn nt_link_reparse_buffer_refuses_an_empty_target() { + assert_eq!( + util::create_nt_link_reparse_buffer(ffi::OsStr::new(""), 0).unwrap_err(), + lx::Error::ENOENT + ); + } + #[test] fn no_follow_stat_fallbacks() { for (query_by_name, stat_info) in [(true, true), (false, true), (false, false)] { diff --git a/vm/devices/support/fs/lxutil/src/windows/util.rs b/vm/devices/support/fs/lxutil/src/windows/util.rs index a49c6b073a8..c15755f1a69 100644 --- a/vm/devices/support/fs/lxutil/src/windows/util.rs +++ b/vm/devices/support/fs/lxutil/src/windows/util.rs @@ -604,6 +604,12 @@ pub fn file_info_to_stat( // Create the reparse buffer for an NT symlink. pub fn create_nt_link_reparse_buffer(target: &ffi::OsStr, flags: u32) -> lx::Result> { + // The whole REPARSE_DATA_BUFFER written below extends past the start of the names, so the + // buffer can hold it only if the target is not empty. Linux fails an empty target with ENOENT. + if target.is_empty() { + return Err(lx::Error::ENOENT); + } + let mut link_target: windows::UnicodeString = target.try_into().map_err(|_| lx::Error::EINVAL)?; @@ -619,7 +625,8 @@ pub fn create_nt_link_reparse_buffer(target: &ffi::OsStr, flags: u32) -> lx::Res let mut reparse = vec![0; local_size]; - // SAFETY: The buffer is large enough to hold the reparse data. + // SAFETY: The buffer is large enough to hold the reparse data, since the + // target is not empty: its two copies reach past the end of the struct. // This is necessary because unfortunately the Windows types don't // implement the necessary traits to use zerocopy. unsafe { @@ -1195,6 +1202,15 @@ pub fn create_link( HeaderVec::::with_capacity(link, new_path.len()); buffer.extend_tail_from_slice(new_path.as_slice()); + // NtSetInformationFile fails with STATUS_INFO_LENGTH_MISMATCH for a buffer + // shorter than the whole FILE_LINK_INFORMATION, whose size counts the first + // FileName unit and the trailing padding (24 bytes on 64-bit Windows), while + // the header above stops at FileName. Pad a name of one UTF-16 unit with a + // NUL that FileNameLength leaves out. + while buffer.total_byte_len() < size_of::() { + buffer.push_tail(0); + } + set_information_file(handle, &buffer)?; Ok(()) diff --git a/vm/devices/support/fs/lxutil/src/windows/xattr.rs b/vm/devices/support/fs/lxutil/src/windows/xattr.rs index 18cf8bb1e88..817feef615f 100644 --- a/vm/devices/support/fs/lxutil/src/windows/xattr.rs +++ b/vm/devices/support/fs/lxutil/src/windows/xattr.rs @@ -15,7 +15,11 @@ const LX_UTIL_CASE_SENSITIVE: &str = "system.wsl_case_sensitive"; const LX_UTIL_XATTR_NAME_PREFIX: &str = "LX."; const LX_UTIL_XATTR_NAME_PREFIX_LENGTH: usize = LX_UTIL_XATTR_NAME_PREFIX.len(); -const LX_UTIL_XATTR_NAME_MAX: usize = u16::MAX as usize - LX_UTIL_XATTR_NAME_PREFIX_LENGTH; + +/// The longest EA name, prefix included, that NTFS accepts. `EaNameLength` is one byte, and NTFS +/// rejects a name of 255 bytes. +const LX_UTILP_EA_NAME_MAX: usize = 254; +const LX_UTIL_XATTR_NAME_MAX: usize = LX_UTILP_EA_NAME_MAX - LX_UTIL_XATTR_NAME_PREFIX_LENGTH; const LX_UTILP_XATTR_QUERY_RESTART_SCAN: i32 = 0x1; const LX_UTILP_XATTR_QUERY_RETURN_SINGLE_ENTRY: i32 = 0x2; @@ -114,26 +118,27 @@ pub fn get_system(handle: &OwnedHandle, name: &str, value: Option<&mut [u8]>) -> Ok(1) } -/// Copy the Linux EA attribute prefix and the specified name into the start of the provided buffer. -fn set_name(name: &str, buffer: &mut [u8]) -> lx::Result { +/// Copy the Linux EA attribute prefix and the specified name into the start of the provided buffer, +/// and return the length of the resulting EA name. +fn set_name(name: &str, buffer: &mut [u8]) -> lx::Result { let name_bytes = name.as_bytes(); - if name_bytes.len() >= LX_UTIL_XATTR_NAME_MAX { + if name_bytes.len() > LX_UTIL_XATTR_NAME_MAX { return Err(lx::Error::ERANGE); } - let total_required = LX_UTIL_XATTR_NAME_PREFIX_LENGTH + name_bytes.len() + 1; + let ea_name_len = LX_UTIL_XATTR_NAME_PREFIX_LENGTH + name_bytes.len(); + let total_required = ea_name_len + 1; if buffer.len() < total_required { return Err(lx::Error::ERANGE); } buffer[..LX_UTIL_XATTR_NAME_PREFIX_LENGTH] .copy_from_slice(LX_UTIL_XATTR_NAME_PREFIX.as_bytes()); - buffer[LX_UTIL_XATTR_NAME_PREFIX_LENGTH..LX_UTIL_XATTR_NAME_PREFIX_LENGTH + name_bytes.len()] - .copy_from_slice(name_bytes); - buffer[LX_UTIL_XATTR_NAME_PREFIX_LENGTH + name_bytes.len()] = 0; + buffer[LX_UTIL_XATTR_NAME_PREFIX_LENGTH..ea_name_len].copy_from_slice(name_bytes); + buffer[ea_name_len] = 0; - Ok(LX_UTIL_XATTR_NAME_PREFIX_LENGTH + name_bytes.len()) + ea_name_len.try_into().map_err(|_| lx::Error::ERANGE) } /// Queries an EA on a file. @@ -167,7 +172,7 @@ fn query_ea( let header = FileGetEaInformation { next_entry_offset: Unalign::new(0), - ea_name_length: name_len as u8, + ea_name_length: name_len, }; buffer[..size_of::()].copy_from_slice(header.as_bytes()); Some(buffer) @@ -354,13 +359,13 @@ pub fn set(handle: &OwnedHandle, name: &str, value: &[u8], flags: i32) -> lx::Re let ea_info = FileFullEaInformation { next_entry_offset: Unalign::new(0), flags: 0, - ea_name_length: name_len as u8, + ea_name_length: name_len, ea_value_length: Unalign::new(value_size as u16), }; buffer[..size_of::()].copy_from_slice(ea_info.as_bytes()); // Set the EA value header. - let ea_value_start = size_of::() + name_len + 1; + let ea_value_start = size_of::() + usize::from(name_len) + 1; buffer[ea_value_start..ea_value_start + 4] .copy_from_slice(&LX_UTILP_EA_VALUE_HEADER.to_le_bytes()); @@ -492,7 +497,7 @@ pub fn remove(handle: &OwnedHandle, name: &str) -> lx::Result<()> { let ea_info = FileFullEaInformation { next_entry_offset: Unalign::new(0), flags: 0, - ea_name_length: name_len as u8, + ea_name_length: name_len, ea_value_length: Unalign::new(0), // Zero length to remove the attribute }; buf[..size_of::()].copy_from_slice(ea_info.as_bytes()); diff --git a/vm/devices/virtio/virtiofs/src/lib.rs b/vm/devices/virtio/virtiofs/src/lib.rs index 9677b92da21..463f7b83d34 100644 --- a/vm/devices/virtio/virtiofs/src/lib.rs +++ b/vm/devices/virtio/virtiofs/src/lib.rs @@ -1017,7 +1017,7 @@ impl InodeReservation<'_> { fn insert(mut self, inode: VirtioFsInode) -> lx::Result<(Arc, u64)> { let mut inodes = self.inodes.write(); if self.microvm { - inodes.preflight_microvm_insert(&inode)?; + inodes.preflight_microvm_reserved_insert(&inode)?; } let result = inodes.insert_reserved(&self.reservation, inode)?; self.committed = true; @@ -2158,6 +2158,23 @@ mod tests { assert!(fs.get_inode(FUSE_ROOT_ID).is_ok()); } + /// A guest SYMLINK with an empty target fails with `ENOENT`, as Linux's + /// `symlink(2)` does, and creates nothing on the host. A microVM share + /// refuses it before it reaches the host (see `symlink_tests`); a direct + /// share leaves it to the host volume. + #[test] + fn direct_symlink_rejects_an_empty_target() { + let root = tempfile::tempdir().unwrap(); + let fs = VirtioFs::new(root.path(), None).unwrap(); + + assert_eq!( + fs.symlink(&request(FUSE_ROOT_ID), "link".as_ref(), "".as_ref()) + .unwrap_err(), + lx::Error::ENOENT + ); + assert!(std::fs::symlink_metadata(root.path().join("link")).is_err()); + } + /// Returns a direct file system of `root`, or a writable microVM one if /// `microvm`, whose root holds the regular file `file`, which the guest /// has looked up once, with the file's node ID. diff --git a/vm/devices/virtio/virtiofs/src/microvm/fs_tests.rs b/vm/devices/virtio/virtiofs/src/microvm/fs_tests.rs index 53579836c46..23fd46919e8 100644 --- a/vm/devices/virtio/virtiofs/src/microvm/fs_tests.rs +++ b/vm/devices/virtio/virtiofs/src/microvm/fs_tests.rs @@ -3,12 +3,18 @@ //! Tests for microVM filesystem persistence and limits. +use super::policy_tests::create; +use super::policy_tests::create_with_flags; +use super::policy_tests::error; use super::policy_tests::lookup; +use super::policy_tests::mkdir; use super::policy_tests::name; use super::policy_tests::open; +use super::policy_tests::owned; use super::policy_tests::read_node; use super::policy_tests::release; use super::policy_tests::request; +use super::policy_tests::write; use super::profile::MICROVM_ATTACHMENT_ID; use super::profile::MICROVM_FUSE_MAJOR; use super::profile::MICROVM_FUSE_MAX_WRITE; @@ -39,6 +45,7 @@ use fuse::SessionInfoState; use fuse::SessionState; use fuse::protocol::FUSE_ASYNC_READ; use fuse::protocol::FUSE_DIRECT_IO_ALLOW_MMAP_FLAG2; +use fuse::protocol::FUSE_GETATTR_FH; use fuse::protocol::FUSE_INIT; use fuse::protocol::FUSE_INIT_EXT; use fuse::protocol::FUSE_ROOT_ID; @@ -46,6 +53,7 @@ use fuse::protocol::fuse_dirent_align; use fuse::protocol::fuse_direntplus; use fuse::protocol::fuse_in_header; use fuse::protocol::fuse_init_in; +use fuse::protocol::fuse_mknod_in; use fuse::protocol::fuse_read_in; use fuse::protocol::fuse_release_in; use std::path::Path; @@ -175,6 +183,84 @@ fn largest_restored_next_node_id_is_never_handed_out() { .unwrap(); } +/// A saved state may also hold the last node ID that the node table hands +/// out, `u64::MAX - 1`. `MKDIR`, `MKNOD`, `SYMLINK`, and `CREATE` reserve the +/// node ID of the object that they make before they make it on the host, so +/// the object takes that ID even though the table can hand out no other: the +/// reply returns the object's node rather than fail and leave the object on +/// the host without one. The next request that makes an object then fails +/// with `ENOSPC` before it changes the host, and the state saves the node and +/// the next node ID `u64::MAX`, which a restore accepts. +#[test] +fn a_created_object_takes_the_last_node_id() { + for operation in ["MKDIR", "MKNOD", "SYMLINK", "CREATE"] { + let temporary_directory = tempdir().unwrap(); + let root_path = temporary_directory.path(); + let profile = MicroVmVirtioFsProfile::from_attachment( + MICROVM_ATTACHMENT_ID.to_owned(), + microvm_root_identity(root_path).unwrap(), + false, + Vec::new(), + ) + .unwrap(); + let source = VirtioFs::new_microvm(root_path, profile.clone()).unwrap(); + let mut state = source + .save_microvm_state(&profile, SessionState::default()) + .unwrap(); + state.next_node_id = u64::MAX - 1; + let fs = VirtioFs::new_microvm(root_path, profile.clone()).unwrap(); + let session = Session::new(fs.clone()); + fs.restore_microvm_state(&profile, state, &session).unwrap(); + + let make = |object: &str| -> lx::Result { + let parent = request(FUSE_ROOT_ID); + match operation { + "MKDIR" => mkdir(&fs, FUSE_ROOT_ID, object), + "MKNOD" => { + let arg = fuse_mknod_in { + mode: lx::S_IFREG | 0o644, + rdev: 0, + umask: 0, + padding: 0, + }; + Ok(fs.mknod(&parent, name(object), &arg)?.nodeid) + } + "SYMLINK" => Ok(fs.symlink(&parent, name(object), name("target"))?.nodeid), + "CREATE" => { + let (node_id, fh) = create(&fs, FUSE_ROOT_ID, object)?; + release(&fs, node_id, fh); + Ok(node_id) + } + _ => unreachable!(), + } + }; + let on_host = |object: &str| root_path.join(object).symlink_metadata().is_ok(); + + assert_eq!(make("first"), Ok(u64::MAX - 1), "{operation}"); + assert!(on_host("first"), "{operation}"); + assert_eq!(lookup(&fs, "first"), Ok(u64::MAX - 1), "{operation}"); + assert_eq!(make("second"), Err(lx::Error::ENOSPC), "{operation}"); + assert!(!on_host("second"), "{operation}"); + + let state = fs + .save_microvm_state(&profile, SessionState::default()) + .unwrap(); + assert_eq!(state.next_node_id, u64::MAX, "{operation}"); + assert!( + state + .inodes + .iter() + .any(|inode| inode.node_id == u64::MAX - 1), + "{operation}" + ); + let restored = VirtioFs::new_microvm(root_path, profile.clone()).unwrap(); + let session = Session::new(restored.clone()); + restored + .restore_microvm_state(&profile, state, &session) + .unwrap(); + } +} + /// A reset or `FUSE_DESTROY` ends a restored session as it ends a new one, so /// a remounting guest gets nodes from 2 and handles from 1 again, even after a /// restore whose tables were full. @@ -1078,6 +1164,89 @@ fn saved_negotiation_must_match_the_exact_microvm_policy() { assert!(validate_microvm_state(&state, &profile).is_err()); } +/// The guest's FUSE client passes `O_DIRECT` in the flags of `FUSE_OPEN` and +/// `FUSE_CREATE`, which the server accepts, keeps in the handle's open flags, +/// and passes to the host open. A restore reopens such a handle with +/// `O_DIRECT` and the access that the guest opened it with, rather than refuse +/// the saved state. +#[test] +fn handles_opened_with_o_direct_restore_with_it() { + // The flags that FUSE_OPEN and FUSE_CREATE record for the handles below, + // and those with which a restore reopens them, whatever the host + // filesystem. + for (saved, reopened) in [ + (lx::O_RDWR | lx::O_DIRECT, lx::O_RDWR | lx::O_DIRECT), + ( + lx::O_WRONLY | lx::O_CREAT | lx::O_DIRECT, + lx::O_WRONLY | lx::O_DIRECT, + ), + ] { + assert_eq!( + reopen_flags(saved as u32).unwrap(), + reopened as u32, + "{saved:#x}" + ); + } + + let temporary_directory = tempdir().unwrap(); + let root_path = temporary_directory.path(); + std::fs::write(root_path.join("opened"), b"data").unwrap(); + // Linux lets a filesystem refuse O_DIRECT, as tmpfs did before Linux 6.6. + #[cfg(target_os = "linux")] + { + use std::os::unix::fs::OpenOptionsExt; + + let probe = std::fs::OpenOptions::new() + .read(true) + .custom_flags(lx::O_DIRECT) + .open(root_path.join("opened")); + match probe { + Err(error) if error.kind() == std::io::ErrorKind::InvalidInput => { + eprintln!("skipping: the host filesystem refuses O_DIRECT: {error}"); + return; + } + probe => drop(probe.unwrap()), + } + } + let profile = MicroVmVirtioFsProfile::from_attachment( + MICROVM_ATTACHMENT_ID.to_owned(), + microvm_root_identity(root_path).unwrap(), + false, + Vec::new(), + ) + .unwrap(); + let source = VirtioFs::new_microvm(root_path, profile.clone()).unwrap(); + let opened = lookup(&source, "opened").unwrap(); + let opened_fh = open(&source, opened, lx::O_RDWR | lx::O_DIRECT).unwrap(); + let (created, created_fh) = create_with_flags( + &source, + FUSE_ROOT_ID, + "created", + lx::O_WRONLY | lx::O_CREAT | lx::O_DIRECT, + ) + .unwrap(); + let state = source + .save_microvm_state(&profile, SessionState::default()) + .unwrap(); + + let destination = VirtioFs::new_microvm(root_path, profile.clone()).unwrap(); + let session = Session::new(destination.clone()); + destination + .restore_microvm_state(&profile, state, &session) + .unwrap(); + for (node_id, fh, access) in [ + (opened, opened_fh, lx::O_RDWR), + (created, created_fh, lx::O_WRONLY), + ] { + let file = destination.get_file(node_id, fh).unwrap(); + assert_eq!( + file.open_flags(), + (access | lx::O_DIRECT) as u32, + "node {node_id}" + ); + } +} + #[test] fn reopen_flags_preserve_safe_status_bits_and_reject_effects() { const O_NONBLOCK: u32 = 0x800; @@ -1119,6 +1288,65 @@ fn readonly_profile_rejects_a_writable_saved_handle() { assert!(validate_microvm_state(&state, &profile).is_err()); } +/// Linux's access mode 3 opens a file for neither reading nor writing, so +/// `FUSE_OPEN` gives such a handle of a file that the guest may not write too: +/// on a read-only share, and outside the writable paths of a read-write share. +/// A restore must reopen that handle with the same access, as it reopens the +/// handles of the other access modes. +#[test] +fn a_handle_that_neither_reads_nor_writes_survives_save_and_restore() { + let cases: [(bool, &[&str]); 3] = [(false, &[]), (true, &[]), (false, &["out"])]; + for (read_only, writable_paths) in cases { + let case = format!("read_only={read_only}, writable_paths={writable_paths:?}"); + let temporary_directory = tempdir().unwrap(); + let root_path = temporary_directory.path(); + std::fs::create_dir(root_path.join("out")).unwrap(); + std::fs::write(root_path.join("file"), b"data").unwrap(); + let profile = MicroVmVirtioFsProfile::from_attachment_with_policy( + MICROVM_ATTACHMENT_ID.to_owned(), + microvm_root_identity(root_path).unwrap(), + read_only, + Vec::new(), + Vec::new(), + owned(writable_paths), + ) + .unwrap(); + let source = VirtioFs::new_microvm(root_path, profile.clone()).unwrap(); + let node_id = lookup(&source, "file").unwrap(); + let fh = open(&source, node_id, lx::O_NOACCESS).unwrap(); + let state = source + .save_microvm_state(&profile, SessionState::default()) + .unwrap(); + + let destination = VirtioFs::new_microvm(root_path, profile.clone()).unwrap(); + let session = Session::new(destination.clone()); + if let Err(error) = destination.restore_microvm_state(&profile, state, &session) { + panic!("{case}: {error:#}"); + } + destination + .get_attr(&request(node_id), FUSE_GETATTR_FH, fh) + .unwrap(); + let mut read = fuse_read_in::new_zeroed(); + read.fh = fh; + read.size = 64; + assert_eq!( + error(destination.read(&request(node_id), &read)), + lx::Error::EBADF, + "{case}" + ); + assert_eq!( + error(write(&destination, node_id, fh, b"guest")), + lx::Error::EBADF, + "{case}" + ); + assert_eq!( + std::fs::read(root_path.join("file")).unwrap(), + b"data", + "{case}" + ); + } +} + #[test] fn saved_parent_alias_is_rejected_before_reopen() { let temporary_directory = tempdir().unwrap(); diff --git a/vm/devices/virtio/virtiofs/src/microvm/limits.rs b/vm/devices/virtio/virtiofs/src/microvm/limits.rs index 2fe439d296a..1e8bc79ca74 100644 --- a/vm/devices/virtio/virtiofs/src/microvm/limits.rs +++ b/vm/devices/virtio/virtiofs/src/microvm/limits.rs @@ -28,6 +28,33 @@ impl InodeMap { } pub(crate) fn preflight_microvm_insert(&self, inode: &VirtioFsInode) -> lx::Result<()> { + self.preflight_microvm_insert_with(inode, false) + } + + /// Checks an insert of `inode` with the node ID that a reservation holds + /// (see [`InodeMap::insert_reserved`]). + /// + /// Unlike [`Self::preflight_microvm_insert`], this does not check that the + /// table can hand out another node ID, since the insert takes none: a + /// request that reserved the last node ID, `u64::MAX - 1`, must still be + /// able to insert the node of the object that it has made on the host, + /// rather than fail and leave that object there without a node. The + /// inode and alias limits apply as to any insert. + pub(crate) fn preflight_microvm_reserved_insert( + &self, + inode: &VirtioFsInode, + ) -> lx::Result<()> { + self.preflight_microvm_insert_with(inode, true) + } + + /// Checks an insert of `inode`, whose node, if it adds one, takes the node + /// ID that a reservation holds if `reserved`, and otherwise the table's + /// next node ID. + fn preflight_microvm_insert_with( + &self, + inode: &VirtioFsInode, + reserved: bool, + ) -> lx::Result<()> { let path = inode.clone_path(); Self::validate_microvm_alias_path(&path)?; // The insert aliases the inode under the dedup key only if it reuses @@ -35,12 +62,20 @@ impl InodeMap { if let Some(existing) = self.reused(inode) { return self.preflight_microvm_alias_add(existing, &path); } - self.preflight_microvm_new_inode(&path) + self.preflight_microvm_node(&path, reserved) } pub(crate) fn preflight_microvm_new_inode(&self, path: &Path) -> lx::Result<()> { + self.preflight_microvm_node(path, false) + } + + /// Checks a new node at `path` against the inode and alias limits and, + /// unless a reservation holds its node ID (`reserved`), checks that the + /// table can hand out its next node ID. + fn preflight_microvm_node(&self, path: &Path, reserved: bool) -> lx::Result<()> { Self::validate_microvm_alias_path(path)?; - if self.inodes_by_node_id.values.len() >= MAX_INODES || !self.inodes_by_node_id.can_insert() + if self.inodes_by_node_id.values.len() >= MAX_INODES + || (!reserved && !self.inodes_by_node_id.can_insert()) { return Err(lx::Error::ENOSPC); } diff --git a/vm/devices/virtio/virtiofs/src/microvm/policy_tests.rs b/vm/devices/virtio/virtiofs/src/microvm/policy_tests.rs index b90ec29322e..209dbd9ebdf 100644 --- a/vm/devices/virtio/virtiofs/src/microvm/policy_tests.rs +++ b/vm/devices/virtio/virtiofs/src/microvm/policy_tests.rs @@ -102,7 +102,7 @@ pub(super) fn create(fs: &VirtioFs, parent: u64, file_name: &str) -> lx::Result< /// Creates and opens a file with the open flags `flags`, and returns its node /// ID and handle. -fn create_with_flags( +pub(super) fn create_with_flags( fs: &VirtioFs, parent: u64, file_name: &str, diff --git a/vm/devices/virtio/virtiofs/src/microvm/state.rs b/vm/devices/virtio/virtiofs/src/microvm/state.rs index 1a1d7ddbab7..9c5cc01870d 100644 --- a/vm/devices/virtio/virtiofs/src/microvm/state.rs +++ b/vm/devices/virtio/virtiofs/src/microvm/state.rs @@ -31,6 +31,7 @@ use super::saved_state::SavedState; use crate::FuseNegotiation; use crate::file::VirtioFsFile; use crate::inode::VirtioFsVolume; +use crate::opens_for_writing; use anyhow::Context; use fuse::SessionInfoState; use fuse::SessionState; @@ -526,7 +527,9 @@ pub(crate) fn validate_microvm_state( "saved handle has an unsupported object kind" ); let reopen_flags = reopen_flags(handle.open_flags)?; - let writable_handle = reopen_flags & lx::O_ACCESS_MASK as u32 != lx::O_RDONLY as u32; + // As for `FUSE_OPEN`, only an open for writing needs a writable node: + // access mode 3 opens the file for neither reading nor writing. + let writable_handle = opens_for_writing(reopen_flags as i32); if readonly { anyhow::ensure!( !writable_handle, @@ -596,6 +599,7 @@ pub(crate) fn reopen_flags(saved: u32) -> anyhow::Result { | lx::O_EXCL as u32 | lx::O_TRUNC as u32 | lx::O_APPEND as u32 + | lx::O_DIRECT as u32 | lx::O_DIRECTORY as u32 | lx::O_NOFOLLOW as u32 | lx::O_NOATIME as u32 @@ -610,10 +614,6 @@ pub(crate) fn reopen_flags(saved: u32) -> anyhow::Result { "saved handle has unsupported open flags {:#x}", saved ); - anyhow::ensure!( - saved & lx::O_ACCESS_MASK as u32 != lx::O_NOACCESS as u32, - "saved handle has invalid access mode" - ); Ok(saved & !(lx::O_CREAT as u32 | lx::O_EXCL as u32 | lx::O_TRUNC as u32)) }