oscall 0.1.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
//! What `process::linux` says of the credentials of the calling thread:
//! capabilities, the identifiers of its user and groups, and what the
//! child of `spawn` does about them.
//!
//! The constants are those of `include/uapi/linux/capability.h`,
//! `securebits.h` and `prctl.h`, which every architecture shares.

use crate::sys::{errno, syscall};
use crate::{ErrorKind, Result};

/// `_LINUX_CAPABILITY_VERSION_3`: sets of 64 bits, in two words each.
const CAPABILITY_VERSION_3: u32 = 0x2008_0522;

const PR_GET_KEEPCAPS: usize = 7;
const PR_SET_KEEPCAPS: usize = 8;
const PR_CAPBSET_READ: usize = 23;
const PR_CAPBSET_DROP: usize = 24;
const PR_GET_SECUREBITS: usize = 27;
const PR_SET_SECUREBITS: usize = 28;
const PR_CAP_AMBIENT: usize = 47;
const PR_CAP_AMBIENT_IS_SET: usize = 1;
const PR_CAP_AMBIENT_RAISE: usize = 2;
const PR_CAP_AMBIENT_LOWER: usize = 3;
const PR_CAP_AMBIENT_CLEAR_ALL: usize = 4;

/// `struct __user_cap_header_struct`.
#[repr(C)]
struct CapHeader {
    version: u32,
    /// A thread; 0 is the caller.
    pid: i32,
}

/// `struct __user_cap_data_struct`: the low or the high half of the three
/// sets.
#[repr(C)]
#[derive(Clone, Copy, Default)]
struct CapData {
    effective: u32,
    permitted: u32,
    inheritable: u32,
}

const _: () = assert!(size_of::<CapHeader>() == 8 && size_of::<[CapData; 2]>() == 24);

/// The three sets of the calling thread: effective, permitted,
/// inheritable.
pub(crate) fn capabilities() -> Result<[u64; 3]> {
    let header = CapHeader {
        version: CAPABILITY_VERSION_3,
        pid: 0,
    };
    let mut data = [CapData::default(); 2];
    // SAFETY: the kernel reads the header and, for this version, writes
    // two structures.
    unsafe { syscall!(CAPGET, &raw const header, &raw mut data) }?;
    let join = |low: u32, high: u32| u64::from(low) | u64::from(high) << 32;
    Ok([
        join(data[0].effective, data[1].effective),
        join(data[0].permitted, data[1].permitted),
        join(data[0].inheritable, data[1].inheritable),
    ])
}

/// `capset` for the calling thread: effective, permitted, inheritable.
/// Only a system call.
pub(crate) fn set_capabilities(sets: [u64; 3]) -> Result<()> {
    let header = CapHeader {
        version: CAPABILITY_VERSION_3,
        pid: 0,
    };
    let half = |shift: u32| CapData {
        effective: (sets[0] >> shift) as u32,
        permitted: (sets[1] >> shift) as u32,
        inheritable: (sets[2] >> shift) as u32,
    };
    let data = [half(0), half(32)];
    // SAFETY: the kernel reads the header and, for this version, two
    // structures.
    unsafe { syscall!(CAPSET, &raw const header, &raw const data) }.map(drop)
}

/// `prctl` with integer arguments.
fn prctl(option: usize, a: usize, b: usize) -> Result<usize> {
    // SAFETY: none of the options used with this passes memory.
    unsafe { syscall!(PRCTL, option, a, b, 0, 0) }
}

pub(crate) fn has_bounding(capability: u32) -> Result<bool> {
    prctl(PR_CAPBSET_READ, capability as usize, 0).map(|value| value != 0)
}

pub(crate) fn drop_bounding(capability: u32) -> Result<()> {
    prctl(PR_CAPBSET_DROP, capability as usize, 0).map(drop)
}

pub(crate) fn has_ambient(capability: u32) -> Result<bool> {
    prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_IS_SET, capability as usize).map(|value| value != 0)
}

pub(crate) fn raise_ambient(capability: u32) -> Result<()> {
    prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, capability as usize).map(drop)
}

