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}
20
21impl Step {
22    /// The short code `cant __probe-netns` prints.
23    pub fn code(self) -> &'static str {
24        match self {
25            Step::Unshare => "unshare",
26            Step::Setgroups => "setgroups",
27            Step::UidMap => "uid_map",
28            Step::GidMap => "gid_map",
29        }
30    }
31
32    /// The step with this [`Step::code`].
33    pub fn from_code(code: &str) -> Option<Step> {
34        [Step::Unshare, Step::Setgroups, Step::UidMap, Step::GidMap]
35            .into_iter()
36            .find(|s| s.code() == code)
37    }
38}
39
40impl fmt::Display for Step {
41    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42        f.write_str(match self {
43            Step::Unshare => "unshare(CLONE_NEWUSER|CLONE_NEWNET)",
44            Step::Setgroups => "writing /proc/self/setgroups",
45            Step::UidMap => "writing /proc/self/uid_map",
46            Step::GidMap => "writing /proc/self/gid_map",
47        })
48    }
49}
50
51/// The step that failed, and its errno.
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub struct Failure {
54    pub step: Step,
55    pub errno: i32,
56}
57
58impl fmt::Display for Failure {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        let e = std::io::Error::from_raw_os_error(self.errno);
61        write!(f, "{}: {e}", self.step)
62    }
63}
64
65/// What explains a failure: the sysctls that turn user namespaces off, Ubuntu's AppArmor
66/// restriction, and whether this looks like a container.
67#[derive(Debug, Clone, Default, PartialEq, Eq)]
68pub struct Facts {
69    /// `kernel.apparmor_restrict_unprivileged_userns` (Ubuntu 24.04+).
70    pub apparmor_restrict: Option<u32>,
71    /// `user.max_user_namespaces`.
72    pub max_user_namespaces: Option<u64>,
73    /// `kernel.unprivileged_userns_clone` (Debian's patch).
74    pub unprivileged_userns_clone: Option<u32>,
75    /// `/proc/self/attr/apparmor/current`, e.g. `docker-default (enforce)`.
76    pub apparmor_label: Option<String>,
77    /// `/.dockerenv`, `/run/.containerenv`, `$container`, or a container AppArmor label.
78    pub in_container: bool,
79}
80
81/// Reads [`Facts`] from `/proc` and the root directory.
82pub fn facts() -> Facts {
83    let read = |p: &str| {
84        std::fs::read_to_string(p)
85            .ok()
86            .map(|s| s.trim().to_string())
87    };
88    let label = read("/proc/self/attr/apparmor/current");
89    let in_container = std::path::Path::new("/.dockerenv").exists()
90        || std::path::Path::new("/run/.containerenv").exists()
91        || std::env::var_os("container").is_some()
92        || label.as_deref().is_some_and(|l| {
93            l.starts_with("docker-default") || l.starts_with("containers-default")
94        });
95    Facts {
96        apparmor_restrict: read("/proc/sys/kernel/apparmor_restrict_unprivileged_userns")
97            .and_then(|s| s.parse().ok()),
98        max_user_namespaces: read("/proc/sys/user/max_user_namespaces")
99            .and_then(|s| s.parse().ok()),
100        unprivileged_userns_clone: read("/proc/sys/kernel/unprivileged_userns_clone")
101            .and_then(|s| s.parse().ok()),
102        apparmor_label: label,
103        in_container,
104    }
105}
106
107/// Why the namespace can't be made here and what would fix it, in a sentence.
108pub fn hint(f: &Failure, facts: &Facts) -> String {
109    const EPERM: i32 = 1;
110    const EACCES: i32 = 13;
111    if facts.max_user_namespaces == Some(0) {
112        return "user namespaces are turned off (user.max_user_namespaces = 0)".into();
113    }
114    if facts.unprivileged_userns_clone == Some(0) {
115        return "unprivileged user namespaces are turned off \
116                (kernel.unprivileged_userns_clone = 0)"
117            .into();
118    }
119    match (f.step, f.errno) {
120        (Step::Unshare, EPERM) if facts.in_container => "this container's seccomp profile \
121             refuses user namespaces; start it with `--security-opt \
122             seccomp=cant-seccomp.json` (in Cantainer's release files), not with \
123             `apparmor=unconfined`, `seccomp=unconfined` or `--privileged`"
124            .into(),
125        (Step::Setgroups, EACCES) if facts.apparmor_restrict == Some(1) => "Ubuntu's AppArmor \
126             restricts user namespaces for programs without a profile \
127             (kernel.apparmor_restrict_unprivileged_userns = 1); Cantainer's .deb will \
128             install one for /usr/bin/cant"
129            .into(),
130        _ => "user namespaces aren't available to this user here".into(),
131    }
132}
133
134/// Enters a new user + network namespace and maps this user to itself: the steps that fail
135/// where namespaces are restricted. Changes the calling process for good, and must run while
136/// it has a single thread (`cant __probe-netns` calls it first thing).
137#[cfg(target_os = "linux")]
138pub fn enter() -> Result<(), Failure> {
139    use rustix::thread::UnshareFlags;
140    let uid = rustix::process::getuid().as_raw();
141    let gid = rustix::process::getgid().as_raw();
142    let fail = |step| {
143        move |e: std::io::Error| Failure {
144            step,
145            errno: e.raw_os_error().unwrap_or(0),
146        }
147    };
148    // rustix deprecates the safe `unshare` in favour of an `unsafe` one, because unsharing in a
149    // process with several threads leaves them in different namespaces. This process has one
150    // thread, and the crates forbid `unsafe`.
151    #[allow(deprecated)]
152    rustix::thread::unshare(UnshareFlags::NEWUSER | UnshareFlags::NEWNET)
153        .map_err(std::io::Error::from)
154        .map_err(fail(Step::Unshare))?;
155    std::fs::write("/proc/self/setgroups", "deny").map_err(fail(Step::Setgroups))?;
156    std::fs::write("/proc/self/uid_map", format!("{uid} {uid} 1")).map_err(fail(Step::UidMap))?;
157    std::fs::write("/proc/self/gid_map", format!("{gid} {gid} 1")).map_err(fail(Step::GidMap))?;
158    Ok(())
159}
160
161/// Not Linux: no namespaces.
162#[cfg(not(target_os = "linux"))]
163pub fn enter() -> Result<(), Failure> {
164    Err(Failure {
165        step: Step::Unshare,
166        errno: 38, // ENOSYS
167    })
168}
169
170/// The line `cant __probe-netns` prints for a result.
171pub fn report(result: &Result<(), Failure>) -> String {
172    match result {
173        Ok(()) => "ok".into(),
174        Err(f) => format!("failed {} {}", f.step.code(), f.errno),
175    }
176}
177
178/// Reads a [`report`] line back; anything else is `None`.
179pub fn parse_report(line: &str) -> Option<Result<(), Failure>> {
180    let line = line.trim();
181    if line == "ok" {
182        return Some(Ok(()));
183    }
184    let mut w = line.strip_prefix("failed ")?.split(' ');
185    let step = Step::from_code(w.next()?)?;
186    let errno = w.next()?.parse().ok()?;
187    w.next().is_none().then_some(Err(Failure { step, errno }))
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193
194    #[test]
195    fn reports_round_trip() {
196        for r in [
197            Ok(()),
198            Err(Failure {
199                step: Step::Unshare,
200                errno: 1,
201            }),
202            Err(Failure {
203                step: Step::Setgroups,
204                errno: 13,
205            }),
206            Err(Failure {
207                step: Step::UidMap,
208                errno: 1,
209            }),
210            Err(Failure {
211                step: Step::GidMap,
212                errno: 22,
213            }),
214        ] {
215            assert_eq!(parse_report(&report(&r)), Some(r));
216        }
217        for junk in [
218            "",
219            "OK",
220            "failed",
221            "failed unshare",
222            "failed mount 1",
223            "failed unshare x",
224            "failed unshare 1 2",
225        ] {
226            assert_eq!(parse_report(junk), None, "{junk}");
227        }
228        assert_eq!(Step::from_code("nope"), None);
229    }
230
231    #[test]
232    fn hints_name_the_cause_and_the_fix() {
233        let f = |step, errno| Failure { step, errno };
234        let ubuntu = Facts {
235            apparmor_restrict: Some(1),
236            max_user_namespaces: Some(64279),
237            apparmor_label: Some("unconfined".into()),
238            ..Facts::default()
239        };
240        assert!(hint(&f(Step::Setgroups, 13), &ubuntu).contains("Ubuntu's AppArmor"));
241        let docker = Facts {
242            apparmor_label: Some("docker-default (enforce)".into()),
243            in_container: true,
244            ..Facts::default()
245        };
246        let h = hint(&f(Step::Unshare, 1), &docker);
247        assert!(
248            h.contains("seccomp=cant-seccomp.json") && h.contains("not with"),
249            "{h}"
250        );
251        let off = Facts {
252            max_user_namespaces: Some(0),
253            ..Facts::default()
254        };
255        assert!(hint(&f(Step::Unshare, 28), &off).contains("max_user_namespaces = 0"));
256        let debian = Facts {
257            unprivileged_userns_clone: Some(0),
258            ..Facts::default()
259        };
260        assert!(hint(&f(Step::Unshare, 1), &debian).contains("unprivileged_userns_clone = 0"));
261        // The same errno without the explaining fact: the plain sentence.
262        assert!(hint(&f(Step::Setgroups, 13), &Facts::default()).contains("aren't available"));
263        assert!(hint(&f(Step::Unshare, 1), &Facts::default()).contains("aren't available"));
264        assert_eq!(
265            f(Step::Setgroups, 13).to_string(),
266            format!(
267                "writing /proc/self/setgroups: {}",
268                std::io::Error::from_raw_os_error(13)
269            )
270        );
271        for s in [Step::Unshare, Step::UidMap, Step::GidMap] {
272            assert!(!s.to_string().is_empty());
273        }
274    }
275
276    #[test]
277    fn facts_read_without_failing() {
278        let f = facts();
279        // Whatever this machine is, the label (when there is one) has no newline.
280        assert!(
281            f.apparmor_label
282                .as_deref()
283                .is_none_or(|l| !l.contains('\n'))
284        );
285    }
286}