syd 3.58.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
//
// Syd: rock-solid application kernel
// src/kernel/fanotify.rs: fanotify(7) handlers
//
// Copyright (c) 2023, 2024, 2025, 2026 Ali Polatel <alip@chesswob.org>
//
// SPDX-License-Identifier: GPL-3.0

// SAFETY: This module has been liberated from unsafe code!
#![forbid(unsafe_code)]

use std::os::fd::AsRawFd;

use libseccomp::ScmpNotifResp;
use nix::errno::Errno;

use crate::{
    caps::{util::capable, Capabilities},
    compat::{readlinkat, EventFFlags, Fanotify, FsType, InitFlags, MarkFlags, MaskFlags},
    confine::{scmp_arch_bits, scmp_arch_is_big_endian, ScmpNotifReq, SydSys::SysFanotifyMark},
    cookie::{safe_exit_group, safe_fanotify_init},
    fd::{to_fd, PROC_FILE},
    kernel::syscall_path_handler,
    log_enabled,
    lookup::{file_type, FsFlags},
    path::{XPath, XPathBuf},
    req::{SysArg, SysFlags, UNotifyEventRequest},
    sandbox::{Action, Capability, SandboxGuard},
    syslog::LogLevel,
    warn, xfmt,
};

const MARK_CMD: MarkFlags = MarkFlags::from_bits_retain(
    MarkFlags::FAN_MARK_ADD.bits()
        | MarkFlags::FAN_MARK_REMOVE.bits()
        | MarkFlags::FAN_MARK_FLUSH.bits(),
);

const MARK_TYPE: MarkFlags = MarkFlags::from_bits_retain(
    // FAN_MARK_INODE == 0
    MarkFlags::FAN_MARK_FILESYSTEM.bits()
        | MarkFlags::FAN_MARK_MNTNS.bits()
        | MarkFlags::FAN_MARK_MOUNT.bits(),
);
const FAN_MARK_INODE: MarkFlags = MarkFlags::from_bits_retain(0);

const FANOTIFY_ADMIN_INIT_FLAGS: InitFlags = InitFlags::FAN_CLASS_CONTENT
    .union(InitFlags::FAN_CLASS_PRE_CONTENT)
    .union(InitFlags::FAN_REPORT_TID)
    .union(InitFlags::FAN_REPORT_PIDFD)
    .union(InitFlags::FAN_REPORT_FD_ERROR)
    .union(InitFlags::FAN_UNLIMITED_QUEUE)
    .union(InitFlags::FAN_UNLIMITED_MARKS);

const FANOTIFY_FID_BITS: InitFlags = InitFlags::FAN_REPORT_DIR_FID
    .union(InitFlags::FAN_REPORT_NAME)
    .union(InitFlags::FAN_REPORT_FID)
    .union(InitFlags::FAN_REPORT_TARGET_FID);

const FANOTIFY_CLASS_BITS: InitFlags =
    InitFlags::FAN_CLASS_CONTENT.union(InitFlags::FAN_CLASS_PRE_CONTENT);

// Linux rejects FAN_ENABLE_AUDIT with EINVAL when !CONFIG_AUDITSYSCALL.
const FANOTIFY_INIT_FLAGS: InitFlags = InitFlags::all().difference(InitFlags::FAN_ENABLE_AUDIT);