pub(crate) fn lower_ambient(capability: u32) -> Result<()> {
    prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_LOWER, capability as usize).map(drop)
}

pub(crate) fn clear_ambient() -> Result<()> {
    prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0).map(drop)
}

/// The capabilities, of the 64 a set can hold, that `has` says are there.
/// The kernel answers `EINVAL` for a number it does not know, and knows
/// every number below the last one it has.
pub(crate) fn probe(has: fn(u32) -> Result<bool>) -> Result<u64> {
    let mut set = 0;
    for capability in 0..64 {
        match has(capability) {
            Ok(true) => set |= 1 << capability,
            Ok(false) => {}
            Err(error) if error.raw_os_error() == errno::EINVAL && capability > 0 => break,
            Err(error) => return Err(error),
        }
    }
    Ok(set)
}

pub(crate) fn keep_capabilities() -> Result<bool> {
    prctl(PR_GET_KEEPCAPS, 0, 0).map(|value| value != 0)
}

pub(crate) fn set_keep_capabilities(keep: bool) -> Result<()> {
    prctl(PR_SET_KEEPCAPS, usize::from(keep), 0).map(drop)
}

pub(crate) fn secure_bits() -> Result<u32> {
    prctl(PR_GET_SECUREBITS, 0, 0).map(|value| value as u32)
}

pub(crate) fn set_secure_bits(bits: u32) -> Result<()> {
    prctl(PR_SET_SECUREBITS, bits as usize, 0).map(drop)
}

// The identity. x86 and arm have two sets of calls: those without a suffix
// take and return 16-bit identifiers, and the `32` ones are those to use.
// The other architectures only have the one set, of 32 bits.

/// The real and effective user, the real and effective group: these calls
/// cannot fail.
pub(crate) fn ids() -> [u32; 4] {
    // SAFETY: no argument.
    unsafe {
        #[cfg(any(target_arch = "x86", target_arch = "arm"))]
        let ids = [
            syscall!(GETUID32),
            syscall!(GETEUID32),
            syscall!(GETGID32),
            syscall!(GETEGID32),
        ];
        #[cfg(not(any(target_arch = "x86", target_arch = "arm")))]
        let ids = [
            syscall!(GETUID),
            syscall!(GETEUID),
            syscall!(GETGID),
            syscall!(GETEGID),
        ];
        ids.map(|id| id.map_or(u32::MAX, |id| id as u32))
    }
}

pub(crate) fn groups(buf: &mut [u32]) -> Result<usize> {
    // The size is an `int`. A size of 0 asks for the number of groups.
    let len = buf.len().min(i32::MAX as usize);
    // SAFETY: the kernel writes at most `len` identifiers of 32 bits.
    unsafe {
        #[cfg(any(target_arch = "x86", target_arch = "arm"))]
        return syscall!(GETGROUPS32, len, buf.as_mut_ptr());
        #[cfg(not(any(target_arch = "x86", target_arch = "arm")))]
        return syscall!(GETGROUPS, len, buf.as_mut_ptr());
    }
}

pub(crate) fn set_groups(groups: &[u32]) -> Result<()> {
    // SAFETY: the kernel reads `groups.len()` identifiers of 32 bits.
    unsafe {
        #[cfg(any(target_arch = "x86", target_arch = "arm"))]
        return syscall!(SETGROUPS32, groups.len(), groups.as_ptr()).map(drop);
        #[cfg(not(any(target_arch = "x86", target_arch = "arm")))]
        return syscall!(SETGROUPS, groups.len(), groups.as_ptr()).map(drop);
    }
}

/// An identifier for `setresuid` and `setresgid`, where -1 means "as it
/// is".
fn id_or_keep(id: Option<u32>) -> Result<u32> {
    match id {
        None => Ok(u32::MAX),
        Some(u32::MAX) => Err(ErrorKind::InvalidInput.into()),
        Some(id) => Ok(id),
    }
}

