syd 3.52.0

rock-solid application kernel
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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
//
// Syd: rock-solid application kernel
// src/kernel/stat.rs: stat syscall handlers
//
// Copyright (c) 2023, 2024, 2025, 2026 Ali Polatel <alip@chesswob.org>
//
// SPDX-License-Identifier: GPL-3.0

use std::io::BufReader;

use libseccomp::ScmpNotifResp;
use nix::{errno::Errno, fcntl::AtFlags, NixPath};

use crate::{
    compat::{
        fstatat64, statx, FileStat, FileStat64, FileStatx, FileStatxTimestamp, STATX_BASIC_STATS,
        STATX_MODE, STATX_TYPE,
    },
    config::{API_VERSION, MAGIC_LOAD, MAGIC_PREFIX},
    confine::{is_valid_ptr, scmp_arch_bits, EOWNERDEAD},
    fd::{is_file, parse_fd},
    hash::SydHashSet,
    kernel::to_atflags,
    lookup::{CanonicalPath, FileInfo, FileType, FsFlags},
    path::XPath,
    req::{SysArg, SysFlags, UNotifyEventRequest},
    sandbox::{Capability, Options},
};

const AT_STATX_FORCE_SYNC: AtFlags = AtFlags::from_bits_retain(0x2000);
const AT_STATX_DONT_SYNC: AtFlags = AtFlags::from_bits_retain(0x4000);
// const AT_STATX_SYNC_AS_STAT: AtFlags = AtFlags::empty();

pub(crate) fn sys_stat(request: UNotifyEventRequest) -> ScmpNotifResp {
    let arg = SysArg {
        path: Some(0),
        flags: SysFlags::CHECK_MAGIC,
        fsflags: FsFlags::MUST_PATH,
        ..Default::default()
    };

    syscall_stat_handler(request, arg, 1, false)
}

pub(crate) fn sys_stat64(request: UNotifyEventRequest) -> ScmpNotifResp {
    let arg = SysArg {
        path: Some(0),
        flags: SysFlags::CHECK_MAGIC,
        fsflags: FsFlags::MUST_PATH,
        ..Default::default()
    };

    syscall_stat_handler(request, arg, 1, true)
}

pub(crate) fn sys_fstat(request: UNotifyEventRequest) -> ScmpNotifResp {
    let arg = SysArg {
        dirfd: Some(0),
        ..Default::default()
    };

    syscall_stat_handler(request, arg, 1, false)
}

pub(crate) fn sys_fstat64(request: UNotifyEventRequest) -> ScmpNotifResp {
    let arg = SysArg {
        dirfd: Some(0),
        ..Default::default()
    };

    syscall_stat_handler(request, arg, 1, true)
}

pub(crate) fn sys_lstat(request: UNotifyEventRequest) -> ScmpNotifResp {
    let arg = SysArg {
        path: Some(0),
        flags: SysFlags::CHECK_MAGIC,
        fsflags: FsFlags::MUST_PATH | FsFlags::NO_FOLLOW_LAST,
        ..Default::default()
    };

    syscall_stat_handler(request, arg, 1, false)
}

pub(crate) fn sys_lstat64(request: UNotifyEventRequest) -> ScmpNotifResp {
    let arg = SysArg {
        path: Some(0),
        flags: SysFlags::CHECK_MAGIC,
        fsflags: FsFlags::MUST_PATH | FsFlags::NO_FOLLOW_LAST,
        ..Default::default()
    };

    syscall_stat_handler(request, arg, 1, true)
}

