use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Step {
Unshare,
Setgroups,
UidMap,
GidMap,
LoUp,
Bind,
Mount,
}
impl Step {
pub fn code(self) -> &'static str {
match self {
Step::Unshare => "unshare",
Step::Setgroups => "setgroups",
Step::UidMap => "uid_map",
Step::GidMap => "gid_map",
Step::LoUp => "lo_up",
Step::Bind => "bind",
Step::Mount => "mount",
}
}
pub fn from_code(code: &str) -> Option<Step> {
[
Step::Unshare,
Step::Setgroups,
Step::UidMap,
Step::GidMap,
Step::LoUp,
Step::Bind,
Step::Mount,
]
.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)",
Step::Setgroups => "writing /proc/self/setgroups",
Step::UidMap => "writing /proc/self/uid_map",
Step::GidMap => "writing /proc/self/gid_map",
Step::LoUp => "bringing up lo",
Step::Bind => "binding the proxy's listener",
Step::Mount => "mounting a directory read-only",
})
}
}
#[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 exe: Option<std::path::PathBuf>,
pub exe_writable: Option<String>,
}
pub fn root_owned(path: &std::path::Path) -> Result<(), String> {
use std::os::unix::fs::MetadataExt;
for p in path.ancestors() {
let m = std::fs::metadata(p).map_err(|e| format!("{}: {e}", p.display()))?;
if m.uid() != 0 {
return Err(format!(
"{} belongs to uid {}, not root",
p.display(),
m.uid()
));
}
if m.mode() & 0o022 != 0 {
return Err(format!(
"{} can be written by its group or others",
p.display()
));
}
}
Ok(())
}
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 exe = std::env::current_exe().and_then(std::fs::canonicalize).ok();
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,
exe_writable: exe.as_deref().and_then(|e| root_owned(e).err()),
exe,
}
}
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) => {
let why = "Ubuntu's AppArmor restricts user namespaces for programs without a \
profile (kernel.apparmor_restrict_unprivileged_userns = 1)";
let fix = match &facts.exe {
Some(e) if e == std::path::Path::new("/usr/bin/cant") => {
"the package's profile isn't loaded: `sudo apparmor_parser -r \
/etc/apparmor.d/cant`, or reinstall the package"
.to_string()
}
Some(e) => match &facts.exe_writable {
None => format!("give {0} one with `sudo {0} setup apparmor`", e.display()),
Some(why) => format!(
"no profile can safely cover {} ({why}): install the .deb, or put cant \
in a directory only root can write and run `sudo <that path> setup \
apparmor` there",
e.display()
),
},
None => "install Cantainer's .deb, which has one".to_string(),
};
format!("{why}; {fix}")
}
_ => "user namespaces aren't available to this user here".into(),
}
}
#[cfg(target_os = "linux")]
pub fn enter() -> Result<(), Failure> {
enter_with(rustix::thread::UnshareFlags::NEWNET)
}
#[cfg(target_os = "linux")]
pub fn enter_for_mounts() -> Result<(), Failure> {
enter_with(rustix::thread::UnshareFlags::NEWNS)
}
#[cfg(target_os = "linux")]
fn enter_with(also: rustix::thread::UnshareFlags) -> 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 | also)
.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 lo_up_message() -> Vec<u8> {
const RTM_NEWLINK: u16 = 16;
const NLM_F_REQUEST: u16 = 1;
const NLM_F_ACK: u16 = 4;
const IFF_UP: u32 = 1;
let mut m = Vec::with_capacity(32);
m.extend_from_slice(&32u32.to_ne_bytes()); m.extend_from_slice(&RTM_NEWLINK.to_ne_bytes()); m.extend_from_slice(&(NLM_F_REQUEST | NLM_F_ACK).to_ne_bytes()); m.extend_from_slice(&1u32.to_ne_bytes()); m.extend_from_slice(&0u32.to_ne_bytes()); m.extend_from_slice(&[0, 0]); m.extend_from_slice(&0u16.to_ne_bytes()); m.extend_from_slice(&1i32.to_ne_bytes()); m.extend_from_slice(&IFF_UP.to_ne_bytes()); m.extend_from_slice(&IFF_UP.to_ne_bytes()); m
}
pub fn lo_up_answer(reply: &[u8]) -> Result<(), i32> {
const NLMSG_ERROR: u16 = 2;
const EPROTO: i32 = 71;
if reply.len() < 20 || u16::from_ne_bytes([reply[4], reply[5]]) != NLMSG_ERROR {
return Err(EPROTO);
}
match i32::from_ne_bytes([reply[16], reply[17], reply[18], reply[19]]) {
0 => Ok(()),
e => Err(-e),
}
}
#[cfg(target_os = "linux")]
fn lo_up() -> Result<(), i32> {
use rustix::net::{AddressFamily, RecvFlags, SendFlags, SocketType};
let errno = |e: rustix::io::Errno| e.raw_os_error();
let s = rustix::net::socket(AddressFamily::NETLINK, SocketType::RAW, None).map_err(errno)?;
rustix::net::send(&s, &lo_up_message(), SendFlags::empty()).map_err(errno)?;
let mut buf = [0u8; 256];
let (_, n) = rustix::net::recv(&s, &mut buf, RecvFlags::empty()).map_err(errno)?;
lo_up_answer(&buf[..n.min(buf.len())])
}
#[cfg(not(target_os = "linux"))]
fn lo_up() -> Result<(), i32> {
Err(38) }
pub fn enter_with_listener() -> Result<std::net::TcpListener, Failure> {
enter()?;
lo_up().map_err(|errno| Failure {
step: Step::LoUp,
errno,
})?;
std::net::TcpListener::bind("127.0.0.1:0").map_err(|e| Failure {
step: Step::Bind,
errno: e.raw_os_error().unwrap_or(0),
})
}
#[cfg(target_os = "linux")]
pub fn send_listener(
sock: impl std::os::fd::AsFd,
listener: &std::net::TcpListener,
) -> std::io::Result<()> {
use rustix::net::{SendAncillaryBuffer, SendAncillaryMessage, SendFlags};
use std::os::fd::AsFd;
let mut space = [std::mem::MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(1))];
let mut cmsg = SendAncillaryBuffer::new(&mut space);
let fds = [listener.as_fd()];
cmsg.push(SendAncillaryMessage::ScmRights(&fds));
rustix::net::sendmsg(
sock,
&[std::io::IoSlice::new(b"L")],
&mut cmsg,
SendFlags::empty(),
)?;
Ok(())
}
#[cfg(target_os = "linux")]
pub fn send_end(sock: impl std::os::fd::AsFd) -> std::io::Result<()> {
rustix::net::send(sock, b"E", rustix::net::SendFlags::empty())?;
Ok(())
}
#[cfg(target_os = "linux")]
pub fn recv_listener(
sock: impl std::os::fd::AsFd,
) -> std::io::Result<Option<std::net::TcpListener>> {
use rustix::net::{RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags};
let mut space = [std::mem::MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(1))];
let mut cmsg = RecvAncillaryBuffer::new(&mut space);
let mut byte = [0u8; 1];
rustix::net::recvmsg(
sock,
&mut [std::io::IoSliceMut::new(&mut byte)],
&mut cmsg,
RecvFlags::CMSG_CLOEXEC,
)?;
for m in cmsg.drain() {
if let RecvAncillaryMessage::ScmRights(mut fds) = m
&& let Some(fd) = fds.next()
{
return Ok(Some(std::net::TcpListener::from(fd)));
}
}
Ok(None)
}
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,
}),
Err(Failure {
step: Step::Mount,
errno: 1,
}),
] {
assert_eq!(parse_report(&report(&r)), Some(r));
}
for junk in [
"",
"OK",
"failed",
"failed unshare",
"failed nope 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"));
assert!(hint(&f(Step::Setgroups, 13), &ubuntu).contains("install Cantainer's .deb"));
let at = |path: &str, root: bool| Facts {
exe: Some(path.into()),
exe_writable: (!root).then(|| format!("{path} belongs to uid 1000, not root")),
..ubuntu.clone()
};
let h = hint(&f(Step::Setgroups, 13), &at("/usr/bin/cant", true));
assert!(
h.contains("sudo apparmor_parser -r /etc/apparmor.d/cant"),
"{h}"
);
let h = hint(&f(Step::Setgroups, 13), &at("/usr/local/bin/cant", true));
assert!(
h.contains("`sudo /usr/local/bin/cant setup apparmor`"),
"{h}"
);
let h = hint(
&f(Step::Setgroups, 13),
&at("/home/u/.cargo/bin/cant", false),
);
assert!(h.contains("a directory only root can write"), "{h}");
assert!(
h.contains(
"no profile can safely cover /home/u/.cargo/bin/cant (/home/u/.cargo/bin/cant \
belongs to uid 1000, not root)"
),
"{h}"
);
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 the_lo_up_message_and_its_answers() {
let m = lo_up_message();
assert_eq!(m.len(), 32);
assert_eq!(u32::from_ne_bytes([m[0], m[1], m[2], m[3]]), 32);
assert_eq!(u16::from_ne_bytes([m[4], m[5]]), 16, "RTM_NEWLINK");
assert_eq!(
u16::from_ne_bytes([m[6], m[7]]),
5,
"NLM_F_REQUEST | NLM_F_ACK"
);
assert_eq!(
i32::from_ne_bytes([m[20], m[21], m[22], m[23]]),
1,
"index of lo"
);
assert_eq!(
u32::from_ne_bytes([m[24], m[25], m[26], m[27]]),
1,
"IFF_UP"
);
assert_eq!(
u32::from_ne_bytes([m[28], m[29], m[30], m[31]]),
1,
"change IFF_UP"
);
let answer = |kind: u16, err: i32| {
let mut a = vec![0u8; 36];
a[4..6].copy_from_slice(&kind.to_ne_bytes());
a[16..20].copy_from_slice(&err.to_ne_bytes());
a
};
assert_eq!(lo_up_answer(&answer(2, 0)), Ok(()));
assert_eq!(lo_up_answer(&answer(2, -1)), Err(1), "EPERM");
assert_eq!(lo_up_answer(&answer(16, 0)), Err(71), "not an ack");
assert_eq!(lo_up_answer(&[0; 8]), Err(71), "too short");
for s in [Step::LoUp, Step::Bind] {
assert_eq!(Step::from_code(s.code()), Some(s));
assert!(!s.to_string().is_empty());
}
}
#[cfg(target_os = "linux")]
#[test]
fn a_listener_crosses_a_unix_socket() {
let (a, b) = std::os::unix::net::UnixStream::pair().expect("pair");
let l = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
send_listener(&a, &l).expect("send");
let got = recv_listener(&b).expect("recv").expect("a listener");
assert_eq!(
got.local_addr().expect("addr"),
l.local_addr().expect("addr")
);
use std::io::Write as _;
(&a).write_all(b"x").expect("write");
assert!(recv_listener(&b).expect("recv").is_none());
let f = enter_with_listener().expect_err("threads");
assert_eq!(f.step, Step::Unshare);
}
#[test]
fn only_root_owned_paths_can_get_a_profile() {
let dir = tempfile::tempdir().expect("tempdir");
let file = dir.path().join("cant");
std::fs::write(&file, "").expect("write");
use std::os::unix::fs::MetadataExt;
if std::fs::metadata(&file).expect("meta").uid() == 0 {
return; }
let e = root_owned(&file).expect_err("ours");
assert!(e.contains("not root"), "{e}");
assert!(
root_owned(std::path::Path::new("/no/such"))
.expect_err("missing")
.contains("/no/such")
);
let e = root_owned(std::path::Path::new("/tmp")).expect_err("tmp");
assert!(
e.contains("/tmp can be written by its group or others"),
"{e}"
);
root_owned(std::path::Path::new("/usr/bin")).expect("system directories");
}
#[test]
fn facts_read_without_failing() {
let f = facts();
assert!(
f.apparmor_label
.as_deref()
.is_none_or(|l| !l.contains('\n'))
);
}
}