reverie-process 0.4.0

Deterministic async process spawning and management for the Reverie framework.
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
/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 */

//! Provides helpers for constructing a [`seccomp`][seccomp] filter. This is a
//! pure Rust implementation and does not require libseccomp.
//!
//! # Seccomp Background
//!
//! [`seccomp(2)`][seccomp] is a powerful tool for changing how a process tree
//! behaves when a syscall happens. Seccomp can be used to install a filter that
//! applies to every child process in a process tree. Since filters cannot be
//! removed, they can only get more restrictive. The language used for filters is
//! called `seccomp-bpf`. It is a subset of the BPF byte code language.
//!
//! Some of the restrictions include:
//!  - Only being able to JMP forward and never backward. This prevents loops and
//!    ensures seccomp-bpf filters always terminate. This is also true of BPF.
//!  - Cannot call libbpf functions.
//!  - Cannot operate on 64-bit integers, only 32-bit integers.
//!
//! [seccomp]: https://man7.org/linux/man-pages/man2/seccomp.2.html
//!
//! You can think of a seccomp-bpf program as a little function that gets
//! executed for every syscall:
//!
//! ```no_compile
//! // NOTE: seccomp-bpf programs are actually written in byte code, but if a
//! // high-level language could be compiled to BPF byte code, this is what it'd
//! // look like.
//! fn my_program(data: seccomp_data) -> Action {
//!     if data.nr == 2 {
//!         return Action::Trace;
//!     }
//!
//!     if data.nr == 3 {
//!         return Action::KillProcess;
//!     }
//!
//!     // Allow the syscall by default.
//!     Action::Allow
//! }
//! ```
//!
//! where `seccomp_data` is defined as:
//!
//! ```no_compile
//! struct seccomp_data {
//!     // The syscall number.
//!     nr: u32,
//!     // The architecture.
//!     arch: u32,
//!     // Instruction pointer.
//!     ip: u64,
//!     // The 6 syscall arguments.
//!     args: [u64; 6],
//! }
//! ```
//!
//! This is the only input available to the seccomp filter and is the only bit of
//! data available to make a decision about a syscall (i.e., an "action"). An
//! action might be nothing (i.e., allow the syscall through), kill the
//! process/thread with `SIGSYS`, forward the syscall to ptrace, or return an
//! error code.

#[macro_use]
mod bpf;

#[allow(unused)]
mod notif;

use std::collections::BTreeMap;

pub use bpf::Filter;
use bpf::*;
pub use notif::*;
use syscalls::Errno;
use syscalls::Sysno;

/// Builder for creating seccomp filters.
#[derive(Debug, Clone)]
pub struct FilterBuilder {
    /// The target architecture.
    target_arch: TargetArch,

    /// The action to take if there are no matches.
    default_action: Action,

    /// The action to take for each syscall.
    syscalls: BTreeMap<Sysno, Action>,

    /// Ranges of instruction pointer values.
    ip_ranges: Vec<(u64, u64, Action)>,

    /// Exact instruction pointer values, checked before `ip_ranges`.
    instruction_pointers: Vec<(u64, Action)>,

    /// A second architecture whose syscalls take an action instead of killing
    /// the process.
    alternate_arch: Option<(TargetArch, Action)>,
}

/// The target architecture.
#[allow(non_camel_case_types, missing_docs)]
#[derive(Debug, Copy, Clone)]
#[repr(u32)]
pub enum TargetArch {
    x86 = AUDIT_ARCH_X86,
    x86_64 = AUDIT_ARCH_X86_64,
    mips = AUDIT_ARCH_MIPS,
    powerpc = AUDIT_ARCH_PPC,
    powerpc64 = AUDIT_ARCH_PPC64,
    arm = AUDIT_ARCH_ARM,
    aarch64 = AUDIT_ARCH_AARCH64,
}

/// The action to take if the conditions of a rule all match.
#[derive(Debug, Copy, Clone)]
pub enum Action {
    /// Allows the syscallto be executed.
    Allow,

    /// Returns the specified error instead of executing the syscall.
    Errno(Errno),

    /// Prevents the syscall from being executed and the kernel will kill the
    /// calling thread with `SIGSYS`.
    KillThread,