pub(crate) fn sys_statx(request: UNotifyEventRequest) -> ScmpNotifResp {
    let req = request.scmpreq;

    // Reject undefined/invalid flags.
    let atflags = match to_atflags(
        req.data.args[2],
        AtFlags::AT_EMPTY_PATH
            | AtFlags::AT_SYMLINK_NOFOLLOW
            | AtFlags::AT_NO_AUTOMOUNT
            | AT_STATX_FORCE_SYNC
            | AT_STATX_DONT_SYNC,
    ) {
        Ok(atflags) => atflags,
        Err(errno) => return request.fail_syscall(errno),
    };

    // Reject mutually exclusive sync flags.
    if atflags.contains(AT_STATX_FORCE_SYNC | AT_STATX_DONT_SYNC) {
        return request.fail_syscall(Errno::EINVAL);
    }

    // Reject reserved mask bits.
    const STATX__RESERVED: u64 = 0x80000000;
    if req.data.args[3] & STATX__RESERVED != 0 {
        return request.fail_syscall(Errno::EINVAL);
    }

    let mut flags = SysFlags::empty();
    let mut fsflags = FsFlags::MUST_PATH;
    if atflags.contains(AtFlags::AT_EMPTY_PATH) {
        flags |= SysFlags::EMPTY_PATH | SysFlags::MAYBE_NULL;
    } else {
        flags |= SysFlags::CHECK_MAGIC;
    }
    if atflags.contains(AtFlags::AT_SYMLINK_NOFOLLOW) {
        fsflags |= FsFlags::NO_FOLLOW_LAST;
    }

    let arg = SysArg {
        dirfd: Some(0),
        path: Some(1),
        flags,
        fsflags,
    };

    syscall_stat_handler(request, arg, 4, false)
}

pub(crate) fn sys_newfstatat(request: UNotifyEventRequest) -> ScmpNotifResp {
    let req = request.scmpreq;

    // Reject undefined/invalid flags.
    let atflags = match to_atflags(
        req.data.args[3],
        AtFlags::AT_EMPTY_PATH
            | AtFlags::AT_SYMLINK_NOFOLLOW
            | AtFlags::AT_NO_AUTOMOUNT
            | AT_STATX_FORCE_SYNC
            | AT_STATX_DONT_SYNC,
    ) {
        Ok(atflags) => atflags,
        Err(errno) => return request.fail_syscall(errno),
    };

    let mut flags = SysFlags::empty();
    let mut fsflags = FsFlags::MUST_PATH;
    if atflags.contains(AtFlags::AT_EMPTY_PATH) {
        flags |= SysFlags::EMPTY_PATH | SysFlags::MAYBE_NULL;
    } else {
        flags |= SysFlags::CHECK_MAGIC;
    }
    if atflags.contains(AtFlags::AT_SYMLINK_NOFOLLOW) {
        fsflags |= FsFlags::NO_FOLLOW_LAST;
    }

    let arg = SysArg {
        dirfd: Some(0),
        path: Some(1),
        flags,
        fsflags,
    };

    syscall_stat_handler(request, arg, 2, true)
}

