syd 3.54.1

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
//
// Syd: rock-solid application kernel
// src/workers/not.rs: `syd_not' notifier thread
//
// Copyright (c) 2026 Ali Polatel <alip@chesswob.org>
//
// SPDX-License-Identifier: GPL-3.0

// SAFETY:
// 1. This module has (almost) been liberated from unsafe code.
//    SafeOwnedFd::from_raw_fd is used for crypt_fd which is unsafe.
//    Use deny rather than forbid so we can allow this case.
// 2. This module forbids arithmetic side effects, et al.
#![deny(unsafe_code)]
#![forbid(clippy::arithmetic_side_effects)]
#![forbid(clippy::cast_possible_truncation)]
#![forbid(clippy::cast_possible_wrap)]

use std::{
    os::fd::{AsRawFd, FromRawFd, RawFd},
    sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    },
    thread,
};

use concurrent_queue::{PopError, PushError};
use libseccomp::{ScmpAction, ScmpFilterContext};
use nix::{
    errno::Errno,
    sched::{unshare, CloneFlags},
    unistd::{gettid, Gid, Uid},
};

use crate::{
    alert,
    cache::SysNotif,
    compat::seccomp_notif_resp,
    config::*,
    confine::{
        confine_scmp_close_not, confine_scmp_fcntl, confine_scmp_ioctl_not, confine_scmp_kill,
        confine_scmp_madvise, confine_scmp_open_stat, confine_scmp_prctl, confine_scmp_setid,
        confine_scmp_tgkill, confine_scmp_tkill, confine_scmp_write_not, confine_scmp_wx_syd,
        secure_getenv, ExportMode, ScmpNotifReq, SydNotifReq, SydNotifResp, Sydcall, SIGCANCEL,
        SIGSETXID, SIGTIMER,
    },
    cookie::safe_kill,
    err::{err2no, scmp2no, SydJoinHandle, SydResult},
    error,
    fd::{closeexcept, SafeOwnedFd},
    fs::{block_signal, seccomp_notify_receive, seccomp_notify_respond, unblock_signal},
    id::SydId,
    info,
    landlock::Errata,
    landlock_policy::LandlockPolicy,
    sandbox::{Options, Sandbox},
    workers::WorkerCache,
};

#[derive(Clone)]
pub(crate) struct Notifier {
    seccomp_fd: RawFd,
    queue_wr_fd: RawFd,
    options: Options,
    transit_uids: Vec<(Uid, Uid)>,
    transit_gids: Vec<(Gid, Gid)>,
    should_exit: Arc<AtomicBool>,
    cache: Arc<WorkerCache>,
}

impl Notifier {
    pub(crate) fn new(
        seccomp_fd: RawFd,
        queue_wr_fd: RawFd,
        options: Options,
        transit_uids: &[(Uid, Uid)],
        transit_gids: &[(Gid, Gid)],
        should_exit: Arc<AtomicBool>,
        cache: Arc<WorkerCache>,
    ) -> Self {
        Self {
            options,
            seccomp_fd,
            queue_wr_fd,
            should_exit,
            cache,
            transit_uids: transit_uids.to_vec(),
            transit_gids: transit_gids.to_vec(),
        }
    }

