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
//! Tests of `oscall::process::linux::landlock`.
//!
//! A restriction cannot be taken back: whatever restricts itself does it
//! in a helper process (this binary, run again with `OSCALL_TEST_HELPER`
//! set), never in the test harness. Landlock needs no privilege, so these
//! run wherever the kernel has it; where it has not (an emulator of
//! programs, a kernel built or started without it) the tests say so
//! (`skipped: ...`) and pass, except in a run that must skip nothing
//! (`OSCALL_REQUIRE_PRIVILEGED`).
#![cfg(any(target_os = "linux", target_os = "fullrust"))]

mod common;

use oscall::ErrorKind;
use oscall::process::linux::landlock::{self, AccessFs, AccessNet, RestrictFlags, Scope};

const ENOMSG: i32 = 42;
const EBADFD: i32 = 77;

/// The version of Landlock here, or `None`, having said why, where there
/// is none.
fn version() -> Option<u32> {
    match landlock::abi_version() {
        Ok(version) => {
            assert!(version >= 1);
            Some(version)
        }
        Err(error) => {
            assert_eq!(error.kind(), ErrorKind::Unsupported, "{error:?}");
            // The kernel says which security modules it runs; the file is
            // not there in every container.
            let modules = std::fs::read_to_string("/sys/kernel/security/lsm").unwrap_or_default();
            let listed = modules.split(',').any(|module| module.trim() == "landlock");
            if common::emulated() {
                common::note(&format!("skipped: no Landlock under an emulator: {error}"));
            } else {
                assert!(
                    !listed,
                    "the kernel runs Landlock and refuses it: {error:?}"
                );
                common::skip(&format!("the kernel has no Landlock: {error}"));
            }
            None
        }
    }
}

#[test]
fn rights() {
    let fs = [
        AccessFs::EXECUTE,
        AccessFs::WRITE_FILE,
        AccessFs::READ_FILE,
        AccessFs::READ_DIR,
        AccessFs::REMOVE_DIR,
        AccessFs::REMOVE_FILE,
        AccessFs::MAKE_CHAR,
        AccessFs::MAKE_DIR,
        AccessFs::MAKE_REG,
        AccessFs::MAKE_SOCK,
        AccessFs::MAKE_FIFO,
        AccessFs::MAKE_BLOCK,
        AccessFs::MAKE_SYM,
        AccessFs::REFER,
        AccessFs::TRUNCATE,
        AccessFs::IOCTL_DEV,
    ];
    let mut all = AccessFs::empty();
    for right in fs {
        assert!(!right.is_empty() && !all.intersects(right));
        all |= right;
    }
    // Each version knows what the one before knew.
    assert!(AccessFs::for_abi(0).is_empty());
    assert_eq!(
        AccessFs::for_abi(1),
        all - AccessFs::REFER - AccessFs::TRUNCATE - AccessFs::IOCTL_DEV
    );
    assert_eq!(AccessFs::for_abi(2), AccessFs::for_abi(1) | AccessFs::REFER);
    assert_eq!(
        AccessFs::for_abi(3),
        AccessFs::for_abi(2) | AccessFs::TRUNCATE
    );
    assert_eq!(AccessFs::for_abi(4), AccessFs::for_abi(3));
    assert_eq!(AccessFs::for_abi(5), all);
    assert_eq!(AccessFs::for_abi(u32::MAX), all);
    for abi in 0..8 {
        assert!(AccessFs::for_abi(abi + 1).contains(AccessFs::for_abi(abi)));
        assert!(AccessNet::for_abi(abi + 1).contains(AccessNet::for_abi(abi)));
        assert!(Scope::for_abi(abi + 1).contains(Scope::for_abi(abi)));
    }
    assert!(!AccessFs::READING.intersects(AccessFs::WRITING));
    assert_eq!(
        AccessFs::READING | AccessFs::WRITING | AccessFs::IOCTL_DEV,
        all
    );
    assert!(AccessFs::FILE.contains(AccessFs::EXECUTE | AccessFs::TRUNCATE));
    assert!(!AccessFs::FILE.intersects(AccessFs::READ_DIR | AccessFs::MAKE_REG));

    assert!(AccessNet::for_abi(3).is_empty());
    assert_eq!(
        AccessNet::for_abi(4),
        AccessNet::BIND_TCP | AccessNet::CONNECT_TCP
    );
    assert!(Scope::for_abi(5).is_empty());
    assert_eq!(
        Scope::for_abi(6),
        Scope::ABSTRACT_UNIX_SOCKET | Scope::SIGNAL
    );
    let flags = RestrictFlags::LOG_SAME_EXEC_OFF
        | RestrictFlags::LOG_NEW_EXEC_ON
        | RestrictFlags::LOG_SUBDOMAINS_OFF;
    assert_eq!(
        format!("{flags:?}"),
        "RestrictFlags(LOG_SAME_EXEC_OFF | LOG_NEW_EXEC_ON | LOG_SUBDOMAINS_OFF)"
    );
}

