Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
225 changes: 198 additions & 27 deletions crates/libcontainer/src/rootfs/mount.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ impl Mount {
_ => {}
}

self.check_proc_mount(options.root, mount)?;
self.check_proc_mount(options.root, &dest_path, mount)?;

self.mount_into_container(mount, options.root, &mount_option_config, options.label)
.map_err(|err| {
Expand Down Expand Up @@ -642,6 +642,32 @@ impl Mount {
let dest: OwnedFd = root.resolve(container_dest)?.into();
let dest_fd = dest.as_fd();

let procfs = ProcfsHandle::new()?;
let real_path = |fd: BorrowedFd| {
procfs.readlink(ProcfsBase::ProcThreadSelf, format!("fd/{}", fd.as_raw_fd()))
};
let real_rootfs = real_path(root.as_fd())?;
let real_dest = real_path(dest_fd)?;
if !real_dest.starts_with(&real_rootfs) {
return Err(MountError::Custom(format!(
"mountpoint {real_dest:?} is outside of rootfs {real_rootfs:?}"
)));
}
if real_dest == real_rootfs {
return Err(MountError::Custom(format!(
"mountpoint {real_dest:?} is on the top of rootfs {real_rootfs:?}"
)));
}
self.check_proc_mount(&real_rootfs, &real_dest, m)
Comment thread
Copilot marked this conversation as resolved.
Resolved
.inspect_err(|err| {
tracing::error!(
?err,
destination = ?container_dest,
resolved = ?real_dest,
"proc-safety check failed"
);
})?;

// fd-based mount flow:
// - bind: open_tree -> mount_setattr -> move_mount
// - nonbind: fsopen -> fsconfig -> fsmount -> mount_setattr -> move_mount
Expand Down Expand Up @@ -757,10 +783,10 @@ impl Mount {
}
tracing::debug!(?err, "fsconfig failed, falling back to mount(2)");
return self.legacy_mount(
m,
source,
&root,
container_dest,
typ,
dest_fd,
mount_option_config,
&data_options,
);
Expand Down Expand Up @@ -853,10 +879,10 @@ impl Mount {

fn legacy_mount(
&self,
m: &SpecMount,
source: &Path,
root: &Root,
container_dest: &Path,
typ: Option<&str>,
dest_fd: BorrowedFd,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is sufficiently expressed by the type.

Suggested change
dest_fd: BorrowedFd,
dest: BorrowedFd,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The same applies to src_fd.

mount_option_config: &MountOptionConfig,
data_options: &[String],
) -> Result<()> {
Expand All @@ -865,17 +891,16 @@ impl Mount {
.map(String::as_str)
.filter(|s| !s.is_empty())
.collect();
let dest: OwnedFd = root.resolve(container_dest)?.into();
self.syscall.mount(
Some(source),
Path::new(&format!("/proc/self/fd/{}", dest.as_raw_fd())),
typ,
Path::new(&format!("/proc/self/fd/{}", dest_fd.as_raw_fd())),
m.typ().as_deref(),
mount_option_config.flags,
Some(&data.join(",")),
)?;

if let Some(rec_attr) = &mount_option_config.rec_attr {
let mounted: OwnedFd = root.resolve(container_dest)?.into();
let mounted: OwnedFd = root.resolve(m.destination())?.into();
self.syscall.mount_setattr(
mounted.as_fd(),
Path::new(""),
Expand Down Expand Up @@ -983,7 +1008,8 @@ impl Mount {
}

/// check_proc_mount checks to ensure that the mount destination is not over the top of /proc.
/// dest is required to be an abs path and have any symlinks resolved before calling this function.
/// dest_path is the host path of the mount destination under rootfs. It should have any
/// symlinks resolved, otherwise a symlink in the rootfs can point the mount at /proc.
/// # Example (a valid case where `/proc` is mounted with `proc` type.)
///
/// ```
Expand All @@ -1005,7 +1031,8 @@ impl Mount {
/// .build()
/// .expect("failed to build SpecMount");
///
/// assert!(mounter.check_proc_mount(rootfs.as_path(), &mount).is_ok());
/// let dest_path = rootfs.join("proc");
/// assert!(mounter.check_proc_mount(&rootfs, &dest_path, &mount).is_ok());
/// ```
/// # Example (bind mount to `/proc` that should fail)
/// ```
Expand All @@ -1027,9 +1054,15 @@ impl Mount {
/// .build()
/// .expect("failed to build SpecMount");
///
/// assert!(mounter.check_proc_mount(rootfs.as_path(), &mount).is_err());
/// let dest_path = rootfs.join("proc");
/// assert!(mounter.check_proc_mount(&rootfs, &dest_path, &mount).is_err());
/// ```
pub fn check_proc_mount(&self, rootfs: &Path, mount: &SpecMount) -> Result<()> {
pub fn check_proc_mount(
&self,
rootfs: &Path,
dest_path: &Path,
mount: &SpecMount,
) -> Result<()> {
const PROC_ROOT_INO: u64 = 1;
const VALID_PROC_MOUNTS: &[&str] = &[
"/proc/cpuinfo",
Expand All @@ -1045,16 +1078,7 @@ impl Mount {
];

let dest = mount.destination();

let container_proc_path = rootfs.join("proc");
let dest_path = rootfs.join_safely(dest).map_err(|err| {
tracing::error!(
"could not join rootfs path with mount destination {:?}: {}",
dest,
err
);
MountError::Other(err.into())
})?;

// If path is Ok, it means dest_path is under /proc.
// - Ok(p) with p.is_empty(): mount target is exactly /proc.
Expand Down Expand Up @@ -1796,7 +1820,12 @@ mod tests {
.source(PathBuf::from("proc"))
.build()?;

assert!(mounter.check_proc_mount(rootfs.path(), &mount).is_ok());
let dest_path = rootfs.path().join("proc");
assert!(
mounter
.check_proc_mount(rootfs.path(), &dest_path, &mount)
.is_ok()
);
Ok(())
}

Expand All @@ -1810,10 +1839,14 @@ mod tests {
let mount = SpecMountBuilder::default()
.destination(PathBuf::from("/proc/uptime"))
.typ("bind".to_string())
.source(uptime)
.source(uptime.clone())
.build()?;

assert!(mounter.check_proc_mount(rootfs.path(), &mount).is_ok());
assert!(
mounter
.check_proc_mount(rootfs.path(), &uptime, &mount)
.is_ok()
);
Ok(())
}

Expand All @@ -1827,10 +1860,14 @@ mod tests {
let mount = SpecMountBuilder::default()
.destination(PathBuf::from("/proc/custom"))
.typ("bind".to_string())
.source(custom)
.source(custom.clone())
.build()?;

assert!(mounter.check_proc_mount(rootfs.path(), &mount).is_err());
assert!(
mounter
.check_proc_mount(rootfs.path(), &custom, &mount)
.is_err()
);
Ok(())
}

Expand Down Expand Up @@ -1903,4 +1940,138 @@ mod tests {

Ok(())
}

#[test]
fn setup_mount_bind_fails_if_destination_resolves_to_proc() -> Result<()> {
let tmp = tempfile::tempdir()?;
let rootfs = tmp.path();
let src = tempfile::tempdir()?;

fs::create_dir_all(rootfs.join("proc"))?;
symlink("proc", rootfs.join("data"))?;

let mount = SpecMountBuilder::default()
.destination(PathBuf::from("/data"))
.typ("bind")
.source(src.path())
.options(vec!["bind".to_string()])
.build()?;

let options = MountOptions {
root: rootfs,
label: None,
cgroup_ns: true,
};

let m = Mount::new();
let res = m.setup_mount(&mount, &options);

// /data resolves to /proc, so it must be checked like a mount on /proc
assert!(res.is_err());
let err = format!("{:?}", res.err().unwrap());
assert!(err.contains("cannot be mounted because it is not type proc"));
assert!(helper_syscall(&m).get_move_mount_args().is_empty());

Ok(())
}

#[test]
fn setup_mount_bind_fails_if_destination_resolves_under_proc() -> Result<()> {
let tmp = tempfile::tempdir()?;
let rootfs = tmp.path();
let src = tempfile::tempdir()?;

fs::create_dir_all(rootfs.join("proc/sys"))?;
symlink("proc/sys", rootfs.join("data"))?;

let mount = SpecMountBuilder::default()
.destination(PathBuf::from("/data"))
.typ("bind")
.source(src.path())
.options(vec!["bind".to_string()])
.build()?;

let options = MountOptions {
root: rootfs,
label: None,
cgroup_ns: true,
};

let m = Mount::new();
let res = m.setup_mount(&mount, &options);

assert!(res.is_err());
let err = format!("{:?}", res.err().unwrap());
assert!(err.contains("is not a valid mount under /proc"));
assert!(helper_syscall(&m).get_move_mount_args().is_empty());

Ok(())
}

#[test]
fn setup_mount_bind_to_symlink_outside_proc_is_allowed() -> Result<()> {
let tmp = tempfile::tempdir()?;
let rootfs = tmp.path();
let src = tempfile::tempdir()?;

fs::create_dir_all(rootfs.join("real"))?;
symlink("real", rootfs.join("data"))?;

let mount = SpecMountBuilder::default()
.destination(PathBuf::from("/data"))
.typ("bind")
.source(src.path())
.options(vec!["bind".to_string()])
.build()?;

let options = MountOptions {
root: rootfs,
label: None,
cgroup_ns: true,
};

let m = Mount::new();
m.setup_mount(&mount, &options)?;

let mv = helper_syscall(&m).get_move_mount_args();
assert_eq!(mv.len(), 1);
assert_eq!(
mv[0].to_dirfd_path.as_deref(),
Some(fs::canonicalize(rootfs.join("real"))?.as_path())
);

Ok(())
}

#[test]
fn setup_mount_bind_fails_if_destination_resolves_to_rootfs() -> Result<()> {
let tmp = tempfile::tempdir()?;
let rootfs = tmp.path();
let src = tempfile::tempdir()?;

symlink("/", rootfs.join("data"))?;

let mount = SpecMountBuilder::default()
.destination(PathBuf::from("/data"))
.typ("bind")
.source(src.path())
.options(vec!["bind".to_string()])
.build()?;

let options = MountOptions {
root: rootfs,
label: None,
cgroup_ns: true,
};

let m = Mount::new();
let res = m.setup_mount(&mount, &options);

assert!(res.is_err());
let err = format!("{:?}", res.err().unwrap());
assert!(err.contains("is on the top of rootfs"));
assert!(helper_syscall(&m).get_move_mount_args().is_empty());

Ok(())
}
}
Loading
Loading