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

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

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

#[cfg(feature = "kcov")]
use crate::confine::{
    SYS_CHDIR, SYS_EXECVE, SYS_EXECVEAT, SYS_FCHDIR, SYS_MMAP, SYS_MMAP2, SYS_RT_SIGRETURN,
    SYS_SETGROUPS, SYS_SETGROUPS32, SYS_SIGRETURN,
};
use crate::{
    cache::SigreturnTrampolineIP,
    config::{
        PTRACE_DATA_CHDIR, PTRACE_DATA_EXECVE, PTRACE_DATA_EXECVEAT, PTRACE_DATA_FCHDIR,
        PTRACE_DATA_MMAP, PTRACE_DATA_MMAP2, PTRACE_DATA_RT_SIGRETURN, PTRACE_DATA_SETGROUPS,
        PTRACE_DATA_SETGROUPS32, PTRACE_DATA_SIGRETURN,
    },
    confine::{scmp_arch, scmp_arch_has_single_step, scmp_arch_raw, SydArch, SydNotifResp},
    cookie::safe_kill,
    error,
    hash::hex_encode_lower,
    kernel::ptrace::{
        chdir::{sysenter_chdir, sysenter_fchdir, sysexit_chdir},
        exec::sysenter_exec,
        mmap::{ptrace_mmap_args, sysenter_mmap, sysexit_mmap, MmapSyscall},
        setgroups::{sysenter_setgroups, sysenter_setgroups32},
    },
    proc::{proc_ip_in_sigtramp, proc_maps},
    ptrace::{ptrace_set_return, ptrace_syscall_info},
    req::RemoteProcess,
    sandbox::{Action, Capability, Sandbox, SandboxGuard},
    workers::WorkerCache,
};

// ptrace chdir(2) handlers
pub(crate) mod chdir;

// ptrace exec(3) handlers
pub(crate) mod exec;

// ptrace mmap(2) handlers
pub(crate) mod mmap;

// ptrace setgroups(2) handlers
pub(crate) mod setgroups;

// ptrace event handlers
pub(crate) mod event;