/// What a ruleset takes and refuses. No thread is restricted: a ruleset
/// is only a handle.
#[test]
fn rulesets() {
    let Some(abi) = version() else {
        let none = (AccessNet::empty(), Scope::empty());
        let error = landlock::create_ruleset(AccessFs::for_abi(1), none.0, none.1).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::Unsupported, "{error:?}");
        return;
    };
    match landlock::errata() {
        Ok(_) => {}
        // A kernel older than the question.
        Err(error) => assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}"),
    }
    let (fs, net, scopes) = (
        AccessFs::for_abi(abi),
        AccessNet::for_abi(abi),
        Scope::for_abi(abi),
    );
    let ruleset = landlock::create_ruleset(fs, net, scopes).unwrap();
    // Close-on-exec, as every handle is.
    assert_eq!(oscall::io::is_inheritable(&ruleset), Ok(false));
    // A ruleset is about something.
    let error = landlock::create_ruleset(AccessFs::empty(), AccessNet::empty(), Scope::empty())
        .unwrap_err();
    assert_eq!(error.raw_os_error(), ENOMSG, "{error:?}");

    let dir = common::tmp_dir("process_linux_landlock_rulesets");
    std::fs::write(dir.join("file"), "").unwrap();
    let directory = std::fs::File::open(&dir).unwrap();
    let file = std::fs::File::open(dir.join("file")).unwrap();
    let (directory, file) = (common::handle_of(&directory), common::handle_of(&file));
    landlock::add_path_rule(&ruleset, &directory, fs).unwrap();
    landlock::add_path_rule(&ruleset, &directory, AccessFs::READ_DIR).unwrap();
    landlock::add_path_rule(&ruleset, &file, AccessFs::FILE & fs).unwrap();
    // A file is no directory, and a rule allows something.
    let error = landlock::add_path_rule(&ruleset, &file, AccessFs::READ_DIR).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
    let error = landlock::add_path_rule(&ruleset, &directory, AccessFs::empty()).unwrap_err();
    assert_eq!(error.raw_os_error(), ENOMSG, "{error:?}");
    // What a ruleset does not handle, it has no rule about.
    let reading = landlock::create_ruleset(AccessFs::READ_FILE, AccessNet::empty(), Scope::empty());
    let reading = reading.unwrap();
    let error = landlock::add_path_rule(&reading, &directory, AccessFs::WRITE_FILE).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
    // A handle that is no ruleset, where one is wanted and where a file
    // is.
    let error = landlock::add_path_rule(&directory, &directory, AccessFs::READ_FILE).unwrap_err();
    assert_eq!(error.raw_os_error(), EBADFD, "{error:?}");
    let error = landlock::add_path_rule(&reading, &reading, AccessFs::READ_FILE).unwrap_err();
    assert_eq!(error.raw_os_error(), EBADFD, "{error:?}");

    if net.is_empty() {
        common::note("skipped: Landlock here has no network rules (before version 4)");
        // An older kernel does not know the structure that says them.
        let error = landlock::add_port_rule(&ruleset, 80, AccessNet::BIND_TCP).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
    } else {
        landlock::add_port_rule(&ruleset, 443, AccessNet::CONNECT_TCP).unwrap();
        landlock::add_port_rule(&ruleset, 0, net).unwrap();
        landlock::add_port_rule(&ruleset, u16::MAX, AccessNet::BIND_TCP).unwrap();
        let error = landlock::add_port_rule(&ruleset, 80, AccessNet::empty()).unwrap_err();
        assert_eq!(error.raw_os_error(), ENOMSG, "{error:?}");
        let error = landlock::add_port_rule(&reading, 80, AccessNet::BIND_TCP).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidInput, "{error:?}");
    }
}

