|
| 1 | +/// A seccomp-bpf filter program. |
| 2 | +/// |
| 3 | +/// The caller builds the BPF program as a list of `(code, jt, jf, k)` |
| 4 | +/// instructions. Styrolite installs it via `seccomp(2)` after |
| 5 | +/// capabilities are set but before `execvpe()`. |
| 6 | +/// |
| 7 | +/// Requires `no_new_privs = true` on the `ExecutableSpec`. |
| 8 | +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] |
| 9 | +pub struct SeccompFilter { |
| 10 | + /// BPF instructions as `(code, jt, jf, k)` tuples. |
| 11 | + pub instructions: Vec<(u16, u8, u8, u32)>, |
| 12 | +} |
| 13 | + |
| 14 | +impl SeccompFilter { |
| 15 | + /// Install the seccomp filter via `seccomp(2)` with |
| 16 | + /// `SECCOMP_FILTER_FLAG_TSYNC`. |
| 17 | + /// |
| 18 | + /// Uses `seccomp(2)` instead of `prctl(PR_SET_SECCOMP)` to synchronize the |
| 19 | + /// filter across all threads via `SECCOMP_FILTER_FLAG_TSYNC`. |
| 20 | + /// |
| 21 | + /// # Safety |
| 22 | + /// |
| 23 | + /// Must be called after `prctl(PR_SET_NO_NEW_PRIVS, 1)` and before |
| 24 | + /// `execvpe()`. The caller must ensure the BPF program is valid. |
| 25 | + pub unsafe fn install(&self) -> std::io::Result<()> { |
| 26 | + let filters: Vec<libc::sock_filter> = self |
| 27 | + .instructions |
| 28 | + .iter() |
| 29 | + .map(|&(code, jt, jf, k)| libc::sock_filter { code, jt, jf, k }) |
| 30 | + .collect(); |
| 31 | + let prog = libc::sock_fprog { |
| 32 | + len: filters.len() as u16, |
| 33 | + filter: filters.as_ptr() as *mut _, |
| 34 | + }; |
| 35 | + |
| 36 | + let ret = unsafe { libc::syscall(libc::SYS_seccomp, 1u64, 1u64, &prog as *const _) }; |
| 37 | + if ret != 0 { |
| 38 | + return Err(std::io::Error::last_os_error()); |
| 39 | + } |
| 40 | + Ok(()) |
| 41 | + } |
| 42 | +} |
0 commit comments