use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Step {
Unshare,
Setgroups,
UidMap,
GidMap,
}
impl Step {
pub fn code(self) -> &'static str {
match self {
Step::Unshare => "unshare",
Step::Setgroups => "setgroups",
Step::UidMap => "uid_map",
Step::GidMap => "gid_map",
}
}
pub fn from_code(code: &str) -> Option<Step> {
[Step::Unshare, Step::Setgroups, Step::UidMap, Step::GidMap]
.into_iter()
.find(|s| s.code() == code)
}
}
impl fmt::Display for Step {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Step::Unshare => "unshare(CLONE_NEWUSER|CLONE_NEWNET)",
Step::Setgroups => "writing /proc/self/setgroups",
Step::UidMap => "writing /proc/self/uid_map",
Step::GidMap => "writing /proc/self/gid_map",
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Failure {
pub step: Step,
pub errno: i32,
}
impl fmt::Display for Failure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let e = std::io::Error::from_raw_os_error(self.errno);
write!(f, "{}: {e}", self.step)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Facts {
pub apparmor_restrict: Option<u32>,
pub max_user_namespaces: Option<u64>,
pub unprivileged_userns_clone: Option<u32>,
pub apparmor_label: Option<String>,
pub in_container: bool,
}
pub fn facts() -> Facts {
let read = |p: &str| {
std::fs::read_to_string(p)
.ok()
.map(|s| s.trim().to_string())
};
let label = read("/proc/self/attr/apparmor/current");
let in_container = std::path::Path::new("/.dockerenv").exists()
|| std::path::Path::new("/run/.containerenv").exists()
|| std::env::var_os("container").is_some()
|| label.as_deref().is_some_and(|l| {
l.starts_with("docker-default") || l.starts_with("containers-default")
});
Facts {
apparmor_restrict: read("/proc/sys/kernel/apparmor_restrict_unprivileged_userns")
.and_then(|s| s.parse().ok()),
max_user_namespaces: read("/proc/sys/user/max_user_namespaces")
.and_then(|s| s.parse().ok()),
unprivileged_userns_clone: read("/proc/sys/kernel/unprivileged_userns_clone")
.and_then(|s| s.parse().ok()),
apparmor_label: label,
in_container,
}
}
pub fn hint(f: &Failure, facts: &Facts) -> String {
const EPERM: i32 = 1;
const EACCES: i32 = 13;
if facts.max_user_namespaces == Some(0) {
return "user namespaces are turned off (user.max_user_namespaces = 0)".into();
}
if facts.unprivileged_userns_clone == Some(0) {
return "unprivileged user namespaces are turned off \
(kernel.unprivileged_userns_clone = 0)"
.into();
}
match (f.step, f.errno) {
(Step::Unshare, EPERM) if facts.in_container => "this container's seccomp profile \
refuses user namespaces; start it with `--security-opt \
seccomp=cant-seccomp.json` (in Cantainer's release files), not with \
`apparmor=unconfined`, `seccomp=unconfined` or `--privileged`"
.into(),
(Step::Setgroups, EACCES) if facts.apparmor_restrict == Some(1) => "Ubuntu's AppArmor \
restricts user namespaces for programs without a profile \
(kernel.apparmor_restrict_unprivileged_userns = 1); Cantainer's .deb will \
install one for /usr/bin/cant"
.into(),
_ => "user namespaces aren't available to this user here".into(),
}
}
#[cfg(target_os = "linux")]
pub fn enter() -> Result<(), Failure> {
use rustix::thread::UnshareFlags;
let uid = rustix::process::getuid().as_raw();
let gid = rustix::process::getgid().as_raw();
let fail = |step| {
move |e: std::io::Error| Failure {
step,
errno: e.raw_os_error().unwrap_or(0),
}
};
#[allow(deprecated)]
rustix::thread::unshare(UnshareFlags::NEWUSER | UnshareFlags::NEWNET)
.map_err(std::io::Error::from)
.map_err(fail(Step::Unshare))?;
std::fs::write("/proc/self/setgroups", "deny").map_err(fail(Step::Setgroups))?;
std::fs::write("/proc/self/uid_map", format!("{uid} {uid} 1")).map_err(fail(Step::UidMap))?;
std::fs::write("/proc/self/gid_map", format!("{gid} {gid} 1")).map_err(fail(Step::GidMap))?;
Ok(())
}
#[cfg(not(target_os = "linux"))]
pub fn enter() -> Result<(), Failure> {
Err(Failure {
step: Step::Unshare,
errno: 38, })
}
pub fn report(result: &Result<(), Failure>) -> String {
match result {
Ok(()) => "ok".into(),
Err(f) => format!("failed {} {}", f.step.code(), f.errno),
}
}
pub fn parse_report(line: &str) -> Option<Result<(), Failure>> {
let line = line.trim();
if line == "ok" {
return Some(Ok(()));
}
let mut w = line.strip_prefix("failed ")?.split(' ');
let step = Step::from_code(w.next()?)?;
let errno = w.next()?.parse().ok()?;
w.next().is_none().then_some(Err(Failure { step, errno }))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reports_round_trip() {
for r in [
Ok(()),
Err(Failure {
step: Step::Unshare,
errno: 1,
}),
Err(Failure {
step: Step::Setgroups,
errno: 13,
}),
Err(Failure {
step: Step::UidMap,
errno: 1,
}),
Err(Failure {
step: Step::GidMap,
errno: 22,
}),
] {
assert_eq!(parse_report(&report(&r)), Some(r));
}
for junk in [
"",
"OK",
"failed",
"failed unshare",
"failed mount 1",
"failed unshare x",
"failed unshare 1 2",
] {
assert_eq!(parse_report(junk), None, "{junk}");
}
assert_eq!(Step::from_code("nope"), None);
}
#[test]
fn hints_name_the_cause_and_the_fix() {
let f = |step, errno| Failure { step, errno };
let ubuntu = Facts {
apparmor_restrict: Some(1),
max_user_namespaces: Some(64279),
apparmor_label: Some("unconfined".into()),
..Facts::default()
};
assert!(hint(&f(Step::Setgroups, 13), &ubuntu).contains("Ubuntu's AppArmor"));
let docker = Facts {
apparmor_label: Some("docker-default (enforce)".into()),
in_container: true,
..Facts::default()
};
let h = hint(&f(Step::Unshare, 1), &docker);
assert!(
h.contains("seccomp=cant-seccomp.json") && h.contains("not with"),
"{h}"
);
let off = Facts {
max_user_namespaces: Some(0),
..Facts::default()
};
assert!(hint(&f(Step::Unshare, 28), &off).contains("max_user_namespaces = 0"));
let debian = Facts {
unprivileged_userns_clone: Some(0),
..Facts::default()
};
assert!(hint(&f(Step::Unshare, 1), &debian).contains("unprivileged_userns_clone = 0"));
assert!(hint(&f(Step::Setgroups, 13), &Facts::default()).contains("aren't available"));
assert!(hint(&f(Step::Unshare, 1), &Facts::default()).contains("aren't available"));
assert_eq!(
f(Step::Setgroups, 13).to_string(),
format!(
"writing /proc/self/setgroups: {}",
std::io::Error::from_raw_os_error(13)
)
);
for s in [Step::Unshare, Step::UidMap, Step::GidMap] {
assert!(!s.to_string().is_empty());
}
}
#[test]
fn facts_read_without_failing() {
let f = facts();
assert!(
f.apparmor_label
.as_deref()
.is_none_or(|l| !l.contains('\n'))
);
}
}