Skip to main content

cant_launch/
netns.rs

1//! Can this system make a user + network namespace? (Phase 6.2; docs/NETWORK-ALLOWLIST.md
2//! ยง10.) Host allowlists need one: the can gets a network with only `lo`, and a filtering
3//! proxy outside is its only way out (Phase 6.4). Until then this only *reports*: `cant check`
4//! and `--explain` say whether host enforcement will be possible here, and if not, the step
5//! that failed and the fix.
6//!
7//! [`enter`] changes the calling process for good, so it runs in a short-lived child (`cant
8//! __probe-netns`). [`facts`] and [`hint`] are plain functions of what `/proc` says.
9
10use std::fmt;
11
12/// A step of entering the namespace, in order.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum Step {
15    Unshare,
16    Setgroups,
17    UidMap,
18    GidMap,
19    /// Bringing the namespace's loopback interface up.
20    LoUp,
21    /// Binding the proxy's listener inside the namespace.
22    Bind,
23}
24
25impl Step {
26    /// The short code `cant __probe-netns` prints.
27    pub fn code(self) -> &'static str {
28        match self {
29            Step::Unshare => "unshare",
30            Step::Setgroups => "setgroups",
31            Step::UidMap => "uid_map",
32            Step::GidMap => "gid_map",
33            Step::LoUp => "lo_up",
34            Step::Bind => "bind",
35        }
36    }
37
38    /// The step with this [`Step::code`].
39    pub fn from_code(code: &str) -> Option<Step> {
40        [
41            Step::Unshare,
42            Step::Setgroups,
43            Step::UidMap,
44            Step::GidMap,
45            Step::LoUp,
46            Step::Bind,
47        ]
48        .into_iter()
49        .find(|s| s.code() == code)
50    }
51}
52
53impl fmt::Display for Step {
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        f.write_str(match self {
56            Step::Unshare => "unshare(CLONE_NEWUSER|CLONE_NEWNET)",
57            Step::Setgroups => "writing /proc/self/setgroups",
58            Step::UidMap => "writing /proc/self/uid_map",
59            Step::GidMap => "writing /proc/self/gid_map",
60            Step::LoUp => "bringing up lo",
61            Step::Bind => "binding the proxy's listener",
62        })
63    }
64}
65
66/// The step that failed, and its errno.
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub struct Failure {
69    pub step: Step,
70    pub errno: i32,
71}
72
73impl fmt::Display for Failure {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        let e = std::io::Error::from_raw_os_error(self.errno);
76        write!(f, "{}: {e}", self.step)
77    }
78}
79
80/// What explains a failure: the sysctls that turn user namespaces off, Ubuntu's AppArmor
81/// restriction, and whether this looks like a container.
82#[derive(Debug, Clone, Default, PartialEq, Eq)]
83pub struct Facts {
84    /// `kernel.apparmor_restrict_unprivileged_userns` (Ubuntu 24.04+).
85    pub apparmor_restrict: Option<u32>,
86    /// `user.max_user_namespaces`.
87    pub max_user_namespaces: Option<u64>,
88    /// `kernel.unprivileged_userns_clone` (Debian's patch).
89    pub unprivileged_userns_clone: Option<u32>,
90    /// `/proc/self/attr/apparmor/current`, e.g. `docker-default (enforce)`.
91    pub apparmor_label: Option<String>,
92    /// `/.dockerenv`, `/run/.containerenv`, `$container`, or a container AppArmor label.
93    pub in_container: bool,
94    /// This `cant`'s executable, canonical.
95    pub exe: Option<std::path::PathBuf>,
96    /// Why [`root_owned`] fails for it, if it does: only a root-owned binary can safely get an
97    /// AppArmor profile.
98    pub exe_writable: Option<String>,
99}
100
101/// Whether `path` and every directory above it belong to root and can't be written by group
102/// or others: only such a binary can safely get an AppArmor profile (anyone who can replace it
103/// would get the profile's rights). The error names the first path that fails.
104pub fn root_owned(path: &std::path::Path) -> Result<(), String> {
105    use std::os::unix::fs::MetadataExt;
106    for p in path.ancestors() {
107        let m = std::fs::metadata(p).map_err(|e| format!("{}: {e}", p.display()))?;
108        if m.uid() != 0 {
109            return Err(format!(
110                "{} belongs to uid {}, not root",
111                p.display(),
112                m.uid()
113            ));
114        }
115        if m.mode() & 0o022 != 0 {
116            return Err(format!(
117                "{} can be written by its group or others",
118                p.display()
119            ));
120        }
121    }
122    Ok(())
123}
124
125/// Reads [`Facts`] from `/proc` and the root directory.
126pub fn facts() -> Facts {
127    let read = |p: &str| {
128        std::fs::read_to_string(p)
129            .ok()
130            .map(|s| s.trim().to_string())
131    };
132    let label = read("/proc/self/attr/apparmor/current");
133    let exe = std::env::current_exe().and_then(std::fs::canonicalize).ok();
134    let in_container = std::path::Path::new("/.dockerenv").exists()
135        || std::path::Path::new("/run/.containerenv").exists()
136        || std::env::var_os("container").is_some()
137        || label.as_deref().is_some_and(|l| {
138            l.starts_with("docker-default") || l.starts_with("containers-default")
139        });
140    Facts {
141        apparmor_restrict: read("/proc/sys/kernel/apparmor_restrict_unprivileged_userns")
142            .and_then(|s| s.parse().ok()),
143        max_user_namespaces: read("/proc/sys/user/max_user_namespaces")
144            .and_then(|s| s.parse().ok()),
145        unprivileged_userns_clone: read("/proc/sys/kernel/unprivileged_userns_clone")
146            .and_then(|s| s.parse().ok()),
147        apparmor_label: label,
148        in_container,
149        exe_writable: exe.as_deref().and_then(|e| root_owned(e).err()),
150        exe,
151    }
152}
153
154/// Why the namespace can't be made here and what would fix it, in a sentence.
155pub fn hint(f: &Failure, facts: &Facts) -> String {
156    const EPERM: i32 = 1;
157    const EACCES: i32 = 13;
158    if facts.max_user_namespaces == Some(0) {
159        return "user namespaces are turned off (user.max_user_namespaces = 0)".into();
160    }
161    if facts.unprivileged_userns_clone == Some(0) {
162        return "unprivileged user namespaces are turned off \
163                (kernel.unprivileged_userns_clone = 0)"
164            .into();
165    }
166    match (f.step, f.errno) {
167        (Step::Unshare, EPERM) if facts.in_container => "this container's seccomp profile \
168             refuses user namespaces; start it with `--security-opt \
169             seccomp=cant-seccomp.json` (in Cantainer's release files), not with \
170             `apparmor=unconfined`, `seccomp=unconfined` or `--privileged`"
171            .into(),
172        (Step::Setgroups, EACCES) if facts.apparmor_restrict == Some(1) => {
173            let why = "Ubuntu's AppArmor restricts user namespaces for programs without a \
174                       profile (kernel.apparmor_restrict_unprivileged_userns = 1)";
175            let fix = match &facts.exe {
176                Some(e) if e == std::path::Path::new("/usr/bin/cant") => {
177                    "the package's profile isn't loaded: `sudo apparmor_parser -r \
178                     /etc/apparmor.d/cant`, or reinstall the package"
179                        .to_string()
180                }
181                Some(e) => match &facts.exe_writable {
182                    None => format!("give {0} one with `sudo {0} setup apparmor`", e.display()),
183                    Some(why) => format!(
184                        "no profile can safely cover {} ({why}): install the .deb, or put cant \
185                         in a directory only root can write and run `sudo <that path> setup \
186                         apparmor` there",
187                        e.display()
188                    ),
189                },
190                None => "install Cantainer's .deb, which has one".to_string(),
191            };
192            format!("{why}; {fix}")
193        }
194        _ => "user namespaces aren't available to this user here".into(),
195    }
196}
197
198/// Enters a new user + network namespace and maps this user to itself: the steps that fail
199/// where namespaces are restricted. Changes the calling process for good, and must run while
200/// it has a single thread (`cant __probe-netns` calls it first thing).
201#[cfg(target_os = "linux")]
202pub fn enter() -> Result<(), Failure> {
203    use rustix::thread::UnshareFlags;
204    let uid = rustix::process::getuid().as_raw();
205    let gid = rustix::process::getgid().as_raw();
206    let fail = |step| {
207        move |e: std::io::Error| Failure {
208            step,
209            errno: e.raw_os_error().unwrap_or(0),
210        }
211    };
212    // rustix deprecates the safe `unshare` in favour of an `unsafe` one, because unsharing in a
213    // process with several threads leaves them in different namespaces. This process has one
214    // thread, and the crates forbid `unsafe`.
215    #[allow(deprecated)]
216    rustix::thread::unshare(UnshareFlags::NEWUSER | UnshareFlags::NEWNET)
217        .map_err(std::io::Error::from)
218        .map_err(fail(Step::Unshare))?;
219    std::fs::write("/proc/self/setgroups", "deny").map_err(fail(Step::Setgroups))?;
220    std::fs::write("/proc/self/uid_map", format!("{uid} {uid} 1")).map_err(fail(Step::UidMap))?;
221    std::fs::write("/proc/self/gid_map", format!("{gid} {gid} 1")).map_err(fail(Step::GidMap))?;
222    Ok(())
223}
224
225/// Not Linux: no namespaces.
226#[cfg(not(target_os = "linux"))]
227pub fn enter() -> Result<(), Failure> {
228    Err(Failure {
229        step: Step::Unshare,
230        errno: 38, // ENOSYS
231    })
232}
233
234/// `RTM_NEWLINK` for interface index 1 (`lo` in a new namespace) with `IFF_UP`, asking for an
235/// acknowledgement: a 16-byte `nlmsghdr` and a 16-byte `ifinfomsg`, in this machine's byte order.
236pub fn lo_up_message() -> Vec<u8> {
237    const RTM_NEWLINK: u16 = 16;
238    const NLM_F_REQUEST: u16 = 1;
239    const NLM_F_ACK: u16 = 4;
240    const IFF_UP: u32 = 1;
241    let mut m = Vec::with_capacity(32);
242    m.extend_from_slice(&32u32.to_ne_bytes()); // nlmsg_len
243    m.extend_from_slice(&RTM_NEWLINK.to_ne_bytes()); // nlmsg_type
244    m.extend_from_slice(&(NLM_F_REQUEST | NLM_F_ACK).to_ne_bytes()); // nlmsg_flags
245    m.extend_from_slice(&1u32.to_ne_bytes()); // nlmsg_seq
246    m.extend_from_slice(&0u32.to_ne_bytes()); // nlmsg_pid: the kernel fills it in
247    m.extend_from_slice(&[0, 0]); // ifi_family AF_UNSPEC, padding
248    m.extend_from_slice(&0u16.to_ne_bytes()); // ifi_type
249    m.extend_from_slice(&1i32.to_ne_bytes()); // ifi_index: lo
250    m.extend_from_slice(&IFF_UP.to_ne_bytes()); // ifi_flags
251    m.extend_from_slice(&IFF_UP.to_ne_bytes()); // ifi_change
252    m
253}
254
255/// The errno in the kernel's answer to [`lo_up_message`]: `Ok(())` for an acknowledgement
256/// (`NLMSG_ERROR` with error 0), `Err(errno)` otherwise (`EPROTO` for an unexpected answer).
257pub fn lo_up_answer(reply: &[u8]) -> Result<(), i32> {
258    const NLMSG_ERROR: u16 = 2;
259    const EPROTO: i32 = 71;
260    if reply.len() < 20 || u16::from_ne_bytes([reply[4], reply[5]]) != NLMSG_ERROR {
261        return Err(EPROTO);
262    }
263    match i32::from_ne_bytes([reply[16], reply[17], reply[18], reply[19]]) {
264        0 => Ok(()),
265        e => Err(-e),
266    }
267}
268
269/// Brings the namespace's `lo` up over netlink (no `ioctl`, so no `unsafe`).
270#[cfg(target_os = "linux")]
271fn lo_up() -> Result<(), i32> {
272    use rustix::net::{AddressFamily, RecvFlags, SendFlags, SocketType};
273    let errno = |e: rustix::io::Errno| e.raw_os_error();
274    let s = rustix::net::socket(AddressFamily::NETLINK, SocketType::RAW, None).map_err(errno)?;
275    rustix::net::send(&s, &lo_up_message(), SendFlags::empty()).map_err(errno)?;
276    let mut buf = [0u8; 256];
277    let (_, n) = rustix::net::recv(&s, &mut buf, RecvFlags::empty()).map_err(errno)?;
278    lo_up_answer(&buf[..n.min(buf.len())])
279}
280
281/// Not Linux: never reached ([`enter`] fails first).
282#[cfg(not(target_os = "linux"))]
283fn lo_up() -> Result<(), i32> {
284    Err(38) // ENOSYS
285}
286
287/// Enters the namespace ([`enter`]), brings `lo` up and binds the proxy's listener on
288/// 127.0.0.1 inside it. The same single-thread rule as [`enter`] applies.
289pub fn enter_with_listener() -> Result<std::net::TcpListener, Failure> {
290    enter()?;
291    lo_up().map_err(|errno| Failure {
292        step: Step::LoUp,
293        errno,
294    })?;
295    std::net::TcpListener::bind("127.0.0.1:0").map_err(|e| Failure {
296        step: Step::Bind,
297        errno: e.raw_os_error().unwrap_or(0),
298    })
299}
300
301/// Sends the listener (and nothing else) over the socketpair to the supervisor.
302#[cfg(target_os = "linux")]
303pub fn send_listener(
304    sock: impl std::os::fd::AsFd,
305    listener: &std::net::TcpListener,
306) -> std::io::Result<()> {
307    use rustix::net::{SendAncillaryBuffer, SendAncillaryMessage, SendFlags};
308    use std::os::fd::AsFd;
309    let mut space = [std::mem::MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(1))];
310    let mut cmsg = SendAncillaryBuffer::new(&mut space);
311    let fds = [listener.as_fd()];
312    cmsg.push(SendAncillaryMessage::ScmRights(&fds));
313    rustix::net::sendmsg(
314        sock,
315        &[std::io::IoSlice::new(b"L")],
316        &mut cmsg,
317        SendFlags::empty(),
318    )?;
319    Ok(())
320}
321
322/// What the child sent: the listener, or (`None`) no descriptor, in which case it writes a
323/// [`report`] line next.
324#[cfg(target_os = "linux")]
325pub fn recv_listener(
326    sock: impl std::os::fd::AsFd,
327) -> std::io::Result<Option<std::net::TcpListener>> {
328    use rustix::net::{RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags};
329    let mut space = [std::mem::MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(1))];
330    let mut cmsg = RecvAncillaryBuffer::new(&mut space);
331    let mut byte = [0u8; 1];
332    rustix::net::recvmsg(
333        sock,
334        &mut [std::io::IoSliceMut::new(&mut byte)],
335        &mut cmsg,
336        RecvFlags::CMSG_CLOEXEC,
337    )?;
338    for m in cmsg.drain() {
339        if let RecvAncillaryMessage::ScmRights(mut fds) = m
340            && let Some(fd) = fds.next()
341        {
342            return Ok(Some(std::net::TcpListener::from(fd)));
343        }
344    }
345    Ok(None)
346}
347
348/// The line `cant __probe-netns` prints for a result.
349pub fn report(result: &Result<(), Failure>) -> String {
350    match result {
351        Ok(()) => "ok".into(),
352        Err(f) => format!("failed {} {}", f.step.code(), f.errno),
353    }
354}
355
356/// Reads a [`report`] line back; anything else is `None`.
357pub fn parse_report(line: &str) -> Option<Result<(), Failure>> {
358    let line = line.trim();
359    if line == "ok" {
360        return Some(Ok(()));
361    }
362    let mut w = line.strip_prefix("failed ")?.split(' ');
363    let step = Step::from_code(w.next()?)?;
364    let errno = w.next()?.parse().ok()?;
365    w.next().is_none().then_some(Err(Failure { step, errno }))
366}
367
368#[cfg(test)]
369mod tests {
370    use super::*;
371
372    #[test]
373    fn reports_round_trip() {
374        for r in [
375            Ok(()),
376            Err(Failure {
377                step: Step::Unshare,
378                errno: 1,
379            }),
380            Err(Failure {
381                step: Step::Setgroups,
382                errno: 13,
383            }),
384            Err(Failure {
385                step: Step::UidMap,
386                errno: 1,
387            }),
388            Err(Failure {
389                step: Step::GidMap,
390                errno: 22,
391            }),
392        ] {
393            assert_eq!(parse_report(&report(&r)), Some(r));
394        }
395        for junk in [
396            "",
397            "OK",
398            "failed",
399            "failed unshare",
400            "failed mount 1",
401            "failed unshare x",
402            "failed unshare 1 2",
403        ] {
404            assert_eq!(parse_report(junk), None, "{junk}");
405        }
406        assert_eq!(Step::from_code("nope"), None);
407    }
408
409    #[test]
410    fn hints_name_the_cause_and_the_fix() {
411        let f = |step, errno| Failure { step, errno };
412        let ubuntu = Facts {
413            apparmor_restrict: Some(1),
414            max_user_namespaces: Some(64279),
415            apparmor_label: Some("unconfined".into()),
416            ..Facts::default()
417        };
418        assert!(hint(&f(Step::Setgroups, 13), &ubuntu).contains("Ubuntu's AppArmor"));
419        assert!(hint(&f(Step::Setgroups, 13), &ubuntu).contains("install Cantainer's .deb"));
420        let at = |path: &str, root: bool| Facts {
421            exe: Some(path.into()),
422            exe_writable: (!root).then(|| format!("{path} belongs to uid 1000, not root")),
423            ..ubuntu.clone()
424        };
425        let h = hint(&f(Step::Setgroups, 13), &at("/usr/bin/cant", true));
426        assert!(
427            h.contains("sudo apparmor_parser -r /etc/apparmor.d/cant"),
428            "{h}"
429        );
430        let h = hint(&f(Step::Setgroups, 13), &at("/usr/local/bin/cant", true));
431        assert!(
432            h.contains("`sudo /usr/local/bin/cant setup apparmor`"),
433            "{h}"
434        );
435        let h = hint(
436            &f(Step::Setgroups, 13),
437            &at("/home/u/.cargo/bin/cant", false),
438        );
439        assert!(h.contains("a directory only root can write"), "{h}");
440        assert!(
441            h.contains(
442                "no profile can safely cover /home/u/.cargo/bin/cant (/home/u/.cargo/bin/cant \
443                 belongs to uid 1000, not root)"
444            ),
445            "{h}"
446        );
447        let docker = Facts {
448            apparmor_label: Some("docker-default (enforce)".into()),
449            in_container: true,
450            ..Facts::default()
451        };
452        let h = hint(&f(Step::Unshare, 1), &docker);
453        assert!(
454            h.contains("seccomp=cant-seccomp.json") && h.contains("not with"),
455            "{h}"
456        );
457        let off = Facts {
458            max_user_namespaces: Some(0),
459            ..Facts::default()
460        };
461        assert!(hint(&f(Step::Unshare, 28), &off).contains("max_user_namespaces = 0"));
462        let debian = Facts {
463            unprivileged_userns_clone: Some(0),
464            ..Facts::default()
465        };
466        assert!(hint(&f(Step::Unshare, 1), &debian).contains("unprivileged_userns_clone = 0"));
467        // The same errno without the explaining fact: the plain sentence.
468        assert!(hint(&f(Step::Setgroups, 13), &Facts::default()).contains("aren't available"));
469        assert!(hint(&f(Step::Unshare, 1), &Facts::default()).contains("aren't available"));
470        assert_eq!(
471            f(Step::Setgroups, 13).to_string(),
472            format!(
473                "writing /proc/self/setgroups: {}",
474                std::io::Error::from_raw_os_error(13)
475            )
476        );
477        for s in [Step::Unshare, Step::UidMap, Step::GidMap] {
478            assert!(!s.to_string().is_empty());
479        }
480    }
481
482    #[test]
483    fn the_lo_up_message_and_its_answers() {
484        let m = lo_up_message();
485        assert_eq!(m.len(), 32);
486        assert_eq!(u32::from_ne_bytes([m[0], m[1], m[2], m[3]]), 32);
487        assert_eq!(u16::from_ne_bytes([m[4], m[5]]), 16, "RTM_NEWLINK");
488        assert_eq!(
489            u16::from_ne_bytes([m[6], m[7]]),
490            5,
491            "NLM_F_REQUEST | NLM_F_ACK"
492        );
493        assert_eq!(
494            i32::from_ne_bytes([m[20], m[21], m[22], m[23]]),
495            1,
496            "index of lo"
497        );
498        assert_eq!(
499            u32::from_ne_bytes([m[24], m[25], m[26], m[27]]),
500            1,
501            "IFF_UP"
502        );
503        assert_eq!(
504            u32::from_ne_bytes([m[28], m[29], m[30], m[31]]),
505            1,
506            "change IFF_UP"
507        );
508        let answer = |kind: u16, err: i32| {
509            let mut a = vec![0u8; 36];
510            a[4..6].copy_from_slice(&kind.to_ne_bytes());
511            a[16..20].copy_from_slice(&err.to_ne_bytes());
512            a
513        };
514        assert_eq!(lo_up_answer(&answer(2, 0)), Ok(()));
515        assert_eq!(lo_up_answer(&answer(2, -1)), Err(1), "EPERM");
516        assert_eq!(lo_up_answer(&answer(16, 0)), Err(71), "not an ack");
517        assert_eq!(lo_up_answer(&[0; 8]), Err(71), "too short");
518        for s in [Step::LoUp, Step::Bind] {
519            assert_eq!(Step::from_code(s.code()), Some(s));
520            assert!(!s.to_string().is_empty());
521        }
522    }
523
524    #[cfg(target_os = "linux")]
525    #[test]
526    fn a_listener_crosses_a_unix_socket() {
527        let (a, b) = std::os::unix::net::UnixStream::pair().expect("pair");
528        let l = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
529        send_listener(&a, &l).expect("send");
530        let got = recv_listener(&b).expect("recv").expect("a listener");
531        assert_eq!(
532            got.local_addr().expect("addr"),
533            l.local_addr().expect("addr")
534        );
535        // A plain byte carries no descriptor.
536        use std::io::Write as _;
537        (&a).write_all(b"x").expect("write");
538        assert!(recv_listener(&b).expect("recv").is_none());
539        // This test process has several threads: unshare refuses, nothing changes.
540        let f = enter_with_listener().expect_err("threads");
541        assert_eq!(f.step, Step::Unshare);
542    }
543
544    #[test]
545    fn only_root_owned_paths_can_get_a_profile() {
546        let dir = tempfile::tempdir().expect("tempdir");
547        let file = dir.path().join("cant");
548        std::fs::write(&file, "").expect("write");
549        use std::os::unix::fs::MetadataExt;
550        if std::fs::metadata(&file).expect("meta").uid() == 0 {
551            return; // running as root: everything here belongs to root
552        }
553        let e = root_owned(&file).expect_err("ours");
554        assert!(e.contains("not root"), "{e}");
555        assert!(
556            root_owned(std::path::Path::new("/no/such"))
557                .expect_err("missing")
558                .contains("/no/such")
559        );
560        // /tmp is writable by everyone (sticky): refused even when owned by root.
561        let e = root_owned(std::path::Path::new("/tmp")).expect_err("tmp");
562        assert!(
563            e.contains("/tmp can be written by its group or others"),
564            "{e}"
565        );
566        root_owned(std::path::Path::new("/usr/bin")).expect("system directories");
567    }
568
569    #[test]
570    fn facts_read_without_failing() {
571        let f = facts();
572        // Whatever this machine is, the label (when there is one) has no newline.
573        assert!(
574            f.apparmor_label
575                .as_deref()
576                .is_none_or(|l| !l.contains('\n'))
577        );
578    }
579}