#[expect(clippy::cognitive_complexity)]
fn syscall_stat_handler(
    request: UNotifyEventRequest,
    arg: SysArg,
    arg_stat: usize,
    compat64: bool,
) -> ScmpNotifResp {
    syscall_handler!(request, |request: UNotifyEventRequest| {
        let req = request.scmpreq;
        let sandbox = request.get_sandbox();

        // Read the remote path and check for magic path as necessary.
        let (mut path, magic, empty_path) = request.read_path(&sandbox, arg)?;
        let is_fd = empty_path || arg.path.is_none();

        // Check for chroot.
        if sandbox.is_chroot() {
            return Err(if is_fd { Errno::EACCES } else { Errno::ENOENT });
        }

        let has_crypt = sandbox.enabled(Capability::CAP_CRYPT);
        let restrict_stat_bdev = !sandbox.flags.allow_unsafe_stat_bdev();
        let restrict_stat_cdev = !sandbox.flags.allow_unsafe_stat_cdev();
        let mut ghost = false;
        let caps = *sandbox.state;
        let opts = *sandbox.options;
        if magic {
            if sandbox.locked_drop_for(req.pid()) {
                // Sandbox is locked, access denied.
                return Err(Errno::ENOENT);
            }
            drop(sandbox); // release the read-lock.

            // Handle magic prefix "/dev/syd".
            let cmd = path
                .abs()
                .strip_prefix(MAGIC_PREFIX)
                .unwrap_or_else(|| XPath::from_bytes(&path.abs().as_bytes()[MAGIC_PREFIX.len()..]));

            // Handle magic command.
            ghost = handle_magic_stat(&request, cmd)?;
        } else {
            // Handle fstat for files with encryption in progress.
            #[expect(clippy::disallowed_methods)]
            if is_fd && has_crypt {
                // has_crypt asserts crypt_map is Some.
                let files = request.cache.crypt_map.as_ref().unwrap();

                if let Ok(info) = FileInfo::from_fd(path.dir()) {
                    let files = files.0.lock().unwrap_or_else(|err| err.into_inner());
                    for (enc_path, map) in files.iter() {
                        if info == map.info {
                            // Found underlying encrypted file for the memory fd.
                            // We only ever attempt to encrypt regular files.
                            path = CanonicalPath::new_crypt(
                                path.dir.take().unwrap(),
                                enc_path.clone(),
                            );
                            break;
                        }
                    }
                } // Lock is released here.
            }

            // Return correct stat information for !memfd:syd/ paths.
            // This prefix is internal to Syd and sandbox process cannot
            // create memory file descriptors with this name prefix.
            if is_fd && path.is_memory_fd() && path.abs().starts_with(b"!memfd:syd") {
                let mut p = path.take();
                p.drain(0..b"!memfd:syd".len());
                path = CanonicalPath::new_mask(&p, &p)?;
            }

            // Return correct stat information for masked paths.
            // Fd-only stat(2) calls return correct value already.
            if !is_fd {
                if let Some(mask) = sandbox.is_masked(path.abs()) {
                    let mask = if let Some(mask_dir) = &mask.mask_dir {
                        // Override mask for directories as necessary.
                        if path.is_dir() {
                            Some(mask_dir)
                        } else {
                            mask.mask_all.as_ref()
                        }
                    } else {
                        mask.mask_all.as_ref()
                    };
                    match mask {
                        None => path = CanonicalPath::new_null(),
                        Some(mask) => path = CanonicalPath::new_mask(mask, path.abs())?,
                    };
                }
            }

            drop(sandbox); // release the read-lock.
        }

        // We use MUST_PATH, dir refers to the file.
        assert!(path.base().is_empty()); // MUST_PATH!
        let fd = path.dir();
        let mut flags = libc::AT_EMPTY_PATH;

        // Check for invalid buffer pointer after path lookup.
        if !is_valid_ptr(req.data.args[arg_stat], req.data.arch) {
            return Err(Errno::EFAULT);
        }

        #[expect(clippy::cast_possible_truncation)]
        if arg_stat == 4 {
            // statx

            // Support AT_STATX_* flags.
            flags |= req.data.args[2] as libc::c_int
                & !(libc::AT_SYMLINK_NOFOLLOW | libc::AT_EMPTY_PATH);

            // The sidechannel check below requires the mask to have the following items:
            // 1. STATX_TYPE (to check for char/block device)
            // 2. STATX_MODE (to check for world readable/writable)
            // To ensure that here, we inject these two flags into mask
            // noting if they were set originally. This can be in three
            // ways,
            // (a) Explicitly setting STATX_{TYPE,MODE}.
            // (b) Explicitly setting STATX_BASIC_STATS.
            // (c) Setting the catch-all STATX_ALL flag.
            // No need to strip the added flags back from mask, because
            // Linux always sets STATX_{TYPE,MODE} regardless of the
            // given mask.
            let mut mask = req.data.args[3] as libc::c_uint;
            let orig_mask = mask;
            let basic_stx = (orig_mask & STATX_BASIC_STATS) != 0;
            if !basic_stx {
                mask |= STATX_TYPE | STATX_MODE;
            }

            // Record blocking call so it can get invalidated.
            request.cache.add_sys_block(req, false)?;

            // All done, call the underlying system call.
            let result = statx(fd, c"", flags, mask);

            // Remove invalidation record.
            request.cache.del_sys_block(req.id)?;

            // Check result after critical block.
            let mut statx = result?;

            // Check if the file is a sidechannel device and update its
            // access and modification times to match the creation time
            // if it is. This prevents timing attacks on block or
            // character devices like /dev/ptmx using stat.
            if restrict_stat_bdev || restrict_stat_cdev {
                let filetype = FileType::from(libc::mode_t::from(statx.stx_mode));
                if (restrict_stat_bdev && filetype.is_block_device())
                    || (restrict_stat_cdev && filetype.is_char_device())
                {
                    statx.stx_atime = statx.stx_ctime;
                    statx.stx_mtime = statx.stx_ctime;
                }
            }

            // If magic path, mask values for easy id.
            if magic {
                magic_statx(&mut statx, caps, opts);
            }

            // SAFETY: Create an immutable byte slice of struct statx.
            // This slice cannot outlive the struct on the stack.
            let statx = unsafe {
                std::slice::from_raw_parts(
                    std::ptr::addr_of!(statx) as *const u8,
                    size_of_val(&statx),
                )
            };
            let addr = req.data.args[4];
            if addr != 0 {
                request.write_mem_all(statx, addr)?;
            }
        } else {
            // "stat" | "fstat" | "lstat" | "newfstatat"

            // Record blocking call so it can get invalidated.
            request.cache.add_sys_block(req, false)?;

            // All done, call the underlying system call.
            let result = fstatat64(fd, c"", flags);

            // Remove invalidation record.
            request.cache.del_sys_block(req.id)?;

            // Check result after critical block.
            let mut stat = result?;

            // Check if the file is a sidechannel device and update its
            // access and modification times to match the creation time
            // if it is. This prevents timing attacks on block or
            // character devices like /dev/ptmx using stat.
            if restrict_stat_bdev || restrict_stat_cdev {
                let filetype = FileType::from(stat.st_mode);
                if (restrict_stat_bdev && filetype.is_block_device())
                    || (restrict_stat_cdev && filetype.is_char_device())
                {
                    stat.st_atime = stat.st_ctime;
                    stat.st_mtime = stat.st_ctime;
                    stat.st_atime_nsec = stat.st_ctime_nsec;
                    stat.st_mtime_nsec = stat.st_ctime_nsec;
                }
            }

            // If magic path, mask values for easy id.
            if magic {
                magic_stat(&mut stat, caps, opts);
            }

            let addr = req.data.args[arg_stat];
            if addr != 0 {
                let is32 = scmp_arch_bits(req.data.arch) == 32;
                if is32 && compat64 {
                    let stat64: crate::compat::stat64 = stat.into();

                    // SAFETY: stat64 is repr(C, packed).
                    let stat = unsafe {
                        std::slice::from_raw_parts(
                            std::ptr::addr_of!(stat64).cast::<u8>(),
                            size_of_val(&stat64),
                        )
                    };

                    request.write_mem_all(stat, addr)?;
                } else if is32 {
                    let stat32: crate::compat::stat32 = stat.try_into()?;

                    // SAFETY: stat32 is repr(C).
                    let stat = unsafe {
                        std::slice::from_raw_parts(
                            std::ptr::addr_of!(stat32) as *const u8,
                            size_of_val(&stat32),
                        )
                    };

                    request.write_mem_all(stat, addr)?;
                } else {
                    // Identity function on non-mips64.
                    #[allow(clippy::useless_conversion)]
                    let stat: FileStat = stat.into();

                    // SAFETY: FileStat is repr(C).
                    let stat = unsafe {
                        std::slice::from_raw_parts(
                            std::ptr::addr_of!(stat) as *const u8,
                            size_of_val(&stat),
                        )
                    };

                    request.write_mem_all(stat, addr)?;
                }
            }
        }

        // Use the pseudo errno(3) EOWNERDEAD to initiate ghost mode.
        // We only do it here to ensure metadata of /dev/null was
        // written to sandbox process memory.
        if ghost {
            return Ok(ScmpNotifResp::new(0, 0, EOWNERDEAD, 0));
        }

        // stat(2) system call has been successfully emulated.
        Ok(request.return_syscall(0))
    })
}

