syd 3.56.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
//
// 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_SETGROUPS,
    SYS_SETGROUPS32,
};
use crate::{
    confine::{
        scmp_arch, scmp_arch_raw, SydArch, SydSys,
        SydSys::{
            SysChdir, SysExecve, SysExecveat, SysFchdir, SysMmap, SysMmap2, SysSetgroups,
            SysSetgroups32,
        },
    },
    cookie::safe_kill,
    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},
    },
    ptrace::{
        ptrace_cont, ptrace_set_arg, ptrace_set_return, ptrace_skip_syscall, ptrace_syscall_info,
    },
    sandbox::{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;

pub(crate) fn handle_ptrace_sysenter(
    pid: Pid,
    info: ptrace_syscall_info,
    cache: &Arc<WorkerCache>,
    sandbox: &Arc<RwLock<Sandbox>>,
) -> Result<(), Errno> {
    #[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;

    let syscall = match SydSys::try_from(scmp_trace_data) {
        Ok(syscall) => syscall,
        Err(_) => unreachable!("BUG: invalid syscall data {scmp_trace_data}!"),
    };

    match syscall {
        SysChdir | SysFchdir => {
            #[cfg(feature = "kcov")]
            {
                let scno = if syscall == SysChdir {
                    *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 syscall == SysChdir {
                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 Err(Errno::ECANCELED);
            }

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

            // Record chdir result with dir info and path.
            if cache
                .add_chdir(pid, scmp_trace_data, file_info, move_path)
                .is_err()
            {
                let _ = safe_kill(pid, libc::SIGKILL);
                return Err(Errno::ESRCH);
            }

            // Stop at syscall exit.
            Ok(())
        }
        SysMmap | SysMmap2 => {
            let data = if let Some(data) = info.seccomp() {
                data
            } else {
                unreachable!("BUG: Invalid system call information returned by kernel!");
            };

            let sys_mmap = if syscall == SysMmap {
                MmapSyscall::Mmap
            } else {
                MmapSyscall::Mmap2
            };

            #[cfg(feature = "kcov")]
            {
                let scno = if syscall == SysMmap {
                    *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 sys_mmap == MmapSyscall::Mmap {
                match ptrace_mmap_args(pid, arch.into(), data.args) {
                    Ok(args) => args,
                    Err(errno) => return deny_syscall(pid, info.arch, errno, cache),
                }
            } 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, sys_mmap, &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, move_path)) => {
                    // Record mmap(2) pid and path for check and transit at exit.
                    if cache.add_mmap(pid, sys_mmap, move_path).is_err() {
                        let _ = safe_kill(pid, libc::SIGKILL);
                        return Err(Errno::ESRCH);
                    }
                    Ok(())
                }
                Ok((false, _)) => {
                    // Exec sandboxing disabled, continue process.
                    Err(Errno::ECANCELED)
                }
                Err(errno) => deny_syscall(pid, info.arch, errno, cache),
            }
        }
        SysExecve | SysExecveat => {
            #[cfg(feature = "kcov")]
            {
                let scno = if syscall == SysExecve {
                    *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 {
                return deny_syscall(pid, info.arch, errno, cache);
            }

            // Continue process, it will stop at EVENT_EXEC.
            Err(Errno::ECANCELED)
        }
        SysSetgroups | SysSetgroups32 => {
            #[cfg(feature = "kcov")]
            {
                let scno = if syscall == SysSetgroups {
                    *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 syscall == SysSetgroups {
                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_syscall(pid, info.arch, errno, cache);
            }

            // Emulator validated GID list and called setgroups(2) already.
            // Next is to set argument 0 to 0 so sandbox process drops groups.
            if let Err(errno) = ptrace_set_arg(pid, scmp_arch_raw(arch.into()), 0, 0) {
                if errno != Errno::ESRCH {
                    let _ = safe_kill(pid, libc::SIGKILL);
                }
                return Err(Errno::ESRCH);
            }
            // Continue process to execute setgroups(2) syscall.
            Err(Errno::ECANCELED)
        }

        _ => unreachable!("BUG: invalid syscall data {scmp_trace_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 == u16::from(SysChdir) {
                *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 = {
            let sandbox = SandboxGuard::Read(sandbox.read().unwrap_or_else(|err| err.into_inner()));
            sysexit_chdir(pid, &sandbox, info, entry.info, entry.path)
        };

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

        result
    } else if let Some(entry) = cache.get_mmap(pid) {
        #[cfg(feature = "kcov")]
        {
            let scno = if entry.sys == MmapSyscall::Mmap {
                *SYS_MMAP
            } else {
                *SYS_MMAP2
            };
            let scno = if let Some(scno) = scno {
                scno
            } else if entry.sys == MmapSyscall::Mmap {
                let scno: libc::c_long = 4000;
                scno.saturating_add(u16::from(SysMmap).into())
            } else {
                let scno: libc::c_long = 4000;
                scno.saturating_add(u16::from(SysMmap2).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, entry.sys, entry.path)
        };

        #[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 {
        unreachable!("BUG: Invalid syscall exit stop: {info:?}");
    }
}

// Deny a ptrace-stopped syscall.
fn deny_syscall(pid: Pid, arch: u32, errno: Errno, cache: &Arc<WorkerCache>) -> Result<(), Errno> {
    let errno = if errno == Errno::ECANCELED {
        None // Deny with success.
    } else {
        Some(errno)
    };

    if let Err(errno) = ptrace_skip_syscall(pid, arch, errno) {
        if errno != Errno::ESRCH {
            let _ = safe_kill(pid, libc::SIGKILL);
        }
        Err(Errno::ESRCH)
    } else if cfg!(any(
        target_arch = "mips",
        target_arch = "mips32r6",
        target_arch = "mips64",
        target_arch = "mips64r6",
        target_arch = "s390x"
    )) {
        // MIPS/s390x: stop at syscall-exit to write return value.
        if cache.add_error(pid, errno).is_ok() {
            Ok(())
        } else {
            let _ = safe_kill(pid, libc::SIGKILL);
            Err(Errno::ESRCH)
        }
    } else {
        // Resume process.
        let _ = ptrace_cont(pid, None);
        Err(Errno::ESRCH)
    }
}