/// The child half of the tests that run this binary again: does what the
/// `OSCALL_TEST_HELPER` variable says, and nothing in an ordinary run.
#[test]
fn helper_child_process() {
    let Some(mode) = std::env::var_os("OSCALL_TEST_HELPER") else {
        return;
    };
    let mode = mode.into_string().unwrap();
    #[cfg(feature = "alloc")]
    children::helper_main(&mode);
    panic!("unknown helper mode {mode}");
}

#[cfg(feature = "alloc")]
mod children {
    use std::path::{Path, PathBuf};
    use std::time::{Duration, Instant};

    use oscall::process::linux::landlock::{self, AccessFs, AccessNet, RestrictFlags, Scope};
    use oscall::process::linux::{self, Capability, CommandExt as _, ConfineExt as _};
    use oscall::process::{Child, Command, ExitStatus, Stdio};
    use oscall::{AsHandle as _, Error, ErrorKind};

    use super::{EBADFD, common, version};

    const ENOEXEC: i32 = 8;
    const E2BIG: i32 = 7;

    /// Waits for the child, for a limited time.
    fn wait(child: &mut Child) -> ExitStatus {
        let start = Instant::now();
        loop {
            if let Some(status) = child.try_wait().unwrap() {
                return status;
            }
            if start.elapsed() > Duration::from_secs(60) {
                child.kill().unwrap();
                panic!("the child did not exit");
            }
            std::thread::sleep(Duration::from_millis(2));
        }
    }

    /// This test binary, to run again as the helper of a mode.
    struct Helper {
        exe: PathBuf,
        env: Vec<Vec<u8>>,
    }

    impl Helper {
        fn new(mode: &str) -> Self {
            let mut env: Vec<Vec<u8>> = std::env::vars_os()
                .filter(|(name, _)| name != "OSCALL_TEST_HELPER")
                .map(|(name, value)| {
                    [name.as_encoded_bytes(), b"=", value.as_encoded_bytes()].concat()
                })
                .collect();
            env.push(format!("OSCALL_TEST_HELPER={mode}").into_bytes());
            Self {
                exe: std::env::current_exe().unwrap(),
                env,
            }
        }

        /// Runs the helper, set up by `configure`. `Err` with the error
        /// of `spawn`; `None`, having said why, where the system cannot
        /// run it at all.
        fn run<'a>(
            &'a self,
            configure: impl FnOnce(Command<'a>) -> Command<'a>,
        ) -> Option<Result<ExitStatus, Error>> {
            const ARGS: &[&str] = &["--exact", "--nocapture", "helper_child_process"];
            let command = Command::new(self.exe.as_os_str().as_encoded_bytes())
                .args(ARGS)
                .env(&self.env)
                .stdin(Stdio::Null)
                .stdout(Stdio::Null);
            match configure(command).spawn() {
                Ok(mut child) => Some(Ok(wait(&mut child))),
                // The binary is for another architecture, and runs here
                // under an emulator the kernel knows nothing about.
                Err(error) if error.raw_os_error() == ENOEXEC => {
                    common::skip(&format!("the system cannot execute {}", self.exe.display()));
                    None
                }
                Err(error) => Some(Err(error)),
            }
        }
    }

