Skip to main content

countersign_gateway/
worker_sandbox.rs

1//! The worker sandbox's base layers (ADR 0001): what every grant worker
2//! applies to itself, under the namespace sandbox and the filter sandbox alike.
3
4use nix::libc;
5use std::{fmt, io};
6
7/// What Landlock gave the grant worker.
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum Landlock {
10    /// Every access right of this ABI is handled, and none is granted.
11    Abi(u8),
12    /// The kernel has no Landlock, or it is disabled. The other layers hold.
13    Unavailable,
14}
15
16/// The base layers a confined grant worker runs under. Non-dumpable memory and
17/// the seccomp allow-list are always among them; Landlock depends on the kernel.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub struct Layers {
20    pub landlock: Landlock,
21}
22
23impl fmt::Display for Layers {
24    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25        f.write_str("non-dumpable, ")?;
26        match self.landlock {
27            Landlock::Abi(abi) => write!(f, "Landlock ABI v{abi}")?,
28            Landlock::Unavailable => f.write_str("Landlock unavailable")?,
29        }
30        f.write_str(", seccomp allow-list")
31    }
32}
33
34/// A base layer, as [`ConfineError`] names it.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum Layer {
37    NonDumpable,
38    Landlock,
39    AllowList,
40}
41
42impl fmt::Display for Layer {
43    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44        f.write_str(match self {
45            Layer::NonDumpable => "non-dumpable",
46            Layer::Landlock => "Landlock",
47            Layer::AllowList => "seccomp allow-list",
48        })
49    }
50}
51
52/// The layer that could not be applied, and why. The layers before it stay
53/// applied, so the caller can only exit.
54#[derive(Debug, thiserror::Error)]
55#[error("{layer}: {source}")]
56pub struct ConfineError {
57    pub layer: Layer,
58    #[source]
59    pub source: io::Error,
60}
61
62/// Confine the calling process as a grant worker.
63///
64/// Call it while the process has one thread and before it reads any input.
65/// Afterwards the process can use the descriptors it holds and those it
66/// receives over them, run threads, and signal itself. Any other system call
67/// kills it with `SIGSYS`.
68pub fn confine() -> Result<Layers, ConfineError> {
69    let at = |layer| move |source| ConfineError { layer, source };
70    // Ahead of every layer: Landlock would refuse the files it reads, and its
71    // warm-up thread has to end before any layer goes on, since each binds
72    // only the calling thread and the threads it starts later.
73    settle_malloc().map_err(at(Layer::AllowList))?;
74    prctl(libc::PR_SET_DUMPABLE, 0).map_err(at(Layer::NonDumpable))?;
75    // The allow-list's no_new_privs, set ahead of Landlock and not after it:
76    // an unprivileged landlock_restrict_self fails with EPERM without it
77    // (landlock_restrict_self(2)).
78    prctl(libc::PR_SET_NO_NEW_PRIVS, 1)
79        .map_err(|error| io::Error::new(error.kind(), format!("no_new_privs: {error}")))
80        .map_err(at(Layer::AllowList))?;
81    let landlock = landlock().map_err(at(Layer::Landlock))?;
82    allow_list().map_err(at(Layer::AllowList))?;
83    Ok(Layers { landlock })
84}
85
86/// glibc's default trim threshold: a thread's heap shrinks once this much at
87/// its top is free.
88#[cfg(target_env = "gnu")]
89const TRIM_THRESHOLD: usize = 128 * 1024;
90
91/// A block the warm-up allocates: below the mmap threshold, so it comes from
92/// the thread's heap.
93#[cfg(target_env = "gnu")]
94const WARM_UP_BLOCK: usize = 16 * 1024;
95
96/// The C library's malloc reads two values from files the first time it needs
97/// them, and under the allow-list that read kills the grant worker (#62): the
98/// number of CPUs, for its limit on arenas, when a ninth thread needs an
99/// arena; and the kernel's overcommit policy, when a thread's heap first
100/// shrinks. Settle both while files can still be read: give malloc its arena
101/// limit, and shrink one heap on a thread of its own, so glibc caches the
102/// policy.
103#[cfg(target_env = "gnu")]
104fn settle_malloc() -> io::Result<()> {
105    // Eight arenas per CPU in the process's affinity mask: the limit that
106    // glibc 2.36, in the Gateway's image, computes on a 64-bit host, the only
107    // kind the allow-list is written for. glibc 2.39 counts online CPUs,
108    // which are as many or more.
109    let cpus = cpus_in_affinity_mask().unwrap_or_else(|| {
110        // SAFETY: sysconf takes one integer and no pointers.
111        usize::try_from(unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) }).unwrap_or(1)
112    });
113    let arenas = libc::c_int::try_from(cpus.saturating_mul(8)).unwrap_or(libc::c_int::MAX);
114    // A threshold set by hand no longer rises when a large mapped block is
115    // freed, so the warm-up below always frees more than it.
116    let trim = libc::c_int::try_from(TRIM_THRESHOLD).expect("the threshold fits");
117    for (option, value) in [(libc::M_ARENA_MAX, arenas), (libc::M_TRIM_THRESHOLD, trim)] {
118        // mallopt returns 1 on success.
119        // SAFETY: mallopt takes two integers and no pointers.
120        if unsafe { libc::mallopt(option, value) } != 1 {
121            return Err(io::Error::other(format!("malloc refused option {option}")));
122        }
123    }
124    std::thread::Builder::new()
125        .spawn(|| {
126            let blocks: Vec<Vec<u8>> = (0..8 * TRIM_THRESHOLD / WARM_UP_BLOCK)
127                .map(|_| vec![1; WARM_UP_BLOCK])
128                .collect();
129            drop(std::hint::black_box(blocks));
130        })?
131        .join()
132        .map_err(|_| io::Error::other("the malloc warm-up thread panicked"))
133}
134
135/// How many CPUs the process may run on, as `sched_getaffinity` reports them.
136#[cfg(target_env = "gnu")]
137fn cpus_in_affinity_mask() -> Option<usize> {
138    // SAFETY: an all-zero `cpu_set_t` is a valid, empty set.
139    let mut set: libc::cpu_set_t = unsafe { std::mem::zeroed() };
140    // SAFETY: the set is as large as the size passed, and pid 0 is this thread.
141    if unsafe { libc::sched_getaffinity(0, std::mem::size_of_val(&set), &mut set) } != 0 {
142        return None;
143    }
144    // SAFETY: the set was filled in by sched_getaffinity above.
145    let count = unsafe { libc::CPU_COUNT(&set) };
146    usize::try_from(count).ok().filter(|&count| count > 0)
147}
148
149/// The Gateway ships and is tested on glibc only (`distribution/Dockerfile`).
150#[cfg(not(target_env = "gnu"))]
151fn settle_malloc() -> io::Result<()> {
152    Ok(())
153}
154
155fn check(result: libc::c_long) -> io::Result<libc::c_long> {
156    if result < 0 {
157        Err(io::Error::last_os_error())
158    } else {
159        Ok(result)
160    }
161}
162
163fn prctl(option: libc::c_int, value: libc::c_ulong) -> io::Result<()> {
164    // SAFETY: both options take one integer and no pointers.
165    check(unsafe { libc::prctl(option, value, 0, 0, 0) }.into()).map(drop)
166}
167
168/// The newest Landlock ABI whose access rights are listed below. A newer
169/// kernel is confined as this ABI, and reported as it.
170const LANDLOCK_ABI: u8 = 7;
171
172#[repr(C)]
173struct RulesetAttr {
174    handled_access_fs: u64,
175    handled_access_net: u64,
176    scoped: u64,
177}
178
179/// A rule set that handles every access right the kernel's ABI knows and
180/// grants none: no file access, no TCP bind or connect from ABI 4, and no
181/// signal or abstract-socket reach outside the grant worker from ABI 6.
182fn landlock() -> io::Result<Landlock> {
183    const VERSION: u32 = 1;
184    // SAFETY: a null attribute with size 0 is the documented version query.
185    let abi = match check(unsafe {
186        libc::syscall(
187            libc::SYS_landlock_create_ruleset,
188            std::ptr::null::<RulesetAttr>(),
189            0usize,
190            VERSION,
191        )
192    }) {
193        Ok(abi) => abi.min(LANDLOCK_ABI.into()) as u8,
194        // Not built into the kernel, disabled at boot (landlock(7)), or denied
195        // by a container profile older than Landlock, which answers EPERM.
196        // Only this query may be refused: once the kernel has named an ABI, a
197        // failure to apply it is an error.
198        Err(error)
199            if matches!(
200                error.raw_os_error(),
201                Some(libc::ENOSYS | libc::EOPNOTSUPP | libc::EPERM)
202            ) =>
203        {
204            return Ok(Landlock::Unavailable);
205        }
206        Err(error) => return Err(error),
207    };
208    let attr = RulesetAttr {
209        // ABI 1 has 13 file rights. REFER (2), TRUNCATE (3) and IOCTL_DEV (5)
210        // each added one bit.
211        handled_access_fs: match abi {
212            1 => 0x1fff,
213            2 => 0x3fff,
214            3 | 4 => 0x7fff,
215            _ => 0xffff,
216        },
217        handled_access_net: if abi >= 4 { 0b11 } else { 0 },
218        scoped: if abi >= 6 { 0b11 } else { 0 },
219    };
220    // An older kernel rejects a structure longer than the one it knows.
221    let size: usize = match abi {
222        ..4 => 8,
223        4 | 5 => 16,
224        _ => 24,
225    };
226    // SAFETY: `attr` outlives the call and `size` is within it.
227    let ruleset =
228        check(unsafe { libc::syscall(libc::SYS_landlock_create_ruleset, &attr, size, 0u32) })?
229            as libc::c_int;
230    // SAFETY: `ruleset` is the descriptor just created, closed exactly once.
231    let restricted =
232        check(unsafe { libc::syscall(libc::SYS_landlock_restrict_self, ruleset, 0u32) });
233    unsafe { libc::close(ruleset) };
234    restricted?;
235    Ok(Landlock::Abi(abi))
236}
237
238#[cfg(target_arch = "x86_64")]
239const AUDIT_ARCH: u32 = 0xC000_003E;
240#[cfg(target_arch = "aarch64")]
241const AUDIT_ARCH: u32 = 0xC000_00B7;
242
243/// What a confined grant worker needs, and nothing else.
244const ALLOWED: &[libc::c_long] = &[
245    // Receiving its streams, then reading and writing them.
246    libc::SYS_recvmsg,
247    libc::SYS_recvfrom,
248    libc::SYS_read,
249    libc::SYS_write,
250    libc::SYS_writev,
251    libc::SYS_close,
252    libc::SYS_shutdown,
253    libc::SYS_setsockopt,
254    libc::SYS_epoll_create1,
255    libc::SYS_epoll_ctl,
256    libc::SYS_epoll_pwait,
257    #[cfg(target_arch = "x86_64")]
258    libc::SYS_epoll_wait,
259    libc::SYS_eventfd2,
260    // Threads' synchronisation. Starting one is `clone`, below.
261    libc::SYS_set_robust_list,
262    libc::SYS_rseq,
263    libc::SYS_futex,
264    libc::SYS_sigaltstack,
265    libc::SYS_rt_sigprocmask,
266    // The C library installs its thread-cancellation handler with the first thread.
267    libc::SYS_rt_sigaction,
268    // Returning from a signal handler. Without it a crash that a handler
269    // sees first would end as a filter kill, and be logged as one.
270    libc::SYS_rt_sigreturn,
271    libc::SYS_sched_yield,
272    // A new thread asks the C library for its own attributes, CPU set included.
273    libc::SYS_sched_getaffinity,
274    libc::SYS_restart_syscall,
275    // Memory.
276    libc::SYS_mmap,
277    libc::SYS_munmap,
278    libc::SYS_mprotect,
279    libc::SYS_mremap,
280    libc::SYS_madvise,
281    libc::SYS_brk,
282    // Randomness and clocks.
283    libc::SYS_getrandom,
284    libc::SYS_clock_gettime,
285    // Exit. `abort` looks up the process and thread to signal first.
286    libc::SYS_exit,
287    libc::SYS_exit_group,
288    libc::SYS_getpid,
289    libc::SYS_gettid,
290];
291
292/// Offsets into `struct seccomp_data`, on a little-endian machine.
293const DATA_NR: u32 = 0;
294const DATA_ARCH: u32 = 4;
295const DATA_ARG0: u32 = 16;
296const DATA_ARG1: u32 = 24;
297const DATA_ARG4: u32 = 48;
298
299/// What one word of a system call's arguments has to be.
300enum Test<'a> {
301    /// One of these values.
302    OneOf(&'a [u32]),
303    /// Any value with this bit set.
304    Bit(u32),
305}
306
307/// The seccomp filter. A system call outside it kills the whole process,
308/// bar `clone3`, which fails as unsupported (ADR 0002).
309fn allow_list() -> io::Result<()> {
310    const LOAD: u16 = (libc::BPF_LD | libc::BPF_W | libc::BPF_ABS) as u16;
311    const EQUAL: u16 = (libc::BPF_JMP | libc::BPF_JEQ | libc::BPF_K) as u16;
312    const BIT_SET: u16 = (libc::BPF_JMP | libc::BPF_JSET | libc::BPF_K) as u16;
313    const RETURN: u16 = (libc::BPF_RET | libc::BPF_K) as u16;
314    let op = |code, k, jt, jf| libc::sock_filter { code, jt, jf, k };
315    let allow = op(RETURN, libc::SECCOMP_RET_ALLOW, 0, 0);
316    let kill = op(RETURN, libc::SECCOMP_RET_KILL_PROCESS, 0, 0);
317    let number = |nr: libc::c_long| nr as u32;
318
319    let mut filter = vec![
320        // A foreign architecture numbers its system calls differently.
321        op(LOAD, DATA_ARCH, 0, 0),
322        op(EQUAL, AUDIT_ARCH, 1, 0),
323        kill,
324        op(LOAD, DATA_NR, 0, 0),
325    ];
326    // x32 shares x86-64's architecture value and sets this bit in the number.
327    #[cfg(target_arch = "x86_64")]
328    filter.extend([
329        op(
330            (libc::BPF_JMP | libc::BPF_JGE | libc::BPF_K) as u16,
331            0x4000_0000,
332            0,
333            1,
334        ),
335        kill,
336    ]);
337    // clone3 takes its flags in a structure, which a filter cannot read, so
338    // it cannot be allowed for threads alone. It is answered as a kernel
339    // without it answers, and the C library then starts the thread with clone.
340    // The one call outside the allow-list that does not kill (ADR 0002).
341    filter.extend([
342        op(EQUAL, number(libc::SYS_clone3), 0, 1),
343        op(RETURN, libc::SECCOMP_RET_ERRNO | libc::ENOSYS as u32, 0, 0),
344    ]);
345    for nr in ALLOWED {
346        filter.extend([op(EQUAL, number(*nr), 0, 1), allow]);
347    }
348    // These are allowed only when every listed word of their arguments passes
349    // its test. The kernel reads each argument tested below as a 32-bit
350    // integer, bar the pointer, so the low word is the whole argument.
351    let own_pid = [std::process::id()];
352    let conditional: [(libc::c_long, &[(u32, Test)]); 7] = [
353        // A grant worker may signal only itself (ADR 0001, decision 6).
354        (libc::SYS_kill, &[(DATA_ARG0, Test::OneOf(&own_pid))]),
355        (libc::SYS_tgkill, &[(DATA_ARG0, Test::OneOf(&own_pid))]),
356        // Duplicating a stream's descriptor and reading its flags. Not
357        // F_SETOWN, which has the kernel signal a process of the caller's choice.
358        (
359            libc::SYS_fcntl,
360            &[(
361                DATA_ARG1,
362                Test::OneOf(&[
363                    libc::F_DUPFD_CLOEXEC as u32,
364                    libc::F_GETFD as u32,
365                    libc::F_GETFL as u32,
366                ]),
367            )],
368        ),
369        // A thread. Unlike clone3's, clone's flags are an argument the filter
370        // can read.
371        (
372            libc::SYS_clone,
373            &[(DATA_ARG0, Test::Bit(libc::CLONE_THREAD as u32))],
374        ),
375        // The async runtime wakes itself over a local socket pair, which
376        // reaches nothing outside the grant worker.
377        (
378            libc::SYS_socketpair,
379            &[(DATA_ARG0, Test::OneOf(&[libc::AF_UNIX as u32]))],
380        ),
381        // Switching a received stream between blocking and non-blocking.
382        (
383            libc::SYS_ioctl,
384            &[(DATA_ARG1, Test::OneOf(&[libc::FIONBIO as u32]))],
385        ),
386        // Writing a stream. A null destination, both words of the pointer:
387        // with one, a datagram socket could reach a socket it was not given.
388        (
389            libc::SYS_sendto,
390            &[
391                (DATA_ARG4, Test::OneOf(&[0])),
392                (DATA_ARG4 + 4, Test::OneOf(&[0])),
393            ],
394        ),
395    ];
396    for (nr, tests) in conditional {
397        let mut block = Vec::new();
398        for (word, test) in tests {
399            block.push(op(LOAD, *word, 0, 0));
400            match test {
401                Test::OneOf(values) => {
402                    // A match jumps past the values left to try and the kill.
403                    for (tried, value) in values.iter().enumerate() {
404                        block.push(op(EQUAL, *value, (values.len() - tried) as u8, 0));
405                    }
406                }
407                Test::Bit(bit) => block.push(op(BIT_SET, *bit, 1, 0)),
408            }
409            block.push(kill);
410        }
411        block.push(allow);
412        // Another system call skips the block. Inside it every path ends in
413        // the kill or the allow, so nothing falls through to the next one.
414        filter.push(op(EQUAL, number(nr), 0, block.len() as u8));
415        filter.extend(block);
416    }
417    filter.push(kill);
418
419    let program = libc::sock_fprog {
420        len: filter.len() as u16,
421        filter: filter.as_mut_ptr(),
422    };
423    // SAFETY: `program` points at `filter`, which outlives the call. The
424    // kernel copies the filter.
425    check(
426        unsafe {
427            libc::prctl(
428                libc::PR_SET_SECCOMP,
429                libc::SECCOMP_MODE_FILTER,
430                &program as *const libc::sock_fprog,
431            )
432        }
433        .into(),
434    )
435    .map(drop)
436}