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

use std::{
    io::Seek,
    sync::{Arc, RwLock},
};

use nix::{errno::Errno, fcntl::OFlag, unistd::Pid};

use crate::{
    compat::{fstatx, FsType, ResolveFlag, STATX_INO},
    cookie::safe_kill,
    elf::{ElfError, ElfFileType, ElfType, ExecutableFile, LinkingType},
    err::err2no,
    error,
    fd::{SafeOwnedFd, AT_BADFD, PROC_FILE},
    kernel::ptrace::deny_action,
    lookup::{safe_open, safe_open_msym},
    path::{XPath, XPathBuf},
    proc::{proc_executables, proc_set_at_secure, SydExecMap},
    ptrace::ptrace_cont,
    sandbox::{Action, Capability, IntegrityError, Sandbox, SandboxGuard},
    warn,
    workers::WorkerCache,
    xfmt,
};

pub(crate) fn sysevent_exec(pid: Pid, cache: &Arc<WorkerCache>, sandbox: &Arc<RwLock<Sandbox>>) {
    // This is ptrace syscall exec stop.
    //
    // An important caveat is the TGID may have switched.
    #[cfg(feature = "kcov")]
    let _kcov = crate::kcov::abi::KcovScope::enter(pid, libc::SYS_execve);

    // Read executable paths.
    // This includes the executable, and the loader if executable is dynamically linked.
    let bins = match exec_get_proc(pid) {
        Some(bins) => bins,
        None => return,
    };
    let path = &bins[0].path; // Path to the executable.

    // Open paths and verify open FDs match device ID and inode information.
    let mut fds = match exec_open_bins(pid, &bins, path) {
        Some(fds) => fds,
        None => return,
    };

    // Lock sandbox for read.
    let my_sandbox = SandboxGuard::Read(sandbox.read().unwrap_or_else(|err| err.into_inner()));

    // Check SegvGuard.
    let mut deny = check_segvguard(pid, cache, &my_sandbox, &bins);

    // Check for Exec sandboxing.
    if deny.is_none() && my_sandbox.enabled(Capability::CAP_EXEC) {
        deny = check_exec(pid, &my_sandbox, &bins);
    }

    // Check for Trusted Path Execution (TPE).
    if deny.is_none() && my_sandbox.enabled(Capability::CAP_TPE) {
        match check_tpe(pid, &my_sandbox, &bins, &fds) {
            Ok(action) => deny = action,
            Err(()) => return,
        }
    }

    // Parse ELF, enforce bitness, linking, PIE and execstack restrictions.
    let mut exe = None;
    if deny.is_none() {
        match check_elf(pid, &my_sandbox, &bins, &mut fds) {
            Ok(elf) => exe = Some(elf),
            Err(action) => deny = Some(action),
        }
    }

    // Check for Force sandboxing.
    if deny.is_none() && my_sandbox.enabled(Capability::CAP_FORCE) {
        deny = check_force(pid, &my_sandbox, &bins, &mut fds);
    }

    // Set AT_SECURE for new executable image.
    if deny.is_none() && !my_sandbox.options.allow_unsafe_exec_libc() {
        deny = set_at_secure(pid, &my_sandbox, exe, path);
    }

    // Move domain on exec as necessary.
    if deny.is_none() {
        my_sandbox.move_on_exec(path);
    }

    // Release read lock.
    drop(my_sandbox);

    if let Some(action) = deny {
        let sig = action
            .signal()
            .map(|sig| sig as libc::c_int)
            .unwrap_or(libc::SIGKILL);
        let _ = safe_kill(pid, sig);
    } else {
        let _ = ptrace_cont(pid, None);
    }
}