fn handle_magic_stat(request: &UNotifyEventRequest, cmd: &XPath) -> Result<bool, Errno> {
    // Set to true if ghost mode is initiated.
    let mut ghost = false;

    // Acquire a write lock to the sandbox.
    let mut sandbox = request.get_mut_sandbox();

    // Execute magic command.
    if cmd.is_empty() || cmd.is_equal(b".el") || cmd.is_equal(b".sh") {
        // Call no-ops into sandbox for logging as necessary.
        sandbox.config("")?;
    } else if cmd.is_equal(b"panic") {
        // Rejects if locked or drop-only.
        sandbox.panic()?;
    } else if cmd.is_equal(b"ghost") {
        // Reset sandbox to ensure no run-away execs:
        // Reset rejects if drop-only for !ghost.
        // Reset doesn't change state of Crypt sandboxing.
        sandbox.reset(true)?;
        ghost = true;
    } else if let Some(cmd) = cmd.strip_prefix(b"load") {
        // We handle load specially here as it involves process access.
        // 1. Attempt to parse as FD, pidfd_getfd and load it.
        // 2. Attempt to parse as profile name if (1) fails.
        match parse_fd(cmd) {
            Ok(remote_fd) => {
                // parse_config() checks for the file name "/dev/syd/load", and
                // disables config file include feature depending on this check.
                let name = XPath::from_bytes(MAGIC_LOAD);
                let file = request.get_fd(remote_fd)?;

                // Ensure regular file before parsing.
                if !is_file(&file)? {
                    return Err(Errno::EBADFD);
                }

                // FIXME: Do not waste getrandom(2) cycles for the unused hashset.
                let file = BufReader::new(file);
                sandbox.parse_config(file, name, &mut SydHashSet::default() /*unused*/)?;

                // Fall through to emulate as /dev/null.
            }
            Err(Errno::EBADF) => {
                // Attempt to load as a profile.
                sandbox.parse_profile(cmd.as_bytes())?;

                // Fall through to emulate as /dev/null.
            }
            Err(errno) => return Err(errno),
        }
    } else {
        // Invalid UTF-8 is not permitted.
        // To include non-UTF-8, user must hex-encoded arguments.
        std::str::from_utf8(cmd.as_bytes())
            .or(Err(Errno::EINVAL))
            .and_then(|cmd| sandbox.config(cmd))?;
    }

    // Sandbox write lock released here.
    // Return true if ghost mode was initiated.
    Ok(ghost)
}