    /// Two directories of a new directory `name`, each with a file: what
    /// a ruleset allows, and what it does not.
    fn directories(name: &str) -> (PathBuf, PathBuf) {
        let dir = std::path::absolute(common::tmp_dir(name)).unwrap();
        let (allowed, denied) = (dir.join("allowed"), dir.join("denied"));
        for dir in [&allowed, &denied] {
            std::fs::create_dir(dir).unwrap();
            std::fs::write(dir.join("old"), "old").unwrap();
        }
        (allowed, denied)
    }

    /// A ruleset that handles everything that writes, and allows it under
    /// `allowed`.
    fn writing_under(abi: u32, allowed: &Path) -> oscall::OwnedHandle {
        let writing = AccessFs::WRITING & AccessFs::for_abi(abi);
        let ruleset =
            landlock::create_ruleset(writing, AccessNet::empty(), Scope::empty()).unwrap();
        let directory = std::fs::File::open(allowed).unwrap();
        landlock::add_path_rule(&ruleset, &common::handle_of(&directory), writing).unwrap();
        ruleset
    }

    /// Checks that the caller may write under `allowed` and not under
    /// `denied`, and may read both.
    fn check_writing(allowed: &Path, denied: &Path) {
        let refused = |result: std::io::Result<()>| {
            let error = result.unwrap_err();
            assert_eq!(
                error.kind(),
                std::io::ErrorKind::PermissionDenied,
                "{error:?}"
            );
        };
        std::fs::write(allowed.join("new"), "new").unwrap();
        std::fs::write(allowed.join("old"), "changed").unwrap();
        std::fs::create_dir(allowed.join("dir")).unwrap();
        std::fs::remove_dir(allowed.join("dir")).unwrap();
        std::fs::remove_file(allowed.join("new")).unwrap();
        refused(std::fs::write(denied.join("new"), "new"));
        refused(std::fs::write(denied.join("old"), "changed"));
        refused(std::fs::create_dir(denied.join("dir")));
        refused(std::fs::remove_file(denied.join("old")));
        refused(std::fs::rename(allowed.join("old"), denied.join("moved")));
        refused(std::os::unix::fs::symlink("old", denied.join("link")));
        // Reading is not what the ruleset is about.
        assert_eq!(std::fs::read_to_string(denied.join("old")).unwrap(), "old");
        assert!(std::fs::read_dir(denied).unwrap().count() >= 1);
        assert_eq!(
            std::fs::read_to_string(allowed.join("old")).unwrap(),
            "changed"
        );
    }

    pub(super) fn helper_main(mode: &str) {
        let (name, rest) = mode.split_once(':').unwrap_or((mode, ""));
        let paths: Vec<PathBuf> = rest.split(':').map(PathBuf::from).collect();
        match name {
            "restrict" => helper_restrict(&paths[0], &paths[1]),
            "writing" => check_writing(&paths[0], &paths[1]),
            "nothing" => {}
            _ => panic!("unknown helper mode {mode}"),
        }
        oscall::process::exit(0);
    }

