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
//! Kernel-enforced sandboxing (Linux only).
//!
//! The parent validates the requested policy and probes kernel support before
//! any spawn (fail-closed: an unenforceable request refuses the service rather
//! than running it unprotected). The child applies the enforcement between
//! `fork` and `exec` using only the prepared plan, in a fixed order:
//! `no_new_privs` -> Landlock -> seccomp. Filesystem paths are opened in the
//! parent (their `O_PATH` descriptors carried into the child) and the seccomp
//! `BpfProgram` is compiled in the parent.
//!
//! A child-side failure cannot return a message: Rust's exec handshake carries
//! only an errno, so the SG identity would be lost. `SandboxFault` therefore
//! has a one-byte wire form the child writes to a dedicated pipe before it
//! fails, and the parent turns back into a typed diagnostic. Those live in
//! [`crate::childfault`].
#[cfg(target_os = "linux")]
mod imp {
use std::{io, path::PathBuf};
use landlock::{
ABI, Access, AccessFs, PathBeneath, PathFd, RestrictionStatus, Ruleset,
RulesetAttr, RulesetCreatedAttr, RulesetStatus,
};
use crate::{
childfault::{ApplyFault, ChildFault, PrepareFault},
config::LandlockConfig,
};
/// A validated, kernel-supported sandbox plan built in the parent. The
/// path `PathFd`s own their descriptors and are carried into the child, so
/// the child does no path resolution and the ruleset is rebuilt from the
/// prepared fds immediately before `exec`.
#[derive(Debug)]
pub struct SandboxPlan {
landlock: Option<LandlockPlan>,
seccomp: Option<seccompiler::BpfProgram>,
}
#[derive(Debug)]
struct LandlockPlan {
ro: Vec<PathFd>,
rw: Vec<PathFd>,
}
impl SandboxPlan {
/// Builds and validates the plan for a service. Returns an error (to
/// refuse the spawn) when a requested control cannot be enforced on the
/// running kernel — the fail-closed contract.
pub fn prepare(
landlock: Option<&LandlockConfig>,
seccomp: Option<&str>,
) -> Result<Self, PrepareFault> {
let landlock = match landlock {
Some(cfg) if !cfg.ro_paths.is_empty() || !cfg.rw_paths.is_empty() => {
Some(LandlockPlan::prepare(cfg)?)
}
_ => None,
};
let seccomp = match seccomp {
Some(profile) if !profile.is_empty() => {
Some(build_seccomp_program(profile)?)
}
_ => None,
};
Ok(Self { landlock, seccomp })
}
/// Whether this plan enforces anything.
pub fn is_empty(&self) -> bool {
self.landlock.is_none() && self.seccomp.is_none()
}
/// Applies the plan in the child, in fixed order: no_new_privs →
/// Landlock → seccomp. seccomp goes last because it can forbid the very
/// syscalls Landlock setup needs. Must run after the UID/GID switch and
/// capability trimming, immediately before `exec`.
///
/// # Safety
/// Call only between `fork` and `exec` in the child. The error path
/// allocates nothing, so a failure can be reported without violating
/// async-signal-safety.
pub unsafe fn apply(&self) -> Result<(), ApplyFault> {
if unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) } != 0 {
return Err(ApplyFault::last(ChildFault::NoNewPrivs));
}
if let Some(plan) = &self.landlock {
plan.apply()
.map_err(|_| ApplyFault::last(ChildFault::Landlock))?;
}
if let Some(program) = &self.seccomp {
seccompiler::apply_filter(program)
.map_err(|_| ApplyFault::last(ChildFault::SeccompFilter))?;
}
Ok(())
}
}
impl LandlockPlan {
fn prepare(cfg: &LandlockConfig) -> Result<Self, PrepareFault> {
let open = |paths: &[PathBuf]| -> io::Result<Vec<PathFd>> {
paths
.iter()
.map(|p| {
PathFd::new(p).map_err(|e| {
io::Error::new(
io::ErrorKind::NotFound,
format!(
"landlock path '{}' could not be opened: {e}",
p.display()
),
)
})
})
.collect()
};
// Probe kernel Landlock support in the PARENT: a child pre_exec
// failure only surfaces a bare errno (EINVAL/ENOSYS), losing the
// SG0724 identity. Detecting it here refuses the spawn with a clear
// message instead. landlock_create_ruleset with the version-probe
// flag returns the ABI version, or -1/ENOSYS when unsupported.
const LANDLOCK_CREATE_RULESET: libc::c_long = 444;
const LANDLOCK_CREATE_RULESET_VERSION: libc::c_ulong = 1;
let abi = unsafe {
libc::syscall(
LANDLOCK_CREATE_RULESET,
std::ptr::null::<libc::c_void>(),
0usize,
LANDLOCK_CREATE_RULESET_VERSION,
)
};
if abi < 0 {
return Err(PrepareFault::new(
ChildFault::Landlock,
"landlock is not available on this kernel (needs Linux 5.13+); schema v3 refuses the service rather than run it unconfined",
));
}
let landlock =
|e: io::Error| PrepareFault::new(ChildFault::Landlock, e.to_string());
let plan = Self {
ro: open(&cfg.ro_paths).map_err(landlock)?,
rw: open(&cfg.rw_paths).map_err(landlock)?,
};
// Also build the ruleset once so a malformed policy fails here.
plan.build_ruleset().map_err(landlock)?;
Ok(plan)
}
/// Builds the ruleset without formatting any error, so the child can
/// call it without allocating. The parent uses [`Self::build_ruleset`]
/// for the same work with a readable message.
fn build_ruleset_raw(
&self,
) -> Result<landlock::RulesetCreated, landlock::RulesetError> {
let abi = ABI::V1;
let ro_access = AccessFs::from_read(abi);
let rw_access = AccessFs::from_all(abi);
let mut ruleset = Ruleset::default()
.handle_access(AccessFs::from_all(abi))?
.create()?;
for fd in &self.ro {
ruleset = ruleset.add_rule(PathBeneath::new(fd, ro_access))?;
}
for fd in &self.rw {
ruleset = ruleset.add_rule(PathBeneath::new(fd, rw_access))?;
}
Ok(ruleset)
}
fn build_ruleset(&self) -> io::Result<landlock::RulesetCreated> {
self.build_ruleset_raw().map_err(to_io)
}
/// Applies the ruleset in the child.
///
/// # Safety
/// Runs between `fork` and `exec`, so nothing here may allocate. The
/// error paths deliberately discard the underlying error rather than
/// format it, and report `errno` only where a syscall actually set it.
fn apply(&self) -> Result<(), ApplyFault> {
let ruleset = self
.build_ruleset_raw()
.map_err(|_| ApplyFault::last(ChildFault::Landlock))?;
let status: RestrictionStatus = ruleset
.restrict_self()
.map_err(|_| ApplyFault::last(ChildFault::Landlock))?;
match status.ruleset {
RulesetStatus::FullyEnforced => Ok(()),
// Not a syscall failure, so `errno` would be stale: report none.
RulesetStatus::PartiallyEnforced | RulesetStatus::NotEnforced => {
Err(ApplyFault {
fault: ChildFault::Landlock,
errno: 0,
})
}
}
}
}
fn to_io<E: std::fmt::Display>(e: E) -> io::Error {
io::Error::new(io::ErrorKind::Unsupported, format!("landlock: {e}"))
}
/// The target architecture for seccomp filter compilation. seccomp filters
/// are architecture-specific (the syscall ABI differs), so the wrong arch
/// would silently mismatch every rule.
fn target_arch() -> Result<seccompiler::TargetArch, PrepareFault> {
#[cfg(target_arch = "x86_64")]
{
Ok(seccompiler::TargetArch::x86_64)
}
#[cfg(target_arch = "aarch64")]
{
Ok(seccompiler::TargetArch::aarch64)
}
#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
{
Err(PrepareFault::new(
ChildFault::SeccompArch,
"seccomp is only supported on x86_64 and aarch64",
))
}
}
/// Builds the BPF program for a named seccomp profile in the PARENT, so a
/// bad profile or unsupported arch refuses the spawn before fork. Only
/// versioned built-ins are accepted — never a mutable `default`/`strict`
/// alias whose meaning could drift under a manifest.
fn build_seccomp_program(
profile: &str,
) -> Result<seccompiler::BpfProgram, PrepareFault> {
use std::collections::BTreeMap;
use seccompiler::{SeccompAction, SeccompFilter};
let allow = match profile {
"baseline-v1" => baseline_v1_syscalls(),
other => {
return Err(PrepareFault::new(
ChildFault::SeccompProfile,
format!(
"unknown seccomp profile '{other}'; the only built-in is 'baseline-v1'"
),
));
}
};
let rules: BTreeMap<i64, Vec<seccompiler::SeccompRule>> =
allow.iter().map(|nr| (*nr, Vec::new())).collect();
let filter = SeccompFilter::new(
rules,
// Deny-by-default: unlisted syscalls return EPERM rather than
// killing the process, so a service degrades visibly instead of
// vanishing.
SeccompAction::Errno(libc::EPERM as u32),
SeccompAction::Allow,
target_arch()?,
)
.map_err(|e| {
PrepareFault::new(
ChildFault::SeccompFilter,
format!("seccomp filter could not be built: {e}"),
)
})?;
seccompiler::BpfProgram::try_from(filter).map_err(|e| {
PrepareFault::new(
ChildFault::SeccompFilter,
format!("seccomp filter could not be compiled: {e}"),
)
})
}
/// The `baseline-v1` allowlist: syscalls a typical long-running service
/// needs (file and socket I/O, memory, threads, signals, time, exec). This
/// list is FROZEN — a stricter or different policy ships as `baseline-v2`,
/// never as an edit here, so a manifest's guarantee cannot change under it.
fn baseline_v1_syscalls() -> Vec<i64> {
use libc::*;
let v: Vec<i64> = [
// process / exec (portable across x86_64 and aarch64)
SYS_execve,
SYS_exit,
SYS_exit_group,
SYS_wait4,
SYS_clone,
SYS_getpid,
SYS_getppid,
SYS_gettid,
SYS_set_tid_address,
SYS_set_robust_list,
SYS_prctl,
// memory
SYS_brk,
SYS_mmap,
SYS_munmap,
SYS_mprotect,
SYS_mremap,
SYS_madvise,
SYS_rt_sigaction,
SYS_rt_sigprocmask,
SYS_rt_sigreturn,
SYS_sigaltstack,
// files
SYS_openat,
SYS_read,
SYS_write,
SYS_readv,
SYS_writev,
SYS_pread64,
SYS_pwrite64,
SYS_close,
SYS_lseek,
SYS_fstat,
SYS_newfstatat,
SYS_statx,
SYS_fcntl,
SYS_ioctl,
SYS_getdents64,
SYS_readlinkat,
SYS_dup,
SYS_dup3,
SYS_pipe2,
SYS_fsync,
SYS_ftruncate,
SYS_faccessat,
// sockets / net
SYS_socket,
SYS_connect,
SYS_accept4,
SYS_bind,
SYS_listen,
SYS_sendto,
SYS_recvfrom,
SYS_sendmsg,
SYS_recvmsg,
SYS_shutdown,
SYS_getsockname,
SYS_getpeername,
SYS_getsockopt,
SYS_setsockopt,
SYS_ppoll,
SYS_epoll_create1,
SYS_epoll_ctl,
SYS_epoll_pwait,
// time / sched
SYS_clock_gettime,
SYS_clock_nanosleep,
SYS_nanosleep,
SYS_sched_yield,
SYS_futex,
SYS_getrandom,
SYS_uname,
SYS_sysinfo,
// identity (post-drop reads)
SYS_getuid,
SYS_geteuid,
SYS_getgid,
SYS_getegid,
SYS_getcwd,
]
.into_iter()
.collect();
// Syscalls present only on x86_64 (aarch64 dropped the legacy
// multiplexed/`arch_prctl` forms in favour of clone/ppoll/epoll_pwait).
// Extend through a same-arch closure so neither the mutation nor the
// `mut` binding exists on aarch64 (no unused-mut / dead-return lint).
#[cfg(target_arch = "x86_64")]
let v = {
let mut v = v;
v.extend([
SYS_fork,
SYS_vfork,
SYS_arch_prctl,
SYS_poll,
SYS_epoll_wait,
SYS_gettimeofday,
]);
v
};
v
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn baseline_v1_builds_a_nonempty_program() {
let program =
build_seccomp_program("baseline-v1").expect("baseline-v1 must compile");
assert!(!program.is_empty());
}
#[test]
fn unknown_profile_is_refused() {
let err = build_seccomp_program("strict")
.expect_err("only baseline-v1 is a built-in");
assert_eq!(err.fault, ChildFault::SeccompProfile);
assert_eq!(err.fault.code(), crate::diag::SgCode::SeccompProfileUnknown);
assert!(err.to_string().contains("baseline-v1"));
}
#[test]
fn baseline_v1_denies_chmod() {
// chmod-family syscalls must NOT be in the allowlist.
let allow = baseline_v1_syscalls();
assert!(!allow.contains(&libc::SYS_fchmodat));
assert!(allow.contains(&libc::SYS_openat));
}
#[test]
fn prepare_seccomp_only_is_not_empty() {
let plan = SandboxPlan::prepare(None, Some("baseline-v1"))
.expect("seccomp-only plan prepares");
assert!(!plan.is_empty());
}
}
}
#[cfg(target_os = "linux")]
pub use imp::SandboxPlan;
#[cfg(not(target_os = "linux"))]
mod stub {
use crate::{
childfault::{ApplyFault, ChildFault, PrepareFault},
config::LandlockConfig,
};
/// Non-Linux stub: sandboxing is unsupported. `prepare` refuses any
/// effective request so callers fail closed under schema v3.
#[derive(Debug)]
pub struct SandboxPlan;
impl SandboxPlan {
/// Refuses any effective sandbox request on non-Linux, so schema-v3
/// services fail closed rather than run unconfined.
pub fn prepare(
landlock: Option<&LandlockConfig>,
seccomp: Option<&str>,
) -> Result<Self, PrepareFault> {
let requested = landlock
.is_some_and(|c| !c.ro_paths.is_empty() || !c.rw_paths.is_empty())
|| seccomp.is_some_and(|s| !s.is_empty());
if requested {
return Err(PrepareFault::new(
ChildFault::KeyUnenforceable,
"kernel-enforced sandboxing is only available on Linux",
));
}
Ok(Self)
}
/// Always true off Linux: nothing is enforced.
pub fn is_empty(&self) -> bool {
true
}
/// # Safety
/// No-op; safe to call, present for API parity with the Linux path.
pub unsafe fn apply(&self) -> Result<(), ApplyFault> {
Ok(())
}
}
}
#[cfg(not(target_os = "linux"))]
pub use stub::SandboxPlan;