pub(crate) fn set_user_ids(ids: [Option<u32>; 3]) -> Result<()> {
    let [real, effective, saved] = [
        id_or_keep(ids[0])?,
        id_or_keep(ids[1])?,
        id_or_keep(ids[2])?,
    ];
    // SAFETY: no memory is involved.
    unsafe {
        #[cfg(any(target_arch = "x86", target_arch = "arm"))]
        return syscall!(SETRESUID32, real, effective, saved).map(drop);
        #[cfg(not(any(target_arch = "x86", target_arch = "arm")))]
        return syscall!(SETRESUID, real, effective, saved).map(drop);
    }
}

pub(crate) fn set_group_ids(ids: [Option<u32>; 3]) -> Result<()> {
    let [real, effective, saved] = [
        id_or_keep(ids[0])?,
        id_or_keep(ids[1])?,
        id_or_keep(ids[2])?,
    ];
    // SAFETY: no memory is involved.
    unsafe {
        #[cfg(any(target_arch = "x86", target_arch = "arm"))]
        return syscall!(SETRESGID32, real, effective, saved).map(drop);
        #[cfg(not(any(target_arch = "x86", target_arch = "arm")))]
        return syscall!(SETRESGID, real, effective, saved).map(drop);
    }
}

/// `struct new_utsname`: six strings of 65 bytes.
pub(crate) type UtsName = [[u8; 65]; 6];

pub(crate) fn uname() -> Result<UtsName> {
    let mut name: UtsName = [[0; 65]; 6];
    // SAFETY: the kernel writes one `struct new_utsname` (the call of
    // this name is the one that takes it on every architecture supported:
    // x86 and arm have older ones under other names).
    unsafe { syscall!(UNAME, &raw mut name) }?;
    Ok(name)
}

/// Executes an instruction the processor refuses: the kernel ends the
/// process with `SIGILL`, whose disposition the child of `spawn` has put
/// back to the default, and which is delivered even when blocked.
#[cfg(feature = "alloc")]
fn invalid_instruction() -> ! {
    // SAFETY: the instruction does not return, and touches nothing.
    unsafe {
        #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
        core::arch::asm!("ud2", options(noreturn, nomem, nostack));
        #[cfg(any(target_arch = "arm", target_arch = "aarch64"))]
        core::arch::asm!("udf #0", options(noreturn, nomem, nostack));
        #[cfg(any(target_arch = "riscv32", target_arch = "riscv64"))]
        core::arch::asm!("unimp", options(noreturn, nomem, nostack));
    }
}

/// What the child of `spawn` does about its capabilities and its system
/// call filter. Plain data: the child shares the memory of the parent and
/// only makes system calls.
#[cfg(feature = "alloc")]
pub(crate) struct ChildSecurity {
    /// Whether to keep the permitted capabilities across the change of
    /// user: `PR_SET_KEEPCAPS`.
    keep: bool,
    /// What stays in the bounding set.
    bounding: Option<u64>,
    /// Effective, permitted, inheritable.
    capabilities: Option<[u64; 3]>,
    ambient: Option<u64>,
    /// A `struct sock_fprog` and the flags of `seccomp`.
    filter: Option<(super::seccomp::Program, usize)>,
    /// How the listener of the filter gets to the parent, if it is to.
    relay: Option<Relay>,
    /// The descriptor of a Landlock ruleset to restrict the child with,
    /// or -1.
    landlock: i32,
    /// Whether the child makes itself a tracee of its parent.
    trace_me: bool,
}