pub(crate) fn sys_fanotify_init(request: UNotifyEventRequest) -> ScmpNotifResp {
    syscall_handler!(request, |request: UNotifyEventRequest| {
        let req = request.scmpreq;

        // Linux kernel truncates upper bits.
        #[expect(clippy::cast_possible_truncation)]
        let flags = InitFlags::from_bits_retain(req.data.args[0] as libc::c_uint);
        #[expect(clippy::cast_possible_truncation)]
        let event_f_flags = EventFFlags::from_bits_retain(req.data.args[1] as libc::c_uint);

        let fid_mode = flags & FANOTIFY_FID_BITS;
        let class = flags & FANOTIFY_CLASS_BITS;

        // Linux requires CAP_SYS_ADMIN unless group only reports file
        // handles or mount ids.
        if (flags.intersects(FANOTIFY_ADMIN_INIT_FLAGS)
            || !flags.intersects(FANOTIFY_FID_BITS | InitFlags::FAN_REPORT_MNT))
            && !capable(Capabilities::CAP_SYS_ADMIN)
        {
            return Err(Errno::EPERM);
        }

        // Reject unknown init flags.
        if !flags.difference(FANOTIFY_INIT_FLAGS).is_empty() {
            return Err(Errno::EINVAL);
        }

        // Linux prevents mixing mount events with inode events.
        if flags.contains(InitFlags::FAN_REPORT_MNT) {
            // class != FAN_CLASS_NOTIF
            if !class.is_empty() {
                return Err(Errno::EINVAL);
            }
            if flags.intersects(FANOTIFY_FID_BITS | InitFlags::FAN_REPORT_FD_ERROR) {
                return Err(Errno::EINVAL);
            }
        }

        // Linux rejects unknown event_f_flags bits.
        if !event_f_flags.difference(EventFFlags::all()).is_empty() {
            return Err(Errno::EINVAL);
        }

        // Linux rejects invalid access mode.
        if event_f_flags & EventFFlags::O_ACCMODE == EventFFlags::O_ACCMODE {
            return Err(Errno::EINVAL);
        }

        // Linux allows file id reporting only for notification class.
        if !fid_mode.is_empty() && !class.is_empty() {
            return Err(Errno::EINVAL);
        }

        // Child name is reported with parent fid, so name requires dir fid.
        if fid_mode.contains(InitFlags::FAN_REPORT_NAME)
            && !fid_mode.contains(InitFlags::FAN_REPORT_DIR_FID)
        {
            return Err(Errno::EINVAL);
        }

        // FAN_REPORT_TARGET_FID requires FAN_REPORT_NAME|FAN_REPORT_FID.
        if fid_mode.contains(InitFlags::FAN_REPORT_TARGET_FID)
            && !(fid_mode.contains(InitFlags::FAN_REPORT_NAME)
                && fid_mode.contains(InitFlags::FAN_REPORT_FID))
        {
            return Err(Errno::EINVAL);
        }

        // Linux rejects requesting both content classes at once.
        if class == FANOTIFY_CLASS_BITS {
            return Err(Errno::EINVAL);
        }

        handle_fanotify_init(&request, flags, event_f_flags)
    })
}