    /// Prevents the syscall from being executed and the kernel will kill the
    /// calling process with `SIGSYS`.
    KillProcess,

    /// Same as [`Action::Allow`] but logs the call.
    Log,

    /// If the thread is being ptraced and the tracing process specified
    /// `PTRACE_O_SECCOMP`, the tracing process will be notified via
    /// `PTRACE_EVENT_SECCOMP` and the value provided can be retrieved using
    /// `PTRACE_GETEVENTMSG`.
    Trace(u16),

    /// Disallow and raise a SIGSYS in the calling process.
    Trap,

    /// Notifies userspace.
    Notify,
}

impl From<Action> for u32 {
    fn from(action: Action) -> u32 {
        match action {
            Action::Allow => libc::SECCOMP_RET_ALLOW,
            Action::Errno(x) => {
                libc::SECCOMP_RET_ERRNO | (x.into_raw() as u32 & libc::SECCOMP_RET_DATA)
            }
            Action::KillThread => libc::SECCOMP_RET_KILL_THREAD,
            Action::KillProcess => libc::SECCOMP_RET_KILL_PROCESS,
            Action::Log => libc::SECCOMP_RET_LOG,
            Action::Trace(x) => libc::SECCOMP_RET_TRACE | (x as u32 & libc::SECCOMP_RET_DATA),
            Action::Trap => libc::SECCOMP_RET_TRAP,
            Action::Notify => 0x7fc00000u32,
        }
    }
}

impl From<Action> for sock_filter {
    fn from(action: Action) -> sock_filter {
        BPF_STMT(BPF_RET + BPF_K, u32::from(action))
    }
}

impl TargetArch {
    #![allow(missing_docs)]

    #[cfg(target_arch = "x86")]
    pub const CURRENT: TargetArch = Self::x86;

    #[cfg(target_arch = "x86_64")]
    pub const CURRENT: TargetArch = Self::x86_64;

    #[cfg(target_arch = "mips")]
    pub const CURRENT: TargetArch = Self::mips;

    #[cfg(target_arch = "powerpc")]
    pub const CURRENT: TargetArch = Self::powerpc;

    #[cfg(target_arch = "powerpc64")]
    pub const CURRENT: TargetArch = Self::powerpc64;

    #[cfg(target_arch = "arm")]
    pub const CURRENT: TargetArch = Self::arm;

    #[cfg(target_arch = "aarch64")]
    pub const CURRENT: TargetArch = Self::aarch64;
}

impl Default for TargetArch {
    fn default() -> Self {
        Self::CURRENT
    }
}

impl Default for FilterBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl FilterBuilder {
    /// Creates the seccomp filter builder.
    pub fn new() -> Self {
        Self {
            target_arch: TargetArch::default(),
            default_action: Action::KillThread,
            syscalls: Default::default(),
            ip_ranges: Default::default(),
            instruction_pointers: Default::default(),
            alternate_arch: None,
        }
    }

    /// Sets the target architecture. If this doesn't match the architecture of
    /// the process, then the process is killed. This is the first step in the
    /// seccomp filter and ensures that we're working with the right syscall
    /// table. Each architecture has a slightly different syscall table and we
    /// need to make sure the syscall numbers we're using are the right ones for
    /// the architecture.
    ///
    /// By default, the target architecture is set to the architecture of the
    /// current program (i.e., `TargetArch::CURRENT`).
    pub fn target_arch(&mut self, target_arch: TargetArch) -> &mut Self {
        self.target_arch = target_arch;
        self
    }

    /// The default action to take if there are no matches. By default, the
    /// default action is to kill the current thread (i.e., the filter becomes an
    /// allowlist).
    ///
    /// When using an allowlist of syscalls, this should be set to
    /// `Action::KillThread` or `Action::KillProcess`.
    ///
    /// When using a blocklist of syscalls, this should be set to
    /// `Action::Allow`.
    pub fn default_action(&mut self, action: Action) -> &mut Self {
        self.default_action = action;
        self
    }

    /// Sets the action to take for the given syscall.
    pub fn syscall(&mut self, syscall: Sysno, action: Action) -> &mut Self {
        self.syscalls.insert(syscall, action);
        self
    }