    /// A process that restricts itself, in layers, and checks what each
    /// one takes away.
    fn helper_restrict(allowed: &Path, denied: &Path) {
        let abi = landlock::abi_version().unwrap();
        let parent = oscall::process::parent_id();
        // A thread that exists before the restriction, and one made after.
        let (ask, asked) = std::sync::mpsc::channel::<PathBuf>();
        let (answer, answered) = std::sync::mpsc::channel();
        let before = std::thread::spawn(move || {
            for path in asked {
                answer.send(std::fs::write(path, "")).unwrap();
            }
        });

        let ruleset = writing_under(abi, allowed);
        // Not for a thread that could still gain privileges, unless it
        // has the capability.
        let capable = linux::capabilities()
            .unwrap()
            .effective
            .contains(Capability::SysAdmin);
        if !capable {
            let error = landlock::restrict_self(&ruleset, RestrictFlags::empty()).unwrap_err();
            assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
        }
        std::fs::write(denied.join("early"), "").unwrap();
        std::fs::remove_file(denied.join("early")).unwrap();
        linux::set_no_new_privileges().unwrap();
        // A handle that is no ruleset.
        let file = std::fs::File::open(allowed).unwrap();
        let error = landlock::restrict_self(&common::handle_of(&file), RestrictFlags::empty());
        assert_eq!(error.unwrap_err().raw_os_error(), EBADFD);
        landlock::restrict_self(&ruleset, RestrictFlags::empty()).unwrap();
        check_writing(allowed, denied);
        // The same for a thread made since, and for a process: this
        // program, run again.
        let (a, d) = (allowed.to_owned(), denied.to_owned());
        std::thread::spawn(move || check_writing(&a, &d))
            .join()
            .unwrap();
        std::fs::write(allowed.join("old"), "old").unwrap();
        let mode = format!("writing:{}:{}", allowed.display(), denied.display());
        // Opening the null device for a child is opening a file for
        // writing, which the ruleset has no rule for.
        let helper = Helper::new(&mode);
        let error = helper.run(|command| command).unwrap().unwrap_err();
        assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
        let status = helper
            .run(|command| command.stdin(Stdio::Inherit).stdout(Stdio::Inherit))
            .unwrap()
            .unwrap();
        assert!(status.success(), "{status}");
        // A thread that was there before is as it was: the restriction
        // is the calling thread's.
        ask.send(denied.join("by-a-thread")).unwrap();
        answered.recv().unwrap().unwrap();
        drop(ask);
        before.join().unwrap();
        assert!(denied.join("by-a-thread").exists());

        // Ports, and other processes: a second layer.
        let net = AccessNet::for_abi(abi) & AccessNet::BIND_TCP;
        let scopes = Scope::for_abi(abi) & Scope::SIGNAL;
        // Not a restricted call yet.
        oscall::process::unix::send_signal(parent, 0).unwrap();
        if net.is_empty() {
            common::note("skipped: Landlock here has no network rules (before version 4)");
        } else {
            let any = "0.0.0.0:0";
            let port = std::net::TcpListener::bind(any)
                .unwrap()
                .local_addr()
                .unwrap()
                .port();
            let ruleset = landlock::create_ruleset(AccessFs::empty(), net, scopes).unwrap();
            landlock::add_port_rule(&ruleset, port, net).unwrap();
            landlock::restrict_self(&ruleset, RestrictFlags::empty()).unwrap();
            std::net::TcpListener::bind(("0.0.0.0", port)).unwrap();
            // Any other port, the one the system would pick included.
            let error = std::net::TcpListener::bind(any).unwrap_err();
            assert_eq!(
                error.kind(),
                std::io::ErrorKind::PermissionDenied,
                "{error:?}"
            );
            // A datagram socket is not what the rule is about.
            std::net::UdpSocket::bind(any).unwrap();
            if scopes.is_empty() {
                common::note("skipped: Landlock here has no scopes (before version 6)");
            } else {
                // The parent is outside the restriction; this process is
                // inside.
                let error = oscall::process::unix::send_signal(parent, 0).unwrap_err();
                assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
                oscall::process::unix::send_signal(oscall::process::id(), 0).unwrap();
            }
        }
        // The first layer still holds.
        check_writing(allowed, denied);

        // A layer that allows nothing of what it handles; every layer
        // has its say.
        let listing =
            landlock::create_ruleset(AccessFs::READ_DIR, AccessNet::empty(), Scope::empty());
        let listing = listing.unwrap();
        let flags = if abi >= 7 {
            RestrictFlags::LOG_SAME_EXEC_OFF
        } else {
            RestrictFlags::empty()
        };
        landlock::restrict_self(&listing, flags).unwrap();
        for dir in [allowed, denied] {
            let error = std::fs::read_dir(dir).unwrap_err();
            assert_eq!(
                error.kind(),
                std::io::ErrorKind::PermissionDenied,
                "{error:?}"
            );
        }
        std::fs::write(allowed.join("last"), "").unwrap();
        // Sixteen layers, and no more.
        let mut layers = 3 - usize::from(net.is_empty());
        let error = loop {
            match landlock::restrict_self(&listing, RestrictFlags::empty()) {
                Ok(()) => layers += 1,
                Err(error) => break error,
            }
            assert!(layers <= 16);
        };
        assert_eq!((layers, error.raw_os_error()), (16, E2BIG), "{error:?}");
    }