    #[expect(clippy::cognitive_complexity)]
    pub(crate) fn try_spawn(self, sysreq_notif: SysNotif) -> Result<SydJoinHandle<()>, Errno> {
        thread::Builder::new()
            .name(SydId::get_name("syd_not").to_string())
            .stack_size(NOT_STACK_SIZE)
            .spawn(move || {
                // Use exit_group(2) here to bail, because this
                // unsharing is a critical safety feature.
                if let Err(errno) = unshare(CloneFlags::CLONE_FS | CloneFlags::CLONE_FILES | CloneFlags::CLONE_SYSVSEM) {
                    alert!("ctx": "boot", "op": "unshare_not_thread",
                        "msg": format!("failed to unshare(CLONE_FS|CLONE_FILES|CLONE_SYSVSEM): {errno}"),
                        "err": errno as i32);
                    std::process::exit(101);
                }

                // Close write end of the queue at exit to wake blocked emulators.
                // SAFETY: self.queue_wr_fd is a valid file descriptor.
                #[expect(unsafe_code)]
                let fd = unsafe { SafeOwnedFd::from_raw_fd(self.queue_wr_fd) };

                // Close seccomp fd at exit to ensure no blocked syscalls.
                // SAFETY: self.seccomp_fd is a valid file descriptor.
                #[expect(unsafe_code)]
                let seccomp_fd = unsafe { SafeOwnedFd::from_raw_fd(self.seccomp_fd) };

                // SAFETY: Notifier thread needs to inherit FDs.
                // We have to sort the set as the FDs are randomized.
                #[expect(clippy::cast_sign_loss)]
                let mut set = vec![
                    crate::log::LOG_FD.load(Ordering::Relaxed) as libc::c_uint,
                    fd.as_raw_fd() as libc::c_uint,
                    seccomp_fd.as_raw_fd() as libc::c_uint,
                ];
                set.sort_unstable();
                if let Err(errno) = closeexcept(&set) {
                    alert!("ctx": "boot", "op": "close_range_not_thread",
                        "msg": format!("failed to close range: {errno}"),
                        "err": errno as i32);
                    std::process::exit(101);
                }

                // Honour dry-run when exporting.
                let dry_run =
                    secure_getenv(ENV_SKIP_SCMP).is_some() || ExportMode::from_env().is_some();

                // Confine `syd_mon' thread.
                if !dry_run {
                    // We use exit_group(2) here to bail, because this
                    // confinement is a critical safety feature.
                    let ctx = match Self::prepare_confine(
                        self.seccomp_fd,
                        self.queue_wr_fd,
                        self.options,
                        &self.transit_uids,
                        &self.transit_gids,
                        false,
                    ) {
                        Ok(ctx) => ctx,
                        Err(error) => {
                            let errno = error.errno().unwrap_or(Errno::ENOSYS);
                            alert!("ctx": "boot", "op": "confine_not_thread",
                                "msg": format!("failed to confine: {error}"),
                                "err": errno as i32);
                            std::process::exit(101);
                        }
                    };

                    // Load seccomp(2) BPF into the kernel.
                    // We use exit_group(2) here to bail, because this
                    // confinement is a critical safety feature.
                    if let Err(error) = ctx.load() {
                        let errno = scmp2no(&error).unwrap_or(Errno::ENOSYS);
                        alert!("ctx": "boot", "op": "confine_int_thread",
                            "msg": format!("failed to confine: {error}"),
                            "err": errno as i32);
                        std::process::exit(101);
                    }
                    info!("ctx": "confine", "op": "confine_not_thread",
                        "msg": "notify thread confined");
                } else {
                    error!("ctx": "confine", "op": "confine_not_thread",
                        "msg": "notify thread is running unconfined in debug mode");
                }

                // Unblock SIGALRM and register tid so interrupter can signal us.
                let tid = gettid().as_raw();
                if let Err(errno) = unblock_signal(libc::SIGALRM) {
                    alert!("ctx": "notifier", "op": "unblock_sigalrm",
                        "msg": format!("failed to unblock SIGALRM: {errno}!"),
                        "err": errno as i32);
                    std::process::exit(101);
                }
                self.cache.sysint_map.not_tid.store(tid, Ordering::Release);

                // Enter main loop.
                let result = self.main(sysreq_notif);

                // Block SIGALRM and check result.
                if let Err(errno) = block_signal(libc::SIGALRM) {
                    alert!("ctx": "notifier", "op": "block_sigalrm",
                        "msg": format!("failed to block SIGALRM: {errno}!"),
                        "err": errno as i32);
                    std::process::exit(101);
                }

                match result {
                    Ok(()) => Ok(()),
                    Err(errno @ (Errno::EBADF | Errno::ENOTCONN)) => {
                        self.drain(Sandbox::ghost_once());
                        Err(errno.into())
                    }
                    Err(errno) => Err(errno.into()),
                }
            })
            .map_err(|err| err2no(&err))
    }

    fn main(&self, sysreq_notif: SysNotif) -> Result<(), Errno> {
        loop {
            if self.should_exit.load(Ordering::Acquire) {
                return Ok(());
            }

            let req = if let Some(req) = self.receive()? {
                req
            } else {
                continue;
            };

            self.queue(&sysreq_notif, req)?;
        }
    }

    fn drain(&self, is_ghost: bool) {
        while let Ok(req) = self.cache.sysreq_queue.pop() {
            self.discard_request(req, Errno::ENOSYS, is_ghost);
        }
    }