// Open the executable and loader and verify the open FDs match the
// device ID and inode information recorded in proc_pid_maps(5).
//
// FDs will be used for two things:
// 1. Parsing ELF to determine bitness, PIE etc.
// 2. Checksumming binary for Force sandboxing.
#[expect(clippy::cognitive_complexity)]
fn exec_open_bins(pid: Pid, bins: &[SydExecMap], path: &XPath) -> Option<Vec<SafeOwnedFd>> {
    let mut fds = Vec::new();
    fds.try_reserve_exact(2).ok()?;
    let flags = OFlag::O_RDONLY | OFlag::O_NOCTTY;
    for (idx, bin) in bins.iter().enumerate() {
        let result = (|| -> Result<SafeOwnedFd, Errno> {
            if idx == 0 {
                // Executable binary, open via proc_pid_exe(5).
                let mut pfd = XPathBuf::from_pid(pid)?;
                pfd.try_push(b"exe")?;
                safe_open_msym(PROC_FILE(), &pfd, flags, ResolveFlag::empty())
            } else {
                // Linker, open via direct path.
                safe_open(AT_BADFD, &bin.path, flags, ResolveFlag::empty())
            }
        })();
        let fd = match result {
            Ok(fd) => fd,
            Err(errno) => {
                error!("ctx": "exec", "op": "open_elf", "pid": pid.as_raw(),
                    "err": errno as i32, "path": path,
                    "msg": xfmt!("open ÈLF `{path}' failed: {errno}"),
                    "tip": "check with SYD_LOG=debug and/or submit a bug report");
                let _ = safe_kill(pid, libc::SIGKILL);
                return None;
            }
        };

        // WORKAROUND: Check if the FS reports sane device ids.
        // Check the comment on has_broken_device_ids() function
        // for more information. Assume true on errors for safety.
        let dev_check = match FsType::get(&fd).map(|fs_type| !fs_type.has_broken_devid()) {
            Ok(dev_check) => dev_check,
            Err(Errno::ENOSYS) => {
                // Filesystem type does not support this call.
                // Assume true for safety.
                true
            }
            Err(errno) => {
                error!("ctx": "exec", "op": "open_elf", "pid": pid.as_raw(),
                    "err": errno as i32, "path": path,
                    "msg": xfmt!("statfs ELF `{path}' failed: {errno}"),
                    "tip": "check with SYD_LOG=debug and/or submit a bug report");
                let _ = safe_kill(pid, libc::SIGKILL);
                return None;
            }
        };

        let statx = match fstatx(&fd, STATX_INO) {
            Ok(stat) => stat,
            Err(errno) => {
                error!("ctx": "exec", "op": "open_elf", "pid": pid.as_raw(),
                    "err": errno as i32, "path": path,
                    "msg": xfmt!("statx ELF `{path}' failed: {errno}"),
                    "tip": "check with SYD_LOG=debug and/or submit a bug report");
                let _ = safe_kill(pid, libc::SIGKILL);
                return None;
            }
        };

        // Verify we opened the same file!
        #[expect(clippy::cast_sign_loss)]
        let dev_major = bin.dev_major as libc::c_uint;
        #[expect(clippy::cast_sign_loss)]
        let dev_minor = bin.dev_minor as libc::c_uint;
        if bin.inode != statx.stx_ino
            || (dev_check && (dev_major != statx.stx_dev_major || dev_minor != statx.stx_dev_minor))
        {
            let error = format!(
                "ELF metadata mismatch: {}:{}={} is not {}:{}={}",
                statx.stx_dev_major,
                statx.stx_dev_minor,
                statx.stx_ino,
                dev_major,
                dev_minor,
                bin.inode
            );
            warn!("ctx": "exec", "op": "open_elf", "pid": pid.as_raw(),
                "path": path, "msg": error);
            let _ = safe_kill(pid, libc::SIGKILL);
            return None;
        }
        fds.push(fd);
    }

    Some(fds)
}

// Check SegvGuard for executable and loader.
fn check_segvguard(
    pid: Pid,
    cache: &Arc<WorkerCache>,
    sandbox: &SandboxGuard,
    bins: &[SydExecMap],
) -> Option<Action> {
    for bin in bins {
        let path = &bin.path;

        let Some(action) = cache.check_segvguard(
            path,
            sandbox.segvguard_act(),
            sandbox.get_segvguard_expiry(),
        ) else {
            continue;
        };

        if action != Action::Filter {
            error!("ctx": "exec", "op": "segvguard",
                "pid": pid.as_raw(), "path": path,
                "msg": xfmt!("Max crashes {} exceeded, kill process {}",
                    sandbox.segvguard_maxcrashes,
                    pid.as_raw()),
                "tip": "increase `segvguard/maxcrashes'");
        }

        if let Some(act) = deny_action(action) {
            return Some(act);
        }
    }

    None
}