    /// A thread that restricts itself: files, ports, signals, and what
    /// its threads and its children inherit.
    #[test]
    fn restricted_thread() {
        if version().is_none() {
            return;
        }
        let (allowed, denied) = directories("process_linux_landlock_thread");
        let mode = format!("restrict:{}:{}", allowed.display(), denied.display());
        if let Some(result) = Helper::new(&mode).run(|command| command) {
            let status = result.unwrap();
            assert!(status.success(), "{status}");
            assert!(allowed.join("last").exists() && !denied.join("new").exists());
        }
    }

    /// A child that is restricted before its program starts.
    #[test]
    fn restricted_child() {
        let Some(abi) = version() else {
            // The command says so too.
            let file = std::fs::File::open("/").unwrap();
            let helper = Helper::new("nothing");
            let result = helper.run(|command| {
                command
                    .no_new_privileges()
                    .landlock(common::handle_of(&file))
            });
            if let Some(result) = result {
                let error = result.unwrap_err();
                assert_eq!(error.kind(), ErrorKind::Unsupported, "{error:?}");
            }
            return;
        };
        let (allowed, denied) = directories("process_linux_landlock_child");
        let ruleset = writing_under(abi, &allowed);
        let mode = format!("writing:{}:{}", allowed.display(), denied.display());
        let helper = Helper::new(&mode);
        let Some(result) =
            helper.run(|command| command.no_new_privileges().landlock(ruleset.as_handle()))
        else {
            return;
        };
        let status = result.unwrap();
        assert!(status.success(), "{status}");
        // The caller is as it was, and the ruleset serves again.
        std::fs::write(denied.join("new"), "new").unwrap();
        std::fs::remove_file(denied.join("new")).unwrap();
        std::fs::write(allowed.join("old"), "old").unwrap();
        let again = helper.run(|command| command.no_new_privileges().landlock(ruleset.as_handle()));
        assert!(again.unwrap().unwrap().success());

        // It wants a child that cannot gain privileges, or the
        // capability.
        let capable = linux::capabilities()
            .unwrap()
            .effective
            .contains(Capability::SysAdmin);
        if !capable {
            let error = helper
                .run(|command| command.landlock(ruleset.as_handle()))
                .unwrap()
                .unwrap_err();
            assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
        }
        // A handle that is no ruleset.
        let file = std::fs::File::open(&allowed).unwrap();
        let error = helper
            .run(|command| {
                command
                    .no_new_privileges()
                    .landlock(common::handle_of(&file))
            })
            .unwrap()
            .unwrap_err();
        assert_eq!(error.raw_os_error(), EBADFD, "{error:?}");

        // Running the program is an access like another: refused when
        // the ruleset handles it and has no rule for it, and allowed by
        // a rule for the root directory.
        let helper = Helper::new("nothing");
        let none = (AccessNet::empty(), Scope::empty());
        let executing = landlock::create_ruleset(AccessFs::EXECUTE, none.0, none.1).unwrap();
        let error = helper
            .run(|command| command.no_new_privileges().landlock(executing.as_handle()))
            .unwrap()
            .unwrap_err();
        assert_eq!(error.kind(), ErrorKind::PermissionDenied, "{error:?}");
        let root = std::fs::File::open("/").unwrap();
        landlock::add_path_rule(&executing, &common::handle_of(&root), AccessFs::EXECUTE).unwrap();
        let status = helper
            .run(|command| command.no_new_privileges().landlock(executing.as_handle()))
            .unwrap()
            .unwrap();
        assert!(status.success(), "{status}");
    }
}