    fn discard_request(&self, req: SydNotifReq, errno: Errno, is_ghost: bool) {
        match req {
            SydNotifReq::Seccomp(req) => {
                self.deny_syscall(req.id, errno);
            }

            SydNotifReq::PtraceScmp { pid, info } => {
                // sigreturn(2) must be terminated, except for Ghost mode.
                // FIXME: This can be used to circumvent SROP mitigations.
                if req.is_sigreturn() && is_ghost {
                    let resp = SydNotifResp::Cont { pid, signal: None };
                    if self.cache.ptrace_resp.push(resp).is_ok() {
                        self.cache.interrupt_run();
                    } else {
                        let _ = safe_kill(pid, libc::SIGKILL);
                    }
                    return;
                }

                // Deny with given errno, fallback to terminate.
                let resp = SydNotifResp::Deny {
                    pid,
                    errno,
                    arch: info.arch,
                };

                if self.cache.ptrace_resp.push(resp).is_ok() {
                    self.cache.interrupt_run();
                } else {
                    let _ = safe_kill(pid, libc::SIGKILL);
                }
            }

            SydNotifReq::PtraceExit { pid, .. } => {
                // Continue process for Ghost mode.
                if is_ghost {
                    let resp = SydNotifResp::Cont { pid, signal: None };
                    if self.cache.ptrace_resp.push(resp).is_ok() {
                        self.cache.interrupt_run();
                        return;
                    }
                    // Fallback to terminate process.
                }

                // Terminate process.
                let _ = safe_kill(pid, libc::SIGKILL);
            }

            SydNotifReq::PtraceExec { pid } => {
                // Terminate process.
                let _ = safe_kill(pid, libc::SIGKILL);
            }
        }
    }

    fn queue(&self, sysreq_notif: &SysNotif, req: ScmpNotifReq) -> Result<(), Errno> {
        let queue = &self.cache.sysreq_queue;
        let ghost = Sandbox::ghost_once();

        loop {
            match sysreq_notif.push(SydNotifReq::Seccomp(req)) {
                Ok(()) => {
                    if queue.is_full() {
                        self.cache.notify_mon();
                    }
                    return self.cache.notify_emu(self.queue_wr_fd);
                }
                Err(PushError::Full(_)) => {
                    match queue.pop() {
                        Ok(req_old) => self.discard_request(req_old, Errno::EINTR, ghost),
                        Err(PopError::Empty) => {}
                        Err(PopError::Closed) => return Err(Errno::ENOTCONN),
                    }
                    self.cache.notify_mon();
                }
                Err(PushError::Closed(_)) => return Err(Errno::ENOTCONN),
            }
        }
    }

    fn receive(&self) -> Result<Option<ScmpNotifReq>, Errno> {
        // Receive and return request.
        // Break if file descriptor was closed.
        // Ignore rest of the errors as we cannot handle them,
        // e.g: EINTR|ENOENT: task is killed mid-way.
        match seccomp_notify_receive(self.seccomp_fd) {
            Ok(request) => Ok(Some(request)),
            Err(Errno::EBADF) => Err(Errno::EBADF),
            Err(_) => Ok(None),
        }
    }

    fn deny_syscall(&self, id: u64, errno: Errno) {
        let response = seccomp_notif_resp {
            id,
            val: 0,
            flags: 0,
            error: (errno as i32).checked_neg().unwrap_or(-libc::ENOSYS),
        };

        // EINTR is not retried because it may mean child is signaled.
        // ENOENT means child died mid-way.
        // Nothing else we can do on errors here.
        let _ = seccomp_notify_respond(self.seccomp_fd, std::ptr::addr_of!(response));
    }