/// How the listener of the filter a child installs reaches its parent.
///
/// The descriptor exists once the filter is installed, and from then on
/// the child may make no call the filter could stop, answer with an
/// error, or hand to the listener no one holds yet: it cannot send the
/// descriptor itself. And the descriptor is close-on-exec, gone from the
/// child the moment its program starts.
///
/// So before the filter, the child creates a process that shares its
/// memory and its table of descriptors, and so has no filter and will
/// have the descriptor. That process waits, on a futex, for the kernel to
/// say that the child has run its program or ended (which the kernel does
/// for the address given to `set_tid_address`), reads the number of the
/// descriptor the child left in the shared memory, sends it to the parent
/// over a socket, and exits. It still has the descriptor then, because
/// `execve` gave the child a table of its own before closing anything.
///
/// It is created by a first process that exits at once, which the child
/// waits for: the one that waits is then nobody's child (an orphan, which
/// the `init` of its process namespace collects), and the program finds
/// no child it did not create.
#[cfg(feature = "alloc")]
pub(crate) struct Relay {
    /// The socket to the parent, in the child.
    socket: i32,
    /// Where the stacks of the two processes end.
    stacks: [*mut u8; 2],
    /// 1 until the child runs its program or ends: the kernel then writes
    /// 0 and wakes who waits for it.
    running: core::sync::atomic::AtomicU32,
    /// The descriptor of the listener in the child, once there is one.
    listener: core::sync::atomic::AtomicI32,
    /// What kept the process that waits from being created.
    error: core::sync::atomic::AtomicI32,
}

#[cfg(feature = "alloc")]
impl Relay {
    /// The first process: creates the one that waits, and exits.
    ///
    /// # Safety
    ///
    /// `arg` points to the `Relay` of a child of `spawn`, in the memory
    /// this process shares with it: system calls only.
    unsafe extern "C" fn first(arg: *mut core::ffi::c_void) -> ! {
        use core::sync::atomic::Ordering;
        // SAFETY: the caller's contract.
        let relay = unsafe { &*arg.cast::<Self>() };
        let flags = super::spawn::CLONE_VM | super::spawn::CLONE_FILES;
        // SAFETY: the stack is this relay's own, and `second` makes
        // system calls only. No exit signal: no one is to be told.
        let created = unsafe {
            super::spawn::clone_vfork(
                flags,
                relay.stacks[1],
                core::ptr::null_mut(),
                Self::second,
                arg,
            )
        };
        if created < 0 {
            relay.error.store(-created as i32, Ordering::SeqCst);
        }
        loop {
            // SAFETY: no memory is involved.
            let _ = unsafe { syscall!(EXIT_GROUP, 0) };
        }
    }

    /// The process that waits for the child to start its program, and
    /// sends the listener.
    ///
    /// # Safety
    ///
    /// As [`first`](Self::first).
    unsafe extern "C" fn second(arg: *mut core::ffi::c_void) -> ! {
        use core::sync::atomic::Ordering;
        const FUTEX_WAIT: usize = 0;
        const SIG_SETMASK: usize = 2;
        // SAFETY: the caller's contract.
        let relay = unsafe { &*arg.cast::<Self>() };
        // No signal meant for the child is for this process: one sent to
        // their process group while it waits must not end it (only
        // `SIGKILL` can, and the parent is then told by the end of the
        // socket). The kernel's set of signals is 64 bits everywhere.
        let all: u64 = !0;
        // SAFETY: the set is valid for the call.
        let _ = unsafe { syscall!(RT_SIGPROCMASK, SIG_SETMASK, &raw const all, 0usize, 8usize) };
        while relay.running.load(Ordering::SeqCst) != 0 {
            let address = relay.running.as_ptr();
            // SAFETY: the kernel reads the number at the address, and no
            // timeout.
            #[cfg(target_pointer_width = "32")]
            let waited = unsafe { syscall!(FUTEX_TIME64, address, FUTEX_WAIT, 1usize, 0usize) };
            // SAFETY: as above.
            #[cfg(target_pointer_width = "64")]
            let waited = unsafe { syscall!(FUTEX, address, FUTEX_WAIT, 1usize, 0usize) };
            match waited {
                Ok(_) => {}
                // The number changed first, or a signal came.
                Err(error) if matches!(error.raw_os_error(), errno::EAGAIN | errno::EINTR) => {}
                // No way to wait: nothing is sent, and the parent is told
                // so by the end of the socket.
                Err(_) => break,
            }
        }
        let listener = relay.listener.load(Ordering::SeqCst);
        if listener >= 0 && relay.running.load(Ordering::SeqCst) == 0 {
            // SAFETY: a system call, on this stack.
            let _ = unsafe { crate::sys::net::send_handle(relay.socket, listener) };
        }
        loop {
            // SAFETY: no memory is involved.
            let _ = unsafe { syscall!(EXIT_GROUP, 0) };
        }
    }