// Check for Exec sandboxing access on executable and loader.
fn check_exec(pid: Pid, sandbox: &SandboxGuard, bins: &[SydExecMap]) -> Option<Action> {
    for bin in bins {
        let path = &bin.path;

        let mut action = sandbox.check_path(Capability::CAP_EXEC, path);
        if action == Action::Deny {
            // PTRACE_EVENT_EXEC stop:
            // Promote deny action to kill.
            action = Action::Kill;
        }

        if action.is_logging() {
            warn!("ctx": "access", "cap": Capability::CAP_EXEC, "act": action,
                "pid": pid.as_raw(), "sys": "exec", "path": path,
                "tip": xfmt!("configure `allow/exec+{path}'"));
        }

        if let Some(act) = deny_action(action) {
            return Some(act);
        }
    }

    None
}

// Check for Trusted Path Execution (TPE) on the executable and loader.
#[expect(clippy::cognitive_complexity)]
fn check_tpe(
    pid: Pid,
    sandbox: &SandboxGuard,
    bins: &[SydExecMap],
    fds: &[SafeOwnedFd],
) -> Result<Option<Action>, ()> {
    let mut deny = None;
    for (idx, bin) in bins.iter().enumerate() {
        let file = &fds[idx];
        let path = &bin.path;

        let (action, msg) = match sandbox.check_tpe(file, path) {
            Ok(result) => result,
            Err(errno) => {
                error!("ctx": "exec", "op": "check_tpe", "sys": "exec",
                    "act": Action::Kill, "pid": pid.as_raw(), "err": errno as i32, "path": path,
                    "msg": xfmt!("check ELF `{path}' for TPE failed: {errno}"),
                    "tip": "move the binary to a safe location or use `sandbox/tpe:off'");
                let _ = safe_kill(pid, libc::SIGKILL);
                return Err(());
            }
        };

        if !matches!(action, Action::Allow | Action::Filter) {
            let msg = msg.as_deref().unwrap_or("?");
            error!("ctx": "exec", "op": "check_tpe", "sys": "exec",
                "act": action, "pid": pid.as_raw(), "err": libc::EACCES, "path": path,
                "msg": xfmt!("exec from untrusted path `{path}' blocked: {msg}"),
                "tip": "move the binary to a safe location or use `sandbox/tpe:off'");
        }

        if let Some(act) = deny_action(action) {
            deny = Some(act);
        }
    }
    Ok(deny)
}

