Skip to content

Commit c0efd6c

Browse files
committed
virtiofs: list btrfs placeholders and bind mounts in microVM READDIRPLUS
A microVM directory handle numbers each entry of its snapshot as the host lists it, by d_ino, and READDIRPLUS failed with EIO at an entry on the directory's own device whose lookup reported another number, as at a name that a rename replaced since the listing. But the host lists some entries on a directory's own device by another number than a lookup reports (microsoft/nvx#1605). A btrfs snapshot of a subvolume that holds a nested subvolume holds an empty placeholder for it, which the snapshot lists by the nested subvolume's ID while a lookup reaches a directory numbered 2 on the snapshot's device; and a directory lists a mount point of its own filesystem, such as a bind mount of one of its directories, by the number of what the mount covers. A guest therefore could not list such a directory with READDIRPLUS, which the microVM profile negotiates and the guest uses for ls, find, and the like. The root of a btrfs subvolume, which lies on a device of its own, has listed since microsoft/nvx#1619. When the lookup of an entry on the directory's device reports another number than the snapshot's, READDIRPLUS now checks that the inode's path, at which the lookup resolved the name, still reaches the handle's directory, and lists that directory again as a snapshot lists it, within the same bounds, at most once per read. It lists the entry, as its lookup reports it, if the host still lists the entry by the snapshot's number. It still fails with EIO if the host lists the entry by another number, as after a rename over it, or by the number 0, which identifies nothing, or if another directory took the listed one's path. An entry that the host no longer lists is gone, so READDIRPLUS skips it, as it skips one whose lookup fails with ENOENT. As at a mount point of another device, a lookup of a mount point reaches whatever is mounted on it then. Tests, in virtiofs' microVM tests: on Linux, a READDIRPLUS of a directory that holds a bind mount of another of its directories, made in user and mount namespaces of the test's own, lists the mount point with the number that its lookup reports; and a READDIRPLUS still fails with EIO at an entry that a rename replaced since the listing, and at an entry of a directory that took the listed one's path. No test host has btrfs, so the bind mount, which the host lists and looks up as it does a placeholder, stands in for one. Without the fix, at eff41b1 (the microsoft/nvx#1623 fix) on Linux (Azure Linux 3.0, kernel 6.18), the first fails with EIO; with it, the three and the package's other tests pass on Windows and on Linux, with TMPDIR on tmpfs and on ext4. Without the check of the inode's path, the third fails, and without any check, as the issue proposes, the last two fail. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 766a74a commit c0efd6c

2 files changed

Lines changed: 209 additions & 3 deletions

File tree

‎vm/devices/virtio/virtiofs/src/microvm/file.rs‎

Lines changed: 65 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ use fuse::DirEntryWriter;
1616
use fuse::Fuse;
1717
use fuse::protocol::fuse_entry_out;
1818
use parking_lot::Mutex;
19+
use std::collections::HashMap;
1920
use std::sync::Arc;
2021

2122
/// The directory snapshots that the handles of a microVM attachment hold, in
@@ -84,6 +85,10 @@ impl Drop for DirectorySnapshotCharge {
8485
}
8586
}
8687