    /// Creates the process that will send the listener. In the child,
    /// before the filter.
    ///
    /// # Safety
    ///
    /// For a child of `spawn` that has its own copy of the memory of its
    /// parent: system calls only.
    unsafe fn start(&self) -> Result<()> {
        use core::sync::atomic::Ordering;
        /// Children that have no exit signal are waited for with this.
        const WALL: usize = 0x4000_0000;
        let arg = core::ptr::from_ref(self)
            .cast_mut()
            .cast::<core::ffi::c_void>();
        // SAFETY: the kernel keeps the address, and writes to it when
        // this process runs a program or ends: memory that the process
        // that waits shares, and that nothing frees before.
        unsafe { syscall!(SET_TID_ADDRESS, self.running.as_ptr()) }?;
        let flags = super::spawn::CLONE_VM | super::spawn::CLONE_FILES;
        // SAFETY: the stack is this relay's own, and `first` makes system
        // calls only.
        let first = crate::sys::check(unsafe {
            super::spawn::clone_vfork(
                flags,
                self.stacks[0],
                core::ptr::null_mut(),
                Self::first,
                arg,
            ) as usize
        })?;
        // SAFETY: no memory is involved (no `siginfo` is asked for).
        unsafe {
            syscall!(
                WAITID,
                super::spawn::P_PID,
                first,
                0usize,
                super::spawn::WEXITED | WALL,
                0usize
            )
        }?;
        match self.error.load(Ordering::SeqCst) {
            0 => Ok(()),
            error => Err(crate::Error::from_raw_os_error(error)),
        }
    }
}

#[cfg(feature = "alloc")]
impl ChildSecurity {
    /// Checks and converts what the command asks for. `changes_user` says
    /// whether the child sets its user.
    pub(crate) fn new(
        options: &crate::process::linux::Options<'_>,
        changes_user: bool,
        relay: Option<(i32, *mut u8)>,
        landlock: i32,
    ) -> Result<Self> {
        // A listener is a filter's.
        if options.seccomp_listener && options.seccomp.is_none() {
            return Err(ErrorKind::InvalidInput.into());
        }
        let sets = |capabilities: crate::process::linux::Capabilities| {
            [
                capabilities.effective.bits(),
                capabilities.permitted.bits(),
                capabilities.inheritable.bits(),
            ]
        };
        let ambient = options.ambient.map(|set| set.bits());
        Ok(Self {
            // A change of user away from root clears the permitted set,
            // which what follows is taken from.
            keep: changes_user && (options.capabilities.is_some() || ambient.is_some()),
            bounding: options.bounding.map(|set| set.bits()),
            capabilities: options.capabilities.map(sets),
            ambient,
            filter: match options.seccomp {
                Some((program, flags)) => Some((
                    super::seccomp::Program::new(program)?,
                    super::seccomp::filter_flags(flags),
                )),
                None => None,
            },
            relay: relay.map(|(socket, stacks)| {
                let size = super::spawn::STACK_SIZE;
                Relay {
                    socket,
                    // SAFETY: the mapping is two stacks long.
                    stacks: unsafe { [stacks.add(size), stacks.add(2 * size)] },
                    running: core::sync::atomic::AtomicU32::new(1),
                    listener: core::sync::atomic::AtomicI32::new(-1),
                    error: core::sync::atomic::AtomicI32::new(0),
                }
            }),
            landlock,
            trace_me: options.trace_me,
        })
    }

    /// The descriptors the child must keep open until it runs its
    /// program, besides the standard ones and the error pipe: the socket
    /// of its relay and its Landlock ruleset, or -1 for each it has not.
    pub(crate) fn kept(&self) -> [i32; 2] {
        [
            self.relay.as_ref().map_or(-1, |relay| relay.socket),
            self.landlock,
        ]
    }