// Parse executable and loader ELFs, enforce bitness, linking, PIE and
// executable-stack restrictions on each. ld.so(8) exec-indirection
// check is only applied to the executable.
#[expect(clippy::cognitive_complexity)]
fn check_elf(
    pid: Pid,
    sandbox: &SandboxGuard,
    bins: &[SydExecMap],
    fds: &mut [SafeOwnedFd],
) -> Result<ExecutableFile, Action> {
    let restrict_32 = sandbox.options.deny_exec_elf32();
    let restrict_dyn = sandbox.options.deny_exec_elf_dynamic();
    let restrict_sta = sandbox.options.deny_exec_elf_static();
    let restrict_ldd = !sandbox.options.allow_unsafe_exec_ldso();
    let restrict_pie = !sandbox.options.allow_unsafe_exec_nopie();
    let restrict_xs = !sandbox.options.allow_unsafe_exec_stack();

    let check_linking = restrict_ldd || restrict_dyn || restrict_sta || restrict_pie || restrict_xs;

    let mut exe = None;
    for (idx, bin) in bins.iter().enumerate() {
        let path = &bin.path;
        let elf = match ExecutableFile::parse(&mut fds[idx], check_linking) {
            Ok(elf) => elf,
            Err(ElfError::IoError(err)) => {
                error!("ctx": "exec", "op": "parse_elf", "pid": pid.as_raw(),
                    "err": err2no(&err) as i32, "path": path,
                    "msg": xfmt!("parse ELF `{path}' failed: {}", err2no(&err)));
                return Err(Action::Kill);
            }
            Err(ElfError::BadMagic) => {
                error!("ctx": "exec", "op": "parse_elf", "pid": pid.as_raw(),
                    "path": path, "msg": "BUG: not an ELF");
                return Err(Action::Kill);
            }
            Err(ElfError::Malformed) => {
                error!("ctx": "exec", "op": "parse_elf", "pid": pid.as_raw(),
                    "path": path, "msg": "BUG: malformed ELF");
                return Err(Action::Kill);
            }
        };

        // PIE and ld.so(8) exec-indirection applies only to executable.
        if idx == 0 {
            if restrict_ldd
                && !matches!(
                    elf,
                    ExecutableFile::Elf {
                        file_type: ElfFileType::Executable,
                        ..
                    }
                )
            {
                warn!("ctx": "exec", "op": "check_elf", "pid": pid.as_raw(),
                    "path": path, "exe": xfmt!("{elf}"),
                    "msg": "ld.so(8) exec-indirection prevented",
                    "tip": "configure `trace/allow_unsafe_exec_ldso:1'");
                return Err(Action::Kill);
            }

            if restrict_pie && matches!(elf, ExecutableFile::Elf { pie: false, .. }) {
                warn!("ctx": "exec", "op": "check_elf", "pid": pid.as_raw(),
                    "path": path, "exe": xfmt!("{elf}"),
                    "msg": "ELF is not a Position Independent Executable (PIE)",
                    "tip": "configure `trace/allow_unsafe_exec_nopie:1'");
                return Err(Action::Kill);
            }
        }

        if restrict_xs && matches!(elf, ExecutableFile::Elf { xs: true, .. }) {
            warn!("ctx": "exec", "op": "check_elf", "pid": pid.as_raw(),
                "path": path, "exe": xfmt!("{elf}"),
                "msg": "ELF has Executable Stack (PT_GNU_STACK)",
                "tip": "configure `trace/allow_unsafe_exec_stack:1'");
            return Err(Action::Kill);
        }

        if restrict_32
            && matches!(
                elf,
                ExecutableFile::Elf {
                    elf_type: ElfType::Elf32,
                    ..
                }
            )
        {
            warn!("ctx": "exec", "op": "check_elf", "pid": pid.as_raw(),
                "path": path, "exe": xfmt!("{elf}"),
                "msg": "32-bit execution prevented",
                "tip": "configure `trace/deny_exec_elf32:0'");
            return Err(Action::Kill);
        }

        if restrict_dyn
            && matches!(
                elf,
                ExecutableFile::Elf {
                    linking_type: Some(LinkingType::Dynamic),
                    ..
                }
            )
        {
            warn!("ctx": "exec", "op": "check_elf", "pid": pid.as_raw(),
                "path": path, "exe": xfmt!("{elf}"),
                "msg": "dynamic-link execution prevented",
                "tip": "configure `trace/deny_exec_elf_dynamic:0'");
            return Err(Action::Kill);
        }

        if restrict_sta
            && matches!(
                elf,
                ExecutableFile::Elf {
                    linking_type: Some(LinkingType::Static),
                    ..
                }
            )
        {
            error!("ctx": "exec", "op": "check_elf", "pid": pid.as_raw(),
                "path": path, "exe": xfmt!("{elf}"),
                "msg": "static-link execution prevented",
                "tip": "configure `trace/deny_exec_elf_static:0'");
            return Err(Action::Kill);
        }

        if idx == 0 {
            exe = Some(elf);
        }
    }

    // Return executable for AT_SECURE handler.
    exe.ok_or(Action::Kill)
}

