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

use std::{
    fmt,
    io::Seek,
    os::fd::{AsRawFd, RawFd},
};

use libc::c_long;
use libseccomp::ScmpArch;
use nix::{
    errno::Errno,
    fcntl::OFlag,
    sys::signal::{kill, Signal},
    unistd::Pid,
};
use serde::{Serialize, Serializer};

use crate::{
    compat::ResolveFlag,
    config::PAGE_SIZE,
    confine::scmp_arch_is_old_mmap,
    cookie::{safe_pidfd_getfd, safe_pidfd_open},
    elf::ExecutableFile,
    err::err2no,
    error,
    fd::{fd_status_flags, PIDFD_THREAD, PROC_FILE},
    kernel::{ptrace::SYS_MMAP2, sandbox_path},
    lookup::{safe_open_msym, CanonicalPath},
    path::XPathBuf,
    proc::{proc_executables, proc_mem, proc_statm},
    ptrace::{ptrace_get_error, ptrace_syscall_info},
    req::RemoteProcess,
    sandbox::{Action, Capability, IntegrityError, SandboxGuard},
    warn,
};

const PROT_EXEC: u64 = libc::PROT_EXEC as u64;
const MAP_ANONYMOUS: u64 = libc::MAP_ANONYMOUS as u64;
const MAP_SHARED: u64 = libc::MAP_SHARED as u64;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum MmapSyscall {
    Mmap,
    Mmap2,
}

impl MmapSyscall {
    pub(crate) const fn name(self) -> &'static str {
        match self {
            Self::Mmap => "mmap",
            Self::Mmap2 => "mmap2",
        }
    }

    pub(crate) fn from_scno(scno: c_long) -> Self {
        if scno == *SYS_MMAP2 {
            Self::Mmap2
        } else {
            Self::Mmap
        }
    }
}

impl fmt::Display for MmapSyscall {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name())
    }
}

impl Serialize for MmapSyscall {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.name())
    }
}

// Note, sysenter_mmap is a ptrace(2) hook, not a seccomp hook!
// The seccomp hooks are only used with trace/allow_unsafe_ptrace:1.
pub(crate) fn sysenter_mmap(
    pid: Pid,
    sandbox: &SandboxGuard,
    syscall: MmapSyscall,
    args: &[u64; 6],
) -> Result<bool, Errno> {
    handle_mmap(pid, sandbox, syscall, args)
}

pub(crate) fn sysexit_mmap(
    pid: Pid,
    sandbox: &SandboxGuard,
    info: ptrace_syscall_info,
    scno: c_long,
    args: &[u64; 6],
) -> Result<(), Errno> {
    // Check for successful mmap exit.
    match ptrace_get_error(pid, info.arch) {
        Ok(None) => {
            // Successful mmap call, validate file descriptor.
        }
        Ok(Some(_)) => {
            // Unsuccessful mmap call, continue process.
            return Ok(());
        }
        Err(Errno::ESRCH) => return Err(Errno::ESRCH),
        Err(errno) => {
            // Failed to get return value, terminate the process.
            error!("ctx": "mmap", "op": "read_return",
                "msg": format!("failed to read mmap return: {errno}"),
                "err": errno as i32, "pid": pid.as_raw(),
                "tip": "check with SYD_LOG=debug and/or submit a bug report");
            let _ = kill(pid, Some(Signal::SIGKILL));
            return Err(Errno::ESRCH);
        }
    };

    let syscall = MmapSyscall::from_scno(scno);
    if sandbox.enabled(Capability::CAP_EXEC) {
        check_exec(pid, sandbox, syscall)?;
    }

    // Recheck for sandbox access.
    check_mmap(pid, sandbox, syscall, args)?;

    // Continue process.
    Ok(())
}

