1use std::fmt;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum Step {
15 Unshare,
16 Setgroups,
17 UidMap,
18 GidMap,
19 LoUp,
21 Bind,
23 Mount,
25}
26
27impl Step {
28 pub fn code(self) -> &'static str {
30 match self {
31 Step::Unshare => "unshare",
32 Step::Setgroups => "setgroups",
33 Step::UidMap => "uid_map",
34 Step::GidMap => "gid_map",
35 Step::LoUp => "lo_up",
36 Step::Bind => "bind",
37 Step::Mount => "mount",
38 }
39 }
40
41 pub fn from_code(code: &str) -> Option<Step> {
43 [
44 Step::Unshare,
45 Step::Setgroups,
46 Step::UidMap,
47 Step::GidMap,
48 Step::LoUp,
49 Step::Bind,
50 Step::Mount,
51 ]
52 .into_iter()
53 .find(|s| s.code() == code)
54 }
55}
56
57impl fmt::Display for Step {
58 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59 f.write_str(match self {
60 Step::Unshare => "unshare(CLONE_NEWUSER)",
61 Step::Setgroups => "writing /proc/self/setgroups",
62 Step::UidMap => "writing /proc/self/uid_map",
63 Step::GidMap => "writing /proc/self/gid_map",
64 Step::LoUp => "bringing up lo",
65 Step::Bind => "binding the proxy's listener",
66 Step::Mount => "mounting a directory read-only",
67 })
68 }
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub struct Failure {
74 pub step: Step,
75 pub errno: i32,
76}
77
78impl fmt::Display for Failure {
79 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80 let e = std::io::Error::from_raw_os_error(self.errno);
81 write!(f, "{}: {e}", self.step)
82 }
83}
84
85#[derive(Debug, Clone, Default, PartialEq, Eq)]
88pub struct Facts {
89 pub apparmor_restrict: Option<u32>,
91 pub max_user_namespaces: Option<u64>,
93 pub unprivileged_userns_clone: Option<u32>,
95 pub apparmor_label: Option<String>,
97 pub in_container: bool,
99 pub exe: Option<std::path::PathBuf>,
101 pub exe_writable: Option<String>,
104}
105
106pub fn root_owned(path: &std::path::Path) -> Result<(), String> {
110 use std::os::unix::fs::MetadataExt;
111 for p in path.ancestors() {
112 let m = std::fs::metadata(p).map_err(|e| format!("{}: {e}", p.display()))?;
113 if m.uid() != 0 {
114 return Err(format!(
115 "{} belongs to uid {}, not root",
116 p.display(),
117 m.uid()
118 ));
119 }
120 if m.mode() & 0o022 != 0 {
121 return Err(format!(
122 "{} can be written by its group or others",
123 p.display()
124 ));
125 }
126 }
127 Ok(())
128}
129
130pub fn facts() -> Facts {
132 let read = |p: &str| {
133 std::fs::read_to_string(p)
134 .ok()
135 .map(|s| s.trim().to_string())
136 };
137 let label = read("/proc/self/attr/apparmor/current");
138 let exe = std::env::current_exe().and_then(std::fs::canonicalize).ok();
139 let in_container = std::path::Path::new("/.dockerenv").exists()
140 || std::path::Path::new("/run/.containerenv").exists()
141 || std::env::var_os("container").is_some()
142 || label.as_deref().is_some_and(|l| {
143 l.starts_with("docker-default") || l.starts_with("containers-default")
144 });
145 Facts {
146 apparmor_restrict: read("/proc/sys/kernel/apparmor_restrict_unprivileged_userns")
147 .and_then(|s| s.parse().ok()),
148 max_user_namespaces: read("/proc/sys/user/max_user_namespaces")
149 .and_then(|s| s.parse().ok()),
150 unprivileged_userns_clone: read("/proc/sys/kernel/unprivileged_userns_clone")
151 .and_then(|s| s.parse().ok()),
152 apparmor_label: label,
153 in_container,
154 exe_writable: exe.as_deref().and_then(|e| root_owned(e).err()),
155 exe,
156 }
157}
158
159pub fn hint(f: &Failure, facts: &Facts) -> String {
161 const EPERM: i32 = 1;
162 const EACCES: i32 = 13;
163 if facts.max_user_namespaces == Some(0) {
164 return "user namespaces are turned off (user.max_user_namespaces = 0)".into();
165 }
166 if facts.unprivileged_userns_clone == Some(0) {
167 return "unprivileged user namespaces are turned off \
168 (kernel.unprivileged_userns_clone = 0)"
169 .into();
170 }
171 match (f.step, f.errno) {
172 (Step::Unshare, EPERM) if facts.in_container => "this container's seccomp profile \
173 refuses user namespaces; start it with `--security-opt \
174 seccomp=cant-seccomp.json` (in Cantainer's release files), not with \
175 `apparmor=unconfined`, `seccomp=unconfined` or `--privileged`"
176 .into(),
177 (Step::Setgroups, EACCES) if facts.apparmor_restrict == Some(1) => {
178 let why = "Ubuntu's AppArmor restricts user namespaces for programs without a \
179 profile (kernel.apparmor_restrict_unprivileged_userns = 1)";
180 let fix = match &facts.exe {
181 Some(e) if e == std::path::Path::new("/usr/bin/cant") => {
182 "the package's profile isn't loaded: `sudo apparmor_parser -r \
183 /etc/apparmor.d/cant`, or reinstall the package"
184 .to_string()
185 }
186 Some(e) => match &facts.exe_writable {
187 None => format!("give {0} one with `sudo {0} setup apparmor`", e.display()),
188 Some(why) => format!(
189 "no profile can safely cover {} ({why}): install the .deb, or put cant \
190 in a directory only root can write and run `sudo <that path> setup \
191 apparmor` there",
192 e.display()
193 ),
194 },
195 None => "install Cantainer's .deb, which has one".to_string(),
196 };
197 format!("{why}; {fix}")
198 }
199 _ => "user namespaces aren't available to this user here".into(),
200 }
201}
202
203#[cfg(target_os = "linux")]
207pub fn enter() -> Result<(), Failure> {
208 enter_with(rustix::thread::UnshareFlags::NEWNET)
209}
210
211#[cfg(target_os = "linux")]
214pub fn enter_for_mounts() -> Result<(), Failure> {
215 enter_with(rustix::thread::UnshareFlags::NEWNS)
216}
217
218#[cfg(target_os = "linux")]
220fn enter_with(also: rustix::thread::UnshareFlags) -> Result<(), Failure> {
221 use rustix::thread::UnshareFlags;
222 let uid = rustix::process::getuid().as_raw();
223 let gid = rustix::process::getgid().as_raw();
224 let fail = |step| {
225 move |e: std::io::Error| Failure {
226 step,
227 errno: e.raw_os_error().unwrap_or(0),
228 }
229 };
230 #[allow(deprecated)]
234 rustix::thread::unshare(UnshareFlags::NEWUSER | also)
235 .map_err(std::io::Error::from)
236 .map_err(fail(Step::Unshare))?;
237 std::fs::write("/proc/self/setgroups", "deny").map_err(fail(Step::Setgroups))?;
238 std::fs::write("/proc/self/uid_map", format!("{uid} {uid} 1")).map_err(fail(Step::UidMap))?;
239 std::fs::write("/proc/self/gid_map", format!("{gid} {gid} 1")).map_err(fail(Step::GidMap))?;
240 Ok(())
241}
242
243#[cfg(not(target_os = "linux"))]
245pub fn enter() -> Result<(), Failure> {
246 Err(Failure {
247 step: Step::Unshare,
248 errno: 38, })
250}
251
252pub fn lo_up_message() -> Vec<u8> {
255 const RTM_NEWLINK: u16 = 16;
256 const NLM_F_REQUEST: u16 = 1;
257 const NLM_F_ACK: u16 = 4;
258 const IFF_UP: u32 = 1;
259 let mut m = Vec::with_capacity(32);
260 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
271}
272
273pub fn lo_up_answer(reply: &[u8]) -> Result<(), i32> {
276 const NLMSG_ERROR: u16 = 2;
277 const EPROTO: i32 = 71;
278 if reply.len() < 20 || u16::from_ne_bytes([reply[4], reply[5]]) != NLMSG_ERROR {
279 return Err(EPROTO);
280 }
281 match i32::from_ne_bytes([reply[16], reply[17], reply[18], reply[19]]) {
282 0 => Ok(()),
283 e => Err(-e),
284 }
285}
286
287#[cfg(target_os = "linux")]
289fn lo_up() -> Result<(), i32> {
290 use rustix::net::{AddressFamily, RecvFlags, SendFlags, SocketType};
291 let errno = |e: rustix::io::Errno| e.raw_os_error();
292 let s = rustix::net::socket(AddressFamily::NETLINK, SocketType::RAW, None).map_err(errno)?;
293 rustix::net::send(&s, &lo_up_message(), SendFlags::empty()).map_err(errno)?;
294 let mut buf = [0u8; 256];
295 let (_, n) = rustix::net::recv(&s, &mut buf, RecvFlags::empty()).map_err(errno)?;
296 lo_up_answer(&buf[..n.min(buf.len())])
297}
298
299#[cfg(not(target_os = "linux"))]
301fn lo_up() -> Result<(), i32> {
302 Err(38) }
304
305pub fn enter_with_listener() -> Result<std::net::TcpListener, Failure> {
308 enter()?;
309 lo_up().map_err(|errno| Failure {
310 step: Step::LoUp,
311 errno,
312 })?;
313 std::net::TcpListener::bind("127.0.0.1:0").map_err(|e| Failure {
314 step: Step::Bind,
315 errno: e.raw_os_error().unwrap_or(0),
316 })
317}
318
319#[cfg(target_os = "linux")]
321pub fn send_listener(
322 sock: impl std::os::fd::AsFd,
323 listener: &std::net::TcpListener,
324) -> std::io::Result<()> {
325 use rustix::net::{SendAncillaryBuffer, SendAncillaryMessage, SendFlags};
326 use std::os::fd::AsFd;
327 let mut space = [std::mem::MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(1))];
328 let mut cmsg = SendAncillaryBuffer::new(&mut space);
329 let fds = [listener.as_fd()];
330 cmsg.push(SendAncillaryMessage::ScmRights(&fds));
331 rustix::net::sendmsg(
332 sock,
333 &[std::io::IoSlice::new(b"L")],
334 &mut cmsg,
335 SendFlags::empty(),
336 )?;
337 Ok(())
338}
339
340#[cfg(target_os = "linux")]
343pub fn send_end(sock: impl std::os::fd::AsFd) -> std::io::Result<()> {
344 rustix::net::send(sock, b"E", rustix::net::SendFlags::empty())?;
345 Ok(())
346}
347
348#[cfg(target_os = "linux")]
351pub fn recv_listener(
352 sock: impl std::os::fd::AsFd,
353) -> std::io::Result<Option<std::net::TcpListener>> {
354 use rustix::net::{RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags};
355 let mut space = [std::mem::MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(1))];
356 let mut cmsg = RecvAncillaryBuffer::new(&mut space);
357 let mut byte = [0u8; 1];
358 rustix::net::recvmsg(
359 sock,
360 &mut [std::io::IoSliceMut::new(&mut byte)],
361 &mut cmsg,
362 RecvFlags::CMSG_CLOEXEC,
363 )?;
364 for m in cmsg.drain() {
365 if let RecvAncillaryMessage::ScmRights(mut fds) = m
366 && let Some(fd) = fds.next()
367 {
368 return Ok(Some(std::net::TcpListener::from(fd)));
369 }
370 }
371 Ok(None)
372}
373
374pub fn report(result: &Result<(), Failure>) -> String {
376 match result {
377 Ok(()) => "ok".into(),
378 Err(f) => format!("failed {} {}", f.step.code(), f.errno),
379 }
380}
381
382pub fn parse_report(line: &str) -> Option<Result<(), Failure>> {
384 let line = line.trim();
385 if line == "ok" {
386 return Some(Ok(()));
387 }
388 let mut w = line.strip_prefix("failed ")?.split(' ');
389 let step = Step::from_code(w.next()?)?;
390 let errno = w.next()?.parse().ok()?;
391 w.next().is_none().then_some(Err(Failure { step, errno }))
392}
393
394#[cfg(test)]
395mod tests {
396 use super::*;
397
398 #[test]
399 fn reports_round_trip() {
400 for r in [
401 Ok(()),
402 Err(Failure {
403 step: Step::Unshare,
404 errno: 1,
405 }),
406 Err(Failure {
407 step: Step::Setgroups,
408 errno: 13,
409 }),
410 Err(Failure {
411 step: Step::UidMap,
412 errno: 1,
413 }),
414 Err(Failure {
415 step: Step::GidMap,
416 errno: 22,
417 }),
418 Err(Failure {
419 step: Step::Mount,
420 errno: 1,
421 }),
422 ] {
423 assert_eq!(parse_report(&report(&r)), Some(r));
424 }
425 for junk in [
426 "",
427 "OK",
428 "failed",
429 "failed unshare",
430 "failed nope 1",
431 "failed unshare x",
432 "failed unshare 1 2",
433 ] {
434 assert_eq!(parse_report(junk), None, "{junk}");
435 }
436 assert_eq!(Step::from_code("nope"), None);
437 }
438
439 #[test]
440 fn hints_name_the_cause_and_the_fix() {
441 let f = |step, errno| Failure { step, errno };
442 let ubuntu = Facts {
443 apparmor_restrict: Some(1),
444 max_user_namespaces: Some(64279),
445 apparmor_label: Some("unconfined".into()),
446 ..Facts::default()
447 };
448 assert!(hint(&f(Step::Setgroups, 13), &ubuntu).contains("Ubuntu's AppArmor"));
449 assert!(hint(&f(Step::Setgroups, 13), &ubuntu).contains("install Cantainer's .deb"));
450 let at = |path: &str, root: bool| Facts {
451 exe: Some(path.into()),
452 exe_writable: (!root).then(|| format!("{path} belongs to uid 1000, not root")),
453 ..ubuntu.clone()
454 };
455 let h = hint(&f(Step::Setgroups, 13), &at("/usr/bin/cant", true));
456 assert!(
457 h.contains("sudo apparmor_parser -r /etc/apparmor.d/cant"),
458 "{h}"
459 );
460 let h = hint(&f(Step::Setgroups, 13), &at("/usr/local/bin/cant", true));
461 assert!(
462 h.contains("`sudo /usr/local/bin/cant setup apparmor`"),
463 "{h}"
464 );
465 let h = hint(
466 &f(Step::Setgroups, 13),
467 &at("/home/u/.cargo/bin/cant", false),
468 );
469 assert!(h.contains("a directory only root can write"), "{h}");
470 assert!(
471 h.contains(
472 "no profile can safely cover /home/u/.cargo/bin/cant (/home/u/.cargo/bin/cant \
473 belongs to uid 1000, not root)"
474 ),
475 "{h}"
476 );
477 let docker = Facts {
478 apparmor_label: Some("docker-default (enforce)".into()),
479 in_container: true,
480 ..Facts::default()
481 };
482 let h = hint(&f(Step::Unshare, 1), &docker);
483 assert!(
484 h.contains("seccomp=cant-seccomp.json") && h.contains("not with"),
485 "{h}"
486 );
487 let off = Facts {
488 max_user_namespaces: Some(0),
489 ..Facts::default()
490 };
491 assert!(hint(&f(Step::Unshare, 28), &off).contains("max_user_namespaces = 0"));
492 let debian = Facts {
493 unprivileged_userns_clone: Some(0),
494 ..Facts::default()
495 };
496 assert!(hint(&f(Step::Unshare, 1), &debian).contains("unprivileged_userns_clone = 0"));
497 assert!(hint(&f(Step::Setgroups, 13), &Facts::default()).contains("aren't available"));
499 assert!(hint(&f(Step::Unshare, 1), &Facts::default()).contains("aren't available"));
500 assert_eq!(
501 f(Step::Setgroups, 13).to_string(),
502 format!(
503 "writing /proc/self/setgroups: {}",
504 std::io::Error::from_raw_os_error(13)
505 )
506 );
507 for s in [Step::Unshare, Step::UidMap, Step::GidMap] {
508 assert!(!s.to_string().is_empty());
509 }
510 }
511
512 #[test]
513 fn the_lo_up_message_and_its_answers() {
514 let m = lo_up_message();
515 assert_eq!(m.len(), 32);
516 assert_eq!(u32::from_ne_bytes([m[0], m[1], m[2], m[3]]), 32);
517 assert_eq!(u16::from_ne_bytes([m[4], m[5]]), 16, "RTM_NEWLINK");
518 assert_eq!(
519 u16::from_ne_bytes([m[6], m[7]]),
520 5,
521 "NLM_F_REQUEST | NLM_F_ACK"
522 );
523 assert_eq!(
524 i32::from_ne_bytes([m[20], m[21], m[22], m[23]]),
525 1,
526 "index of lo"
527 );
528 assert_eq!(
529 u32::from_ne_bytes([m[24], m[25], m[26], m[27]]),
530 1,
531 "IFF_UP"
532 );
533 assert_eq!(
534 u32::from_ne_bytes([m[28], m[29], m[30], m[31]]),
535 1,
536 "change IFF_UP"
537 );
538 let answer = |kind: u16, err: i32| {
539 let mut a = vec![0u8; 36];
540 a[4..6].copy_from_slice(&kind.to_ne_bytes());
541 a[16..20].copy_from_slice(&err.to_ne_bytes());
542 a
543 };
544 assert_eq!(lo_up_answer(&answer(2, 0)), Ok(()));
545 assert_eq!(lo_up_answer(&answer(2, -1)), Err(1), "EPERM");
546 assert_eq!(lo_up_answer(&answer(16, 0)), Err(71), "not an ack");
547 assert_eq!(lo_up_answer(&[0; 8]), Err(71), "too short");
548 for s in [Step::LoUp, Step::Bind] {
549 assert_eq!(Step::from_code(s.code()), Some(s));
550 assert!(!s.to_string().is_empty());
551 }
552 }
553
554 #[cfg(target_os = "linux")]
555 #[test]
556 fn a_listener_crosses_a_unix_socket() {
557 let (a, b) = std::os::unix::net::UnixStream::pair().expect("pair");
558 let l = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
559 send_listener(&a, &l).expect("send");
560 let got = recv_listener(&b).expect("recv").expect("a listener");
561 assert_eq!(
562 got.local_addr().expect("addr"),
563 l.local_addr().expect("addr")
564 );
565 use std::io::Write as _;
567 (&a).write_all(b"x").expect("write");
568 assert!(recv_listener(&b).expect("recv").is_none());
569 let f = enter_with_listener().expect_err("threads");
571 assert_eq!(f.step, Step::Unshare);
572 }
573
574 #[test]
575 fn only_root_owned_paths_can_get_a_profile() {
576 let dir = tempfile::tempdir().expect("tempdir");
577 let file = dir.path().join("cant");
578 std::fs::write(&file, "").expect("write");
579 use std::os::unix::fs::MetadataExt;
580 if std::fs::metadata(&file).expect("meta").uid() == 0 {
581 return; }
583 let e = root_owned(&file).expect_err("ours");
584 assert!(e.contains("not root"), "{e}");
585 assert!(
586 root_owned(std::path::Path::new("/no/such"))
587 .expect_err("missing")
588 .contains("/no/such")
589 );
590 let e = root_owned(std::path::Path::new("/tmp")).expect_err("tmp");
592 assert!(
593 e.contains("/tmp can be written by its group or others"),
594 "{e}"
595 );
596 root_owned(std::path::Path::new("/usr/bin")).expect("system directories");
597 }
598
599 #[test]
600 fn facts_read_without_failing() {
601 let f = facts();
602 assert!(
604 f.apparmor_label
605 .as_deref()
606 .is_none_or(|l| !l.contains('\n'))
607 );
608 }
609}