    /// Whether the child must have a copy of the memory of its parent
    /// instead of sharing it: when it installs a filter, which may leave
    /// it no way out but the one [`exit`](Self::exit) ends with.
    pub(crate) fn needs_own_memory(&self) -> bool {
        self.filter.is_some()
    }

    /// Ends the child that could not run its program.
    ///
    /// `exit_group` does it, unless the filter the child has just
    /// installed forbids that too, by an error: a list of allowed calls
    /// that has neither `execve` nor `exit_group` is enough. The child
    /// then tries what else ends a process, and at last executes an
    /// instruction that is none: no filter stands between a process and
    /// the signal of its own fault. Spinning instead would leave the
    /// thread that called `spawn` suspended for good.
    ///
    /// That signal is one whose default action writes a core dump, and
    /// before Linux 5.16 a core dump ended every process that shared the
    /// memory of the one that dumped: the parent, for the usual child of
    /// `spawn`. That is why a child with a filter has its own
    /// ([`needs_own_memory`](Self::needs_own_memory)).
    ///
    /// # Safety
    ///
    /// For the child of `spawn`: system calls only.
    pub(crate) unsafe fn exit(&self, code: i32) -> ! {
        const SIGKILL: usize = 9;
        loop {
            // SAFETY: none of these calls takes memory.
            unsafe {
                let _ = syscall!(EXIT_GROUP, code);
                let _ = syscall!(EXIT, code);
                if let Ok(pid) = syscall!(GETPID) {
                    let _ = syscall!(KILL, pid, SIGKILL);
                }
            }
            if self.filter.is_some() {
                invalid_instruction();
            }
        }
    }

    /// What must be done while the child still has the privileges it
    /// starts with: before it changes its user.
    ///
    /// # Safety
    ///
    /// For a child that is about to call `execve`: system calls only.
    pub(crate) unsafe fn before_identity(&self) -> Result<()> {
        if self.keep {
            set_keep_capabilities(true)?;
        }
        if let Some(keep) = self.bounding {
            let mut capability = 0;
            while capability < 64 {
                if keep & (1 << capability) == 0 {
                    match drop_bounding(capability) {
                        Ok(()) => {}
                        // Past the last capability of this kernel.
                        Err(error) if error.raw_os_error() == errno::EINVAL && capability > 0 => {
                            break;
                        }
                        Err(error) => return Err(error),
                    }
                }
                capability += 1;
            }
        }
        Ok(())
    }

    /// The last things before `execve`: the sets, then the filter, after
    /// which few system calls may be left.
    ///
    /// # Safety
    ///
    /// As [`before_identity`](Self::before_identity); the memory the
    /// filter was borrowed from must still be there.
    pub(crate) unsafe fn before_exec(&self) -> Result<()> {
        // First, while the child may still have the capability that
        // stands in for "no new privileges"; nothing below is something
        // Landlock restricts.
        if self.landlock >= 0 {
            super::landlock::restrict_self_raw(self.landlock, 0)?;
        }
        if let Some(sets) = self.capabilities {
            set_capabilities(sets)?;
        }
        if let Some(ambient) = self.ambient {
            clear_ambient()?;
            let mut capability = 0;
            while capability < 64 {
                if ambient & (1 << capability) != 0 {
                    raise_ambient(capability)?;
                }
                capability += 1;
            }
        }
        // Before the filter, which need not allow it.
        if self.trace_me {
            super::ptrace::trace_me()?;
        }
        if let Some((program, flags)) = &self.filter {
            match &self.relay {
                Some(relay) => {
                    // SAFETY: the caller's contract; a child with a
                    // filter has its own memory.
                    unsafe { relay.start() }?;
                    // SAFETY: the caller's contract.
                    let listener = unsafe { program.install_listener(*flags) }?;
                    // Not a system call: none is safe from here on.
                    relay
                        .listener
                        .store(listener, core::sync::atomic::Ordering::SeqCst);
                }
                // SAFETY: the caller's contract.
                None => unsafe { program.install(*flags) }?,
            }
        }
        Ok(())
    }
}