diff --git a/crates/libcontainer/src/container/mount_validation.rs b/crates/libcontainer/src/container/mount_validation.rs index e6b3dbd7cd..47260871a7 100644 --- a/crates/libcontainer/src/container/mount_validation.rs +++ b/crates/libcontainer/src/container/mount_validation.rs @@ -26,6 +26,13 @@ fn container_userns_has_mappings(linux: Option<&Linux>) -> bool { } } +pub(crate) fn is_idmap_requested(mount: &SpecMount) -> bool { + let has_any_mount_mappings = mount.uid_mappings().is_some() || mount.gid_mappings().is_some(); + let options = mount.options().as_deref().unwrap_or(&[]); + let has_idmap_option = options.iter().any(|o| o == "idmap" || o == "ridmap"); + has_idmap_option || has_any_mount_mappings +} + fn validate_mount_mappings(mount: &SpecMount) -> Result { match ( mount.uid_mappings().as_deref(), @@ -56,14 +63,11 @@ pub(crate) fn validate_idmapped_mounts( let can_use_container_userns = container_userns_has_mappings(linux); for mount in mounts { - let has_any_mount_mappings = - mount.uid_mappings().is_some() || mount.gid_mappings().is_some(); - let options = mount.options().as_deref().unwrap_or(&[]); - let has_idmap_option = options.iter().any(|o| o == "idmap" || o == "ridmap"); - if !has_idmap_option && !has_any_mount_mappings { + if !is_idmap_requested(mount) { continue; } + let options = mount.options().as_deref().unwrap_or(&[]); let is_bind = mount.typ().as_deref() == Some("bind") || options.iter().any(|o| o == "bind" || o == "rbind"); @@ -92,13 +96,6 @@ pub(crate) fn validate_idmapped_mounts( ); return Err(ErrInvalidSpec::MountIdmapMissingMappings); } - - // TODO: remove this guard when idmapped mount support is implemented. - tracing::error!( - destination = ?mount.destination(), - "idmapped mounts are not supported" - ); - return Err(ErrInvalidSpec::MountIdmapUnsupported); } Ok(()) @@ -143,7 +140,7 @@ mod tests { } #[test] - fn validate_idmapped_mounts_rejects_idmap_with_mappings_bind_as_unsupported() { + fn validate_idmapped_mounts_allows_idmap_with_mappings_bind() { let mount = base_mount() .options(vec!["bind".to_string(), "idmap".to_string()]) .uid_mappings(vec![make_mapping()]) @@ -152,11 +149,11 @@ mod tests { .unwrap(); let syscall = create_root_syscall(); let res = validate_idmapped_mounts(&[mount], None, rootless_required(&*syscall).unwrap()); - assert!(matches!(res, Err(ErrInvalidSpec::MountIdmapUnsupported))); + assert!(res.is_ok()); } #[test] - fn validate_idmapped_mounts_rejects_mappings_without_idmap_flag_as_unsupported() { + fn validate_idmapped_mounts_allows_mappings_without_idmap_flag() { let mount = base_mount() .options(vec!["bind".to_string()]) .uid_mappings(vec![make_mapping()]) @@ -165,11 +162,11 @@ mod tests { .unwrap(); let syscall = create_root_syscall(); let res = validate_idmapped_mounts(&[mount], None, rootless_required(&*syscall).unwrap()); - assert!(matches!(res, Err(ErrInvalidSpec::MountIdmapUnsupported))); + assert!(res.is_ok()); } #[test] - fn validate_idmapped_mounts_rejects_implied_idmap_with_userns_as_unsupported() { + fn validate_idmapped_mounts_allows_implied_idmap_with_userns() { let mount = base_mount() .options(vec!["bind".to_string(), "idmap".to_string()]) .build() @@ -191,11 +188,11 @@ mod tests { Some(&linux), rootless_required(&*syscall).unwrap(), ); - assert!(matches!(res, Err(ErrInvalidSpec::MountIdmapUnsupported))); + assert!(res.is_ok()); } #[test] - fn validate_idmapped_mounts_rejects_implied_idmap_with_joined_userns_as_unsupported() { + fn validate_idmapped_mounts_allows_implied_idmap_with_joined_userns() { let mount = base_mount() .options(vec!["bind".to_string(), "idmap".to_string()]) .build() @@ -216,11 +213,11 @@ mod tests { Some(&linux), rootless_required(&*syscall).unwrap(), ); - assert!(matches!(res, Err(ErrInvalidSpec::MountIdmapUnsupported))); + assert!(res.is_ok()); } #[test] - fn validate_idmapped_mounts_rejects_ridmap_with_userns_as_unsupported() { + fn validate_idmapped_mounts_allows_ridmap_with_userns() { let mount = base_mount() .options(vec!["bind".to_string(), "ridmap".to_string()]) .build() @@ -242,11 +239,11 @@ mod tests { Some(&linux), rootless_required(&*syscall).unwrap(), ); - assert!(matches!(res, Err(ErrInvalidSpec::MountIdmapUnsupported))); + assert!(res.is_ok()); } #[test] - fn validate_idmapped_mounts_rejects_rbind_idmap_as_unsupported() { + fn validate_idmapped_mounts_allows_rbind_idmap() { let mount = MountBuilder::default() .destination(PathBuf::from("/mnt")) .source(PathBuf::from("/src")) @@ -257,7 +254,7 @@ mod tests { .unwrap(); let syscall = create_root_syscall(); let res = validate_idmapped_mounts(&[mount], None, rootless_required(&*syscall).unwrap()); - assert!(matches!(res, Err(ErrInvalidSpec::MountIdmapUnsupported))); + assert!(res.is_ok()); } #[test] @@ -436,8 +433,7 @@ mod tests { } #[test] - fn validate_idmapped_mounts_rejects_bind_type_without_bind_option_as_unsupported() { - // typ="bind" のみで is_bind を満たし、options に "bind"/"rbind" を含まないケース + fn validate_idmapped_mounts_allows_bind_type_without_bind_option() { let mount = base_mount() .options(vec!["idmap".to_string()]) .uid_mappings(vec![make_mapping()]) @@ -446,11 +442,11 @@ mod tests { .unwrap(); let syscall = create_root_syscall(); let res = validate_idmapped_mounts(&[mount], None, rootless_required(&*syscall).unwrap()); - assert!(matches!(res, Err(ErrInvalidSpec::MountIdmapUnsupported))); + assert!(res.is_ok()); } #[test] - fn validate_idmapped_mounts_rejects_unsupported_idmap_among_multiple_mounts() { + fn validate_idmapped_mounts_allows_idmap_among_multiple_mounts() { let mapped_mount = base_mount() .options(vec!["bind".to_string(), "idmap".to_string()]) .uid_mappings(vec![make_mapping()]) @@ -469,7 +465,7 @@ mod tests { None, rootless_required(&*syscall).unwrap(), ); - assert!(matches!(res, Err(ErrInvalidSpec::MountIdmapUnsupported))); + assert!(res.is_ok()); } #[test] @@ -495,7 +491,7 @@ mod tests { None, rootless_required(&*syscall).unwrap(), ); - assert!(matches!(res, Err(ErrInvalidSpec::MountIdmapUnsupported))); + assert!(matches!(res, Err(ErrInvalidSpec::MountIdmapNonBind))); } #[test] diff --git a/crates/libcontainer/src/error.rs b/crates/libcontainer/src/error.rs index 9f7b32eb3a..8ef2f26385 100644 --- a/crates/libcontainer/src/error.rs +++ b/crates/libcontainer/src/error.rs @@ -112,8 +112,6 @@ pub enum ErrInvalidSpec { MountIdmapNonBind, #[error("idmapped mount requires uid/gid mappings or a usable user namespace")] MountIdmapMissingMappings, - #[error("idmapped mount is not supported")] - MountIdmapUnsupported, #[error("idmapped mounts are not supported in rootless containers")] MountIdmapRootless, #[error("invalid netns path: {0}")] diff --git a/crates/libcontainer/src/process/container_main_process.rs b/crates/libcontainer/src/process/container_main_process.rs index ad30204669..324d56212b 100644 --- a/crates/libcontainer/src/process/container_main_process.rs +++ b/crates/libcontainer/src/process/container_main_process.rs @@ -13,7 +13,10 @@ use crate::hooks; use crate::network::network_device::dev_change_net_namespace; use crate::process::args::{ContainerArgs, ContainerType}; use crate::process::fork::{self, CloneCb}; -use crate::process::message::{Message, format_error_chain}; +use crate::process::idmapped_mount::{ + IdmappedMountError, MountFdService, mount_fd_service_required, +}; +use crate::process::message::{Message, MountMsg, format_error_chain}; use crate::process::{channel, container_intermediate_process}; use crate::syscall::SyscallError; use crate::user_ns::UserNamespaceConfig; @@ -39,6 +42,8 @@ pub enum ProcessError { Network(#[from] crate::network::NetworkError), #[error("network device setup requested but {0}")] NetworkDeviceSetup(&'static str), + #[error(transparent)] + IdmappedMount(#[from] IdmappedMountError), #[error("failed syscall")] SyscallOther(#[source] SyscallError), #[error("failed hooks {0}")] @@ -170,11 +175,24 @@ pub fn container_main_process(container_args: &ContainerArgs) -> Result<(Pid, Op } } + let mount_fd_service = + if mount_fd_service_required(container_args.container_type, &container_args.spec) { + Some(MountFdService::start(init_pid, container_args.syscall)?) + } else { + None + }; + let mut sequence = InitRequestSequence::new(container_args.container_type, &container_args.spec); let foreground_pty_fd = loop { let (msg, fd) = init_main_receiver.recv_init_message()?; match sequence.accept(&msg)? { + InitRequest::MountFd => { + let Message::AskMountFd(request) = msg else { + unreachable!("mount fd request must carry a mount fd payload") + }; + handle_mount_fd_request(mount_fd_service.as_ref(), request, &mut init_sender)?; + } InitRequest::Ready => break fd, InitRequest::Hooks => { let hooks = container_args @@ -279,9 +297,11 @@ pub fn container_main_process(container_args: &ContainerArgs) -> Result<(Pid, Op Ok((init_pid, foreground_pty_fd)) } -/// One-shot init-side setup requests. +/// Init-side setup requests. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] enum InitRequest { + /// Requests a detached idmapped mount file descriptor during rootfs setup. + MountFd, /// Indicates that the init process requests execution of the configured runtime hooks. Hooks, /// Indicates that the init process is ready for network device setup. @@ -292,12 +312,14 @@ enum InitRequest { Ready, } -/// Ordering groups for one-shot init requests. +/// Ordering groups for init requests. /// /// The declaration order is the protocol order. Requests in the same phase /// may arrive in any order. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] enum InitPhase { + /// Accepts any number of mount fd requests while init prepares the rootfs. + Mounts, /// Waits for configured hook and network requests. They have no ordering /// dependency and may arrive in either order. Setup, @@ -312,11 +334,16 @@ enum InitPhase { impl InitRequest { fn phase(self) -> InitPhase { match self { + Self::MountFd => InitPhase::Mounts, Self::Hooks | Self::Network => InitPhase::Setup, Self::Seccomp => InitPhase::Seccomp, Self::Ready => InitPhase::Ready, } } + + fn is_repeatable(self) -> bool { + matches!(self, Self::MountFd) + } } impl TryFrom<&Message> for InitRequest { @@ -324,6 +351,7 @@ impl TryFrom<&Message> for InitRequest { fn try_from(message: &Message) -> std::result::Result { match message { + Message::AskMountFd(_) => Ok(Self::MountFd), Message::HookRequest => Ok(Self::Hooks), Message::SetupNetworkDeviceReady => Ok(Self::Network), Message::SeccompNotify => Ok(Self::Seccomp), @@ -334,12 +362,13 @@ impl TryFrom<&Message> for InitRequest { } struct InitRequestSequence { - /// Expected one-shot requests that have not been received yet. + /// Expected requests that are still valid in the current protocol phase. pending_requests: HashSet, } impl InitRequestSequence { fn new(container_type: ContainerType, spec: &Spec) -> Self { + let mount_fd = mount_fd_service_required(container_type, spec); let hooks = match container_type { ContainerType::InitContainer => spec.hooks().is_some(), ContainerType::TenantContainer { .. } => false, @@ -359,11 +388,14 @@ impl InitRequestSequence { #[cfg(not(feature = "libseccomp"))] let seccomp = false; - Self::from_requirements(hooks, network_device, seccomp) + Self::from_requirements(mount_fd, hooks, network_device, seccomp) } - fn from_requirements(hooks: bool, network: bool, seccomp: bool) -> Self { + fn from_requirements(mount_fd: bool, hooks: bool, network: bool, seccomp: bool) -> Self { let mut pending_requests = HashSet::new(); + if mount_fd { + pending_requests.insert(InitRequest::MountFd); + } if hooks { pending_requests.insert(InitRequest::Hooks); } @@ -388,6 +420,11 @@ impl InitRequestSequence { return Err(unexpected_init_message(message)); } + // Closes repeatable requests. Must run before the check below, which + // would otherwise see them as pending and reject everything after. + self.pending_requests + .retain(|request| !(request.is_repeatable() && request.phase() < received.phase())); + if self .pending_requests .iter() @@ -396,7 +433,9 @@ impl InitRequestSequence { return Err(unexpected_init_message(message)); } - self.pending_requests.remove(&received); + if !received.is_repeatable() { + self.pending_requests.remove(&received); + } Ok(received) } } @@ -441,6 +480,40 @@ fn handle_hook_request( Ok(()) } +fn handle_mount_fd_request( + service: Option<&MountFdService>, + request: MountMsg, + init_sender: &mut channel::InitSender, +) -> Result<()> { + // Init blocks until it gets a reply, so answer it even when failing. + let Some(service) = service else { + if let Err(send_err) = + init_sender.send_mount_fd_error("unexpected mount fd request".to_string()) + { + tracing::warn!(?send_err, "failed to send mount fd error to init"); + } + return Err(ProcessError::Channel( + channel::ChannelError::UnexpectedInitMessage(Box::new(Message::AskMountFd(request))), + )); + }; + + // Main process -> worker: block until the worker replies. + match service.request_mount_fd(request) { + Ok(mount_fd) => { + // Main process -> init: send the fd over the init channel. + init_sender.send_mount_fd_reply(mount_fd.as_raw_fd())?; + // Dropping `mount_fd` is safe: SCM_RIGHTS already duplicated it. + Ok(()) + } + Err(err) => { + if let Err(send_err) = init_sender.send_mount_fd_error(err.to_string()) { + tracing::warn!(?send_err, "failed to send mount fd error to init"); + } + Err(err.into()) + } + } +} + #[cfg(feature = "libseccomp")] fn handle_seccomp_notify( container: Option<&Container>, @@ -601,11 +674,21 @@ mod tests { use super::*; use crate::process::channel::{intermediate_channel, main_channel}; + use crate::process::message::{MountIdMap, MountIdMapUsernsSource}; + use crate::syscall::syscall::SyscallType; use crate::user_ns::UserNamespaceIDMapper; + fn mount_fd_request() -> Message { + Message::AskMountFd(MountMsg { + source: PathBuf::from("/src"), + idmap: None, + clone_mount_tree_recursively: false, + }) + } + #[test] fn init_request_sequence_accepts_requests_in_order() { - let mut sequence = InitRequestSequence::from_requirements(true, true, true); + let mut sequence = InitRequestSequence::from_requirements(false, true, true, true); assert_eq!( sequence.accept(&Message::HookRequest).unwrap(), @@ -627,7 +710,7 @@ mod tests { #[test] fn init_request_sequence_accepts_hooks_and_network_in_any_order() { - let mut sequence = InitRequestSequence::from_requirements(true, true, true); + let mut sequence = InitRequestSequence::from_requirements(false, true, true, true); assert_eq!( sequence.accept(&Message::SetupNetworkDeviceReady).unwrap(), @@ -649,7 +732,7 @@ mod tests { #[test] fn init_request_sequence_skips_optional_requests() { - let mut sequence = InitRequestSequence::from_requirements(false, true, false); + let mut sequence = InitRequestSequence::from_requirements(false, false, true, false); assert_eq!( sequence.accept(&Message::SetupNetworkDeviceReady).unwrap(), @@ -663,8 +746,46 @@ mod tests { #[test] fn init_request_sequence_accepts_ready_when_no_setup_is_required() { - let mut sequence = InitRequestSequence::from_requirements(false, false, false); + let mut sequence = InitRequestSequence::from_requirements(false, false, false, false); + + assert_eq!( + sequence.accept(&Message::InitReady).unwrap(), + InitRequest::Ready + ); + } + + #[test] + fn init_request_sequence_accepts_repeatable_mount_requests() { + let mut sequence = InitRequestSequence::from_requirements(true, true, false, false); + + assert_eq!( + sequence.accept(&mount_fd_request()).unwrap(), + InitRequest::MountFd + ); + assert_eq!( + sequence.accept(&mount_fd_request()).unwrap(), + InitRequest::MountFd + ); + assert_eq!( + sequence.accept(&Message::HookRequest).unwrap(), + InitRequest::Hooks + ); + + let err = sequence.accept(&mount_fd_request()).unwrap_err(); + assert!(matches!( + err, + channel::ChannelError::UnexpectedInitMessage(_) + )); + } + + #[test] + fn init_request_sequence_closes_mount_requests_at_ready() { + let mut sequence = InitRequestSequence::from_requirements(true, false, false, false); + assert_eq!( + sequence.accept(&mount_fd_request()).unwrap(), + InitRequest::MountFd + ); assert_eq!( sequence.accept(&Message::InitReady).unwrap(), InitRequest::Ready @@ -673,7 +794,7 @@ mod tests { #[test] fn init_request_sequence_rejects_seccomp_while_setup_is_pending() { - let mut sequence = InitRequestSequence::from_requirements(true, true, true); + let mut sequence = InitRequestSequence::from_requirements(false, true, true, true); let err = sequence.accept(&Message::SeccompNotify).unwrap_err(); assert!(matches!( @@ -684,7 +805,7 @@ mod tests { #[test] fn init_request_sequence_rejects_duplicate_request() { - let mut sequence = InitRequestSequence::from_requirements(true, false, false); + let mut sequence = InitRequestSequence::from_requirements(false, true, false, false); sequence.accept(&Message::HookRequest).unwrap(); let err = sequence.accept(&Message::HookRequest).unwrap_err(); @@ -696,7 +817,7 @@ mod tests { #[test] fn init_request_sequence_rejects_ready_while_setup_is_pending() { - let mut sequence = InitRequestSequence::from_requirements(false, true, false); + let mut sequence = InitRequestSequence::from_requirements(false, false, true, false); let err = sequence.accept(&Message::InitReady).unwrap_err(); assert!(matches!( @@ -707,7 +828,7 @@ mod tests { #[test] fn init_request_sequence_rejects_ready_while_seccomp_is_pending() { - let mut sequence = InitRequestSequence::from_requirements(false, false, true); + let mut sequence = InitRequestSequence::from_requirements(false, false, false, true); let err = sequence.accept(&Message::InitReady).unwrap_err(); assert!(matches!( @@ -718,7 +839,7 @@ mod tests { #[test] fn init_request_sequence_rejects_seccomp_when_not_required() { - let mut sequence = InitRequestSequence::from_requirements(false, false, false); + let mut sequence = InitRequestSequence::from_requirements(false, false, false, false); let err = sequence.accept(&Message::SeccompNotify).unwrap_err(); assert!(matches!( @@ -727,6 +848,63 @@ mod tests { )); } + #[test] + fn handle_mount_fd_request_without_service_is_unexpected() -> Result<()> { + let (mut init_sender, mut init_receiver) = channel::init_channel()?; + let Message::AskMountFd(request) = mount_fd_request() else { + unreachable!() + }; + + let err = handle_mount_fd_request(None, request, &mut init_sender).unwrap_err(); + assert!(matches!( + err, + ProcessError::Channel(channel::ChannelError::UnexpectedInitMessage(_)) + )); + let reply_err = init_receiver.wait_for_mount_fd_reply().unwrap_err(); + assert!(matches!(reply_err, channel::ChannelError::MountFdError(_))); + Ok(()) + } + + #[test] + fn handle_mount_fd_request_forwards_fd_to_init() -> Result<()> { + let (mut init_sender, mut init_receiver) = channel::init_channel()?; + let service = MountFdService::start(Pid::this(), SyscallType::Test) + .map_err(ProcessError::IdmappedMount)?; + let request = MountMsg { + source: PathBuf::from("/src"), + idmap: Some(MountIdMap { + userns_source: MountIdMapUsernsSource::ContainerUserns, + apply_idmap_recursively: false, + }), + clone_mount_tree_recursively: false, + }; + + handle_mount_fd_request(Some(&service), request, &mut init_sender)?; + + let mount_fd = init_receiver.wait_for_mount_fd_reply()?; + assert!(mount_fd.as_raw_fd() >= 0); + Ok(()) + } + + #[test] + fn handle_mount_fd_request_reports_worker_error_to_init() -> Result<()> { + let (mut init_sender, mut init_receiver) = channel::init_channel()?; + let service = MountFdService::start(Pid::this(), SyscallType::Test) + .map_err(ProcessError::IdmappedMount)?; + let Message::AskMountFd(request) = mount_fd_request() else { + unreachable!() + }; + + let err = handle_mount_fd_request(Some(&service), request, &mut init_sender).unwrap_err(); + assert!(matches!( + err, + ProcessError::IdmappedMount(IdmappedMountError::InvalidRequest(_)) + )); + let reply_err = init_receiver.wait_for_mount_fd_reply().unwrap_err(); + assert!(matches!(reply_err, channel::ChannelError::MountFdError(_))); + Ok(()) + } + #[test] #[serial] fn setup_uid_mapping_should_succeed() -> Result<()> { diff --git a/crates/libcontainer/src/process/idmapped_mount.rs b/crates/libcontainer/src/process/idmapped_mount.rs new file mode 100644 index 0000000000..38998205bb --- /dev/null +++ b/crates/libcontainer/src/process/idmapped_mount.rs @@ -0,0 +1,566 @@ +//! Parent-side service that creates idmapped mount file descriptors on +//! behalf of the container init process. +//! +//! `mount_setattr(MOUNT_ATTR_IDMAP)` requires privileges the init process no +//! longer has once it has joined the container namespaces, so rootfs setup +//! asks the main process for the mount fd with `AskMountFd`. Mirrors runc's +//! `goCreateMountSources` in `libcontainer/process_linux.go`. + +use std::fs::File; +use std::io::ErrorKind; +use std::os::fd::{AsFd, AsRawFd, OwnedFd}; +use std::path::Path; +use std::sync::mpsc; +use std::{fs, mem, thread}; + +use nix::errno::Errno; +use nix::fcntl::OFlag; +use nix::sched::CloneFlags; +use nix::sys::wait::waitpid; +use nix::unistd::{ForkResult, Pid, fork, pipe2, read, write}; +use oci_spec::runtime::{LinuxIdMapping, Spec}; + +use crate::container::mount_validation::is_idmap_requested; +use crate::process::args::ContainerType; +use crate::process::message::{MountIdMapUsernsSource, MountMsg}; +use crate::syscall::syscall::SyscallType; +use crate::syscall::{Syscall, SyscallError, linux}; + +#[derive(Debug, thiserror::Error)] +pub enum IdmappedMountError { + #[error("failed to join init mount namespace: {0}")] + JoinMountNamespace(String), + #[error("failed to create user namespace for mount id-mappings: {0}")] + CreateUserNamespace(String), + #[error("invalid idmapped mount request: {0}")] + InvalidRequest(String), + #[error("idmapped mounts require open_tree/mount_setattr support (Linux 5.12+)")] + NotSupported(#[source] SyscallError), + #[error("failed to attach id-mapping, the source filesystem may not support idmapped mounts")] + FilesystemNotSupported(#[source] SyscallError), + #[error("failed syscall for idmapped mount")] + Syscall(#[source] SyscallError), + #[error("mount fd worker is unavailable: {0}")] + WorkerUnavailable(String), +} + +type Result = std::result::Result; + +pub(crate) fn spec_has_idmapped_mounts(spec: &Spec) -> bool { + spec.mounts() + .as_deref() + .unwrap_or(&[]) + .iter() + .any(is_idmap_requested) +} + +pub(crate) fn mount_fd_service_required(container_type: ContainerType, spec: &Spec) -> bool { + // Only an init container prepares the rootfs, so only it can ask for mount fds. + matches!(container_type, ContainerType::InitContainer) && spec_has_idmapped_mounts(spec) +} + +#[derive(Debug)] +pub(crate) struct MountFdService { + request_tx: mpsc::Sender, + reply_rx: mpsc::Receiver>, +} + +impl MountFdService { + /// Blocks until the worker has detached its filesystem state, so a broken + /// setup fails the container start rather than the first mount request. + /// + /// The mount namespace join is deferred to the first request: init enters + /// that namespace only after the main process learns its pid, but is + /// guaranteed to be inside by the time rootfs setup sends `AskMountFd`. + pub(crate) fn start(init_pid: Pid, syscall: SyscallType) -> Result { + // Main process -> worker: one request per idmapped mount. + let (request_tx, request_rx) = mpsc::channel::(); + // Worker -> main process: the mount fd or error for each request. + let (reply_tx, reply_rx) = mpsc::channel::>(); + // Worker -> main process: the one-time worker setup result. + let (setup_tx, setup_rx) = mpsc::channel::>(); + thread::spawn(move || { + let syscall = syscall.create_syscall(); + // setns(CLONE_NEWNS) fails on a thread that shares filesystem + // state with the rest of the process. + if let Err(err) = syscall.unshare(CloneFlags::CLONE_FS) { + let _ = setup_tx.send(Err(IdmappedMountError::JoinMountNamespace(format!( + "unshare(CLONE_FS): {err}" + )))); + return; + } + let _ = setup_tx.send(Ok(())); + + let mut mntns_joined: Option> = None; + // Main process -> worker: wait for the next mount request. + for msg in request_rx { + let joined = mntns_joined.get_or_insert_with(|| { + join_init_mount_namespace(syscall.as_ref(), init_pid) + .map_err(|err| err.to_string()) + }); + let reply = match joined { + Ok(()) => create_idmapped_mount_fd(syscall.as_ref(), &msg, init_pid), + Err(err) => Err(IdmappedMountError::JoinMountNamespace(err.clone())), + }; + // Worker -> main process: main forwards the result to init. + let _ = reply_tx.send(reply); + } + }); + + match setup_rx.recv() { + Ok(Ok(())) => Ok(Self { + request_tx, + reply_rx, + }), + Ok(Err(err)) => Err(err), + Err(err) => Err(IdmappedMountError::WorkerUnavailable(err.to_string())), + } + } + + pub(crate) fn request_mount_fd(&self, msg: MountMsg) -> Result { + self.request_tx + .send(msg) + .map_err(|err| IdmappedMountError::WorkerUnavailable(err.to_string()))?; + self.reply_rx + .recv() + .map_err(|err| IdmappedMountError::WorkerUnavailable(err.to_string()))? + } +} + +/// Resolves mount sources the way the init process sees them. Requires the +/// calling thread to have run unshare(CLONE_FS) first. +fn join_init_mount_namespace(syscall: &dyn Syscall, init_pid: Pid) -> Result<()> { + let mntns_path = format!("/proc/{}/ns/mnt", init_pid.as_raw()); + let mntns = File::open(&mntns_path).map_err(|err| { + IdmappedMountError::JoinMountNamespace(format!("open {mntns_path}: {err}")) + })?; + syscall + .set_ns(mntns.as_raw_fd(), CloneFlags::CLONE_NEWNS) + .map_err(|err| IdmappedMountError::JoinMountNamespace(format!("setns: {err}")))?; + Ok(()) +} + +/// The mount must be detached: mount_setattr(2) rejects MOUNT_ATTR_IDMAP on a +/// mount that has ever been visible in a mount namespace. The returned fd is +/// ready to be installed with move_mount(2). +fn create_idmapped_mount_fd( + syscall: &dyn Syscall, + msg: &MountMsg, + init_pid: Pid, +) -> Result { + let idmap = msg.idmap.as_ref().ok_or_else(|| { + IdmappedMountError::InvalidRequest("mount fd request without id-mappings".to_string()) + })?; + let userns_fd = match &idmap.userns_source { + MountIdMapUsernsSource::Mappings { + uid_mappings, + gid_mappings, + } => create_userns_fd(uid_mappings, gid_mappings)?, + MountIdMapUsernsSource::ContainerUserns => open_user_namespace(init_pid)?, + }; + + let source = msg.source.to_str().ok_or_else(|| { + IdmappedMountError::InvalidRequest(format!( + "mount source is not valid UTF-8: {:?}", + msg.source + )) + })?; + let mut open_flags = linux::OPEN_TREE_CLONE | linux::OPEN_TREE_CLOEXEC; + if msg.clone_mount_tree_recursively { + open_flags |= linux::AT_RECURSIVE; + } + let mount_fd = syscall + .open_tree(libc::AT_FDCWD, Some(source), open_flags) + .map_err(syscall_error)?; + + let mut setattr_flags = linux::AT_EMPTY_PATH; + if idmap.apply_idmap_recursively { + setattr_flags |= linux::AT_RECURSIVE; + } + let mount_attr = linux::MountAttr { + attr_set: linux::MOUNT_ATTR_IDMAP, + attr_clr: 0, + propagation: 0, + userns_fd: userns_fd.as_raw_fd() as u64, + }; + syscall + .mount_setattr( + mount_fd.as_fd(), + Path::new(""), + setattr_flags, + &mount_attr, + mem::size_of::(), + ) + .map_err(|err| match err { + // Usually means the source filesystem has no idmapped mount support. + SyscallError::Nix(Errno::EINVAL) => IdmappedMountError::FilesystemNotSupported(err), + err => syscall_error(err), + })?; + Ok(mount_fd) +} + +fn syscall_error(err: SyscallError) -> IdmappedMountError { + match err { + SyscallError::Nix(Errno::ENOSYS) => IdmappedMountError::NotSupported(err), + _ => IdmappedMountError::Syscall(err), + } +} + +fn release_userns_helper(release_write: &OwnedFd) { + while let Err(Errno::EINTR) = write(release_write, &[1]) {} +} + +/// `mount_setattr` takes the id-mapping as a user namespace, so one has to be +/// materialized to carry it. Nothing ever runs in it: a child process only +/// exists to give the id-map files a pid, and dies once the fd keeps the +/// namespace alive. The worker cannot unshare it itself without losing the +/// host privileges that mount_setattr(2) then needs. +fn create_userns_fd( + uid_mappings: &[LinuxIdMapping], + gid_mappings: &[LinuxIdMapping], +) -> Result { + for (file_name, mappings) in [("uid_map", uid_mappings), ("gid_map", gid_mappings)] { + if mappings.is_empty() { + return Err(IdmappedMountError::InvalidRequest(format!( + "{file_name} mappings are empty" + ))); + } + } + + // Another concurrently forked helper may inherit a writer, so EOF is not a reliable signal. + let (ready_read, ready_write) = pipe2(OFlag::O_CLOEXEC).map_err(|err| { + IdmappedMountError::CreateUserNamespace(format!("create ready pipe: {err}")) + })?; + let (release_read, release_write) = pipe2(OFlag::O_CLOEXEC).map_err(|err| { + IdmappedMountError::CreateUserNamespace(format!("create release pipe: {err}")) + })?; + + match unsafe { fork() } { + Ok(ForkResult::Child) => { + // Forked from a multi-threaded process: async-signal-safe calls + // only, so failures are reported through the exit code. + drop(ready_read); + drop(release_write); + if nix::sched::unshare(CloneFlags::CLONE_NEWUSER).is_ok() { + let _ = write(&ready_write, &[1]); + let mut buf = [0u8; 1]; + // Exiting early would take /proc//{uid,gid}_map with it + // before the parent has written them. + while let Err(Errno::EINTR) = read(&release_read, &mut buf) {} + unsafe { libc::_exit(0) } + } + let _ = write(&ready_write, &[0]); + unsafe { libc::_exit(1) } + } + Ok(ForkResult::Parent { child }) => { + drop(ready_write); + drop(release_read); + let mut buf = [0u8; 1]; + let ready = loop { + match read(&ready_read, &mut buf) { + Err(Errno::EINTR) => continue, + other => break other, + } + }; + let unshared = matches!(ready, Ok(1)) && buf[0] == 1; + let result = if unshared { + write_userns_mappings(child, uid_mappings, gid_mappings) + .and_then(|()| open_user_namespace(child)) + } else { + Err(IdmappedMountError::CreateUserNamespace( + "user namespace helper process failed to unshare".to_string(), + )) + }; + // The child must outlive the id-map writes above: its /proc entries + // vanish when it exits. + if unshared { + release_userns_helper(&release_write); + } + drop(release_write); + while let Err(Errno::EINTR) = waitpid(child, None) {} + result + } + Err(err) => Err(IdmappedMountError::CreateUserNamespace(format!( + "fork user namespace helper process: {err}" + ))), + } +} + +fn write_userns_mappings( + pid: Pid, + uid_mappings: &[LinuxIdMapping], + gid_mappings: &[LinuxIdMapping], +) -> Result<()> { + // Required before an unprivileged process may write the gid map, see + // user_namespaces(7). ENOENT means the kernel predates the file. + let setgroups_path = format!("/proc/{}/setgroups", pid.as_raw()); + if let Err(err) = fs::write(&setgroups_path, "deny") { + if err.kind() != ErrorKind::NotFound { + return Err(IdmappedMountError::CreateUserNamespace(format!( + "write deny to {setgroups_path}: {err}" + ))); + } + } + + write_id_mapping_file(pid, "uid_map", uid_mappings)?; + write_id_mapping_file(pid, "gid_map", gid_mappings) +} + +fn write_id_mapping_file(pid: Pid, file_name: &str, mappings: &[LinuxIdMapping]) -> Result<()> { + use std::fmt::Write; + let mut content = String::new(); + for mapping in mappings { + let _ = writeln!( + content, + "{} {} {}", + mapping.container_id(), + mapping.host_id(), + mapping.size() + ); + } + let path = format!("/proc/{}/{}", pid.as_raw(), file_name); + fs::write(&path, content) + .map_err(|err| IdmappedMountError::CreateUserNamespace(format!("write {path}: {err}"))) +} + +fn open_user_namespace(pid: Pid) -> Result { + let path = format!("/proc/{}/ns/user", pid.as_raw()); + let file = File::open(&path) + .map_err(|err| IdmappedMountError::CreateUserNamespace(format!("open {path}: {err}")))?; + Ok(file.into()) +} + +#[cfg(test)] +mod tests { + use std::path::PathBuf; + + use anyhow::Result; + use nix::unistd::{getgid, getuid}; + use oci_spec::runtime::{LinuxIdMappingBuilder, MountBuilder, SpecBuilder}; + use serial_test::serial; + + use super::*; + use crate::process::message::MountIdMap; + use crate::syscall::syscall::create_syscall; + use crate::syscall::test::{ArgName, TestHelperSyscall}; + + fn container_userns_request(recursive: bool) -> MountMsg { + MountMsg { + source: PathBuf::from("/src"), + idmap: Some(MountIdMap { + userns_source: MountIdMapUsernsSource::ContainerUserns, + apply_idmap_recursively: recursive, + }), + clone_mount_tree_recursively: recursive, + } + } + + fn mock_syscall(syscall: &dyn Syscall) -> &TestHelperSyscall { + syscall + .as_any() + .downcast_ref::() + .unwrap() + } + + fn own_id_mappings() -> (LinuxIdMapping, LinuxIdMapping) { + let uid_mapping = LinuxIdMappingBuilder::default() + .container_id(0u32) + .host_id(getuid()) + .size(1u32) + .build() + .unwrap(); + let gid_mapping = LinuxIdMappingBuilder::default() + .container_id(0u32) + .host_id(getgid()) + .size(1u32) + .build() + .unwrap(); + (uid_mapping, gid_mapping) + } + + #[test] + fn mount_fd_service_only_runs_for_init_containers_with_idmapped_mounts() { + let plain = MountBuilder::default() + .destination(PathBuf::from("/mnt")) + .typ("tmpfs") + .source(PathBuf::from("tmpfs")) + .build() + .unwrap(); + let idmapped = MountBuilder::default() + .destination(PathBuf::from("/mnt")) + .typ("bind") + .source(PathBuf::from("/src")) + .options(vec!["bind".to_string(), "idmap".to_string()]) + .build() + .unwrap(); + + let spec = SpecBuilder::default() + .mounts(vec![plain.clone()]) + .build() + .unwrap(); + assert!(!mount_fd_service_required( + ContainerType::InitContainer, + &spec + )); + + let spec = SpecBuilder::default() + .mounts(vec![plain, idmapped]) + .build() + .unwrap(); + assert!(mount_fd_service_required( + ContainerType::InitContainer, + &spec + )); + assert!(!mount_fd_service_required( + ContainerType::TenantContainer { exec_notify_fd: -1 }, + &spec + )); + } + + #[test] + fn create_idmapped_mount_fd_sets_idmap_attr() -> Result<()> { + let syscall = create_syscall(); + let msg = container_userns_request(false); + + let _fd = create_idmapped_mount_fd(syscall.as_ref(), &msg, Pid::this())?; + + let mock = mock_syscall(syscall.as_ref()); + let open_tree_args = mock.get_open_tree_args(); + assert_eq!(open_tree_args.len(), 1); + assert_eq!(open_tree_args[0].dirfd, libc::AT_FDCWD); + assert_eq!(open_tree_args[0].path.as_deref(), Some("/src")); + assert_eq!( + open_tree_args[0].flags, + linux::OPEN_TREE_CLONE | linux::OPEN_TREE_CLOEXEC + ); + let setattr_args = mock.get_mount_setattr_args(); + assert_eq!(setattr_args.len(), 1); + assert_eq!(setattr_args[0].flags, linux::AT_EMPTY_PATH); + assert_eq!(setattr_args[0].attr_set, linux::MOUNT_ATTR_IDMAP); + assert_eq!(setattr_args[0].attr_clr, 0); + assert_eq!(setattr_args[0].propagation, 0); + assert_ne!(setattr_args[0].userns_fd, 0); + Ok(()) + } + + #[test] + fn create_idmapped_mount_fd_recursive_flags() -> Result<()> { + let syscall = create_syscall(); + let msg = container_userns_request(true); + + let _fd = create_idmapped_mount_fd(syscall.as_ref(), &msg, Pid::this())?; + + let mock = mock_syscall(syscall.as_ref()); + assert_eq!( + mock.get_open_tree_args()[0].flags, + linux::OPEN_TREE_CLONE | linux::OPEN_TREE_CLOEXEC | linux::AT_RECURSIVE + ); + assert_eq!( + mock.get_mount_setattr_args()[0].flags, + linux::AT_EMPTY_PATH | linux::AT_RECURSIVE + ); + Ok(()) + } + + #[test] + #[serial] + fn create_idmapped_mount_fd_uses_mount_level_mappings() -> Result<()> { + let (uid_mapping, gid_mapping) = own_id_mappings(); + let syscall = create_syscall(); + let msg = MountMsg { + source: PathBuf::from("/src"), + idmap: Some(MountIdMap { + userns_source: MountIdMapUsernsSource::Mappings { + uid_mappings: vec![uid_mapping], + gid_mappings: vec![gid_mapping], + }, + apply_idmap_recursively: false, + }), + clone_mount_tree_recursively: false, + }; + + let _fd = create_idmapped_mount_fd(syscall.as_ref(), &msg, Pid::this())?; + + let setattr_args = mock_syscall(syscall.as_ref()).get_mount_setattr_args(); + assert_eq!(setattr_args.len(), 1); + assert_eq!(setattr_args[0].attr_set, linux::MOUNT_ATTR_IDMAP); + assert_ne!(setattr_args[0].userns_fd, 0); + Ok(()) + } + + #[test] + fn create_idmapped_mount_fd_reports_missing_kernel_support() { + let syscall = create_syscall(); + mock_syscall(syscall.as_ref()) + .set_ret_err(ArgName::OpenTree, || Err(SyscallError::Nix(Errno::ENOSYS))); + + let err = create_idmapped_mount_fd( + syscall.as_ref(), + &container_userns_request(false), + Pid::this(), + ) + .unwrap_err(); + assert!(matches!(err, IdmappedMountError::NotSupported(_))); + assert_eq!( + err.to_string(), + "idmapped mounts require open_tree/mount_setattr support (Linux 5.12+)" + ); + } + + #[test] + fn create_idmapped_mount_fd_reports_missing_filesystem_support() { + let syscall = create_syscall(); + mock_syscall(syscall.as_ref()).set_ret_err(ArgName::MountSetattr, || { + Err(SyscallError::Nix(Errno::EINVAL)) + }); + + let err = create_idmapped_mount_fd( + syscall.as_ref(), + &container_userns_request(false), + Pid::this(), + ) + .unwrap_err(); + assert!(matches!(err, IdmappedMountError::FilesystemNotSupported(_))); + } + + #[test] + fn create_userns_fd_rejects_empty_mappings() { + let (uid_mapping, gid_mapping) = own_id_mappings(); + + // Rejected before the fork, so no #[serial] needed. + let err = create_userns_fd(&[], &[gid_mapping]).unwrap_err(); + assert!( + matches!(err, IdmappedMountError::InvalidRequest(msg) if msg == "uid_map mappings are empty") + ); + let err = create_userns_fd(&[uid_mapping], &[]).unwrap_err(); + assert!( + matches!(err, IdmappedMountError::InvalidRequest(msg) if msg == "gid_map mappings are empty") + ); + } + + #[test] + #[serial] + fn create_userns_fd_returns_user_namespace() -> Result<()> { + let (uid_mapping, gid_mapping) = own_id_mappings(); + + let userns_fd = create_userns_fd(&[uid_mapping], &[gid_mapping])?; + + let link = fs::read_link(format!("/proc/self/fd/{}", userns_fd.as_raw_fd()))?; + assert!( + link.to_string_lossy().starts_with("user:["), + "expected a user namespace fd, got {link:?}" + ); + Ok(()) + } + + #[test] + fn mount_fd_service_joins_mount_namespace_lazily() { + let service = MountFdService::start(Pid::from_raw(-1), SyscallType::Test) + .expect("service startup must not join the init mount namespace"); + + let err = service + .request_mount_fd(container_userns_request(false)) + .unwrap_err(); + assert!(matches!(err, IdmappedMountError::JoinMountNamespace(_))); + } +} diff --git a/crates/libcontainer/src/process/init/process.rs b/crates/libcontainer/src/process/init/process.rs index 48d9a3c61b..bd99f1a232 100644 --- a/crates/libcontainer/src/process/init/process.rs +++ b/crates/libcontainer/src/process/init/process.rs @@ -28,9 +28,10 @@ use crate::network::link::LinkClient; use crate::network::network_device::{resolve_device_name, setup_addresses_in_network_namespace}; use crate::network::wrapper::create_network_client; use crate::process::args::{ContainerArgs, ContainerType}; +use crate::process::idmapped_mount::mount_fd_service_required; use crate::process::{channel, memory_policy}; -use crate::rootfs::RootFS; use crate::rootfs::device::{open_device_fd, verify_dev_null}; +use crate::rootfs::{MountChannels, RootFS}; #[cfg(feature = "libseccomp")] use crate::seccomp; use crate::syscall::{Syscall, SyscallError}; @@ -88,12 +89,18 @@ pub fn container_init_process( let in_user_ns = utils::is_in_new_userns().map_err(InitProcessError::Io)?; let bind_service = ctx.ns.get(LinuxNamespaceType::User)?.is_some() || in_user_ns; let rootfs = RootFS::new(); + let mut mount_channels = mount_fd_service_required(args.container_type, ctx.spec) + .then_some(MountChannels { + main: main_sender, + init: init_receiver, + }); rootfs .prepare_rootfs( ctx.spec, ctx.rootfs, bind_service, ctx.ns.get(LinuxNamespaceType::Cgroup)?.is_some(), + mount_channels.as_mut(), ) .map_err(|err| { tracing::error!(?err, "failed to prepare rootfs"); diff --git a/crates/libcontainer/src/process/mod.rs b/crates/libcontainer/src/process/mod.rs index 77d7bd7fa2..10dcdec339 100644 --- a/crates/libcontainer/src/process/mod.rs +++ b/crates/libcontainer/src/process/mod.rs @@ -7,9 +7,10 @@ pub mod container_intermediate_process; pub mod container_main_process; pub mod cpu_affinity; mod fork; +mod idmapped_mount; pub mod init; pub mod intel_rdt; pub mod memory_policy; -mod message; +pub(crate) mod message; #[cfg(feature = "libseccomp")] mod seccomp_listener; diff --git a/crates/libcontainer/src/rootfs/mod.rs b/crates/libcontainer/src/rootfs/mod.rs index 0ac1c9f867..b75f195eb2 100644 --- a/crates/libcontainer/src/rootfs/mod.rs +++ b/crates/libcontainer/src/rootfs/mod.rs @@ -9,7 +9,7 @@ pub mod device; pub use device::Device; pub(super) mod mount; -pub use mount::Mount; +pub use mount::{Mount, MountChannels}; pub(super) mod symlink; diff --git a/crates/libcontainer/src/rootfs/mount.rs b/crates/libcontainer/src/rootfs/mount.rs index 10de46c6bb..2145b0002e 100644 --- a/crates/libcontainer/src/rootfs/mount.rs +++ b/crates/libcontainer/src/rootfs/mount.rs @@ -31,8 +31,10 @@ use procfs::{FromRead, ProcessCGroups}; #[cfg(feature = "v1")] use super::symlink::Symlink; use super::symlink::SymlinkError; -use super::utils::{MountOptionConfig, parse_mount}; -use crate::rootfs::utils::is_bind; +use super::utils::{MountOptionConfig, is_bind, is_recursive_bind, parse_mount}; +use crate::container::mount_validation::is_idmap_requested; +use crate::process::channel; +use crate::process::message::{MountIdMap, MountIdMapUsernsSource, MountMsg}; use crate::syscall::syscall::create_syscall; use crate::syscall::{Syscall, SyscallError, linux}; use crate::utils::{PathBufExt, retry}; @@ -79,6 +81,11 @@ pub enum MountError { type Result = std::result::Result; +pub struct MountChannels<'a> { + pub main: &'a mut channel::MainSender, + pub init: &'a mut channel::InitReceiver, +} + pub trait MountInfoProvider { fn mountinfo(&self) -> Result>; } @@ -145,10 +152,161 @@ impl Mount { self } - pub fn setup_mount(&self, mount: &SpecMount, options: &MountOptions) -> Result<()> { + fn create_bind_mount_destination( + root: &Root, + container_dest: &Path, + src_is_dir: bool, + ) -> Result<()> { + let dir_perm = Permissions::from_mode(0o755); + + if src_is_dir { + root.mkdir_all(container_dest, &dir_perm)?; + } else { + let parent = container_dest + .parent() + .ok_or(MountError::Custom("destination has no parent".to_string()))?; + root.mkdir_all(parent, &dir_perm)?; + + match root.create_file( + container_dest, + OpenFlags::O_EXCL + | OpenFlags::O_CREAT + | OpenFlags::O_NOFOLLOW + | OpenFlags::O_CLOEXEC, + &Permissions::from_mode(0o644), + ) { + Ok(_) => Ok(()), + // If we get here, the file is already present, so continue. + Err(create_err) => root + .resolve(container_dest) + .map(|_| ()) + .map_err(|_| create_err), + }?; + } + + Ok(()) + } + + fn mount_idmapped( + &self, + mount: &SpecMount, + options: &MountOptions, + mount_option_config: &MountOptionConfig, + mount_channels: &mut MountChannels<'_>, + ) -> Result<()> { + let root = Root::open(options.root)?; + let container_dest = mount.destination(); + let source = mount.source().as_ref().ok_or(MountError::NoSource)?; + + let userns_source = match ( + mount.uid_mappings().as_deref(), + mount.gid_mappings().as_deref(), + ) { + (Some(uid_mappings), Some(gid_mappings)) => MountIdMapUsernsSource::Mappings { + uid_mappings: uid_mappings.to_vec(), + gid_mappings: gid_mappings.to_vec(), + }, + (None, None) => MountIdMapUsernsSource::ContainerUserns, + _ => { + return Err(MountError::Custom( + "mount uid/gid mappings must be specified together".to_string(), + )); + } + }; + let msg = MountMsg { + source: source.to_path_buf(), + idmap: Some(MountIdMap { + userns_source, + apply_idmap_recursively: mount_option_config.apply_recursive_idmap, + }), + clone_mount_tree_recursively: is_recursive_bind(mount), + }; + mount_channels.main.request_mount_fd(msg).map_err(|err| { + tracing::error!("failed to request mount fd: {}", err); + MountError::Other(err.into()) + })?; + let mount_fd = match mount_channels.init.wait_for_mount_fd_reply() { + Ok(fd) => fd, + Err(channel::ChannelError::MountFdError(err)) => { + return Err(MountError::Custom(err)); + } + Err(err) => { + tracing::error!("failed to receive mount fd: {}", err); + return Err(MountError::Other(err.into())); + } + }; + + let source_is_dir = fstat(&mount_fd)?.st_mode & libc::S_IFMT == libc::S_IFDIR; + Self::create_bind_mount_destination(&root, container_dest, source_is_dir)?; + let dest: OwnedFd = root.resolve(container_dest)?.into(); + let dest_fd = dest.as_fd(); + + let attr_set_from_flags = self.mount_flag_to_attr(&mount_option_config.flags); + let mut mount_attr = linux::MountAttr { + attr_set: attr_set_from_flags, + attr_clr: 0, + propagation: 0, + userns_fd: 0, + }; + self.apply_atime_from_msflags( + &mut mount_attr, + attr_set_from_flags, + mount_option_config.flags, + ); + self.syscall.mount_setattr( + mount_fd.as_fd(), + Path::new(""), + linux::AT_EMPTY_PATH, + &mount_attr, + mem::size_of::(), + )?; + + if let Some(rec_attr) = &mount_option_config.rec_attr { + self.syscall.mount_setattr( + mount_fd.as_fd(), + Path::new(""), + linux::AT_EMPTY_PATH | linux::AT_RECURSIVE, + rec_attr, + mem::size_of::(), + )?; + } + + self.syscall.move_mount( + mount_fd.as_fd(), + None, + dest_fd, + None, + linux::MOVE_MOUNT_T_EMPTY_PATH | linux::MOVE_MOUNT_F_EMPTY_PATH, + )?; + + self.apply_mount_propagation( + options.root, + container_dest, + &mount_option_config.propagation_flags, + )?; + + Ok(()) + } + + pub fn setup_mount( + &self, + mount: &SpecMount, + options: &MountOptions, + mut mount_channels: Option<&mut MountChannels<'_>>, + ) -> Result<()> { tracing::debug!("mounting {:?}", mount); let mut mount_option_config = parse_mount(mount)?; + // Spec validation rejects non-bind idmapped mounts, so returning here cannot + // take a cgroup, proc or sysfs mount away from the type match below. + if is_idmap_requested(mount) { + let mount_channels = mount_channels.take().ok_or_else(|| { + MountError::Custom("idmapped mount requires mount fd channel".to_string()) + })?; + self.mount_idmapped(mount, options, &mount_option_config, mount_channels)?; + return Ok(()); + } + match mount.typ().as_deref() { Some("cgroup") => { let cgroup_setup = libcgroups::common::get_cgroup_setup().map_err(|err| { @@ -272,7 +430,7 @@ impl Mount { err })?; - self.setup_mount(&tmpfs, options).map_err(|err| { + self.setup_mount(&tmpfs, options, None).map_err(|err| { tracing::error!("failed to mount tmpfs for cgroup: {}", err); err })?; @@ -405,6 +563,7 @@ impl Mount { rec_attr: None, propagation_flags: vec![], tmpcopyup: false, + apply_recursive_idmap: false, }; self.mount_into_container( @@ -471,7 +630,7 @@ impl Mount { .build()?; tracing::debug!("Mounting emulated cgroup subsystem: {:?}", emulated); - self.setup_mount(&emulated, options).map_err(|err| { + self.setup_mount(&emulated, options, None).map_err(|err| { tracing::error!("failed to mount {subsystem_name} cgroup hierarchy: {}", err); err })?; @@ -620,30 +779,7 @@ impl Mount { })?; let src_is_dir = fstat(&src_fd)?.st_mode & libc::S_IFMT == libc::S_IFDIR; - if src_is_dir { - root.mkdir_all(container_dest, &dir_perm)?; - } else { - let parent = container_dest - .parent() - .ok_or(MountError::Custom("destination has no parent".to_string()))?; - root.mkdir_all(parent, &dir_perm)?; - - match root.create_file( - container_dest, - OpenFlags::O_EXCL - | OpenFlags::O_CREAT - | OpenFlags::O_NOFOLLOW - | OpenFlags::O_CLOEXEC, - &Permissions::from_mode(0o644), - ) { - Ok(_) => Ok(()), - // If we get here, the file is already present, so continue. - Err(create_err) => root - .resolve(container_dest) - .map(|_| ()) - .map_err(|_| create_err), - }?; - }; + Self::create_bind_mount_destination(&root, container_dest, src_is_dir)?; Some(src_fd) } else { @@ -658,15 +794,10 @@ impl Mount { // - bind: open_tree -> mount_setattr -> move_mount // - nonbind: fsopen -> fsconfig -> fsmount -> mount_setattr -> move_mount if let Some(src_fd) = src_fd { - let recursive = m - .options() - .as_ref() - .map(|v| v.iter().any(|o| o == "rbind")) - .unwrap_or(false); let mut open_tree_flags: libc::c_uint = (libc::OPEN_TREE_CLOEXEC as libc::c_uint) | (libc::OPEN_TREE_CLONE as libc::c_uint) | (libc::AT_EMPTY_PATH as libc::c_uint); - if recursive { + if is_recursive_bind(m) { open_tree_flags |= libc::AT_RECURSIVE as libc::c_uint; }; @@ -1263,11 +1394,14 @@ mod tests { #[cfg(feature = "v1")] use std::fs; use std::fs::OpenOptions; + use std::os::fd::AsRawFd; use std::os::unix::fs::symlink; use std::os::unix::net::UnixListener; use std::str::FromStr; + use std::thread; use anyhow::{Context, Ok, Result}; + use oci_spec::runtime::LinuxIdMappingBuilder; use super::*; use crate::syscall::test::{ArgName, FsconfigArgs, FsopenArgs, MountArgs, TestHelperSyscall}; @@ -1279,6 +1413,39 @@ mod tests { .unwrap() } + fn setup_idmapped_mount_and_capture_request( + mounter: &Mount, + mount: &SpecMount, + options: &MountOptions<'_>, + ) -> Result { + let source = mount + .source() + .as_ref() + .context("mount source is required")?; + let mount_fd = std::fs::File::open(source)?; + let (mut main_sender, mut main_receiver) = channel::main_channel()?; + let (mut init_sender, mut init_receiver) = channel::init_channel()?; + let service = thread::spawn(move || -> Result { + let request = main_receiver.wait_for_mount_fd_request()?; + init_sender.send_mount_fd_reply(mount_fd.as_raw_fd())?; + main_receiver.close()?; + init_sender.close()?; + Ok(request) + }); + let mut mount_channels = MountChannels { + main: &mut main_sender, + init: &mut init_receiver, + }; + + mounter.setup_mount(mount, options, Some(&mut mount_channels))?; + main_sender.close()?; + init_receiver.close()?; + + service + .join() + .map_err(|_| anyhow::anyhow!("mount fd service thread panicked"))? + } + // Helpers to build the expected fsconfig calls of the fd-based mount flow. fn fsc_str(key: &str, val: &str) -> FsconfigArgs { FsconfigArgs { @@ -1940,6 +2107,7 @@ mod tests { rec_attr: None, propagation_flags: vec![], tmpcopyup: false, + apply_recursive_idmap: false, }; mounter .mount_cgroup_v2(&spec_cgroup_mount, &mount_opts, &mount_option_config) @@ -2070,6 +2238,212 @@ mod tests { Ok(()) } + #[test] + fn setup_idmapped_mount_requires_mount_channels() -> Result<()> { + let rootfs = tempfile::tempdir()?; + let mount = SpecMountBuilder::default() + .destination(PathBuf::from("/mnt")) + .typ("bind") + .source(PathBuf::from("/src")) + .options(vec!["bind".to_string(), "idmap".to_string()]) + .build()?; + let options = MountOptions { + root: rootfs.path(), + label: None, + cgroup_ns: true, + }; + + let err = Mount::new() + .setup_mount(&mount, &options, None) + .unwrap_err(); + + assert!(matches!( + err, + MountError::Custom(msg) if msg == "idmapped mount requires mount fd channel" + )); + Ok(()) + } + + #[test] + fn setup_idmapped_mount_constructs_bind_idmap_request() -> Result<()> { + let rootfs = tempfile::tempdir()?; + let source = tempfile::tempdir()?; + let mount = SpecMountBuilder::default() + .destination(PathBuf::from("/mnt")) + .typ("bind") + .source(source.path().to_path_buf()) + .options(vec!["bind".to_string(), "idmap".to_string()]) + .build()?; + let options = MountOptions { + root: rootfs.path(), + label: None, + cgroup_ns: true, + }; + + let request = setup_idmapped_mount_and_capture_request(&Mount::new(), &mount, &options)?; + + assert_eq!(request.source, source.path()); + assert!(!request.clone_mount_tree_recursively); + assert_eq!( + request.idmap, + Some(MountIdMap { + userns_source: MountIdMapUsernsSource::ContainerUserns, + apply_idmap_recursively: false, + }) + ); + Ok(()) + } + + #[test] + fn setup_idmapped_mount_constructs_rbind_idmap_request() -> Result<()> { + let rootfs = tempfile::tempdir()?; + let source = tempfile::tempdir()?; + let mount = SpecMountBuilder::default() + .destination(PathBuf::from("/mnt")) + .typ("bind") + .source(source.path().to_path_buf()) + .options(vec!["rbind".to_string(), "idmap".to_string()]) + .build()?; + let options = MountOptions { + root: rootfs.path(), + label: None, + cgroup_ns: true, + }; + + let request = setup_idmapped_mount_and_capture_request(&Mount::new(), &mount, &options)?; + + assert!(request.clone_mount_tree_recursively); + assert_eq!( + request.idmap, + Some(MountIdMap { + userns_source: MountIdMapUsernsSource::ContainerUserns, + apply_idmap_recursively: false, + }) + ); + Ok(()) + } + + #[test] + fn setup_idmapped_mount_constructs_rbind_ridmap_request() -> Result<()> { + let rootfs = tempfile::tempdir()?; + let source = tempfile::tempdir()?; + let mount = SpecMountBuilder::default() + .destination(PathBuf::from("/mnt")) + .typ("bind") + .source(source.path().to_path_buf()) + .options(vec!["rbind".to_string(), "ridmap".to_string()]) + .build()?; + let options = MountOptions { + root: rootfs.path(), + label: None, + cgroup_ns: true, + }; + + let request = setup_idmapped_mount_and_capture_request(&Mount::new(), &mount, &options)?; + + assert!(request.clone_mount_tree_recursively); + assert_eq!( + request.idmap, + Some(MountIdMap { + userns_source: MountIdMapUsernsSource::ContainerUserns, + apply_idmap_recursively: true, + }) + ); + Ok(()) + } + + #[test] + fn setup_idmapped_mount_constructs_mapping_request() -> Result<()> { + let rootfs = tempfile::tempdir()?; + let source = tempfile::tempdir()?; + let uid_mapping = LinuxIdMappingBuilder::default() + .container_id(0_u32) + .host_id(1000_u32) + .size(1_u32) + .build()?; + let gid_mapping = LinuxIdMappingBuilder::default() + .container_id(0_u32) + .host_id(2000_u32) + .size(1_u32) + .build()?; + let mount = SpecMountBuilder::default() + .destination(PathBuf::from("/mnt")) + .typ("bind") + .source(source.path().to_path_buf()) + .options(vec!["bind".to_string(), "idmap".to_string()]) + .uid_mappings(vec![uid_mapping]) + .gid_mappings(vec![gid_mapping]) + .build()?; + let options = MountOptions { + root: rootfs.path(), + label: None, + cgroup_ns: true, + }; + + let request = setup_idmapped_mount_and_capture_request(&Mount::new(), &mount, &options)?; + + assert_eq!( + request.idmap, + Some(MountIdMap { + userns_source: MountIdMapUsernsSource::Mappings { + uid_mappings: vec![uid_mapping], + gid_mappings: vec![gid_mapping], + }, + apply_idmap_recursively: false, + }) + ); + Ok(()) + } + + #[test] + fn setup_idmapped_mount_creates_destinations_inside_rootfs() -> Result<()> { + let rootfs = tempfile::tempdir()?; + let source_dir = tempfile::tempdir()?; + let source_file_dir = tempfile::tempdir()?; + let source_file = source_file_dir.path().join("source"); + OpenOptions::new() + .write(true) + .create_new(true) + .open(&source_file)?; + let options = MountOptions { + root: rootfs.path(), + label: None, + cgroup_ns: true, + }; + let cases = [ + (source_dir.path(), Path::new("/dir/dest"), true), + (source_file.as_path(), Path::new("/file/dest"), false), + ]; + + for (source, destination, is_dir) in cases { + let mount = SpecMountBuilder::default() + .destination(destination.to_path_buf()) + .typ("bind") + .source(source.to_path_buf()) + .options(vec!["bind".to_string(), "idmap".to_string()]) + .build()?; + let mounter = Mount::new(); + + setup_idmapped_mount_and_capture_request(&mounter, &mount, &options)?; + + let created = rootfs.path().join(destination.strip_prefix("/")?); + assert_eq!(created.is_dir(), is_dir); + assert_eq!(created.is_file(), !is_dir); + let moves = helper_syscall(&mounter).get_move_mount_args(); + assert_eq!(moves.len(), 1); + assert_eq!(moves[0].to_path, None); + assert_eq!(moves[0].to_dirfd_path.as_deref(), Some(created.as_path())); + assert_eq!( + moves[0].flags, + linux::MOVE_MOUNT_T_EMPTY_PATH | linux::MOVE_MOUNT_F_EMPTY_PATH + ); + let attrs = helper_syscall(&mounter).get_mount_setattr_args(); + assert_eq!(attrs.len(), 1); + assert_eq!(attrs[0].dirfd, moves[0].from_dirfd); + } + Ok(()) + } + #[test] fn setup_mount_proc_fails_if_destination_is_symlink() -> Result<()> { let tmp = tempfile::tempdir()?; @@ -2095,7 +2469,7 @@ mod tests { let m = Mount::new(); - let res = m.setup_mount(&mount, &options); + let res = m.setup_mount(&mount, &options, None); // proc destination symlink should be rejected assert!(res.is_err()); @@ -2130,7 +2504,7 @@ mod tests { let m = Mount::new(); - let res = m.setup_mount(&mount, &options); + let res = m.setup_mount(&mount, &options, None); // sys destination symlink should be rejected assert!(res.is_err()); diff --git a/crates/libcontainer/src/rootfs/rootfs.rs b/crates/libcontainer/src/rootfs/rootfs.rs index a3ce89740d..5a1056bf79 100644 --- a/crates/libcontainer/src/rootfs/rootfs.rs +++ b/crates/libcontainer/src/rootfs/rootfs.rs @@ -5,7 +5,7 @@ use nix::mount::MsFlags; use oci_spec::runtime::{Linux, Spec}; use super::device::Device; -use super::mount::{Mount, MountOptions}; +use super::mount::{Mount, MountChannels, MountOptions}; use super::symlink::Symlink; use super::utils::default_devices; use super::{Result, RootfsError}; @@ -42,6 +42,7 @@ impl RootFS { spec: &Spec, rootfs: &Path, cgroup_ns: bool, + mut mount_channels: Option<&mut MountChannels<'_>>, ) -> Result<()> { let flags = prepare_root_propagation(linux.rootfs_propagation().as_deref())?; @@ -83,7 +84,7 @@ impl RootFS { if let Some(mounts) = spec.mounts() { for mount in mounts { - mounter.setup_mount(mount, &global_options)?; + mounter.setup_mount(mount, &global_options, mount_channels.as_deref_mut())?; } } Ok(()) @@ -95,11 +96,12 @@ impl RootFS { rootfs: &Path, bind_devices: bool, cgroup_ns: bool, + mount_channels: Option<&mut MountChannels<'_>>, ) -> Result<()> { tracing::debug!(?rootfs, "prepare rootfs"); let linux = spec.linux().as_ref().ok_or(MissingSpecError::Linux)?; - self.mount_to_rootfs(linux, spec, rootfs, cgroup_ns)?; + self.mount_to_rootfs(linux, spec, rootfs, cgroup_ns, mount_channels)?; let symlinker = Symlink::new(); symlinker.setup_kcore_symlink(rootfs)?; diff --git a/crates/libcontainer/src/rootfs/utils.rs b/crates/libcontainer/src/rootfs/utils.rs index f9148ac52d..d2c1c7c853 100644 --- a/crates/libcontainer/src/rootfs/utils.rs +++ b/crates/libcontainer/src/rootfs/utils.rs @@ -11,6 +11,7 @@ use crate::syscall::linux::{self, MountOption, MountRecursive}; const IDMAP_FLAG: &str = "idmap"; const RIDMAP_FLAG: &str = "ridmap"; const TMPCOPYUP: &str = "tmpcopyup"; +const RBIND_FLAG: &str = "rbind"; #[derive(Debug, Clone, PartialEq, Eq)] pub struct MountOptionConfig { @@ -30,6 +31,9 @@ pub struct MountOptionConfig { /// `tmpcopyup`, an extension from runc and crun: the new tmpfs starts with a copy of what /// the directory it is mounted on holds. pub tmpcopyup: bool, + + /// Whether `ridmap` asked for the id-mapping to apply to submounts too. + pub apply_recursive_idmap: bool, } pub fn default_devices() -> Vec { @@ -100,6 +104,7 @@ pub fn parse_mount(m: &Mount) -> std::result::Result = None; let mut tmpcopyup = false; + let mut apply_recursive_idmap = false; if let Some(options) = &m.options() { for option in options { @@ -108,6 +113,7 @@ pub fn parse_mount(m: &Mount) -> std::result::Result { + apply_recursive_idmap = true; continue; } TMPCOPYUP => { @@ -222,6 +228,7 @@ pub fn parse_mount(m: &Mount) -> std::result::Result bool { m.typ().as_deref() == Some("bind") || m.options() .as_deref() - .is_some_and(|opts| opts.iter().any(|o| o == "bind" || o == "rbind")) + .is_some_and(|opts| opts.iter().any(|o| o == "bind" || o == RBIND_FLAG)) +} + +pub fn is_recursive_bind(m: &Mount) -> bool { + m.options() + .as_deref() + .is_some_and(|options| options.iter().any(|option| option == RBIND_FLAG)) } #[cfg(test)] mod tests { use anyhow::Result; - use oci_spec::runtime::MountBuilder; + use oci_spec::runtime::{LinuxIdMappingBuilder, MountBuilder}; use super::*; use crate::syscall::linux::MountAttr; @@ -303,6 +316,7 @@ mod tests { rec_attr: None, propagation_flags: vec![], tmpcopyup: false, + apply_recursive_idmap: false, }, mount_option_config ); @@ -327,6 +341,7 @@ mod tests { rec_attr: None, propagation_flags: vec![], tmpcopyup: false, + apply_recursive_idmap: false, }, mount_option_config ); @@ -359,6 +374,7 @@ mod tests { rec_attr: None, propagation_flags: vec![], tmpcopyup: false, + apply_recursive_idmap: false, }, mount_option_config ); @@ -384,6 +400,7 @@ mod tests { rec_attr: None, propagation_flags: vec![], tmpcopyup: false, + apply_recursive_idmap: false, }, mount_option_config ); @@ -408,6 +425,7 @@ mod tests { rec_attr: None, propagation_flags: vec![], tmpcopyup: false, + apply_recursive_idmap: false, }, mount_option_config ); @@ -435,6 +453,7 @@ mod tests { rec_attr: None, propagation_flags: vec![], tmpcopyup: false, + apply_recursive_idmap: false, }, mount_option_config ); @@ -464,6 +483,7 @@ mod tests { rec_attr: None, propagation_flags: vec![], tmpcopyup: false, + apply_recursive_idmap: false, }, mount_option_config, ); @@ -532,6 +552,7 @@ mod tests { MsFlags::MS_SLAVE | MsFlags::MS_REC, ], tmpcopyup: false, + apply_recursive_idmap: false, }, mount_option_config ); @@ -568,6 +589,7 @@ mod tests { rec_attr: Some(MountAttr::all()), propagation_flags: vec![], tmpcopyup: false, + apply_recursive_idmap: false, }, mount_option_config ); @@ -582,6 +604,7 @@ mod tests { .options(vec!["idmap".to_string()]) .build()?, )?; + assert!(!mount_option_config.apply_recursive_idmap); assert_eq!(mount_option_config.data, Vec::::new()); let mount_option_config = parse_mount( @@ -589,8 +612,22 @@ mod tests { .options(vec!["ridmap".to_string()]) .build()?, )?; + assert!(mount_option_config.apply_recursive_idmap); assert_eq!(mount_option_config.data, Vec::::new()); + let mapping = LinuxIdMappingBuilder::default() + .container_id(0_u32) + .host_id(1000_u32) + .size(1_u32) + .build()?; + let mount_option_config = parse_mount( + &MountBuilder::default() + .uid_mappings(vec![mapping]) + .gid_mappings(vec![mapping]) + .build()?, + )?; + assert!(!mount_option_config.apply_recursive_idmap); + Ok(()) } @@ -775,4 +812,19 @@ mod tests { let m4 = MountBuilder::default().typ("tmpfs").build().unwrap(); assert!(!is_bind(&m4)); } + + #[test] + fn test_is_recursive_bind() { + let recursive = MountBuilder::default() + .options(vec!["rbind".to_string()]) + .build() + .unwrap(); + assert!(is_recursive_bind(&recursive)); + + let bind = MountBuilder::default() + .options(vec!["bind".to_string()]) + .build() + .unwrap(); + assert!(!is_recursive_bind(&bind)); + } } diff --git a/crates/libcontainer/src/syscall/linux.rs b/crates/libcontainer/src/syscall/linux.rs index c63a1e48b5..f7309676f0 100644 --- a/crates/libcontainer/src/syscall/linux.rs +++ b/crates/libcontainer/src/syscall/linux.rs @@ -41,9 +41,15 @@ pub const MOUNT_ATTR_NOATIME: u64 = 0x00000010; pub const MOUNT_ATTR_STRICTATIME: u64 = 0x00000020; pub const MOUNT_ATTR_NODIRATIME: u64 = 0x00000080; pub const MOUNT_ATTR_NOSYMFOLLOW: u64 = 0x00200000; +pub const MOUNT_ATTR_IDMAP: u64 = 0x00100000; // Idmap mount to @userns_fd in struct mount_attr. pub const MOVE_MOUNT_F_EMPTY_PATH: u32 = 0x00000004; pub const MOVE_MOUNT_T_EMPTY_PATH: u32 = 0x00000040; +// Flags used in open_tree(2). +// see https://man7.org/linux/man-pages/man2/open_tree.2.html. +pub const OPEN_TREE_CLONE: u32 = 0x00000001; // Clone the target path as a detached mount. +pub const OPEN_TREE_CLOEXEC: u32 = 0x00080000; // == O_CLOEXEC. + // The type of fsconfig() call made. pub const FSCONFIG_SET_FLAG: u64 = 0; pub const FSCONFIG_SET_STRING: u64 = 1; diff --git a/crates/youki/src/commands/features.rs b/crates/youki/src/commands/features.rs index 554854faeb..4324f61d5f 100644 --- a/crates/youki/src/commands/features.rs +++ b/crates/youki/src/commands/features.rs @@ -79,8 +79,7 @@ pub fn features(_: Features) -> Result<()> { .apparmor(ApparmorBuilder::default().enabled(true).build().unwrap()) .mount_extensions( MountExtensionsBuilder::default() - // idmapped mounts is not supported in youki - .idmap(IDMapBuilder::default().enabled(false).build().unwrap()) + .idmap(IDMapBuilder::default().enabled(true).build().unwrap()) .build() .unwrap(), ) diff --git a/tests/contest/contest/src/tests/idmap/idmap_test.rs b/tests/contest/contest/src/tests/idmap/idmap_test.rs new file mode 100644 index 0000000000..c7e0d81b7b --- /dev/null +++ b/tests/contest/contest/src/tests/idmap/idmap_test.rs @@ -0,0 +1,945 @@ +use std::fs; +use std::os::unix::fs::symlink; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result}; +use nix::mount::{MntFlags, MsFlags, mount, umount2}; +use nix::unistd::{Gid, Uid, chown}; +use oci_spec::runtime::{ + LinuxBuilder, LinuxIdMapping, LinuxIdMappingBuilder, LinuxNamespace, LinuxNamespaceBuilder, + LinuxNamespaceType, Mount, MountBuilder, ProcessBuilder, RootBuilder, Spec, SpecBuilder, + get_default_mounts, +}; +use tempfile::TempDir; +use test_framework::{ConditionalTest, Test, TestGroup, TestResult, test_result}; + +use crate::tests::lifecycle::ContainerLifecycle; +use crate::utils::test_utils::CreateOptions; +use crate::utils::{ + State, get_runtimetest_path, get_state, is_runtime_runc, set_config, test_inside_container, +}; + +const USERNS_HOST_ID: u32 = 100_000; +const USERNS_SIZE: u32 = 65_536; +const STATE_WAIT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10); + +// Ported from runc/tests/integration/idmap.bats, keeping its order. + +fn id_mapping(container_id: u32, host_id: u32, size: u32) -> Result { + LinuxIdMappingBuilder::default() + .container_id(container_id) + .host_id(host_id) + .size(size) + .build() + .context("failed to build id mapping") +} + +fn id_mappings(container_id: u32, host_id: u32, size: u32) -> Result> { + Ok(vec![id_mapping(container_id, host_id, size)?]) +} + +fn id_mappings_from_tuples(mappings: &[(u32, u32, u32)]) -> Result> { + mappings + .iter() + .map(|(container_id, host_id, size)| id_mapping(*container_id, *host_id, *size)) + .collect() +} + +fn userns_mappings(host_id: u32) -> Result> { + id_mappings(0, host_id, USERNS_SIZE) +} + +fn create_linux_config(use_userns: bool, userns_host_id: u32) -> Result { + let mut builder = LinuxBuilder::default().readonly_paths(vec![]); + if use_userns { + let mut namespaces: Vec = oci_spec::runtime::get_default_namespaces(); + namespaces.push( + LinuxNamespaceBuilder::default() + .typ(LinuxNamespaceType::User) + .build() + .context("failed to build user namespace")?, + ); + builder = builder + .namespaces(namespaces) + .uid_mappings(userns_mappings(userns_host_id)?) + .gid_mappings(userns_mappings(userns_host_id)?); + } + builder.build().context("failed to build linux config") +} + +fn create_linux_config_joining_userns(userns_path: PathBuf) -> Result { + let mut namespaces: Vec = oci_spec::runtime::get_default_namespaces(); + namespaces.retain(|namespace| namespace.typ() != LinuxNamespaceType::User); + namespaces.push( + LinuxNamespaceBuilder::default() + .typ(LinuxNamespaceType::User) + .path(userns_path) + .build() + .context("failed to build joined user namespace")?, + ); + + LinuxBuilder::default() + .readonly_paths(vec![]) + .namespaces(namespaces) + .build() + .context("failed to build linux config") +} + +fn create_idmap_spec_with_linux( + mounts: Vec, + case: &str, + linux: oci_spec::runtime::Linux, +) -> Result { + let mut all_mounts = get_default_mounts(); + all_mounts.extend(mounts); + + SpecBuilder::default() + .mounts(all_mounts) + .root( + RootBuilder::default() + .readonly(false) + .build() + .context("failed to build root")?, + ) + .linux(linux) + .process( + ProcessBuilder::default() + .args(vec![ + "runtimetest".to_string(), + "idmap".to_string(), + case.to_string(), + ]) + .build() + .context("failed to build process")?, + ) + .build() + .context("failed to build spec") +} + +fn create_idmap_spec( + mounts: Vec, + case: &str, + use_userns: bool, + userns_host_id: u32, +) -> Result { + create_idmap_spec_with_linux( + mounts, + case, + create_linux_config(use_userns, userns_host_id)?, + ) +} + +fn create_userns_holder_spec() -> Result { + // This container only needs to keep a user namespace alive. In principle + // `sleep` would be enough, as in runc's test, but contest's bundled rootfs + // is a fixed x86_64 artifact. On aarch64 local environments such as Apple + // Silicon Lima, rootfs binaries like /bin/sleep cannot run. Use the + // current-arch runtimetest binary copied into the rootfs instead. + create_idmap_spec(vec![], "target_userns_sleep", true, USERNS_HOST_ID) +} + +fn build_bind_mount( + source: &Path, + destination: &str, + options: &[&str], + uid_mappings: Option>, + gid_mappings: Option>, +) -> Result { + let mut builder = MountBuilder::default() + .destination(PathBuf::from(destination)) + .typ("bind") + .source(source) + .options( + options + .iter() + .map(|option| option.to_string()) + .collect::>(), + ); + + if let Some(uid_mappings) = uid_mappings { + builder = builder.uid_mappings(uid_mappings); + } + if let Some(gid_mappings) = gid_mappings { + builder = builder.gid_mappings(gid_mappings); + } + + builder.build().context("failed to build bind mount") +} + +fn build_basic_idmapped_bind_mount( + source: &Path, + destination: &str, + options: &[&str], + uid_host_id: u32, + gid_host_id: u32, + size: u32, +) -> Result { + build_bind_mount( + source, + destination, + options, + Some(id_mappings(0, uid_host_id, size)?), + Some(id_mappings(0, gid_host_id, size)?), + ) +} + +fn build_idmapped_bind_mount( + source: &Path, + destination: &str, + options: &[&str], + uid_mapping: (u32, u32, u32), + gid_mapping: (u32, u32, u32), +) -> Result { + build_bind_mount( + source, + destination, + options, + Some(id_mappings(uid_mapping.0, uid_mapping.1, uid_mapping.2)?), + Some(id_mappings(gid_mapping.0, gid_mapping.1, gid_mapping.2)?), + ) +} + +fn build_idmapped_bind_mount_with_mappings( + source: &Path, + destination: &str, + options: &[&str], + uid_mappings: &[(u32, u32, u32)], + gid_mappings: &[(u32, u32, u32)], +) -> Result { + build_bind_mount( + source, + destination, + options, + Some(id_mappings_from_tuples(uid_mappings)?), + Some(id_mappings_from_tuples(gid_mappings)?), + ) +} + +fn build_tree_idmapped_bind_mount( + source: &Path, + destination: &str, + options: &[&str], +) -> Result { + build_bind_mount( + source, + destination, + options, + Some(vec![ + id_mapping(100, 101000, 3)?, + id_mapping(200, 102000, 3)?, + id_mapping(300, 103000, 3)?, + ]), + Some(vec![ + id_mapping(210, 101100, 10)?, + id_mapping(220, 102200, 10)?, + id_mapping(230, 103300, 10)?, + ]), + ) +} + +fn write_owned_file(path: &Path, uid: u32, gid: u32) -> Result<()> { + fs::write(path, b"idmap test\n") + .with_context(|| format!("failed to write {}", path.display()))?; + chown(path, Some(Uid::from_raw(uid)), Some(Gid::from_raw(gid))) + .with_context(|| format!("failed to chown {}", path.display())) +} + +fn setup_single_owned_file(source: &Path, uid: u32, gid: u32) -> Result<()> { + fs::create_dir_all(source).with_context(|| format!("failed to create {}", source.display()))?; + write_owned_file(&source.join("foo.txt"), uid, gid) +} + +fn setup_owned_files(source: &Path, files: &[(u32, u32); 3]) -> Result<()> { + fs::create_dir_all(source).with_context(|| format!("failed to create {}", source.display()))?; + for (name, (uid, gid)) in ["foo.txt", "bar.txt", "baz.txt"] + .into_iter() + .zip(files.iter()) + { + write_owned_file(&source.join(name), *uid, *gid)?; + } + Ok(()) +} + +fn bind_mount(source: &Path, target: &Path) -> Result<()> { + mount( + Some(source), + target, + None::<&str>, + MsFlags::MS_BIND, + None::<&str>, + ) + .with_context(|| { + format!( + "failed to bind mount {} on {}", + source.display(), + target.display() + ) + }) +} + +fn setup_owned_bind_mount_tree( + mount_tree: &Path, + top_files: &[(u32, u32); 3], + child1_files: &[(u32, u32); 3], + child2_files: &[(u32, u32); 3], +) -> Result<()> { + fs::create_dir_all(mount_tree) + .with_context(|| format!("failed to create {}", mount_tree.display()))?; + setup_owned_files(mount_tree, top_files)?; + + let parent = mount_tree + .parent() + .context("mount tree source must have a parent directory")?; + let child1_source = parent.join("source-multi1"); + let child2_source = parent.join("source-multi2"); + setup_owned_files(&child1_source, child1_files)?; + setup_owned_files(&child2_source, child2_files)?; + + let multi1 = mount_tree.join("multi1"); + let multi2 = mount_tree.join("multi2"); + fs::create_dir_all(&multi1)?; + fs::create_dir_all(&multi2)?; + bind_mount(&child1_source, &multi1)?; + bind_mount(&child2_source, &multi2) +} + +fn setup_runc_idmap_tree(source: &Path) -> Result<()> { + setup_owned_bind_mount_tree( + source, + &[(100, 211), (200, 222), (300, 233)], + &[(100, 211), (101, 222), (102, 233)], + &[(200, 211), (201, 222), (202, 233)], + ) +} + +fn cleanup_tree(source: &Path) { + for dir in ["multi1", "multi2"] { + let mountpoint = source.join(dir); + if let Err(err) = umount2(&mountpoint, MntFlags::MNT_DETACH) { + eprintln!( + "failed to cleanup idmap test mount {}: {err}", + mountpoint.display() + ); + } + } +} + +fn run_idmap_case(case: &str, spec: Spec, setup: F) -> TestResult +where + F: Fn() -> Result<()>, +{ + test_inside_container(&spec, &CreateOptions::default(), &|rootfs| { + if let Some(mounts) = spec.mounts() { + for mount in mounts { + let relative_destination = mount + .destination() + .strip_prefix("/") + .unwrap_or_else(|_| mount.destination()); + fs::create_dir_all(rootfs.join(relative_destination)).with_context(|| { + format!( + "failed to create mount destination {:?}", + mount.destination() + ) + })?; + } + } + setup().with_context(|| format!("failed to setup idmap case {case}")) + }) +} + +fn require_passed(result: TestResult, context: &str) -> Result<()> { + match result { + TestResult::Passed => Ok(()), + TestResult::Skipped(_) => anyhow::bail!("{context}: skipped"), + TestResult::Failed(err) => Err(err).with_context(|| context.to_string()), + } +} + +fn container_state(container: &ContainerLifecycle) -> Result { + let (stdout, stderr) = get_state(container.get_id(), container.get_project_path()) + .context("failed to get state")?; + if !stderr.is_empty() { + anyhow::bail!("failed to get container state: {stderr}"); + } + serde_json::from_str(&stdout).context("failed to parse container state") +} + +struct UsernsHolderContainer { + container: ContainerLifecycle, + pid: i32, +} + +impl UsernsHolderContainer { + fn userns_path(&self) -> PathBuf { + PathBuf::from(format!("/proc/{}/ns/user", self.pid)) + } +} + +impl Drop for UsernsHolderContainer { + fn drop(&mut self) { + let _ = self.container.kill(); + let _ = self.container.delete(); + } +} + +fn start_userns_holder_container() -> Result { + let container = ContainerLifecycle::new(); + let spec = create_userns_holder_spec()?; + set_config(container.get_project_path(), &spec) + .context("failed to set target userns config")?; + + spec.save( + container + .get_project_path() + .join("bundle") + .join("rootfs") + .join("config.json"), + ) + .context("failed to save target userns spec inside rootfs")?; + // The holder runs runtimetest like the other cases, so its rootfs needs + // that binary too. + std::fs::copy( + get_runtimetest_path(), + container + .get_project_path() + .join("bundle") + .join("rootfs") + .join("bin") + .join("runtimetest"), + ) + .context("failed to copy runtimetest into target userns bundle")?; + + require_passed( + container.create(), + "failed to create target userns container", + )?; + require_passed( + container.wait_for_state("created", STATE_WAIT_TIMEOUT), + "target userns container did not reach created state", + )?; + require_passed(container.start(), "failed to start target userns container")?; + require_passed( + container.wait_for_state("running", STATE_WAIT_TIMEOUT), + "target userns container did not reach running state", + )?; + + let state = container_state(&container).context("failed to get target userns state")?; + let pid = state + .pid + .context("target userns state did not include a pid")?; + + Ok(UsernsHolderContainer { container, pid }) +} + +fn run_single_file_idmapped_bind_case(case: &'static str, use_userns: bool) -> TestResult { + let tmp = test_result!(TempDir::new().context("failed to create tempdir")); + let source = tmp.path().join("mount-1"); + let mount = test_result!(build_basic_idmapped_bind_mount( + &source, + "/tmp/mount-1", + &["bind"], + USERNS_HOST_ID, + USERNS_HOST_ID, + USERNS_SIZE, + )); + let spec = test_result!(create_idmap_spec( + vec![mount], + case, + use_userns, + USERNS_HOST_ID + )); + run_idmap_case(case, spec, || setup_single_owned_file(&source, 0, 0)) +} + +fn run_relative_destination_idmapped_bind_case() -> TestResult { + let tmp = test_result!(TempDir::new().context("failed to create tempdir")); + let source = tmp.path().join("mount-1"); + let mount = test_result!(build_basic_idmapped_bind_mount( + &source, + "tmp/mount-1", + &["bind"], + USERNS_HOST_ID, + USERNS_HOST_ID, + USERNS_SIZE, + )); + let spec = test_result!(create_idmap_spec( + vec![mount], + "idmap_mount_with_relative_path_userns", + true, + USERNS_HOST_ID + )); + run_idmap_case("idmap_mount_with_relative_path_userns", spec, || { + setup_single_owned_file(&source, 0, 0) + }) +} + +fn run_joined_userns_implied_idmap_case() -> TestResult { + let tmp = test_result!(TempDir::new().context("failed to create tempdir")); + let source = tmp.path().join("mount-tree"); + let mount = test_result!(build_bind_mount( + &source, + "/tmp/mount-tree", + &["rbind", "idmap"], + None, + None, + )); + let target = test_result!(start_userns_holder_container()); + let linux = test_result!(create_linux_config_joining_userns(target.userns_path())); + let spec = test_result!(create_idmap_spec_with_linux( + vec![mount], + "idmap_mount_idmap_flag_implied_mapping_userns_join_userns", + linux, + )); + let result = run_idmap_case( + "idmap_mount_idmap_flag_implied_mapping_userns_join_userns", + spec, + || setup_runc_idmap_tree(&source), + ); + cleanup_tree(&source); + result +} + +fn run_propagation_idmapped_bind_case() -> TestResult { + let tmp = test_result!(TempDir::new().context("failed to create tempdir")); + let source = tmp.path().join("mount-1"); + let mount = test_result!(build_basic_idmapped_bind_mount( + &source, + "/tmp/mount-1", + &["bind", "shared"], + USERNS_HOST_ID, + USERNS_HOST_ID, + USERNS_SIZE, + )); + let spec = test_result!(create_idmap_spec( + vec![mount], + "idmap_mount_with_propagation_flag_userns", + true, + USERNS_HOST_ID, + )); + run_idmap_case("idmap_mount_with_propagation_flag_userns", spec, || { + setup_single_owned_file(&source, 0, 0) + }) +} + +fn run_idmapped_and_plain_bind_case(case: &'static str, use_userns: bool) -> TestResult { + let tmp = test_result!(TempDir::new().context("failed to create tempdir")); + let source = tmp.path().join("mount-1"); + let idmapped = test_result!(build_basic_idmapped_bind_mount( + &source, + "/tmp/mount-1", + &["bind"], + USERNS_HOST_ID, + USERNS_HOST_ID, + USERNS_SIZE, + )); + let plain = test_result!(build_bind_mount( + &source, + "/tmp/bind-mount-1", + &["bind"], + None, + None + )); + let spec = test_result!(create_idmap_spec( + vec![idmapped, plain], + case, + use_userns, + USERNS_HOST_ID, + )); + run_idmap_case(case, spec, || setup_single_owned_file(&source, 0, 0)) +} + +fn run_two_idmapped_binds_same_mapping_case() -> TestResult { + let tmp = test_result!(TempDir::new().context("failed to create tempdir")); + let source1 = tmp.path().join("mount-1"); + let source2 = tmp.path().join("mount-2"); + let idmapped1 = test_result!(build_basic_idmapped_bind_mount( + &source1, + "/tmp/mount-1", + &["bind"], + USERNS_HOST_ID, + USERNS_HOST_ID, + USERNS_SIZE, + )); + let plain1 = test_result!(build_bind_mount( + &source1, + "/tmp/bind-mount-1", + &["bind"], + None, + None, + )); + let plain2 = test_result!(build_bind_mount( + &source2, + "/tmp/bind-mount-2", + &["bind"], + None, + None, + )); + let idmapped2 = test_result!(build_basic_idmapped_bind_mount( + &source2, + "/tmp/mount-2", + &["bind"], + USERNS_HOST_ID, + USERNS_HOST_ID, + USERNS_SIZE, + )); + let spec = test_result!(create_idmap_spec( + vec![idmapped1, plain1, plain2, idmapped2], + "two_idmap_mounts_same_mapping_with_two_bind_mounts_userns", + true, + USERNS_HOST_ID, + )); + run_idmap_case( + "two_idmap_mounts_same_mapping_with_two_bind_mounts_userns", + spec, + || { + setup_single_owned_file(&source1, 0, 0)?; + setup_single_owned_file(&source2, 1, 1) + }, + ) +} + +fn run_same_source_different_mappings_case(case: &'static str, use_userns: bool) -> TestResult { + let tmp = test_result!(TempDir::new().context("failed to create tempdir")); + let source = tmp.path().join("multi1"); + let source_symlink = tmp.path().join("multi1-symlink"); + let mount1 = test_result!(build_idmapped_bind_mount( + &source, + "/tmp/mount-multi1", + &["bind"], + (100, 100000, 100), + (200, 100000, 100), + )); + let mount2 = test_result!(build_idmapped_bind_mount( + &source, + "/tmp/mount-multi1-alt", + &["bind"], + (100, 101000, 100), + (200, 102000, 100), + )); + let mount3 = test_result!(build_idmapped_bind_mount( + &source_symlink, + "/tmp/mount-multi1-alt-sym", + &["bind"], + (100, 102000, 100), + (200, 103000, 100), + )); + let spec = test_result!(create_idmap_spec( + vec![mount1, mount2, mount3], + case, + use_userns, + USERNS_HOST_ID, + )); + run_idmap_case(case, spec, || { + setup_owned_files(&source, &[(100, 211), (101, 222), (102, 233)])?; + symlink(&source, &source_symlink).with_context(|| { + format!( + "failed to symlink {} to {}", + source_symlink.display(), + source.display() + ) + }) + }) +} + +fn run_multiple_sources_different_mappings_case( + case: &'static str, + use_userns: bool, +) -> TestResult { + let tmp = test_result!(TempDir::new().context("failed to create tempdir")); + let source1 = tmp.path().join("multi1"); + let source2 = tmp.path().join("multi2"); + let source3 = tmp.path().join("multi3"); + let userns_offset = if use_userns { USERNS_HOST_ID } else { 0 }; + let mount1 = test_result!(build_idmapped_bind_mount( + &source1, + "/tmp/mount-multi1", + &["bind"], + (100, userns_offset + 1100, 3), + (200, userns_offset + 1900, 50), + )); + let mount2 = test_result!(build_idmapped_bind_mount( + &source2, + "/tmp/mount-multi2", + &["bind"], + (200, userns_offset + 2200, 3), + (200, userns_offset + 2900, 100), + )); + let mount3 = test_result!(build_idmapped_bind_mount( + &source3, + "/tmp/mount-multi3", + &["bind"], + (5000000, userns_offset + 3000, 1000), + (6000000, userns_offset + 3000, 500), + )); + let spec = test_result!(create_idmap_spec( + vec![mount1, mount2, mount3], + case, + use_userns, + USERNS_HOST_ID + )); + run_idmap_case(case, spec, || { + setup_owned_files(&source1, &[(100, 211), (101, 222), (102, 233)])?; + setup_owned_files(&source2, &[(200, 211), (201, 222), (202, 233)])?; + setup_owned_files( + &source3, + &[(5000528, 6000491), (5000133, 6000337), (5000999, 6000444)], + ) + }) +} + +fn run_complicated_mapping_case(case: &'static str, use_userns: bool) -> TestResult { + let tmp = test_result!(TempDir::new().context("failed to create tempdir")); + let source = tmp.path().join("multi1"); + let userns_offset = if use_userns { USERNS_HOST_ID } else { 0 }; + let mount = test_result!(build_idmapped_bind_mount_with_mappings( + &source, + "/tmp/mount-multi1", + &["bind"], + &[ + (100, userns_offset + 1000, 1), + (101, userns_offset + 2000, 1), + (102, userns_offset + 3000, 1), + ], + &[ + (210, userns_offset + 1100, 10), + (220, userns_offset + 2200, 10), + (230, userns_offset + 3300, 10), + ], + )); + let spec = test_result!(create_idmap_spec( + vec![mount], + case, + use_userns, + USERNS_HOST_ID + )); + run_idmap_case(case, spec, || { + setup_owned_files(&source, &[(100, 211), (101, 222), (102, 233)]) + }) +} + +fn run_tree_idmapped_bind_case( + case: &'static str, + options: &[&'static str], + use_userns: bool, +) -> TestResult { + let tmp = test_result!(TempDir::new().context("failed to create tempdir")); + let source = tmp.path().join("mount-tree"); + let mount = test_result!(build_tree_idmapped_bind_mount( + &source, + "/tmp/mount-tree", + options, + )); + let spec = test_result!(create_idmap_spec( + vec![mount], + case, + use_userns, + USERNS_HOST_ID + )); + let result = run_idmap_case(case, spec, || setup_runc_idmap_tree(&source)); + cleanup_tree(&source); + result +} + +fn run_implied_mapping_tree_case(case: &'static str, option: &'static str) -> TestResult { + let tmp = test_result!(TempDir::new().context("failed to create tempdir")); + let source = tmp.path().join("mount-tree"); + let mount = test_result!(build_bind_mount( + &source, + "/tmp/mount-tree", + &["rbind", option], + None, + None + )); + let spec = test_result!(create_idmap_spec(vec![mount], case, true, USERNS_HOST_ID)); + let result = run_idmap_case(case, spec, || setup_runc_idmap_tree(&source)); + cleanup_tree(&source); + result +} + +pub fn get_idmap_test() -> TestGroup { + let mut test_group = TestGroup::new("idmap"); + test_group.set_nonparallel(); + + // runc warns on stderr that a relative destination is deprecated, which + // test_inside_container treats as a failure. + test_group.add(vec![Box::new(ConditionalTest::new( + "idmap_mount_with_relative_path_userns", + Box::new(|| !is_runtime_runc()), + Box::new(run_relative_destination_idmapped_bind_case), + ))]); + + test_group.add(vec![ + Box::new(Test::new( + "simple_idmap_mount_userns", + Box::new(|| run_single_file_idmapped_bind_case("simple_idmap_mount_userns", true)), + )), + Box::new(Test::new( + "simple_idmap_mount_no_userns", + Box::new(|| run_single_file_idmapped_bind_case("simple_idmap_mount_no_userns", false)), + )), + Box::new(Test::new( + "write_to_an_idmap_mount_userns", + Box::new(|| run_single_file_idmapped_bind_case("write_to_an_idmap_mount_userns", true)), + )), + Box::new(Test::new( + "write_to_an_idmap_mount_no_userns", + Box::new(|| { + run_single_file_idmapped_bind_case("write_to_an_idmap_mount_no_userns", false) + }), + )), + Box::new(Test::new( + "idmap_mount_with_propagation_flag_userns", + Box::new(run_propagation_idmapped_bind_case), + )), + Box::new(Test::new( + "idmap_mount_with_bind_mount_userns", + Box::new(|| { + run_idmapped_and_plain_bind_case("idmap_mount_with_bind_mount_userns", true) + }), + )), + Box::new(Test::new( + "idmap_mount_with_bind_mount_no_userns", + Box::new(|| { + run_idmapped_and_plain_bind_case("idmap_mount_with_bind_mount_no_userns", false) + }), + )), + Box::new(Test::new( + "two_idmap_mounts_same_mapping_with_two_bind_mounts_userns", + Box::new(run_two_idmapped_binds_same_mapping_case), + )), + Box::new(Test::new( + "same_idmap_mount_different_mappings_userns", + Box::new(|| { + run_same_source_different_mappings_case( + "same_idmap_mount_different_mappings_userns", + true, + ) + }), + )), + Box::new(Test::new( + "same_idmap_mount_different_mappings_no_userns", + Box::new(|| { + run_same_source_different_mappings_case( + "same_idmap_mount_different_mappings_no_userns", + false, + ) + }), + )), + Box::new(Test::new( + "multiple_idmap_mounts_different_mappings_userns", + Box::new(|| { + run_multiple_sources_different_mappings_case( + "multiple_idmap_mounts_different_mappings_userns", + true, + ) + }), + )), + Box::new(Test::new( + "multiple_idmap_mounts_different_mappings_no_userns", + Box::new(|| { + run_multiple_sources_different_mappings_case( + "multiple_idmap_mounts_different_mappings_no_userns", + false, + ) + }), + )), + Box::new(Test::new( + "idmap_mount_complicated_mapping_userns", + Box::new(|| { + run_complicated_mapping_case("idmap_mount_complicated_mapping_userns", true) + }), + )), + Box::new(Test::new( + "idmap_mount_complicated_mapping_no_userns", + Box::new(|| { + run_complicated_mapping_case("idmap_mount_complicated_mapping_no_userns", false) + }), + )), + Box::new(Test::new( + "idmap_mount_non_recursive_idmap_userns", + Box::new(|| { + run_tree_idmapped_bind_case( + "idmap_mount_non_recursive_idmap_userns", + &["rbind"], + true, + ) + }), + )), + Box::new(Test::new( + "idmap_mount_non_recursive_idmap_no_userns", + Box::new(|| { + run_tree_idmapped_bind_case( + "idmap_mount_non_recursive_idmap_no_userns", + &["rbind"], + false, + ) + }), + )), + Box::new(Test::new( + "idmap_mount_idmap_flag_userns", + Box::new(|| { + run_tree_idmapped_bind_case( + "idmap_mount_idmap_flag_userns", + &["rbind", "idmap"], + true, + ) + }), + )), + Box::new(Test::new( + "idmap_mount_idmap_flag_no_userns", + Box::new(|| { + run_tree_idmapped_bind_case( + "idmap_mount_idmap_flag_no_userns", + &["rbind", "idmap"], + false, + ) + }), + )), + Box::new(Test::new( + "idmap_mount_ridmap_flag_userns", + Box::new(|| { + run_tree_idmapped_bind_case( + "idmap_mount_ridmap_flag_userns", + &["rbind", "ridmap"], + true, + ) + }), + )), + Box::new(Test::new( + "idmap_mount_ridmap_flag_no_userns", + Box::new(|| { + run_tree_idmapped_bind_case( + "idmap_mount_ridmap_flag_no_userns", + &["rbind", "ridmap"], + false, + ) + }), + )), + Box::new(Test::new( + "idmap_mount_idmap_flag_implied_mapping_userns", + Box::new(|| { + run_implied_mapping_tree_case( + "idmap_mount_idmap_flag_implied_mapping_userns", + "idmap", + ) + }), + )), + Box::new(Test::new( + "idmap_mount_ridmap_flag_implied_mapping_userns", + Box::new(|| { + run_implied_mapping_tree_case( + "idmap_mount_ridmap_flag_implied_mapping_userns", + "ridmap", + ) + }), + )), + Box::new(Test::new( + "idmap_mount_idmap_flag_implied_mapping_userns_join_userns", + Box::new(run_joined_userns_implied_idmap_case), + )), + ]); + + test_group +} + +test_framework::register_test_group!(get_idmap_test); diff --git a/tests/contest/contest/src/tests/idmap/mod.rs b/tests/contest/contest/src/tests/idmap/mod.rs new file mode 100644 index 0000000000..a24e1a058d --- /dev/null +++ b/tests/contest/contest/src/tests/idmap/mod.rs @@ -0,0 +1,3 @@ +mod idmap_test; + +pub use idmap_test::get_idmap_test; diff --git a/tests/contest/contest/src/tests/mod.rs b/tests/contest/contest/src/tests/mod.rs index 78294df2ad..52c6f40b01 100644 --- a/tests/contest/contest/src/tests/mod.rs +++ b/tests/contest/contest/src/tests/mod.rs @@ -12,6 +12,7 @@ pub mod exec_env; pub mod fd_control; pub mod hooks; pub mod hostname; +pub mod idmap; pub mod intel_rdt; pub mod io_priority; pub mod kill; diff --git a/tests/contest/runtimetest/src/main.rs b/tests/contest/runtimetest/src/main.rs index 1bad3cb09e..0b3881d86b 100644 --- a/tests/contest/runtimetest/src/main.rs +++ b/tests/contest/runtimetest/src/main.rs @@ -64,6 +64,7 @@ fn main() { "rootfs_propagation" => tests::validate_rootfs_propagation(&spec), "mount_propagation" => tests::validate_mount_propagation(&spec), "uid_mappings" => tests::validate_uid_mappings(&spec), + "idmap" => tests::validate_idmap(&spec), "net_devices" => tests::validate_net_devices(&spec), "time_offsets" => tests::validate_time_offsets(&spec), "default_symlinks" => tests::validate_default_symlinks(&spec), diff --git a/tests/contest/runtimetest/src/tests.rs b/tests/contest/runtimetest/src/tests.rs index 2b7fc0c44d..b0342a70a5 100644 --- a/tests/contest/runtimetest/src/tests.rs +++ b/tests/contest/runtimetest/src/tests.rs @@ -1782,7 +1782,6 @@ pub fn validate_tmpcopyup(spec: &Spec) { } } } - /// Checks that the tmpfs mounts have the expected mode specified in the /// `org.youki.contest.tmpfs` annotation as an octal value. pub fn validate_tmpfs(spec: &Spec) { @@ -1967,3 +1966,238 @@ pub fn validate_device_cgroup(spec: &Spec) { } } } +pub fn validate_idmap(_spec: &Spec) { + let args = env::args().collect::>(); + let Some(case) = args.get(2) else { + eprintln!("idmap test case argument missing"); + std::process::exit(1); + }; + if let Err(err) = validate_idmap_case(case) { + eprintln!("idmap test case {case} failed: {err:?}"); + std::process::exit(1); + } +} + +fn validate_idmap_case(case: &str) -> Result<()> { + match case { + "target_userns_sleep" => { + std::thread::sleep(std::time::Duration::from_secs(1000)); + Ok(()) + } + "simple_idmap_mount_userns" | "idmap_mount_with_relative_path_userns" => { + expect_ids("/tmp/mount-1/foo.txt", 0, 0) + } + "simple_idmap_mount_no_userns" => expect_ids("/tmp/mount-1/foo.txt", 100000, 100000), + "write_to_an_idmap_mount_userns" => { + fs::File::create("/tmp/mount-1/bar")?; + expect_ids("/tmp/mount-1/bar", 0, 0) + } + "write_to_an_idmap_mount_no_userns" => match fs::File::create("/tmp/mount-1/bar") { + Ok(_) => bail!("write to idmapped mount without userns unexpectedly succeeded"), + Err(err) if err.raw_os_error() == Some(libc::EOVERFLOW) => Ok(()), + Err(err) => Err(err.into()), + }, + "idmap_mount_with_propagation_flag_userns" => expect_mount_shared("/tmp/mount-1"), + "idmap_mount_with_bind_mount_userns" => { + let (overflow_uid, overflow_gid) = overflow_ids()?; + expect_ids("/tmp/mount-1/foo.txt", 0, 0)?; + expect_ids("/tmp/bind-mount-1/foo.txt", overflow_uid, overflow_gid) + } + "idmap_mount_with_bind_mount_no_userns" => { + expect_ids("/tmp/mount-1/foo.txt", 100000, 100000)?; + expect_ids("/tmp/bind-mount-1/foo.txt", 0, 0) + } + "two_idmap_mounts_same_mapping_with_two_bind_mounts_userns" => { + expect_ids("/tmp/mount-1/foo.txt", 0, 0)?; + expect_ids("/tmp/mount-2/foo.txt", 1, 1) + } + "same_idmap_mount_different_mappings_userns" => { + expect_multi1("/tmp/mount-multi1", &[(0, 11), (1, 22), (2, 33)])?; + expect_multi1( + "/tmp/mount-multi1-alt", + &[(1000, 2011), (1001, 2022), (1002, 2033)], + )?; + expect_multi1( + "/tmp/mount-multi1-alt-sym", + &[(2000, 3011), (2001, 3022), (2002, 3033)], + ) + } + "same_idmap_mount_different_mappings_no_userns" => { + expect_multi1( + "/tmp/mount-multi1", + &[(100000, 100011), (100001, 100022), (100002, 100033)], + )?; + expect_multi1( + "/tmp/mount-multi1-alt", + &[(101000, 102011), (101001, 102022), (101002, 102033)], + )?; + expect_multi1( + "/tmp/mount-multi1-alt-sym", + &[(102000, 103011), (102001, 103022), (102002, 103033)], + ) + } + "multiple_idmap_mounts_different_mappings_userns" + | "multiple_idmap_mounts_different_mappings_no_userns" => { + expect_multi1( + "/tmp/mount-multi1", + &[(1100, 1911), (1101, 1922), (1102, 1933)], + )?; + expect_multi1( + "/tmp/mount-multi2", + &[(2200, 2911), (2201, 2922), (2202, 2933)], + )?; + expect_multi1( + "/tmp/mount-multi3", + &[(3528, 3491), (3133, 3337), (3999, 3444)], + ) + } + "idmap_mount_complicated_mapping_userns" | "idmap_mount_complicated_mapping_no_userns" => { + expect_multi1( + "/tmp/mount-multi1", + &[(1000, 1101), (2000, 2202), (3000, 3303)], + ) + } + "idmap_mount_non_recursive_idmap_userns" | "idmap_mount_idmap_flag_userns" => { + expect_tree_top(true)?; + expect_tree_children_unmapped(true) + } + "idmap_mount_non_recursive_idmap_no_userns" | "idmap_mount_idmap_flag_no_userns" => { + expect_tree_top(false)?; + expect_tree_children_unmapped(false) + } + "idmap_mount_ridmap_flag_userns" => { + expect_tree_top(true)?; + expect_tree_children_recursive(true) + } + "idmap_mount_ridmap_flag_no_userns" => { + expect_tree_top(false)?; + expect_tree_children_recursive(false) + } + "idmap_mount_idmap_flag_implied_mapping_userns" => { + expect_multi1("/tmp/mount-tree", &[(100, 211), (200, 222), (300, 233)])?; + expect_tree_children_unmapped(true) + } + "idmap_mount_ridmap_flag_implied_mapping_userns" => { + expect_multi1("/tmp/mount-tree", &[(100, 211), (200, 222), (300, 233)])?; + expect_multi1( + "/tmp/mount-tree/multi1", + &[(100, 211), (101, 222), (102, 233)], + )?; + expect_multi1( + "/tmp/mount-tree/multi2", + &[(200, 211), (201, 222), (202, 233)], + ) + } + "idmap_mount_idmap_flag_implied_mapping_userns_join_userns" => { + expect_multi1("/tmp/mount-tree", &[(100, 211), (200, 222), (300, 233)])?; + expect_tree_children_unmapped(true) + } + _ => bail!("unknown idmap test case: {case}"), + } +} + +fn expect_ids(path: &str, expected_uid: u32, expected_gid: u32) -> Result<()> { + let (actual_uid, actual_gid) = stat_ids(path)?; + if (actual_uid, actual_gid) != (expected_uid, expected_gid) { + bail!( + "{path}: expected uid/gid {expected_uid}:{expected_gid}, got {actual_uid}:{actual_gid}" + ); + } + Ok(()) +} + +fn expect_mount_shared(path: &str) -> Result<()> { + let mountinfo = fs::read_to_string("/proc/self/mountinfo")?; + for line in mountinfo.lines() { + let fields = line.split_whitespace().collect::>(); + if fields.len() < 7 || fields[4] != path { + continue; + } + let Some(separator) = fields.iter().position(|field| *field == "-") else { + continue; + }; + if fields[6..separator] + .iter() + .any(|field| field.starts_with("shared:")) + { + return Ok(()); + } + } + bail!("{path}: expected shared propagation in mountinfo") +} + +fn expect_multi1(prefix: &str, expected: &[(u32, u32); 3]) -> Result<()> { + expect_ids(&format!("{prefix}/foo.txt"), expected[0].0, expected[0].1)?; + expect_ids(&format!("{prefix}/bar.txt"), expected[1].0, expected[1].1)?; + expect_ids(&format!("{prefix}/baz.txt"), expected[2].0, expected[2].1) +} + +fn expect_tree_children_recursive(userns: bool) -> Result<()> { + if userns { + expect_multi1( + "/tmp/mount-tree/multi1", + &[(1000, 1101), (1001, 2202), (1002, 3303)], + )?; + expect_multi1( + "/tmp/mount-tree/multi2", + &[(2000, 1101), (2001, 2202), (2002, 3303)], + ) + } else { + expect_multi1( + "/tmp/mount-tree/multi1", + &[(101000, 101101), (101001, 102202), (101002, 103303)], + )?; + expect_multi1( + "/tmp/mount-tree/multi2", + &[(102000, 101101), (102001, 102202), (102002, 103303)], + ) + } +} + +fn expect_tree_children_unmapped(userns: bool) -> Result<()> { + if userns { + let (uid, gid) = overflow_ids()?; + for dir in ["multi1", "multi2"] { + for file in ["foo.txt", "bar.txt", "baz.txt"] { + expect_ids(&format!("/tmp/mount-tree/{dir}/{file}"), uid, gid)?; + } + } + return Ok(()); + } + + expect_multi1( + "/tmp/mount-tree/multi1", + &[(100, 211), (101, 222), (102, 233)], + )?; + expect_multi1( + "/tmp/mount-tree/multi2", + &[(200, 211), (201, 222), (202, 233)], + ) +} + +fn expect_tree_top(userns: bool) -> Result<()> { + if userns { + expect_ids("/tmp/mount-tree/foo.txt", 1000, 1101)?; + expect_ids("/tmp/mount-tree/bar.txt", 2000, 2202)?; + expect_ids("/tmp/mount-tree/baz.txt", 3000, 3303) + } else { + expect_ids("/tmp/mount-tree/foo.txt", 101000, 101101)?; + expect_ids("/tmp/mount-tree/bar.txt", 102000, 102202)?; + expect_ids("/tmp/mount-tree/baz.txt", 103000, 103303) + } +} + +fn overflow_ids() -> Result<(u32, u32)> { + let uid = fs::read_to_string("/proc/sys/kernel/overflowuid")? + .trim() + .parse::()?; + let gid = fs::read_to_string("/proc/sys/kernel/overflowgid")? + .trim() + .parse::()?; + Ok((uid, gid)) +} + +fn stat_ids(path: &str) -> Result<(u32, u32)> { + let metadata = fs::metadata(path)?; + Ok((metadata.st_uid(), metadata.st_gid())) +}