1use nix::libc;
5use std::{fmt, io};
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum Landlock {
10 Abi(u8),
12 Unavailable,
14}
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub struct Layers {
20 pub landlock: Landlock,
21}
22
23impl fmt::Display for Layers {
24 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25 f.write_str("non-dumpable, ")?;
26 match self.landlock {
27 Landlock::Abi(abi) => write!(f, "Landlock ABI v{abi}")?,
28 Landlock::Unavailable => f.write_str("Landlock unavailable")?,
29 }
30 f.write_str(", seccomp allow-list")
31 }
32}
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum Layer {
37 NonDumpable,
38 Landlock,
39 AllowList,
40}
41
42impl fmt::Display for Layer {
43 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44 f.write_str(match self {
45 Layer::NonDumpable => "non-dumpable",
46 Layer::Landlock => "Landlock",
47 Layer::AllowList => "seccomp allow-list",
48 })
49 }
50}
51
52#[derive(Debug, thiserror::Error)]
55#[error("{layer}: {source}")]
56pub struct ConfineError {
57 pub layer: Layer,
58 #[source]
59 pub source: io::Error,
60}
61
62pub fn confine() -> Result<Layers, ConfineError> {
69 let at = |layer| move |source| ConfineError { layer, source };
70 settle_malloc().map_err(at(Layer::AllowList))?;
74 prctl(libc::PR_SET_DUMPABLE, 0).map_err(at(Layer::NonDumpable))?;
75 prctl(libc::PR_SET_NO_NEW_PRIVS, 1)
79 .map_err(|error| io::Error::new(error.kind(), format!("no_new_privs: {error}")))
80 .map_err(at(Layer::AllowList))?;
81 let landlock = landlock().map_err(at(Layer::Landlock))?;
82 allow_list().map_err(at(Layer::AllowList))?;
83 Ok(Layers { landlock })
84}
85
86#[cfg(target_env = "gnu")]
89const TRIM_THRESHOLD: usize = 128 * 1024;
90
91#[cfg(target_env = "gnu")]
94const WARM_UP_BLOCK: usize = 16 * 1024;
95
96#[cfg(target_env = "gnu")]
104fn settle_malloc() -> io::Result<()> {
105 let cpus = cpus_in_affinity_mask().unwrap_or_else(|| {
110 usize::try_from(unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) }).unwrap_or(1)
112 });
113 let arenas = libc::c_int::try_from(cpus.saturating_mul(8)).unwrap_or(libc::c_int::MAX);
114 let trim = libc::c_int::try_from(TRIM_THRESHOLD).expect("the threshold fits");
117 for (option, value) in [(libc::M_ARENA_MAX, arenas), (libc::M_TRIM_THRESHOLD, trim)] {
118 if unsafe { libc::mallopt(option, value) } != 1 {
121 return Err(io::Error::other(format!("malloc refused option {option}")));
122 }
123 }
124 std::thread::Builder::new()
125 .spawn(|| {
126 let blocks: Vec<Vec<u8>> = (0..8 * TRIM_THRESHOLD / WARM_UP_BLOCK)
127 .map(|_| vec![1; WARM_UP_BLOCK])
128 .collect();
129 drop(std::hint::black_box(blocks));
130 })?
131 .join()
132 .map_err(|_| io::Error::other("the malloc warm-up thread panicked"))
133}
134
135#[cfg(target_env = "gnu")]
137fn cpus_in_affinity_mask() -> Option<usize> {
138 let mut set: libc::cpu_set_t = unsafe { std::mem::zeroed() };
140 if unsafe { libc::sched_getaffinity(0, std::mem::size_of_val(&set), &mut set) } != 0 {
142 return None;
143 }
144 let count = unsafe { libc::CPU_COUNT(&set) };
146 usize::try_from(count).ok().filter(|&count| count > 0)
147}
148
149#[cfg(not(target_env = "gnu"))]
151fn settle_malloc() -> io::Result<()> {
152 Ok(())
153}
154
155fn check(result: libc::c_long) -> io::Result<libc::c_long> {
156 if result < 0 {
157 Err(io::Error::last_os_error())
158 } else {
159 Ok(result)
160 }
161}
162
163fn prctl(option: libc::c_int, value: libc::c_ulong) -> io::Result<()> {
164 check(unsafe { libc::prctl(option, value, 0, 0, 0) }.into()).map(drop)
166}
167
168const LANDLOCK_ABI: u8 = 7;
171
172#[repr(C)]
173struct RulesetAttr {
174 handled_access_fs: u64,
175 handled_access_net: u64,
176 scoped: u64,
177}
178
179fn landlock() -> io::Result<Landlock> {
183 const VERSION: u32 = 1;
184 let abi = match check(unsafe {
186 libc::syscall(
187 libc::SYS_landlock_create_ruleset,
188 std::ptr::null::<RulesetAttr>(),
189 0usize,
190 VERSION,
191 )
192 }) {
193 Ok(abi) => abi.min(LANDLOCK_ABI.into()) as u8,
194 Err(error)
199 if matches!(
200 error.raw_os_error(),
201 Some(libc::ENOSYS | libc::EOPNOTSUPP | libc::EPERM)
202 ) =>
203 {
204 return Ok(Landlock::Unavailable);
205 }
206 Err(error) => return Err(error),
207 };
208 let attr = RulesetAttr {
209 handled_access_fs: match abi {
212 1 => 0x1fff,
213 2 => 0x3fff,
214 3 | 4 => 0x7fff,
215 _ => 0xffff,
216 },
217 handled_access_net: if abi >= 4 { 0b11 } else { 0 },
218 scoped: if abi >= 6 { 0b11 } else { 0 },
219 };
220 let size: usize = match abi {
222 ..4 => 8,
223 4 | 5 => 16,
224 _ => 24,
225 };
226 let ruleset =
228 check(unsafe { libc::syscall(libc::SYS_landlock_create_ruleset, &attr, size, 0u32) })?
229 as libc::c_int;
230 let restricted =
232 check(unsafe { libc::syscall(libc::SYS_landlock_restrict_self, ruleset, 0u32) });
233 unsafe { libc::close(ruleset) };
234 restricted?;
235 Ok(Landlock::Abi(abi))
236}
237
238#[cfg(target_arch = "x86_64")]
239const AUDIT_ARCH: u32 = 0xC000_003E;
240#[cfg(target_arch = "aarch64")]
241const AUDIT_ARCH: u32 = 0xC000_00B7;
242
243const ALLOWED: &[libc::c_long] = &[
245 libc::SYS_recvmsg,
247 libc::SYS_recvfrom,
248 libc::SYS_read,
249 libc::SYS_write,
250 libc::SYS_writev,
251 libc::SYS_close,
252 libc::SYS_shutdown,
253 libc::SYS_setsockopt,
254 libc::SYS_epoll_create1,
255 libc::SYS_epoll_ctl,
256 libc::SYS_epoll_pwait,
257 #[cfg(target_arch = "x86_64")]
258 libc::SYS_epoll_wait,
259 libc::SYS_eventfd2,
260 libc::SYS_set_robust_list,
262 libc::SYS_rseq,
263 libc::SYS_futex,
264 libc::SYS_sigaltstack,
265 libc::SYS_rt_sigprocmask,
266 libc::SYS_rt_sigaction,
268 libc::SYS_rt_sigreturn,
271 libc::SYS_sched_yield,
272 libc::SYS_sched_getaffinity,
274 libc::SYS_restart_syscall,
275 libc::SYS_mmap,
277 libc::SYS_munmap,
278 libc::SYS_mprotect,
279 libc::SYS_mremap,
280 libc::SYS_madvise,
281 libc::SYS_brk,
282 libc::SYS_getrandom,
284 libc::SYS_clock_gettime,
285 libc::SYS_exit,
287 libc::SYS_exit_group,
288 libc::SYS_getpid,
289 libc::SYS_gettid,
290];
291
292const DATA_NR: u32 = 0;
294const DATA_ARCH: u32 = 4;
295const DATA_ARG0: u32 = 16;
296const DATA_ARG1: u32 = 24;
297const DATA_ARG4: u32 = 48;
298
299enum Test<'a> {
301 OneOf(&'a [u32]),
303 Bit(u32),
305}
306
307fn allow_list() -> io::Result<()> {
310 const LOAD: u16 = (libc::BPF_LD | libc::BPF_W | libc::BPF_ABS) as u16;
311 const EQUAL: u16 = (libc::BPF_JMP | libc::BPF_JEQ | libc::BPF_K) as u16;
312 const BIT_SET: u16 = (libc::BPF_JMP | libc::BPF_JSET | libc::BPF_K) as u16;
313 const RETURN: u16 = (libc::BPF_RET | libc::BPF_K) as u16;
314 let op = |code, k, jt, jf| libc::sock_filter { code, jt, jf, k };
315 let allow = op(RETURN, libc::SECCOMP_RET_ALLOW, 0, 0);
316 let kill = op(RETURN, libc::SECCOMP_RET_KILL_PROCESS, 0, 0);
317 let number = |nr: libc::c_long| nr as u32;
318
319 let mut filter = vec![
320 op(LOAD, DATA_ARCH, 0, 0),
322 op(EQUAL, AUDIT_ARCH, 1, 0),
323 kill,
324 op(LOAD, DATA_NR, 0, 0),
325 ];
326 #[cfg(target_arch = "x86_64")]
328 filter.extend([
329 op(
330 (libc::BPF_JMP | libc::BPF_JGE | libc::BPF_K) as u16,
331 0x4000_0000,
332 0,
333 1,
334 ),
335 kill,
336 ]);
337 filter.extend([
342 op(EQUAL, number(libc::SYS_clone3), 0, 1),
343 op(RETURN, libc::SECCOMP_RET_ERRNO | libc::ENOSYS as u32, 0, 0),
344 ]);
345 for nr in ALLOWED {
346 filter.extend([op(EQUAL, number(*nr), 0, 1), allow]);
347 }
348 let own_pid = [std::process::id()];
352 let conditional: [(libc::c_long, &[(u32, Test)]); 7] = [
353 (libc::SYS_kill, &[(DATA_ARG0, Test::OneOf(&own_pid))]),
355 (libc::SYS_tgkill, &[(DATA_ARG0, Test::OneOf(&own_pid))]),
356 (
359 libc::SYS_fcntl,
360 &[(
361 DATA_ARG1,
362 Test::OneOf(&[
363 libc::F_DUPFD_CLOEXEC as u32,
364 libc::F_GETFD as u32,
365 libc::F_GETFL as u32,
366 ]),
367 )],
368 ),
369 (
372 libc::SYS_clone,
373 &[(DATA_ARG0, Test::Bit(libc::CLONE_THREAD as u32))],
374 ),
375 (
378 libc::SYS_socketpair,
379 &[(DATA_ARG0, Test::OneOf(&[libc::AF_UNIX as u32]))],
380 ),
381 (
383 libc::SYS_ioctl,
384 &[(DATA_ARG1, Test::OneOf(&[libc::FIONBIO as u32]))],
385 ),
386 (
389 libc::SYS_sendto,
390 &[
391 (DATA_ARG4, Test::OneOf(&[0])),
392 (DATA_ARG4 + 4, Test::OneOf(&[0])),
393 ],
394 ),
395 ];
396 for (nr, tests) in conditional {
397 let mut block = Vec::new();
398 for (word, test) in tests {
399 block.push(op(LOAD, *word, 0, 0));
400 match test {
401 Test::OneOf(values) => {
402 for (tried, value) in values.iter().enumerate() {
404 block.push(op(EQUAL, *value, (values.len() - tried) as u8, 0));
405 }
406 }
407 Test::Bit(bit) => block.push(op(BIT_SET, *bit, 1, 0)),
408 }
409 block.push(kill);
410 }
411 block.push(allow);
412 filter.push(op(EQUAL, number(nr), 0, block.len() as u8));
415 filter.extend(block);
416 }
417 filter.push(kill);
418
419 let program = libc::sock_fprog {
420 len: filter.len() as u16,
421 filter: filter.as_mut_ptr(),
422 };
423 check(
426 unsafe {
427 libc::prctl(
428 libc::PR_SET_SECCOMP,
429 libc::SECCOMP_MODE_FILTER,
430 &program as *const libc::sock_fprog,
431 )
432 }
433 .into(),
434 )
435 .map(drop)
436}