#[expect(clippy::cognitive_complexity)]
pub(crate) fn handle_ptrace_sysenter(
    pid: Pid,
    info: ptrace_syscall_info,
    cache: &Arc<WorkerCache>,
    sandbox: &Arc<RwLock<Sandbox>>,
) -> Option<SydNotifResp> {
    #[expect(clippy::disallowed_methods)]
    let arch: SydArch = scmp_arch(info.arch).unwrap().into();

    #[expect(clippy::disallowed_methods)]
    let info_scmp = info.seccomp().unwrap();

    #[expect(clippy::cast_possible_truncation)]
    let scmp_trace_data = info_scmp.ret_data as u16;

    match scmp_trace_data {
        PTRACE_DATA_CHDIR | PTRACE_DATA_FCHDIR => {
            #[cfg(feature = "kcov")]
            {
                let scno = if scmp_trace_data == PTRACE_DATA_CHDIR {
                    *SYS_CHDIR
                } else {
                    *SYS_FCHDIR
                };
                let scno = if let Some(scno) = scno {
                    scno
                } else {
                    let scno: libc::c_long = 4000;
                    scno.saturating_add(scmp_trace_data.into())
                };
                crate::kcov::abi::kcov_attach(pid);
                crate::kcov::abi::kcov_set_syscall(scno);
                let _ = crate::kcov::abi::kcov_enter_for(pid);
                crate::kcov_edge!();
            }

            // Acquire a read lock to the sandbox.
            let my_sandbox =
                SandboxGuard::Read(sandbox.read().unwrap_or_else(|err| err.into_inner()));

            let mut cont = false;
            let result = if my_sandbox.flags.ghost() {
                // Ghost mode initiated, reject syscall.
                Err(Errno::ENOSYS)
            } else if !my_sandbox.enabled(Capability::CAP_CHDIR) {
                // Chdir sandboxing isn't enabled, continue syscall.
                cont = true;
                Err(Errno::ECANCELED)
            } else if scmp_trace_data == PTRACE_DATA_CHDIR {
                sysenter_chdir(pid, &my_sandbox, arch.into(), info_scmp)
            } else {
                sysenter_fchdir(pid, &my_sandbox, arch.into(), info_scmp)
            };

            drop(my_sandbox); // release the read lock.

            #[cfg(feature = "kcov")]
            {
                crate::kcov_edge!();
                let _ = crate::kcov::abi::kcov_exit_for(pid);
            }

            if cont {
                // Chdir sandboxing isn't enabled, continue syscall.
                return Some(SydNotifResp::Cont { pid, signal: None });
            }

            let file_info = match result {
                Ok(info) => info,
                Err(errno) => return deny_response(pid, info.arch, errno),
            };

            // Record the chdir result with dir information.
            if cache.add_chdir(pid, scmp_trace_data, file_info).is_err() {
                let _ = safe_kill(pid, libc::SIGKILL);
                return None;
            }

            // Stop at syscall exit.
            Some(SydNotifResp::Exit { pid, signal: None })
        }
        PTRACE_DATA_MMAP | PTRACE_DATA_MMAP2 => {
            let data = if let Some(data) = info.seccomp() {
                data
            } else {
                unreachable!("BUG: Invalid system call information returned by kernel!");
            };

            let syscall = if scmp_trace_data == PTRACE_DATA_MMAP {
                MmapSyscall::Mmap
            } else {
                MmapSyscall::Mmap2
            };

            #[cfg(feature = "kcov")]
            {
                let scno = if scmp_trace_data == PTRACE_DATA_MMAP {
                    *SYS_MMAP
                } else {
                    *SYS_MMAP2
                };
                let scno = if let Some(scno) = scno {
                    scno
                } else {
                    let scno: libc::c_long = 4000;
                    scno.saturating_add(scmp_trace_data.into())
                };
                crate::kcov::abi::kcov_attach(pid);
                crate::kcov::abi::kcov_set_syscall(scno);
                let _ = crate::kcov::abi::kcov_enter_for(pid);
                crate::kcov_edge!();
            }

            // Decode mmap arguments for old_mmap using "struct mmap_arg_struct".
            let args = if syscall == MmapSyscall::Mmap {
                match ptrace_mmap_args(pid, arch.into(), data.args) {
                    Ok(args) => args,
                    Err(errno) => return deny_response(pid, info.arch, errno),
                }
            } else {
                data.args
            };

            // Acquire a read lock to the sandbox.
            let my_sandbox =
                SandboxGuard::Read(sandbox.read().unwrap_or_else(|err| err.into_inner()));

            // Call the system call handler, and record the result.
            let result = if my_sandbox.flags.ghost() {
                // Ghost mode initiated, reject syscall.
                Err(Errno::ENOSYS)
            } else {
                sysenter_mmap(pid, &my_sandbox, syscall, &args)
            };

            drop(my_sandbox); // release the read lock.

            #[cfg(feature = "kcov")]
            {
                crate::kcov_edge!();
                let _ = crate::kcov::abi::kcov_exit_for(pid);
            }

            match result {
                Ok(true) => {
                    // Record mmap(2) pid for syscall-exit exec sandbox check.
                    if cache.add_mmap(pid, syscall).is_err() {
                        let _ = safe_kill(pid, libc::SIGKILL);
                        return None;
                    }
                    Some(SydNotifResp::Exit { pid, signal: None })
                }
                Ok(false) => {
                    // Exec sandboxing disabled, continue process.
                    Some(SydNotifResp::Cont { pid, signal: None })
                }
                Err(errno) => deny_response(pid, info.arch, errno),
            }
        }
        PTRACE_DATA_EXECVE | PTRACE_DATA_EXECVEAT => {
            #[cfg(feature = "kcov")]
            {
                let scno = if scmp_trace_data == PTRACE_DATA_EXECVE {
                    *SYS_EXECVE
                } else {
                    *SYS_EXECVEAT
                };
                let scno = if let Some(scno) = scno {
                    scno
                } else {
                    let scno: libc::c_long = 4000;
                    scno.saturating_add(scmp_trace_data.into())
                };
                crate::kcov::abi::kcov_attach(pid);
                crate::kcov::abi::kcov_set_syscall(scno);
                let _ = crate::kcov::abi::kcov_enter_for(pid);
                crate::kcov_edge!();
            }

            // Acquire a read lock to the sandbox.
            let my_sandbox =
                SandboxGuard::Read(sandbox.read().unwrap_or_else(|err| err.into_inner()));

            // Call the system call handler, and record the result.
            let result = if my_sandbox.flags.ghost() {
                // Ghost mode initiated, reject syscall.
                Err(Errno::ENOSYS)
            } else {
                sysenter_exec(pid, info, cache, &my_sandbox)
            };

            drop(my_sandbox); // release the read lock.

            #[cfg(feature = "kcov")]
            {
                crate::kcov_edge!();
                let _ = crate::kcov::abi::kcov_exit_for(pid);
            }

            if let Err(errno) = result {
                // AT_EXECVE_CHECK success is indicated by ECANCELED.
                // See sysenter_exec.
                let errno = if errno == Errno::ECANCELED {
                    return Some(SydNotifResp::Deny {
                        pid,
                        errno,
                        arch: info.arch,
                    });
                } else {
                    errno
                };

                return deny_response(pid, info.arch, errno);
            }

            // Continue process, it will stop at EVENT_EXEC.
            Some(SydNotifResp::Cont { pid, signal: None })
        }
        PTRACE_DATA_SIGRETURN | PTRACE_DATA_RT_SIGRETURN => {
            #[cfg(feature = "kcov")]
            {
                let scno = if scmp_trace_data == PTRACE_DATA_SIGRETURN {
                    *SYS_SIGRETURN
                } else {
                    *SYS_RT_SIGRETURN
                };
                let scno = if let Some(scno) = scno {
                    scno
                } else {
                    let scno: libc::c_long = 4000;
                    scno.saturating_add(scmp_trace_data.into())
                };
                crate::kcov::abi::kcov_attach(pid);
                crate::kcov::abi::kcov_set_syscall(scno);
                let _ = crate::kcov::abi::kcov_enter_for(pid);
                crate::kcov_edge!();
            }

            // Entry to sigreturn(2) or rt_sigreturn(2).
            //
            // Validate sigreturn(2) against saved SROP trampoline cookie.
            let has_handler = cache.enter_sig_handle(pid);
            let ip = info.instruction_pointer;
            let has_savedip = if has_handler {
                match cache.get_sig_trampoline_ip(pid) {
                    None if proc_ip_in_sigtramp(pid, ip) => {
                        cache.set_sig_trampoline_ip(pid, SigreturnTrampolineIP { lo: ip, hi: ip });
                        true
                    }
                    None if !scmp_arch_has_single_step(arch.into()) => {
                        cache.set_sig_trampoline_ip(pid, SigreturnTrampolineIP { lo: ip, hi: ip });
                        true
                    }
                    None => false,
                    Some(cookie) => cookie.matches(ip),
                }
            } else {
                false
            };

            #[cfg(feature = "kcov")]
            {
                crate::kcov_edge!();
                let _ = crate::kcov::abi::kcov_exit_for(pid);
            }

            if has_savedip {
                // Stop at syscall exit to pop cookie.
                return Some(SydNotifResp::Exit { pid, signal: None });
            }

            // !!! SIGRETURN W/O SIGNAL AKA SROP !!!
            //
            // Check sandbox verbosity.
            // Verbose logging is intended for malware analysis.
            let log_scmp = {
                SandboxGuard::Read(sandbox.read().unwrap_or_else(|err| err.into_inner())).log_scmp()
            };

            // Read memory maps for logging.
            let memmap = if log_scmp {
                match proc_maps(pid) {
                    Ok(memmap) => Some(memmap),
                    Err(Errno::ESRCH) => return None, // skip dead.
                    Err(_) => None,
                }
            } else {
                None
            };

            // Read memory pointed by IP and SP.
            let ip = info.instruction_pointer;
            let sp = (info.stack_pointer & !0xF).saturating_sub(16);
            let ip_mem = if log_scmp { Some([0u8; 64]) } else { None };
            let sp_mem = if log_scmp { Some([0u8; 64]) } else { None };
            let process = RemoteProcess::new(pid);

            #[expect(clippy::disallowed_methods)]
            let arch: SydArch = scmp_arch(info.arch).unwrap().into();
            let is_realtime = scmp_trace_data == PTRACE_DATA_RT_SIGRETURN;

            if let Some(mut ip_mem) = ip_mem {
                // SAFETY: This is a ptrace hook, the PID cannot be validated.
                if unsafe { process.read_mem(arch.into(), &mut ip_mem, ip, 64) }
                    == Err(Errno::ESRCH)
                {
                    return None; // skip dead.
                }
            }
            if let Some(mut sp_mem) = sp_mem {
                // SAFETY: This is a ptrace hook, the PID cannot be validated.
                if unsafe { process.read_mem(arch.into(), &mut sp_mem, sp, 64) }
                    == Err(Errno::ESRCH)
                {
                    return None; // skip dead.
                }
            }

            // Terminate process, skip log if already dead.
            if safe_kill(pid, libc::SIGKILL) == Err(Errno::ESRCH) {
                return None;
            }

            // Log SROP detection.
            let cookie = cache.get_sig_trampoline_ip(pid);
            let depth = cache.depth_sig_handle(pid);
            if !log_scmp {
                error!("ctx": "sigreturn", "op": "check_SROP",
                    "msg": "Artificial sigreturn(2) detected: assume SROP!",
                    "act": Action::Kill,
                    "pid": process.pid.as_raw(), "arch": arch,
                    "sys": if is_realtime { "rt_sigreturn" } else { "sigreturn" },
                    "ip": ip, "depth": depth,
                    "trampoline_lo": cookie.map_or(0, |c| c.lo),
                    "trampoline_hi": cookie.map_or(0, |c| c.hi),
                    "tip": "configure `trace/allow_unsafe_sigreturn:1'");
            } else {
                let ip_hex = ip_mem.map(|m| hex_encode_lower(m.as_ref()).ok());
                let sp_hex = sp_mem.map(|m| hex_encode_lower(m.as_ref()).ok());
                error!("ctx": "sigreturn", "op": "check_SROP",
                    "msg": "Artificial sigreturn(2) detected: assume SROP!",
                    "act": Action::Kill,
                    "pid": process.pid.as_raw(), "arch": arch,
                    "sys": if is_realtime { "rt_sigreturn" } else { "sigreturn" },
                    "args": info_scmp.args, "ip": ip, "sp": sp,
                    "ip_mem": ip_hex,
                    "sp_mem": sp_hex,
                    "memmap": memmap,
                    "tip": "configure `trace/allow_unsafe_sigreturn:1'");
            }

            // Process is dead, Jim.
            None
        }
        PTRACE_DATA_SETGROUPS | PTRACE_DATA_SETGROUPS32 => {
            #[cfg(feature = "kcov")]
            {
                let scno = if scmp_trace_data == PTRACE_DATA_SETGROUPS {
                    *SYS_SETGROUPS
                } else {
                    *SYS_SETGROUPS32
                };
                let scno = if let Some(scno) = scno {
                    scno
                } else {
                    let scno: libc::c_long = 4000;
                    scno.saturating_add(scmp_trace_data.into())
                };
                crate::kcov::abi::kcov_attach(pid);
                crate::kcov::abi::kcov_set_syscall(scno);
                let _ = crate::kcov::abi::kcov_enter_for(pid);
                crate::kcov_edge!();
            }

            let result = if scmp_trace_data == PTRACE_DATA_SETGROUPS {
                sysenter_setgroups(pid, arch.into(), info_scmp)
            } else {
                sysenter_setgroups32(pid, arch.into(), info_scmp)
            };

            #[cfg(feature = "kcov")]
            {
                crate::kcov_edge!();
                let _ = crate::kcov::abi::kcov_exit_for(pid);
            }

            if let Err(errno) = result {
                return deny_response(pid, info.arch, errno);
            }

            // Emulator validated GID list and called setgroups(2) already.
            // Next is to set argument 0 to 0 so sandbox process drops groups.
            Some(SydNotifResp::SetGroupsZero {
                pid,
                arch: scmp_arch_raw(arch.into()),
            })
        }

        data => unreachable!("BUG: invalid syscall data {data}!"),
    }
}