// Check for Force sandboxing on executable and loader.
#[expect(clippy::cognitive_complexity)]
fn check_force(
    pid: Pid,
    sandbox: &SandboxGuard,
    bins: &[SydExecMap],
    fds: &mut [SafeOwnedFd],
) -> Option<Action> {
    let mut deny = None;

    for (idx, bin) in bins.iter().enumerate() {
        let path = &bin.path;

        let fd = &mut fds[idx];
        let result = match fd.rewind() {
            Ok(()) => sandbox.check_force2(fd, path),
            Err(err) => Err(IntegrityError::from(err)),
        };

        match result {
            Ok(mut action) => {
                if action == Action::Deny {
                    // PTRACE_EVENT_EXEC stop:
                    // Promote deny action to kill.
                    action = Action::Kill;
                }

                match action {
                    Action::Allow | Action::Filter => {}
                    Action::Exit => {
                        error!("ctx": "exec", "op": "verify_elf", "act": action,
                            "pid": pid.as_raw(), "path": path,
                            "tip": xfmt!("configure `force+{path}:<checksum>'"));
                    }
                    // Warn|Abort|Deny|Panic|Stop|Kill
                    _ => {
                        warn!("ctx": "exec", "op": "verify_elf", "act": action,
                            "pid": pid.as_raw(), "path": path,
                            "tip": xfmt!("configure `force+{path}:<checksum>'"));
                    }
                }

                if let Some(act) = deny_action(action) {
                    deny = Some(act);
                }
            }

            Err(IntegrityError::Sys(errno)) => {
                deny = Some(Action::Kill);
                error!("ctx": "exec", "op": "verify_elf", "act": Action::Kill,
                    "pid": pid.as_raw(), "err": errno as i32, "path": path,
                    "msg": xfmt!("system error during ELF checksum calculation: {errno}"),
                    "tip": xfmt!("configure `force+{path}:<checksum>'"));
            }

            Err(IntegrityError::Hash {
                mut action,
                expected,
                found,
            }) => {
                if action == Action::Deny {
                    // PTRACE_EVENT_EXEC stop:
                    // Promote deny action to kill.
                    action = Action::Kill;
                }

                if !matches!(action, Action::Allow | Action::Filter) {
                    warn!("ctx": "exec", "op": "verify_elf", "act": action,
                        "pid": pid.as_raw(), "path": path,
                        "msg": xfmt!("ELF checksum mismatch: {found} is not {expected}"),
                        "tip": xfmt!("configure `force+{path}:<checksum>'"));
                }

                if let Some(act) = deny_action(action) {
                    deny = Some(act);
                }
            }
        }
    }

    deny
}

// Set AT_SECURE for new executable image.
//
// Verify AT_{E,}{U,G}ID matches Syd's own.
// Overwrite AT_SYSINFO{,_EHDR} if trace/deny_vdso:1.
fn set_at_secure(
    pid: Pid,
    sandbox: &SandboxGuard,
    exe: Option<ExecutableFile>,
    path: &XPath,
) -> Option<Action> {
    let elf_type = match exe {
        Some(ExecutableFile::Elf { elf_type, .. }) => elf_type,
        _ => unreachable!("BUG: set_at_secure called with `{exe:?}', report a bug!"),
    };

    match proc_set_at_secure(pid, elf_type, sandbox.flags.deny_vdso()) {
        Ok(_) | Err(Errno::ESRCH) => None,
        Err(errno) => {
            error!("ctx": "exec", "op": "secure_exec", "pid": pid.as_raw(),
                "err": errno as i32, "path": path,
                "msg": xfmt!("error setting AT_SECURE for ELF `{path}': {errno}"),
                "tip": "configure `trace/allow_unsafe_exec_libc:1'");
            Some(Action::Kill)
        }
    }
}

fn exec_get_proc(pid: Pid) -> Option<Vec<SydExecMap>> {
    match proc_executables(pid) {
        Ok(bins) => Some(bins),
        Err(errno) => {
            error!("ctx": "exec", "op": "read_maps",
                "pid": pid.as_raw(), "err": errno as i32,
                "msg": xfmt!("failed to read /proc/{}/maps: {errno}", pid.as_raw()),
                "tip": "check with SYD_LOG=debug and/or submit a bug report");
            let _ = safe_kill(pid, libc::SIGKILL);
            None
        }
    }
}