fn magic_stat(stat: &mut FileStat64, caps: Capability, opts: Options) {
    stat.st_ino = 0;
    stat.st_nlink = caps.nlink().into();
    stat.st_mode = magic_mode(caps, opts).into();
    stat.st_rdev = API_VERSION.dev();
    stat.st_atime = 505958400; // must match libsyd!
    stat.st_ctime = -2036448000; // ditto!
    stat.st_mtime = -842745600; // ditto!
}

fn magic_statx(statx: &mut FileStatx, caps: Capability, opts: Options) {
    statx.stx_ino = 0;
    statx.stx_nlink = caps.nlink();
    statx.stx_mode = magic_mode(caps, opts);
    statx.stx_rdev_major = API_VERSION.major().into();
    statx.stx_rdev_minor = API_VERSION.minor().into();
    statx.stx_atime = FileStatxTimestamp {
        tv_sec: 505958400, // must match libsyd!
        ..Default::default()
    };
    statx.stx_ctime = FileStatxTimestamp {
        tv_sec: -2036448000, // ditto!
        ..Default::default()
    };
    statx.stx_mtime = FileStatxTimestamp {
        tv_sec: -842745600, // ditto!
        ..Default::default()
    };
}

#[expect(clippy::cast_possible_truncation)]
fn magic_mode(caps: Capability, opts: Options) -> u16 {
    // Start with file type = character device
    let mut mode: u16 = libc::S_IFCHR as u16;

    // Special bits
    if opts.contains(Options::OPT_UNSHARE_MOUNT) {
        mode |= libc::S_ISVTX as u16;
    }
    if opts.contains(Options::OPT_UNSHARE_USER) {
        mode |= libc::S_ISUID as u16;
    }
    if opts.contains(Options::OPT_UNSHARE_NET) {
        mode |= libc::S_ISGID as u16;
    }

    // Permission bits for owner/group/other
    if caps.contains(Capability::CAP_READ) {
        mode |= libc::S_IRUSR as u16;
    }
    if caps.contains(Capability::CAP_WRITE) {
        mode |= libc::S_IWUSR as u16;
    }
    if caps.contains(Capability::CAP_EXEC) {
        mode |= libc::S_IXUSR as u16;
    }
    if caps.contains(Capability::CAP_STAT) {
        mode |= libc::S_IRGRP as u16;
    }
    if caps.contains(Capability::CAP_PROXY) {
        mode |= libc::S_IWGRP as u16;
    }
    if caps.contains(Capability::CAP_TPE) {
        mode |= libc::S_IXGRP as u16;
    }
    if caps.contains(Capability::CAP_LOCK) {
        mode |= libc::S_IROTH as u16;
    }
    if caps.contains(Capability::CAP_CRYPT) {
        mode |= libc::S_IWOTH as u16;
    }
    if caps.contains(Capability::CAP_FORCE) {
        mode |= libc::S_IXOTH as u16;
    }

    mode
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sandbox::{Capability, Options};

    #[test]
    fn test_magic_mode_empty_caps_1() {
        let mode = magic_mode(Capability::empty(), Options::empty());
        assert_eq!(mode, libc::S_IFCHR as u16);
    }

    #[test]
    fn test_magic_mode_cap_read_1() {
        let mode = magic_mode(Capability::CAP_READ, Options::empty());
        assert!(mode & libc::S_IRUSR as u16 != 0);
    }

    #[test]
    fn test_magic_mode_cap_write_1() {
        let mode = magic_mode(Capability::CAP_WRITE, Options::empty());
        assert!(mode & libc::S_IWUSR as u16 != 0);
    }

    #[test]
    fn test_magic_mode_cap_exec_1() {
        let mode = magic_mode(Capability::CAP_EXEC, Options::empty());
        assert!(mode & libc::S_IXUSR as u16 != 0);
    }

    #[test]
    fn test_magic_mode_cap_stat_1() {
        let mode = magic_mode(Capability::CAP_STAT, Options::empty());
        assert!(mode & libc::S_IRGRP as u16 != 0);
    }

    #[test]
    fn test_magic_mode_cap_proxy_1() {
        let mode = magic_mode(Capability::CAP_PROXY, Options::empty());
        assert!(mode & libc::S_IWGRP as u16 != 0);
    }

    #[test]
    fn test_magic_mode_cap_tpe_1() {
        let mode = magic_mode(Capability::CAP_TPE, Options::empty());
        assert!(mode & libc::S_IXGRP as u16 != 0);
    }

    #[test]
    fn test_magic_mode_cap_lock_1() {
        let mode = magic_mode(Capability::CAP_LOCK, Options::empty());
        assert!(mode & libc::S_IROTH as u16 != 0);
    }

    #[test]
    fn test_magic_mode_cap_crypt_1() {
        let mode = magic_mode(Capability::CAP_CRYPT, Options::empty());
        assert!(mode & libc::S_IWOTH as u16 != 0);
    }

    #[test]
    fn test_magic_mode_cap_force_1() {
        let mode = magic_mode(Capability::CAP_FORCE, Options::empty());
        assert!(mode & libc::S_IXOTH as u16 != 0);
    }

    #[test]
    fn test_magic_mode_opt_unshare_mount_1() {
        let mode = magic_mode(Capability::empty(), Options::OPT_UNSHARE_MOUNT);
        assert!(mode & libc::S_ISVTX as u16 != 0);
    }

    #[test]
    fn test_magic_mode_opt_unshare_user_1() {
        let mode = magic_mode(Capability::empty(), Options::OPT_UNSHARE_USER);
        assert!(mode & libc::S_ISUID as u16 != 0);
    }

    #[test]
    fn test_magic_mode_opt_unshare_net_1() {
        let mode = magic_mode(Capability::empty(), Options::OPT_UNSHARE_NET);
        assert!(mode & libc::S_ISGID as u16 != 0);
    }

    #[test]
    fn test_magic_mode_always_has_s_ifchr_1() {
        let caps = Capability::CAP_READ | Capability::CAP_WRITE | Capability::CAP_EXEC;
        let mode = magic_mode(caps, Options::OPT_UNSHARE_MOUNT);
        assert!(mode & libc::S_IFMT as u16 == libc::S_IFCHR as u16);
    }
}