fn check_mmap(
    pid: Pid,
    sandbox: &SandboxGuard,
    syscall: MmapSyscall,
    args: &[u64; 6],
) -> Result<(), Errno> {
    // Recheck for sandbox access.
    if handle_mmap(pid, sandbox, syscall, args).is_err() {
        let _ = kill(pid, Some(Signal::SIGKILL));
        return Err(Errno::ESRCH);
    }

    Ok(())
}

#[expect(clippy::cognitive_complexity)]
fn check_exec(pid: Pid, sandbox: &SandboxGuard, syscall: MmapSyscall) -> Result<(), Errno> {
    // Validate executables in proc_pid_maps(5) against TOCTOU.
    let bins = match proc_executables(pid) {
        Ok(bins) => bins,
        Err(errno) => {
            // Failed to read executables, assume TOCTTOU: terminate the process.
            error!("ctx": "mmap", "op": "read_proc_maps", "sys": syscall,
                "msg": format!("failed to read proc maps: {errno}"),
                "err": errno as i32, "pid": pid.as_raw(),
                "tip": "check with SYD_LOG=debug and/or submit a bug report");
            let _ = kill(pid, Some(Signal::SIGKILL));
            return Err(Errno::ESRCH);
        }
    };

    for exec in bins {
        let path = &exec.path;
        let action = sandbox.check_path(Capability::CAP_EXEC, path);
        if action.is_allowing() {
            continue;
        }

        // Denied executable appeared in proc_pid_maps(5).
        // Successful TOCTTOU attempt: terminate the process.
        error!("ctx": "mmap", "op": "map_mismatch", "sys": syscall,
            "msg": format!("map mismatch detected for executable `{path}': assume TOCTTOU!"),
            "pid": pid.as_raw(), "path": &path,
            "inode": exec.inode,
            "dev_major": exec.dev_major,
            "dev_minor": exec.dev_minor);
        let _ = kill(pid, Some(Signal::SIGKILL));
        return Err(Errno::ESRCH);
    }

    Ok(())
}