#[expect(clippy::arithmetic_side_effects)]
pub(crate) fn sys_fanotify_mark(request: UNotifyEventRequest) -> ScmpNotifResp {
    let req = request.scmpreq;

    // Linux kernel truncates upper bits.
    #[expect(clippy::cast_possible_truncation)]
    let flags = req.data.args[1] as libc::c_uint;

    // Reject invalid flags.
    let flags = match MarkFlags::from_bits(flags) {
        Some(flags) => flags,
        None => return request.fail_syscall(Errno::EINVAL),
    };

    // Reject invalid mark types.
    let mark_type = flags & MARK_TYPE;
    if !matches!(
        mark_type,
        FAN_MARK_INODE
            | MarkFlags::FAN_MARK_MOUNT
            | MarkFlags::FAN_MARK_FILESYSTEM
            | MarkFlags::FAN_MARK_MNTNS
    ) {
        return request.fail_syscall(Errno::EINVAL);
    }

    // Linux rejects the combination FAN_MARK_IGNORE|FAN_MARK_IGNORED_MASK.
    if flags.contains(MarkFlags::FAN_MARK_IGNORE | MarkFlags::FAN_MARK_IGNORED_MASK) {
        return request.fail_syscall(Errno::EINVAL);
    }

    // Mark command must be exactly one of ADD, REMOVE, or FLUSH.
    let mark_cmd = flags & MARK_CMD;
    if !matches!(
        mark_cmd,
        MarkFlags::FAN_MARK_ADD | MarkFlags::FAN_MARK_REMOVE | MarkFlags::FAN_MARK_FLUSH
    ) {
        return request.fail_syscall(Errno::EINVAL);
    }

    // Reject undefined/invalid masks.
    let (mask, narg) = match parse_mark_mask(req) {
        Ok(mask) => mask,
        Err(errno) => return request.fail_syscall(errno),
    };

    // Commands ADD and REMOVE require a non-empty mask.
    if mask.is_empty()
        && matches!(
            mark_cmd,
            MarkFlags::FAN_MARK_ADD | MarkFlags::FAN_MARK_REMOVE
        )
    {
        return request.fail_syscall(Errno::EINVAL);
    }

    // Command FLUSH rejects extra flags beyond mark type and FLUSH.
    if mark_cmd == MarkFlags::FAN_MARK_FLUSH
        && !flags
            .difference(MARK_TYPE | MarkFlags::FAN_MARK_FLUSH)
            .is_empty()
    {
        return request.fail_syscall(Errno::EINVAL);
    }

    // Validate FANotify FD.
    let notify_fd = match to_fd(req.data.args[0]) {
        Ok(fd) => fd,
        Err(errno) => return request.fail_syscall(errno),
    };

    // Get FANotify FD.
    let notify_fd = match request.get_fd(notify_fd).map(Fanotify::from) {
        Ok(fd) => fd,
        Err(errno) => return request.fail_syscall(errno),
    };

    // Linux rejects non-fanotify fds with EINVAL before path lookup.
    match FsType::get(&notify_fd) {
        Ok(fst) if fst.is_anon_inode() => {
            let pfd = match XPathBuf::from_self_fd(notify_fd.as_raw_fd()) {
                Ok(pfd) => pfd,
                Err(errno) => return request.fail_syscall(errno),
            };
            match readlinkat(PROC_FILE(), &pfd) {
                Ok(target) if target.is_equal(b"anon_inode:[fanotify]") => {}
                _ => return request.fail_syscall(Errno::EINVAL),
            }
        }
        Ok(_) => return request.fail_syscall(Errno::EINVAL),
        Err(errno) => return request.fail_syscall(errno),
    }

    // Validate mark type.
    if let Err(errno) = check_mark_type(flags, mask, mark_type) {
        return request.fail_syscall(errno);
    }

    // fanotify(7) requires read access to file or directory.
    let mut fsflags = FsFlags::MUST_PATH;
    if flags.contains(MarkFlags::FAN_MARK_DONT_FOLLOW) {
        fsflags |= FsFlags::NO_FOLLOW_LAST;
    }

    let pidx = narg + 2;

    // Linux accepts NULL pathname with AT_FDCWD.
    // Treat it like AT_EMPTY_PATH.
    let argv = &[SysArg {
        dirfd: Some(narg + 1),
        path: Some(pidx),
        flags: SysFlags::EMPTY_PATH | SysFlags::MAYBE_NULL | SysFlags::PASS_DELETE,
        fsflags,
    }];

    syscall_path_handler(
        request,
        SysFanotifyMark,
        argv,
        |path_args, request, sandbox| {
            let restrict_notify_bdev = !sandbox.options.allow_unsafe_notify_bdev();
            let restrict_notify_cdev = !sandbox.options.allow_unsafe_notify_cdev();
            drop(sandbox); // release read lock.

            // SysArg has one element.
            #[expect(clippy::disallowed_methods)]
            let fd = path_args.0.as_ref().unwrap().path.dir();

            let mut mask = mask;
            if restrict_notify_bdev || restrict_notify_cdev {
                // Strip IN_{ACCESS,MODIFY} if we're marking a
                // sidechannel device. Strip IN_DONT_FOLLOW which has
                // already been handled during canonicalization.
                let filetype = file_type(fd, None, false)?;
                if (restrict_notify_bdev && filetype.is_block_device())
                    || (restrict_notify_cdev && filetype.is_char_device())
                {
                    mask.remove(MaskFlags::FAN_ACCESS);
                    mask.remove(MaskFlags::FAN_ACCESS_PERM);
                    mask.remove(MaskFlags::FAN_MODIFY);
                }
            }
            let mut flags = flags;
            flags.remove(MarkFlags::FAN_MARK_DONT_FOLLOW);

            // We open a FD to path and then use proc(5) path
            // $PROC_FILE/thread-self/fd/$fd in address' path argument
            // to avoid symlink TOCTOU.
            let pfd = XPathBuf::from_self_fd(fd.as_raw_fd())?;

            // Call fanotify_mark(2) through type-safe interface.
            notify_fd
                .mark(flags, mask, PROC_FILE(), Some(&pfd))
                .map(|_| request.return_syscall(0))
        },
    )
}