    /// Sets the action to take for a set of syscalls.
    pub fn syscalls<I>(&mut self, table: I) -> &mut Self
    where
        I: IntoIterator<Item = (Sysno, Action)>,
    {
        self.syscalls.extend(table);
        self
    }

    /// Lets syscalls of a second architecture take `action` instead of killing
    /// the process.
    ///
    /// The architecture check at the start of the filter then continues for
    /// the target architecture, returns `action` for `arch`, and kills the
    /// process for any other architecture. `action` is returned for every
    /// syscall of `arch`, whatever its number or instruction pointer, because
    /// the rest of the filter is written against the target architecture's
    /// syscall table.
    ///
    /// When this is never called, the filter's architecture check is exactly
    /// the same as before this method existed.
    pub fn alternate_arch(&mut self, arch: TargetArch, action: Action) -> &mut Self {
        self.alternate_arch = Some((arch, action));
        self
    }

    /// Take an action if the instruction pointer is exactly `ip`, whatever
    /// the syscall number.
    ///
    /// Seccomp reports the address after the syscall instruction. Rules added
    /// with this method are checked in sequence before every
    /// [`FilterBuilder::ip_range`] rule and every syscall rule.
    pub fn instruction_pointer(&mut self, ip: u64, action: Action) -> &mut Self {
        self.instruction_pointers.push((ip, action));
        self
    }

    /// Take an action if the instruction pointer `ip >= begin && ip < end`.
    ///
    /// This is useful in conjunction with `mmap`. For example, we can use this
    /// to deny any syscalls made outside of `ld.so` or `libc.so`. It can also be
    /// used to avoid tracing syscalls injected with ptrace.
    ///
    /// Multiple ranges can be added and are checked in sequence.
    pub fn ip_range(&mut self, begin: u64, end: u64, action: Action) -> &mut Self {
        self.ip_ranges.push((begin, end, action));
        self
    }

    /// Adds multiple IP ranges. This is equivalent to calling
    /// [`FilterBuilder::ip_range`] multiple times.
    pub fn ip_ranges<I>(&mut self, ranges: I) -> &mut Self
    where
        I: IntoIterator<Item = (u64, u64, Action)>,
    {
        self.ip_ranges.extend(ranges);
        self
    }