#[expect(clippy::cognitive_complexity)]
fn handle_mmap(
    pid: Pid,
    sandbox: &SandboxGuard,
    syscall: MmapSyscall,
    args: &[u64; 6],
) -> Result<bool, Errno> {
    let size = args[1];
    let caps = sandbox.getcaps(Capability::CAP_MMAP);
    let exec = caps.contains(Capability::CAP_EXEC);
    let force = caps.contains(Capability::CAP_FORCE);
    let tpe = caps.contains(Capability::CAP_TPE);
    let mem = caps.contains(Capability::CAP_MEM);
    let mem_max = sandbox.mem_max;
    let mem_vm_max = sandbox.mem_vm_max;
    let mem_act = sandbox.default_action(Capability::CAP_MEM);
    let restrict_exec_memory = !sandbox.options.allow_unsafe_exec_memory();
    let restrict_exec_stack = !sandbox.flags.allow_unsafe_exec_stack();
    let restrict_append_only = sandbox.has_append() || sandbox.enabled(Capability::CAP_CRYPT);

    if !exec
        && !force
        && !tpe
        && !restrict_exec_memory
        && !restrict_exec_stack
        && !restrict_append_only
        && (!mem || (mem_max == 0 && mem_vm_max == 0))
    {
        // Continue system call.
        return Ok(false);
    }

    // W^X checks for old_mmap architectures.
    if restrict_exec_memory {
        const PROT_WRITE: u64 = libc::PROT_WRITE as u64;
        const WRITE_EXEC: u64 = PROT_WRITE | PROT_EXEC;
        if args[2] & WRITE_EXEC == WRITE_EXEC {
            return Err(Errno::EACCES);
        }
        if args[2] & PROT_EXEC != 0 && args[3] & MAP_ANONYMOUS != 0 {
            return Err(Errno::EACCES);
        }
        if args[2] & PROT_EXEC != 0 && args[3] & MAP_SHARED != 0 {
            return Err(Errno::EACCES);
        }
    }

    let check_exec = (exec || force || tpe || restrict_exec_memory || restrict_exec_stack)
        && args[2] & PROT_EXEC != 0
        && args[3] & MAP_ANONYMOUS == 0;
    let check_append_only =
        restrict_append_only && args[3] & MAP_SHARED != 0 && args[3] & MAP_ANONYMOUS == 0;

    // Get the file descriptor before access check.
    let fd = if check_exec || check_append_only {
        #[expect(clippy::cast_possible_truncation)]
        let remote_fd = args[4] as RawFd;
        if remote_fd < 0 {
            return Err(Errno::EBADF);
        }

        let pid_fd = safe_pidfd_open(pid, PIDFD_THREAD)?;
        match safe_pidfd_getfd(pid_fd, remote_fd) {
            Ok(fd) => Some(fd),
            Err(_) => return Err(Errno::EBADF),
        }
    } else {
        None
    };

    #[expect(clippy::disallowed_methods)]
    let oflags = if check_append_only || (check_exec && restrict_exec_memory) {
        fd_status_flags(fd.as_ref().unwrap()).ok()
    } else {
        None
    };

    if check_append_only {
        // Prevent shared mappings on writable append-only fds.
        let deny = oflags
            .map(|fl| {
                fl.contains(OFlag::O_APPEND)
                    && (fl.contains(OFlag::O_RDWR) || fl.contains(OFlag::O_WRONLY))
            })
            .unwrap_or(true);

        if deny {
            return Err(Errno::EPERM);
        }
    }

    if check_exec {
        // Step 1: Check if file is open for write,
        // but set as PROT_READ|PROT_EXEC which breaks W^X!
        // We do not need to check for PROT_WRITE here as
        // this is already enforced at kernel-level when
        // trace/allow_unsafe_exec_memory:1 is not set at startup.
        if restrict_exec_memory {
            let deny = oflags
                .map(|fl| fl.contains(OFlag::O_RDWR) || fl.contains(OFlag::O_WRONLY))
                .unwrap_or(true);

            if deny {
                return Err(Errno::EACCES);
            }
        }

        #[expect(clippy::disallowed_methods)]
        let mut path = CanonicalPath::new_fd(fd.unwrap().into(), pid)?;

        // Step 2: Check for Exec sandboxing.
        if exec {
            sandbox_path(
                None,
                sandbox,
                pid,
                path.abs(),
                Capability::CAP_EXEC,
                syscall.name(),
            )?;
        }

        // Step 3: Check for TPE sandboxing.
        if tpe {
            let (action, msg) = sandbox.check_tpe(path.dir(), path.abs());
            if !matches!(action, Action::Allow | Action::Filter) {
                let msg = msg.as_deref().unwrap_or("?");
                error!("ctx": "trusted_path_execution",
                    "msg": format!("library load from untrusted path blocked: {msg}"),
                    "sys": syscall, "path": &path,
                    "pid": pid.as_raw(),
                    "tip": "move the library to a safe location or use `sandbox/tpe:off'");
            }
            match action {
                Action::Allow | Action::Warn => {}
                Action::Panic | Action::Deny | Action::Filter => return Err(Errno::EACCES),
                //Do NOT panic the main thread!
                //Action::Panic => panic!(),
                Action::Exit => std::process::exit(libc::EACCES),
                Action::Stop => {
                    let _ = kill(pid, Some(Signal::SIGSTOP));
                    return Err(Errno::EACCES);
                }
                Action::Abort => {
                    let _ = kill(pid, Some(Signal::SIGABRT));
                    return Err(Errno::EACCES);
                }
                Action::Kill => {
                    let _ = kill(pid, Some(Signal::SIGKILL));
                    return Err(Errno::EACCES);
                }
            }
        }

        if force || restrict_exec_stack {
            // The following checks require the contents of the file.
            // Reopen the file via `/proc/thread-self/fd` to avoid sharing the file offset.
            // `path` is a remote-fd transfer which asserts `path.dir` is Some.
            #[expect(clippy::disallowed_methods)]
            let fd = path.dir.take().unwrap();

            let mut fd = XPathBuf::from_self_fd(fd.as_raw_fd()).and_then(|pfd| {
                safe_open_msym(
                    PROC_FILE(),
                    &pfd,
                    OFlag::O_RDONLY | OFlag::O_NOCTTY,
                    ResolveFlag::empty(),
                )
            })?;

            if restrict_exec_stack {
                // Step 4: Check for non-executable stack.
                // An execstack library that is dlopened into an executable
                // that is otherwise mapped no-execstack can change the
                // stack permissions to executable! This has been
                // (ab)used in at least one CVE:
                // https://www.qualys.com/2023/07/19/cve-2023-38408/rce-openssh-forwarded-ssh-agent.txt
                let exe = ExecutableFile::parse(&mut fd, true).or(Err(Errno::EACCES))?;
                if matches!(exe, ExecutableFile::Elf { xs: true, .. }) {
                    error!("ctx": "check_lib",
                        "msg": "library load with executable stack blocked",
                        "sys": syscall, "path": path.abs(),
                        "tip": "configure `trace/allow_unsafe_exec_stack:1'",
                        "lib": format!("{exe}"),
                        "pid": pid.as_raw());
                    return Err(Errno::EACCES);
                }
            }

            if force {
                // Step 5: Check for Force sandboxing.
                if restrict_exec_stack {
                    fd.rewind().map_err(|err| err2no(&err))?;
                }
                let result = sandbox.check_force2(fd, path.abs());

                let deny = match result {
                    Ok(action) => {
                        if !matches!(action, Action::Allow | Action::Filter) {
                            warn!("ctx": "verify_lib", "act": action,
                                "sys": syscall, "path": path.abs(),
                                "tip": format!("configure `force+{}:<checksum>'", path.abs()),
                                "pid": pid.as_raw());
                        }
                        match action {
                            Action::Allow | Action::Warn => false,
                            Action::Panic | Action::Deny | Action::Filter => true,
                            //Do NOT panic the main thread!
                            //Action::Panic => panic!(),
                            Action::Exit => std::process::exit(libc::EACCES),
                            Action::Stop => {
                                let _ = kill(pid, Some(Signal::SIGSTOP));
                                true
                            }
                            Action::Abort => {
                                let _ = kill(pid, Some(Signal::SIGABRT));
                                true
                            }
                            Action::Kill => {
                                let _ = kill(pid, Some(Signal::SIGKILL));
                                true
                            }
                        }
                    }
                    Err(IntegrityError::Sys(errno)) => {
                        error!("ctx": "verify_lib",
                            "msg": format!("system error during library checksum calculation: {errno}"),
                            "sys": syscall, "path": path.abs(),
                            "tip": format!("configure `force+{}:<checksum>'", path.abs()),
                            "pid": pid.as_raw());
                        true
                    }
                    Err(IntegrityError::Hash {
                        action,
                        expected,
                        found,
                    }) => {
                        if action != Action::Filter {
                            error!("ctx": "verify_lib", "act": action,
                                "msg": format!("library checksum mismatch: {found} is not {expected}"),
                                "sys": syscall, "path": path.abs(),
                                "tip": format!("configure `force+{}:<checksum>'", path.abs()),
                                "pid": pid.as_raw());
                        }
                        match action {
                            // Allow cannot happen.
                            Action::Allow => unreachable!(),
                            Action::Warn => false,
                            Action::Panic | Action::Deny | Action::Filter => true,
                            //Do NOT panic the main thread!
                            //Action::Panic => panic!(),
                            Action::Exit => std::process::exit(libc::EACCES),
                            Action::Stop => {
                                let _ = kill(pid, Some(Signal::SIGSTOP));
                                true
                            }
                            Action::Abort => {
                                let _ = kill(pid, Some(Signal::SIGABRT));
                                true
                            }
                            Action::Kill => {
                                let _ = kill(pid, Some(Signal::SIGKILL));
                                true
                            }
                        }
                    }
                };

                if deny {
                    return Err(Errno::EACCES);
                }
            }
        }
    }

    if !mem || (mem_max == 0 && mem_vm_max == 0) {
        // (a) Exec and Memory sandboxing are both disabled.
        // (b) Exec granted access, Memory sandboxing is disabled.
        // Stop at syscall exit as necessary.
        return Ok(check_exec || check_append_only);
    }

    // Check VmSize
    if mem_vm_max > 0 {
        let mem_vm_cur = match proc_statm(pid) {
            Ok(statm) => statm.size.saturating_mul(*PAGE_SIZE),
            Err(errno) => return Err(errno),
        };
        if mem_vm_cur.saturating_add(size) >= mem_vm_max {
            if mem_act != Action::Filter {
                warn!("ctx": "access", "cap": Capability::CAP_MEM, "act": mem_act,
                    "sys": syscall, "mem_vm_max": mem_vm_max, "mem_vm_cur": mem_vm_cur,
                    "mem_size": size, "tip": "increase `mem/vm_max'",
                    "pid": pid.as_raw());
            }
            match mem_act {
                // Allow cannot happen.
                Action::Allow => unreachable!(),
                Action::Warn => {}
                Action::Panic | Action::Deny | Action::Filter => return Err(Errno::ENOMEM),
                //Do NOT panic the main thread!
                //Action::Panic => panic!(),
                Action::Exit => std::process::exit(libc::ENOMEM),
                Action::Stop => {
                    let _ = kill(pid, Some(Signal::SIGSTOP));
                    return Err(Errno::ENOMEM);
                }
                Action::Abort => {
                    let _ = kill(pid, Some(Signal::SIGABRT));
                    return Err(Errno::ENOMEM);
                }
                Action::Kill => {
                    let _ = kill(pid, Some(Signal::SIGKILL));
                    return Err(Errno::ENOMEM);
                }
            }
        }
    }

    // Check PSS
    if mem_max > 0 {
        let mem_cur = proc_mem(pid)?;
        if mem_cur.saturating_add(size) >= mem_max {
            if mem_act != Action::Filter {
                warn!("ctx": "access", "cap": Capability::CAP_MEM, "act": mem_act,
                    "sys": syscall, "mem_max": mem_max, "mem_cur": mem_cur,
                    "mem_size": size, "tip": "increase `mem/max'",
                    "pid": pid.as_raw());
            }
            return match mem_act {
                // Allow cannot happen.
                Action::Allow => unreachable!(),
                // Stop at syscall exit if check_exec, otherwise continue.
                Action::Warn => Ok(check_exec),
                Action::Panic | Action::Deny | Action::Filter => Err(Errno::ENOMEM),
                //Do NOT panic the main thread!
                //Action::Panic => panic!(),
                Action::Exit => std::process::exit(libc::ENOMEM),
                Action::Stop => {
                    let _ = kill(pid, Some(Signal::SIGSTOP));
                    return Err(Errno::ENOMEM);
                }
                Action::Abort => {
                    let _ = kill(pid, Some(Signal::SIGABRT));
                    return Err(Errno::ENOMEM);
                }
                Action::Kill => {
                    let _ = kill(pid, Some(Signal::SIGKILL));
                    return Err(Errno::ENOMEM);
                }
            };
        }
    }

    // Stop at syscall exit as necessary.
    Ok(check_exec || check_append_only || mem_max > 0 || mem_vm_max > 0)
}

// Resolve mmap(2) and mmap2(2) arguments with support for old_mmap.
pub(crate) fn ptrace_mmap_args(pid: Pid, arch: ScmpArch, raw: [u64; 6]) -> Result<[u64; 6], Errno> {
    if !scmp_arch_is_old_mmap(arch) {
        return Ok(raw);
    }

    let process = RemoteProcess::new(pid);

    // SAFETY: ptrace(2) hook, request cannot be validated.
    unsafe { process.remote_old_mmap_args(arch, raw[0]) }
}