pub(crate) fn handle_ptrace_sysexit(
    pid: Pid,
    info: ptrace_syscall_info,
    cache: &Arc<WorkerCache>,
    sandbox: &Arc<RwLock<Sandbox>>,
) -> Result<(), Errno> {
    // Get and remove the system call entry from the cache, and
    // call the respective system call handler.
    if let Some(entry) = cache.get_chdir(pid) {
        #[cfg(feature = "kcov")]
        {
            let scno = if entry.data == PTRACE_DATA_CHDIR {
                *SYS_CHDIR
            } else {
                *SYS_FCHDIR
            };
            let scno = if let Some(scno) = scno {
                scno
            } else {
                let scno: libc::c_long = 4000;
                scno.saturating_add(entry.data.into())
            };
            crate::kcov::abi::kcov_attach(pid);
            crate::kcov::abi::kcov_set_syscall(scno);
            let _ = crate::kcov::abi::kcov_enter_for(pid);
            crate::kcov_edge!();
        }

        let result = sysexit_chdir(pid, info, entry.info);

        #[cfg(feature = "kcov")]
        {
            crate::kcov_edge!();
            let _ = crate::kcov::abi::kcov_exit_for(pid);
        }

        result
    } else if let Some(syscall) = cache.get_mmap(pid) {
        #[cfg(feature = "kcov")]
        {
            let scno = if syscall == MmapSyscall::Mmap {
                *SYS_MMAP
            } else {
                *SYS_MMAP2
            };
            let scno = if let Some(scno) = scno {
                scno
            } else if syscall == MmapSyscall::Mmap {
                let scno: libc::c_long = 4000;
                scno.saturating_add(PTRACE_DATA_MMAP.into())
            } else {
                let scno: libc::c_long = 4000;
                scno.saturating_add(PTRACE_DATA_MMAP2.into())
            };
            crate::kcov::abi::kcov_attach(pid);
            crate::kcov::abi::kcov_set_syscall(scno);
            let _ = crate::kcov::abi::kcov_enter_for(pid);
            crate::kcov_edge!();
        }

        let result = {
            let sandbox = SandboxGuard::Read(sandbox.read().unwrap_or_else(|err| err.into_inner()));
            sysexit_mmap(pid, &sandbox, info, syscall)
        };

        #[cfg(feature = "kcov")]
        {
            crate::kcov_edge!();
            let _ = crate::kcov::abi::kcov_exit_for(pid);
        }

        result
    } else if let Some((pid, errno)) = cache.get_error(pid) {
        // Architectures like mips, s390x where return value has to be written twice.
        // errno is None for success.
        ptrace_set_return(pid, info.arch, errno)
    } else if cache.has_sig_handle(pid) {
        // Exit from sigreturn(2) or rt_sigreturn(2):
        // Validate that a signal delivery cookie exists for this TID.
        if cache.exit_sig_handle(pid) {
            return Ok(());
        }

        // SROP detected, terminate with SIGKILL.
        let _ = safe_kill(pid, libc::SIGKILL);

        #[expect(clippy::disallowed_methods)]
        let arch: SydArch = scmp_arch(info.arch).unwrap().into();
        error!("ctx": "sigreturn", "op": "check_SROP",
            "msg": "Artificial sigreturn(2) without signal delivery cookie: assume SROP!",
            "act": Action::Kill, "pid": pid.as_raw(), "arch": arch,
            "tip": "configure `trace/allow_unsafe_sigreturn:1'");

        Err(Errno::ESRCH)
    } else {
        unreachable!("BUG: Invalid syscall exit stop: {info:?}");
    }
}

fn deny_response(pid: Pid, arch: u32, errno: Errno) -> Option<SydNotifResp> {
    Some(SydNotifResp::Deny { pid, arch, errno })
}