88+
/// The guest inode numbers by which the host lists a directory's entries now,
89+
/// by name.
90+
type HostListing = HashMap<Vec<u8>, lx::ino_t>;
91+
8792
impl VirtioFsFile {
8893
pub(crate) fn read_dir_microvm(
8994
&self,
@@ -128,6 +133,9 @@ impl VirtioFsFile {
128133
.map_err(|_| lx::Error::ENOMEM)?;
129134

130135
let mut skipped = 0;
136+
// Listed again at most once per read, for the first entry whose
137+
// lookup reports another number than the snapshot.
138+
let mut host_listing = None;
131139
for entry in &entries[start..] {
132140
let name = lx::LxStr::from_bytes(&entry.name);
133141
if plus {
@@ -140,7 +148,7 @@ impl VirtioFsFile {
140148
break;
141149
}
142150
} else {
143-
match self.write_microvm_entry_plus(fs, &mut buffer, entry) {
151+
match self.write_microvm_entry_plus(fs, &mut buffer, entry, &mut host_listing) {
144152
Ok(true) => {}
145153
Ok(false) => break,
146154
// As in `read_dir_with`, skip an entry whose name is
@@ -179,7 +187,8 @@ impl VirtioFsFile {
179187

180188
/// Writes the readdirplus entry of `entry`, an entry of this directory's
181189
/// snapshot other than `.` and `..`, to `buffer`, and returns whether it
182-
/// fit.
190+
/// fit. `host_listing` is the directory as the host lists it now, if this
191+
/// read has listed it already (see [`Self::check_still_listed`]).
183192
///
184193
/// The entry's lookup takes the lookup reference that the entry hands to
185194
/// the guest, so the reference is held only if the entry is written: an
@@ -189,6 +198,7 @@ impl VirtioFsFile {
189198
fs: &VirtioFs,
190199
buffer: &mut Vec<u8>,
191200
entry: &SavedDirectoryEntry,
201+
host_listing: &mut Option<HostListing>,
192202
) -> lx::Result<bool> {
193203
let name = lx::LxStr::from_bytes(&entry.name);
194204
// This check must happen before insert_lookup, because a
@@ -203,7 +213,7 @@ impl VirtioFsFile {
203213
// object, so only an entry on this directory's device shows whether
204214
// the name still reaches the listed object.
205215
if child.device_nr() == self.inode.device_nr() && attr.ino != entry.guest_inode_id {
206-
return Err(lx::Error::EIO);
216+
self.check_still_listed(entry, host_listing)?;
207217
}
208218
let fuse_entry = fs.insert_lookup(child, attr)?;
209219
let node_id = fuse_entry.nodeid;
@@ -215,6 +225,58 @@ impl VirtioFsFile {
215225
Ok(true)
216226
}
217227

228+
/// Checks that `entry`, an entry of this directory's snapshot whose lookup
229+
/// reached an object of the directory's host device with another number
230+
/// than the snapshot's, still names the listed object.
231+
///
232+
/// The host lists some entries on a directory's own device by another
233+
/// number than a lookup of the entry reports: a mount point of that
234+
/// device, such as a bind mount of one of its directories, by the number
235+
/// of what the mount covers, and the placeholder that a btrfs snapshot
236+
/// holds of a nested subvolume by the subvolume's ID, while a lookup
237+
/// reaches an empty directory numbered 2. Such an entry names the listed
238+
/// object as long as the host lists it by the snapshot's number, so the
239+
/// directory is listed again, as a snapshot lists it, into
240+
/// `host_listing`, at most once per read. An entry that the host now
241+
/// lists by another number, as after a rename over it, fails with EIO,
242+
/// and one that it no longer lists is gone, which fails with ENOENT. A
243+
/// mount point names whatever is mounted on it when the guest looks it
244+
/// up, as one of another device does. An entry that the host lists by
245+
/// the number 0, as a Windows file system that reports no file IDs does,
246+
/// has no number to check, so it fails with EIO too.
247+
fn check_still_listed(
248+
&self,
249+
entry: &SavedDirectoryEntry,
250+
host_listing: &mut Option<HostListing>,
251+
) -> lx::Result<()> {
252+
if entry.guest_inode_id == self.inode.guest_ino(0) {
253+
return Err(lx::Error::EIO);
254+
}
255+
// The lookup resolved the name in the directory at the inode's path,
256+
// which must therefore still be the directory that this handle lists.
257+
let listed_directory = self.object_stat()?;
258+
let named_directory = self.inode.object_stat()?;
259+
if (listed_directory.device_nr, listed_directory.inode_nr)
260+
!= (named_directory.device_nr, named_directory.inode_nr)
261+
{
262+
return Err(lx::Error::EIO);
263+
}
264+
let host_listing = match host_listing {
265+
Some(host_listing) => host_listing,
266+
None => host_listing.insert(
267+
self.build_microvm_directory_snapshot()?
268+
.into_iter()
269+
.map(|listed| (listed.name, listed.guest_inode_id))
270+
.collect(),
271+
),
272+
};
273+
match host_listing.get(&entry.name) {
274+
Some(&guest_inode_id) if guest_inode_id == entry.guest_inode_id => Ok(()),
275+
Some(_) => Err(lx::Error::EIO),
276+
None => Err(lx::Error::ENOENT),
277+
}
278+
}
279+
218280
fn build_microvm_directory_snapshot(&self) -> lx::Result<Vec<SavedDirectoryEntry>> {
219281
let stat = self.object_stat()?;
220282
if stat.mode & lx::S_IFMT != lx::S_IFDIR {

‎vm/devices/virtio/virtiofs/src/microvm/fs_tests.rs‎

Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -695,6 +695,150 @@ fn readdirplus_ends_the_listing_only_after_skipping_every_entry_left() {
695695
);
696696
}
697697

698+
/// Returns the offset at which a read of `directory`, whose snapshot lists
699+
/// `name`, starts at that entry.
700+
fn offset_of(directory: &VirtioFsFile, name: &[u8]) -> u64 {
701+
let entries = directory.directory_entries();
702+
let index = entries.iter().position(|entry| entry.name == name).unwrap();
703+
index
704+
.checked_sub(1)
705+
.map_or(0, |index| entries[index].next_cookie)
706+
}
707+
708+
/// A listed name that a rename replaced since the listing no longer names the
709+
/// listed object, which the host now lists by another number, so READDIRPLUS
710+
/// must fail at it rather than list the object that replaced it.
711+
#[test]
712+
fn readdirplus_fails_at_an_entry_replaced_since_the_listing() {
713+
let temporary_directory = tempdir().unwrap();
714+
let root_path = temporary_directory.path();
715+
let (fs, directory) = microvm_with_an_open_root(root_path, &["entry"]);
716+
// A plain READDIR lists the directory without looking its entries up.
717+
directory.read_dir(&fs, 0, 4096, false).unwrap();
718+
std::fs::write(root_path.join("replacement"), "replacement").unwrap();
719+
std::fs::rename(root_path.join("replacement"), root_path.join("entry")).unwrap();
720+
721+
let offset = offset_of(&directory, b"entry");
722+
assert_eq!(
723+
directory.read_dir(&fs, offset, 4096, true).unwrap_err(),
724+
lx::Error::EIO
725+
);
726+
}
727+
728+
/// READDIRPLUS looks a listed name up in the directory at its inode's path,
729+
/// which the host may have replaced since the guest opened the listed one, as
730+
/// by renaming the listed one away and creating another in its place. A name
731+
/// that reaches an object of that other directory does not name the listed
732+
/// object, even though the listed directory still lists the name as it did,
733+
/// so READDIRPLUS must fail at it.
734+
#[test]
735+
fn readdirplus_fails_at_an_entry_of_another_directory_at_the_listed_path() {
736+
let temporary_directory = tempdir().unwrap();
737+
let root_path = temporary_directory.path();
738+
std::fs::create_dir(root_path.join("listed")).unwrap();
739+
std::fs::write(root_path.join("listed").join("entry"), "listed").unwrap();
740+
let fs = VirtioFs::new_microvm(root_path, profile(root_path)).unwrap();
741+
let root = fs.get_inode(FUSE_ROOT_ID).unwrap();
742+
let listed = fs
743+
.lookup_helper(&root, lx::LxStr::from_bytes(b"listed"))
744+
.unwrap()
745+
.nodeid;
746+
let handle = fs
747+
.insert_file(fs.get_inode(listed).unwrap().open(lx::O_RDONLY).unwrap())
748+
.unwrap();
749+
let directory = fs.get_file(listed, handle).unwrap();
750+
directory.read_dir(&fs, 0, 4096, false).unwrap();
751+
std::fs::rename(root_path.join("listed"), root_path.join("moved")).unwrap();
752+
std::fs::create_dir(root_path.join("listed")).unwrap();
753+
std::fs::write(root_path.join("listed").join("entry"), "replacement").unwrap();
754+
755+
let offset = offset_of(&directory, b"entry");
756+
assert_eq!(
757+
directory.read_dir(&fs, offset, 4096, true).unwrap_err(),
758+
lx::Error::EIO
759+
);
760+
}
761+
762+
/// The host lists some entries of a directory by another inode number than a
763+
/// lookup of the entry reports on the directory's own device: a btrfs
764+
/// snapshot lists the placeholder of a nested subvolume by the subvolume's ID,
765+
/// while a lookup reaches an empty directory numbered 2, and a directory lists
766+
/// a mount point of its own filesystem by the number of the directory that the
767+
/// mount covers, while a lookup reaches the mounted one. Such an entry still
768+
/// names the listed object, so READDIRPLUS must list it, with the number that
769+
/// its lookup reports. A bind mount, which an unprivileged process can make in
770+
/// user and mount namespaces of its own, gives such an entry here; where the
771+
/// host allows no such namespaces, the test does nothing.
772+
#[cfg(target_os = "linux")]
773+
#[test]
774+
fn readdirplus_lists_an_entry_that_the_host_lists_by_another_number() {
775+
use std::os::unix::fs::DirEntryExt;
776+
use std::os::unix::fs::MetadataExt;
777+
use std::process::Command;
778+
779+
const ROOT: &str = "VIRTIOFS_TEST_BIND_MOUNT_ROOT";
780+
let namespaces = ["--user", "--map-root-user", "--mount"];
781+
let Some(root_path) = std::env::var_os(ROOT) else {
782+
// Only a single-threaded process can enter a new user namespace, so
783+
// the test runs again in a child process in the namespaces, in a
784+
// directory that this process removes once the child is done.
785+
let temporary_directory = tempdir().unwrap();
786+
let root_path = temporary_directory.path();
787+
let bind_mount_works = Command::new("unshare")
788+
.args(namespaces)
789+
.args(["mount", "--bind"])
790+
.args([root_path, root_path])
791+
.status()
792+
.is_ok_and(|status| status.success());
793+
if !bind_mount_works {
794+
eprintln!("skipping: no bind mount in user and mount namespaces");
795+
return;
796+
}
797+
let status = Command::new("unshare")
798+
.args(namespaces)
799+
.arg(std::env::current_exe().unwrap())
800+
.args([
801+
"--exact",
802+
"microvm::fs_tests::readdirplus_lists_an_entry_that_the_host_lists_by_another_number",
803+
"--no-capture",
804+
])
805+
.env(ROOT, root_path)
806+
.status()
807+
.unwrap();
808+
assert!(status.success(), "{status}");
809+
return;
810+
};
811+
let root_path = Path::new(&root_path);
812+
std::fs::create_dir(root_path.join("mounted")).unwrap();
813+
std::fs::create_dir(root_path.join("point")).unwrap();
814+
let status = Command::new("mount")
815+
.arg("--bind")
816+
.args([root_path.join("mounted"), root_path.join("point")])
817+
.status()
818+
.unwrap();
819+
assert!(status.success(), "{status}");
820+
let listed = std::fs::read_dir(root_path)
821+
.unwrap()
822+
.map(Result::unwrap)
823+
.find(|entry| entry.file_name() == "point")
824+
.unwrap()
825+
.ino();
826+
let point = std::fs::symlink_metadata(root_path.join("point")).unwrap();
827+
assert_ne!(point.ino(), listed);
828+
assert_eq!(
829+
point.dev(),
830+
std::fs::symlink_metadata(root_path).unwrap().dev()
831+
);
832+
833+
let (fs, directory) = microvm_with_an_open_root(root_path, &[]);
834+
let entries = crate::tests::read_directory(&fs, &directory, 0, 4096, true);
835+
let root = fs.get_inode(FUSE_ROOT_ID).unwrap();
836+
let point = fs
837+
.lookup_helper(&root, lx::LxStr::from_bytes(b"point"))
838+
.unwrap();
839+
assert_eq!(entries["point"].0, point.attr.ino);
840+
}
841+
698842
#[test]
699843
fn saved_negotiation_must_match_the_exact_microvm_policy() {
700844
let temporary_directory = tempdir().unwrap();

0 commit comments

Comments
 (0)