fn handle_fanotify_init(
    request: &UNotifyEventRequest,
    mut flags: InitFlags,
    event_f_flags: EventFFlags,
) -> Result<ScmpNotifResp, Errno> {
    let sandbox = request.get_sandbox();
    let force_cloexec = sandbox.flags.force_cloexec();
    let force_rand_fd = sandbox.flags.force_rand_fd();
    sandbox_fanotify_init(request, &sandbox)?;
    drop(sandbox); // release the read lock.

    let cloexec = force_cloexec || flags.contains(InitFlags::FAN_CLOEXEC);
    flags.insert(InitFlags::FAN_CLOEXEC);

    let fd = safe_fanotify_init(flags, event_f_flags)?;

    request.send_fd(fd, cloexec, force_rand_fd)
}

#[expect(clippy::cognitive_complexity)]
fn sandbox_fanotify_init(
    request: &UNotifyEventRequest,
    sandbox: &SandboxGuard<'_>,
) -> Result<(), Errno> {
    let caps = Capability::CAP_CREATE;
    if sandbox.getcaps(caps).is_empty() {
        // Sandboxing is off.
        return Ok(());
    }

    let name = XPath::from_bytes(b"!fanotify");
    let action = sandbox.check_name(caps, name);

    if action.is_logging() && log_enabled!(LogLevel::Warn) {
        if sandbox.log_scmp() {
            warn!("ctx": "access", "cap": caps, "act": action,
                "sys": "fanotify_init", "path": &name,
                "tip": xfmt!("configure `allow/{caps}+{name}'"),
                "req": request);
        } else {
            warn!("ctx": "access", "cap": caps, "act": action,
                "sys": "fanotify_init", "path": &name,
                "tip": xfmt!("configure `allow/{caps}+{name}'"),
                "pid": request.scmpreq.pid);
        }
    }

    match action {
        Action::Allow | Action::Warn => Ok(()),
        Action::Deny | Action::Filter => Err(Errno::EPERM),
        Action::Panic => panic!(),
        Action::Exit => safe_exit_group(Errno::EPERM as i32),
        action => {
            // Stop|Kill
            let _ = request.kill(action);
            Err(Errno::EPERM)
        }
    }
}

fn check_mark_type(flags: MarkFlags, mask: MaskFlags, mark_type: MarkFlags) -> Result<(), Errno> {
    // Linux requires CAP_SYS_ADMIN to mark a mount, filesystem, or mntns.
    if mark_type != FAN_MARK_INODE && !capable(Capabilities::CAP_SYS_ADMIN) {
        return Err(Errno::EPERM);
    }

    // Linux allows FAN_FS_ERROR only on a filesystem mark.
    if mask.contains(MaskFlags::FAN_FS_ERROR) && mark_type != MarkFlags::FAN_MARK_FILESYSTEM {
        return Err(Errno::EINVAL);
    }

    // Linux allows FAN_MARK_EVICTABLE only on inode marks.
    if flags.contains(MarkFlags::FAN_MARK_EVICTABLE) && mark_type != FAN_MARK_INODE {
        return Err(Errno::EINVAL);
    }

    // Linux does not generate pre-content events for directories.
    if mask.contains(MaskFlags::FAN_PRE_ACCESS) && mask.contains(MaskFlags::FAN_ONDIR) {
        return Err(Errno::EINVAL);
    }

    Ok(())
}

// Parse fanotify_mark(2) event mask and pathname argument index.
fn parse_mark_mask(req: ScmpNotifReq) -> Result<(MaskFlags, usize), Errno> {
    let is32 = scmp_arch_bits(req.data.arch) == 32;
    let (mask, narg) = if is32 {
        let (lo, hi) = if scmp_arch_is_big_endian(req.data.arch) {
            (req.data.args[3], req.data.args[2])
        } else {
            (req.data.args[2], req.data.args[3])
        };

        // Linux rejects upper 32-bits in mask.
        if hi != 0 {
            return Err(Errno::EINVAL);
        }

        (lo, 3)
    } else {
        (req.data.args[2], 2)
    };

    MaskFlags::from_bits(mask)
        .map(|mask| (mask, narg))
        .ok_or(Errno::EINVAL)
}