Skip to content

Commit c62fcd1

Browse files
authored
fix(libcontainer): label mqueue with an xattr instead of context= (#3773)
* fix(libcontainer): label mqueue with an xattr instead of context= With linux.mountLabel set on an SELinux host, youki adds context=<label> to every mount but proc and sysfs. mqueue refuses it with EINVAL (its superblock belongs to the IPC namespace), so every container with a mount label and a /dev/mqueue mount, which is every container Podman creates on an SELinux host, fails with "failed to prepare rootfs". Label mqueue's root with the security.selinux xattr after fsmount() instead, as crun (get_mount_label_how: LABEL_XATTR) and runc (label.SetFileLabel after the mqueue mount) do. Signed-off-by: Emilio Persson <93738720+ItzExotical@users.noreply.github.com> * fix(libcontainer): keep find_parent_mount's doc comment on it The new helper was added between find_parent_mount and its doc comment. Signed-off-by: Emilio Persson <93738720+ItzExotical@users.noreply.github.com> * fix(libcontainer): label mqueue before mount_setattr An mqueue mount with "ro" is read-only once mount_setattr runs, so the security.selinux xattr set after it failed with EROFS. Set the label right after fsmount(), before mount_setattr. The contest test creates a container with linux.mountLabel and a read-only /dev/mqueue; it is skipped unless SELinux is enabled and the policy knows container_file_t. Signed-off-by: Emilio Persson <93738720+ItzExotical@users.noreply.github.com> * test(libcontainer): a labelled mqueue refuses the mount(2) fallback The legacy mount is read-only at once when the spec says ro, so the xattr label could not be set afterwards; the mount refuses the fallback instead of starting unlabelled, as the copy-up already does. Signed-off-by: Emilio Persson <93738720+ItzExotical@users.noreply.github.com> * fix(libcontainer): label mqueue with fsetxattr through the Syscall trait Reopen the fsmount fd through pathrs' verified procfs (open_follow on /proc/self/fd/N) and set security.selinux with fsetxattr, as crun's apply_selinux_xattr does, instead of setxattr on a /proc/self/fd path. fsetxattr is a new Syscall method, so the test syscall records it and can fail it. Whether SELinux is enabled is read once when the Mount is built, so the tests set it instead of depending on the host. The new test checks the label goes to the reopened mount fd before mount_setattr makes it read-only, that a failed label aborts the mount, and that other filesystems keep context=. The fsmount-fallback test now fails every fsconfig: mount_into_container retries once on EINVAL, so a single failure only held on hosts without SELinux. Signed-off-by: Emilio Persson <93738720+ItzExotical@users.noreply.github.com> * test(contest): check /dev/mqueue's SELinux label and read-only mount mount_label_test now runs runtimetest inside the container, which reads /dev/mqueue's security.selinux xattr against linux.mountLabel and checks the mount is read-only as the spec asks. It still runs only where SELinux is enabled and the policy knows container_file_t. Signed-off-by: Emilio Persson <93738720+ItzExotical@users.noreply.github.com> --------- Signed-off-by: Emilio Persson <93738720+ItzExotical@users.noreply.github.com>
1 parent 8ce74e8 commit c62fcd1

10 files changed

Lines changed: 335 additions & 8 deletions

File tree

‎crates/libcontainer/src/rootfs/mount.rs‎

Lines changed: 172 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,7 @@ pub struct MountOptions<'a> {
122122
pub struct Mount {
123123
syscall: Box<dyn Syscall>,
124124
mountinfo_provider: Box<dyn MountInfoProvider>,
125+
selinux_enabled: bool,
125126
}
126127

127128
impl Default for Mount {
@@ -135,6 +136,7 @@ impl Mount {
135136
Mount {
136137
syscall: create_syscall(),
137138
mountinfo_provider: Box::new(ProcMountInfoProvider::new()),
139+
selinux_enabled: Path::new("/sys/fs/selinux").exists(),
138140
}
139141
}
140142

@@ -586,13 +588,16 @@ impl Mount {
586588
let typ = m.typ().as_deref();
587589
let mut data_options = mount_option_config.data.clone();
588590

591+
let mut xattr_label = None;
589592
if let Some(l) = label {
590-
if typ != Some("proc") && typ != Some("sysfs") {
591-
if Path::new("/sys/fs/selinux").exists() {
592-
data_options.push(format!("context={}", l));
593-
} else {
594-
tracing::debug!("ignoring mount label because SELinux is disabled");
593+
if self.selinux_enabled {
594+
match mount_label_how(typ) {
595+
MountLabelHow::None => {}
596+
MountLabelHow::Context => data_options.push(format!("context={}", l)),
597+
MountLabelHow::Xattr => xattr_label = Some(l),
595598
}
599+
} else {
600+
tracing::debug!("ignoring mount label because SELinux is disabled");
596601
}
597602
}
598603

@@ -758,8 +763,8 @@ impl Mount {
758763
};
759764
// fsconfig rejects some options mount(2) takes, e.g. a lowerdir over 255 bytes.
760765
if let Err(err) = configure() {
761-
// The copy-up needs the detached mount.
762-
if mount_option_config.tmpcopyup {
766+
// The copy-up and the xattr label need the detached mount.
767+
if mount_option_config.tmpcopyup || xattr_label.is_some() {
763768
return Err(err.into());
764769
}
765770
tracing::debug!(?err, "fsconfig failed, falling back to mount(2)");
@@ -787,6 +792,11 @@ impl Mount {
787792
})?;
788793
}
789794

795+
// Before mount_setattr: setxattr on a read-only mount fails with EROFS.
796+
if let Some(l) = xattr_label {
797+
set_root_label(self.syscall.as_ref(), mount_fd, l)?;
798+
}
799+
790800
// mount_setattr
791801
let attr_set_from_flags = self.mount_flag_to_attr(&mount_option_config.flags);
792802
let mut mount_attr = linux::MountAttr {
@@ -1122,7 +1132,6 @@ impl Mount {
11221132
}
11231133
}
11241134
}
1125-
11261135
/// Copies what the directory `src` holds into the directory `dst`, keeping owners and modes:
11271136
/// regular files, directories, symlinks, and device nodes, fifos and sockets as nodes. Like crun's
11281137
/// copy_recursive_fd_to_fd(), it works on directory fds and never follows a symlink in `src`.
@@ -1193,6 +1202,45 @@ fn existing_dest_mode(root: &Root, dest: &Path) -> Result<Option<u32>> {
11931202
}
11941203
}
11951204

1205+
/// How a mount gets its SELinux mount label, as in crun's get_mount_label_how().
1206+
#[derive(Debug, PartialEq, Eq)]
1207+
enum MountLabelHow {
1208+
/// proc and sysfs keep the kernel's labels.
1209+
None,
1210+
/// The `context=` mount option.
1211+
Context,
1212+
/// mqueue's superblock belongs to the IPC namespace, so the kernel refuses `context=`
1213+
/// (EINVAL); its root inode is labelled with the security.selinux xattr instead.
1214+
Xattr,
1215+
}
1216+
1217+
fn mount_label_how(typ: Option<&str>) -> MountLabelHow {
1218+
match typ {
1219+
Some("proc" | "sysfs") => MountLabelHow::None,
1220+
Some("mqueue") => MountLabelHow::Xattr,
1221+
_ => MountLabelHow::Context,
1222+
}
1223+
}
1224+
1225+
/// Sets the SELinux label of a detached mount's root. The fsmount fd is O_PATH, so it is
1226+
/// reopened through the verified procfs for fsetxattr, as crun does.
1227+
fn set_root_label(
1228+
syscall: &dyn Syscall,
1229+
mount_fd: BorrowedFd,
1230+
label: &str,
1231+
) -> std::result::Result<(), SyscallError> {
1232+
let root = ProcfsHandle::new()?.open_follow(
1233+
ProcfsBase::ProcSelf,
1234+
format!("fd/{}", mount_fd.as_raw_fd()),
1235+
OpenFlags::O_RDONLY | OpenFlags::O_CLOEXEC,
1236+
)?;
1237+
syscall
1238+
.fsetxattr(root.as_fd(), "security.selinux", label.as_bytes())
1239+
.inspect_err(|err| {
1240+
tracing::error!(?err, label, "failed to set the SELinux label of the mount")
1241+
})
1242+
}
1243+
11961244
/// Find parent mount of rootfs in given mount infos
11971245
pub fn find_parent_mount(
11981246
rootfs: &Path,
@@ -1364,6 +1412,122 @@ mod tests {
13641412
Ok(())
13651413
}
13661414

1415+
#[test]
1416+
fn test_mount_label_how() {
1417+
assert_eq!(mount_label_how(Some("proc")), MountLabelHow::None);
1418+
assert_eq!(mount_label_how(Some("sysfs")), MountLabelHow::None);
1419+
assert_eq!(mount_label_how(Some("mqueue")), MountLabelHow::Xattr);
1420+
assert_eq!(mount_label_how(Some("tmpfs")), MountLabelHow::Context);
1421+
assert_eq!(mount_label_how(Some("devpts")), MountLabelHow::Context);
1422+
assert_eq!(mount_label_how(None), MountLabelHow::Context);
1423+
}
1424+
1425+
#[test]
1426+
fn test_mount_into_container_mqueue_label_needs_fsmount() -> Result<()> {
1427+
let tmp_dir = tempfile::tempdir()?;
1428+
for (selinux, label) in [
1429+
(false, Some("system_u:object_r:container_file_t:s0")),
1430+
(true, None),
1431+
(true, Some("system_u:object_r:container_file_t:s0")),
1432+
] {
1433+
let mut m = Mount::new();
1434+
m.selinux_enabled = selinux;
1435+
let mount = &SpecMountBuilder::default()
1436+
.destination(PathBuf::from("/dev/mqueue"))
1437+
.typ("mqueue")
1438+
.source(PathBuf::from("mqueue"))
1439+
.options(vec!["nosuid".to_string(), "ro".to_string()])
1440+
.build()?;
1441+
let mount_option_config = parse_mount(mount)?;
1442+
let syscall = helper_syscall(&m);
1443+
syscall.set_ret_err(ArgName::Fsconfig, || {
1444+
Err(crate::syscall::SyscallError::Nix(nix::errno::Errno::EINVAL))
1445+
});
1446+
// Every fsconfig fails: mount_into_container retries once on EINVAL.
1447+
syscall.set_ret_err_times(ArgName::Fsconfig, usize::MAX);
1448+
let result = m.mount_into_container(mount, tmp_dir.path(), &mount_option_config, label);
1449+
// The legacy mount(2) is read-only at once, so the xattr label could not be set:
1450+
// a labelled mqueue refuses the fallback instead of starting unlabelled.
1451+
assert_eq!(
1452+
result.is_err(),
1453+
label.is_some() && selinux,
1454+
"selinux {selinux} label {label:?}"
1455+
);
1456+
assert_eq!(
1457+
syscall.get_mount_args().is_empty(),
1458+
label.is_some() && selinux
1459+
);
1460+
}
1461+
Ok(())
1462+
}
1463+
1464+
#[test]
1465+
fn test_mount_into_container_mqueue_xattr_label() -> Result<()> {
1466+
let tmp_dir = tempfile::tempdir()?;
1467+
let label = "system_u:object_r:container_file_t:s0";
1468+
let mount = &SpecMountBuilder::default()
1469+
.destination(PathBuf::from("/dev/mqueue"))
1470+
.typ("mqueue")
1471+
.source(PathBuf::from("mqueue"))
1472+
.options(vec!["nosuid".to_string(), "ro".to_string()])
1473+
.build()?;
1474+
let mount_option_config = parse_mount(mount)?;
1475+
1476+
for selinux in [false, true] {
1477+
let mut m = Mount::new();
1478+
m.selinux_enabled = selinux;
1479+
m.mount_into_container(mount, tmp_dir.path(), &mount_option_config, Some(label))?;
1480+
let s = helper_syscall(&m);
1481+
assert!(
1482+
!s.get_fsconfig_args()
1483+
.iter()
1484+
.any(|a| a.key.as_deref() == Some("context")),
1485+
"mqueue refuses context="
1486+
);
1487+
let xattrs = s.get_fsetxattr_args();
1488+
if selinux {
1489+
assert_eq!(xattrs.len(), 1);
1490+
assert_eq!(xattrs[0].name, "security.selinux");
1491+
assert_eq!(xattrs[0].value, label.as_bytes());
1492+
// The mock fsmount fd is /dev/null; the label goes to its reopened fd.
1493+
assert_eq!(xattrs[0].fd_path.as_deref(), Some(Path::new("/dev/null")));
1494+
} else {
1495+
assert!(xattrs.is_empty());
1496+
}
1497+
let setattr = s.get_mount_setattr_args();
1498+
assert_eq!(setattr.len(), 1);
1499+
assert_ne!(setattr[0].attr_set & linux::MOUNT_ATTR_RDONLY, 0);
1500+
}
1501+
1502+
// A failed label fails the mount before it is made read-only and attached.
1503+
let mut m = Mount::new();
1504+
m.selinux_enabled = true;
1505+
let s = helper_syscall(&m);
1506+
s.set_ret_err(ArgName::Fsetxattr, || {
1507+
Err(crate::syscall::SyscallError::Nix(nix::errno::Errno::EROFS))
1508+
});
1509+
assert!(
1510+
m.mount_into_container(mount, tmp_dir.path(), &mount_option_config, Some(label))
1511+
.is_err()
1512+
);
1513+
assert!(s.get_mount_setattr_args().is_empty());
1514+
assert!(s.get_move_mount_args().is_empty());
1515+
1516+
// Other filesystems keep context=.
1517+
let mut m = Mount::new();
1518+
m.selinux_enabled = true;
1519+
let tmpfs = &SpecMountBuilder::default()
1520+
.destination(PathBuf::from("/dev/shm"))
1521+
.typ("tmpfs")
1522+
.source(PathBuf::from("shm"))
1523+
.build()?;
1524+
m.mount_into_container(tmpfs, tmp_dir.path(), &parse_mount(tmpfs)?, Some(label))?;
1525+
let s = helper_syscall(&m);
1526+
assert!(s.get_fsconfig_args().contains(&fsc_str("context", label)));
1527+
assert!(s.get_fsetxattr_args().is_empty());
1528+
Ok(())
1529+
}
1530+
13671531
#[test]
13681532
fn test_mount_into_container() -> Result<()> {
13691533
let tmp_dir = tempfile::tempdir()?;

‎crates/libcontainer/src/syscall/linux.rs‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -903,6 +903,22 @@ impl Syscall for LinuxSyscall {
903903
Ok(())
904904
}
905905

906+
fn fsetxattr(&self, fd: BorrowedFd<'_>, name: &str, value: &[u8]) -> Result<()> {
907+
let name = CString::new(name).map_err(|_| nix::Error::EINVAL)?;
908+
// SAFETY: name is NUL-terminated and value outlives the call.
909+
let ret = unsafe {
910+
libc::fsetxattr(
911+
fd.as_raw_fd(),
912+
name.as_ptr(),
913+
value.as_ptr().cast(),
914+
value.len(),
915+
0,
916+
)
917+
};
918+
nix::Error::result(ret)?;
919+
Ok(())
920+
}
921+
906922
fn set_io_priority(&self, class: i64, priority: i64) -> Result<()> {
907923
let ioprio_who_progress: libc::c_int = 1;
908924
let ioprio_who_pid = 0;

‎crates/libcontainer/src/syscall/syscall.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@ pub trait Syscall {
7979
mount_attr: &MountAttr,
8080
size: libc::size_t,
8181
) -> Result<()>;
82+
fn fsetxattr(&self, fd: BorrowedFd<'_>, name: &str, value: &[u8]) -> Result<()>;
8283
fn set_io_priority(&self, class: i64, priority: i64) -> Result<()>;
8384
fn set_mempolicy(&self, mode: i32, nodemask: &[libc::c_ulong], maxnode: u64) -> Result<()>;
8485
fn umount2(&self, target: &Path, flags: MntFlags) -> Result<()>;

‎crates/libcontainer/src/syscall/test.rs‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,13 @@ pub struct MountSetattrArgs {
8383
pub size: libc::size_t,
8484
}
8585

86+
#[derive(Clone, PartialEq, Eq, Debug)]
87+
pub struct FsetxattrArgs {
88+
pub fd_path: Option<PathBuf>,
89+
pub name: String,
90+
pub value: Vec<u8>,
91+
}
92+
8693
#[derive(Clone, PartialEq, Eq, Debug)]
8794
pub struct MknodArgs {
8895
pub path: PathBuf,
@@ -146,6 +153,7 @@ pub enum ArgName {
146153
Fsmount,
147154
OpenTree,
148155
MountSetattr,
156+
Fsetxattr,
149157
}
150158

151159
impl ArgName {
@@ -170,6 +178,7 @@ impl ArgName {
170178
ArgName::Fsmount,
171179
ArgName::OpenTree,
172180
ArgName::MountSetattr,
181+
ArgName::Fsetxattr,
173182
]
174183
.iter()
175184
.copied()
@@ -497,6 +506,17 @@ impl Syscall for TestHelperSyscall {
497506
)
498507
}
499508

509+
fn fsetxattr(&self, fd: BorrowedFd<'_>, name: &str, value: &[u8]) -> Result<()> {
510+
self.mocks.act(
511+
ArgName::Fsetxattr,
512+
Box::new(FsetxattrArgs {
513+
fd_path: read_link(format!("/proc/self/fd/{}", fd.as_raw_fd())).ok(),
514+
name: name.to_owned(),
515+
value: value.to_vec(),
516+
}),
517+
)
518+
}
519+
500520
fn set_io_priority(&self, class: i64, priority: i64) -> Result<()> {
501521
self.mocks.act(
502522
ArgName::IoPriority,
@@ -637,6 +657,15 @@ impl TestHelperSyscall {
637657
.collect::<Vec<MountSetattrArgs>>()
638658
}
639659

660+
pub fn get_fsetxattr_args(&self) -> Vec<FsetxattrArgs> {
661+
self.mocks
662+
.fetch(ArgName::Fsetxattr)
663+
.values
664+
.iter()
665+
.map(|x| x.downcast_ref::<FsetxattrArgs>().unwrap().clone())
666+
.collect::<Vec<FsetxattrArgs>>()
667+
}
668+
640669
pub fn get_move_mount_args(&self) -> Vec<MoveMountArgs> {
641670
self.mocks
642671
.fetch(ArgName::MoveMount)

‎tests/contest/contest/src/main.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ use crate::tests::linux_masked_paths::get_linux_masked_paths_tests;
3232
use crate::tests::linux_ns_itype::get_ns_itype_tests;
3333
use crate::tests::memory_policy::get_linux_memory_policy_tests;
3434
use crate::tests::misc_props::get_misc_props_test;
35+
use crate::tests::mount_label::get_mount_label_test;
3536
use crate::tests::mount_propagation::get_mount_propagation_test;
3637
use crate::tests::mounts_recursive::get_mounts_recursive_test;
3738
use crate::tests::net_devices::get_net_devices_test;
@@ -199,6 +200,7 @@ fn main() -> Result<()> {
199200
let time_ns = get_time_ns_test();
200201
let tmpcopyup = get_tmpcopyup_test();
201202
let tmpfs = get_tmpfs_test();
203+
let mount_label = get_mount_label_test();
202204

203205
tm.add_test_group(Box::new(cl));
204206
tm.add_test_group(Box::new(cc));
@@ -268,6 +270,7 @@ fn main() -> Result<()> {
268270
tm.add_test_group(Box::new(time_ns));
269271
tm.add_test_group(Box::new(tmpcopyup));
270272
tm.add_test_group(Box::new(tmpfs));
273+
tm.add_test_group(Box::new(mount_label));
271274
tm.add_cleanup(Box::new(cgroups::cleanup_v2));
272275

273276
match opts.command {

‎tests/contest/contest/src/tests/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ pub mod linux_masked_paths;
2222
pub mod linux_ns_itype;
2323
pub mod memory_policy;
2424
pub mod misc_props;
25+
pub mod mount_label;
2526
pub mod mount_propagation;
2627
pub mod mounts_recursive;
2728
pub mod net_devices;
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
mod mount_label_test;
2+
pub use mount_label_test::get_mount_label_test;

0 commit comments

Comments
 (0)