    // Confine Notifier thread.
    pub(crate) fn prepare_confine(
        seccomp_fd: RawFd,
        queue_wr_fd: RawFd,
        options: Options,
        transit_uids: &[(Uid, Uid)],
        transit_gids: &[(Gid, Gid)],
        dry_run: bool,
    ) -> SydResult<ScmpFilterContext> {
        if !dry_run {
            // Set up a landlock(7) sandbox to disallow all access.
            let abi = crate::landlock::ABI::new_current();
            let errata = crate::landlock::Errata::query();
            let policy = LandlockPolicy {
                scoped_abs: true,
                scoped_sig: errata.contains(Errata::SCOPED_SIGNAL_SAME_TGID),
                ..Default::default()
            };
            let _ = policy.restrict_self(abi);
        }

        let restrict_cookie = !options.allow_unsafe_nocookie();

        // Create seccomp filter with default action.
        let mut ctx = ScmpFilterContext::new(ScmpAction::KillProcess)?;

        // Enforce the NO_NEW_PRIVS functionality before
        // loading the seccomp filter into the kernel.
        ctx.set_ctl_nnp(true)?;

        // Disable Speculative Store Bypass mitigations
        // with trace/allow_unsafe_exec_speculative:1
        ctx.set_ctl_ssb(options.allow_unsafe_exec_speculative())?;

        // DO NOT synchronize filter to all threads.
        // Other threads will self-confine.
        ctx.set_ctl_tsync(false)?;

        // We kill for bad system call and bad arch.
        ctx.set_act_badarch(ScmpAction::KillProcess)?;

        // Use a binary tree sorted by syscall number if possible.
        let _ = ctx.set_ctl_optimize(2);

        // Do NOT add supported architectures to the filter.
        // This ensures Syd can never run a non-native system call,
        // which we do not need at all.
        // seccomp_add_architectures(&mut ctx)?;

        // Deny rest of open and stat family with ENOSYS rather than KillProcess.
        confine_scmp_open_stat(&mut ctx, true /*openat2*/)?;

        // Allow safe seccomp ioctl(2) requests.
        confine_scmp_ioctl_not(&mut ctx, restrict_cookie, seccomp_fd)?;

        // Allow safe fcntl(2) utility calls.
        confine_scmp_fcntl(&mut ctx, NOT_FCNTL_OPS)?;

        // Allow safe prctl(2) operations.
        confine_scmp_prctl(&mut ctx, NOT_PRCTL_OPS)?;

        // Prevent executable memory.
        confine_scmp_wx_syd(&mut ctx)?;

        // Allow writes to log fd and queue only.
        confine_scmp_write_not(&mut ctx, queue_wr_fd, restrict_cookie)?;

        // Allow close for queue and seccomp fds only.
        confine_scmp_close_not(&mut ctx, &[queue_wr_fd, seccomp_fd], restrict_cookie)?;

        // Allow kill with syscall argument cookies.
        confine_scmp_kill(&mut ctx, &[libc::SIGKILL], restrict_cookie)?;

        // Signal allowlist for tkill(2) and tgkill(2):
        // 1. Allow 0 for existence checks.
        // 2. Allow libc internal signals for thread cancellation and timers.
        // 3. SIGRTMIN is used to wake main thread.
        // 4. SIGSETXID is only needed when SafeSetID is enabled.
        let safe_setid =
            options.intersects(Options::OPT_ALLOW_SAFE_SETUID | Options::OPT_ALLOW_SAFE_SETGID);
        if safe_setid {
            confine_scmp_tkill(&mut ctx, &[SIGCANCEL, SIGTIMER, SIGSETXID])?;
            confine_scmp_tgkill(
                &mut ctx,
                &[libc::SIGRTMIN(), SIGCANCEL, SIGTIMER, SIGSETXID],
            )?;
        } else {
            confine_scmp_tkill(&mut ctx, &[SIGCANCEL, SIGTIMER])?;
            confine_scmp_tgkill(&mut ctx, &[libc::SIGRTMIN(), SIGCANCEL, SIGTIMER])?;
        }

        // Allow safe madvise(2) advice.
        confine_scmp_madvise(&mut ctx)?;

        // Allow safe, futex and getid system calls.
        //
        // KCOV_SYSCALLS is empty in case `kcov` feature is disabled.
        for sysname in NOT_SYSCALLS
            .iter()
            .chain(ALLOC_SYSCALLS)
            .chain(FUTEX_SYSCALLS)
            .chain(GETID_SYSCALLS)
            .chain(KCOV_SYSCALLS)
            .chain(VDSO_SYSCALLS)
        {
            match Sydcall::from_name(sysname) {
                Ok(syscall) => {
                    ctx.add_rule(ScmpAction::Allow, syscall)?;
                }
                Err(_) => {
                    info!("ctx": "confine", "op": "allow_not_syscall",
                        "msg": format!("invalid or unsupported syscall {sysname}"));
                }
            }
        }

        // Allow UID/GID changing system calls as necessary.
        let safe_setuid = options.allow_safe_setuid();
        let safe_setgid = options.allow_safe_setgid();
        if safe_setuid || safe_setgid {
            confine_scmp_setid(
                "not",
                &mut ctx,
                safe_setuid,
                safe_setgid,
                transit_uids,
                transit_gids,
            )?;
        }

        Ok(ctx)
    }
}