    /// Generates the byte code for the filter.
    pub fn build(&self) -> Filter {
        let mut filter = Filter::new();

        // This should be the first step for every seccomp-bpf filter.
        match self.alternate_arch {
            None => VALIDATE_ARCH(self.target_arch as u32).into_bpf(&mut filter),
            Some((arch, action)) => {
                VALIDATE_ARCH_OR_ALTERNATE(self.target_arch as u32, arch as u32, action.into())
                    .into_bpf(&mut filter)
            }
        }

        if !self.instruction_pointers.is_empty() || !self.ip_ranges.is_empty() {
            LOAD_SYSCALL_IP().into_bpf(&mut filter);

            for (ip, action) in &self.instruction_pointers {
                IP_EQ(*ip, (*action).into()).into_bpf(&mut filter);
            }

            for (begin, end, action) in &self.ip_ranges {
                IP_RANGE(*begin, *end, (*action).into()).into_bpf(&mut filter);
            }
        }

        if !self.syscalls.is_empty() {
            // Load the syscall number.
            LOAD_SYSCALL_NR.into_bpf(&mut filter);

            for (syscall, action) in &self.syscalls {
                SYSCALL(*syscall, (*action).into()).into_bpf(&mut filter);
            }
        }

        // The default action is always performed last.
        sock_filter::from(self.default_action).into_bpf(&mut filter);

        filter
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn words(filter: &Filter) -> Vec<(u16, u8, u8, u32)> {
        filter
            .instructions()
            .iter()
            .map(|insn| (insn.code, insn.jt, insn.jf, insn.k))
            .collect()
    }

    const LD_ARCH: (u16, u8, u8, u32) = (0x20, 0, 0, 4);
    const RET_KILL_PROCESS: (u16, u8, u8, u32) = (0x06, 0, 0, 0x8000_0000);

    #[test]
    fn alternate_arch_prologue_is_exact_and_unset_emits_nothing_new() {
        let mut plain = FilterBuilder::new();
        plain
            .target_arch(TargetArch::x86_64)
            .default_action(Action::Allow)
            .syscall(Sysno::getpid, Action::Trace(0));
        let mut routed = plain.clone();
        routed.alternate_arch(TargetArch::x86, Action::Trace(0x7101));
        let plain = words(&plain.build());
        let routed = words(&routed.build());

        assert_eq!(
            plain[..3],
            [LD_ARCH, (0x15, 1, 0, AUDIT_ARCH_X86_64), RET_KILL_PROCESS]
        );
        assert_eq!(
            routed[..5],
            [
                LD_ARCH,
                (0x15, 3, 0, AUDIT_ARCH_X86_64),
                (0x15, 0, 1, AUDIT_ARCH_X86),
                (0x06, 0, 0, 0x7ff0_0000 | 0x7101),
                RET_KILL_PROCESS,
            ]
        );
        // Everything after the architecture check is unchanged.
        assert_eq!(plain[3..], routed[5..]);
    }

    #[test]
    fn instruction_pointer_is_an_exact_match_checked_before_ranges() {
        let mut builder = FilterBuilder::new();
        builder
            .default_action(Action::Allow)
            .ip_range(0x7100_0002, 0x7100_0003, Action::Allow)
            .instruction_pointer(0x1234_5678_7100_0006, Action::Trace(0x7102));
        let words = words(&builder.build());
        let ld_mem = |slot| (0x60, 0, 0, slot);
        assert_eq!(
            words[3..7],
            [
                (0x20, 0, 0, 8),
                (0x02, 0, 0, 0),
                (0x20, 0, 0, 12),
                (0x02, 0, 0, 1)
            ],
            "LOAD_SYSCALL_IP"
        );
        assert_eq!(
            words[7..12],
            [
                (0x15, 0, 3, 0x1234_5678),
                ld_mem(0),
                (0x15, 0, 1, 0x7100_0006),
                (0x06, 0, 0, 0x7ff0_0000 | 0x7102),
                ld_mem(1),
            ]
        );
        // The range follows, unchanged.
        let mut range_only = FilterBuilder::new();
        range_only
            .default_action(Action::Allow)
            .ip_range(0x7100_0002, 0x7100_0003, Action::Allow);
        let range_only = self::words(&range_only.build());
        assert_eq!(words[12..], range_only[7..]);
    }

    #[cfg(target_arch = "x86_64")]
    #[test]
    fn smoke() {
        assert_eq!(
            FilterBuilder::new()
                .default_action(Action::Allow)
                .target_arch(TargetArch::x86_64)
                .syscalls([
                    // NOTE: Different architectures will have a different order
                    // to the syscalls.
                    (Sysno::read, Action::KillThread),
                    (Sysno::write, Action::KillThread),
                    (Sysno::open, Action::KillThread),
                    (Sysno::close, Action::KillThread),
                    (Sysno::write, Action::KillThread),
                ])
                .build(),
            seccomp_bpf![
                VALIDATE_ARCH(AUDIT_ARCH_X86_64),
                LOAD_SYSCALL_NR,
                SYSCALL(Sysno::read, DENY),
                SYSCALL(Sysno::write, DENY),
                SYSCALL(Sysno::open, DENY),
                SYSCALL(Sysno::close, DENY),
                ALLOW,
            ]
        );
    }

    #[cfg(target_arch = "aarch64")]
    #[test]
    fn smoke() {
        assert_eq!(
            FilterBuilder::new()
                .default_action(Action::Allow)
                .target_arch(TargetArch::aarch64)
                .syscalls([
                    // NOTE: Different architectures will have a different order
                    // to the syscalls.
                    (Sysno::read, Action::KillThread),
                    (Sysno::write, Action::KillThread),
                    (Sysno::openat, Action::KillThread),
                    (Sysno::close, Action::KillThread),
                    (Sysno::write, Action::KillThread),
                ])
                .build(),
            seccomp_bpf![
                VALIDATE_ARCH(AUDIT_ARCH_AARCH64),
                LOAD_SYSCALL_NR,
                SYSCALL(Sysno::openat, DENY),
                SYSCALL(Sysno::close, DENY),
                SYSCALL(Sysno::read, DENY),
                SYSCALL(Sysno::write, DENY),
                ALLOW,
            ]
        );
    }
}