Debian Codegraph @

src/exec/noexec.rs

raw symbols SCIP
1 // On Linux we can use a seccomp() filter to disable exec.
2 #![allow(non_upper_case_globals)]
3 #![cfg_attr(not(target_arch = "x86_64"), allow(unused))]
4
5 use std::alloc::{GlobalAlloc, Layout, handle_alloc_error};
6 use std::ffi::{c_int, c_uint, c_ulong, c_void};
7 use std::mem::{align_of, offset_of, size_of, zeroed};
8 use std::os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, OwnedFd};
9 use std::os::unix::net::UnixStream;
10 use std::os::unix::process::CommandExt;
11 use std::process::Command;
12 use std::ptr::{self, addr_of};
13 use std::{cmp, io, thread};
14
15 use libc::{
16 __errno_location, BPF_ABS, BPF_ALU, BPF_AND, BPF_JEQ, BPF_JMP, BPF_JUMP, BPF_K, BPF_LD,
17 BPF_RET, BPF_STMT, BPF_W, CMSG_DATA, CMSG_FIRSTHDR, CMSG_LEN, CMSG_SPACE, EACCES, ENOENT,
18 MSG_TRUNC, PR_SET_NO_NEW_PRIVS, SCM_RIGHTS, SECCOMP_FILTER_FLAG_NEW_LISTENER,
19 SECCOMP_GET_NOTIF_SIZES, SECCOMP_RET_ALLOW, SECCOMP_RET_KILL_PROCESS, SECCOMP_SET_MODE_FILTER,
20 SECCOMP_USER_NOTIF_FLAG_CONTINUE, SOL_SOCKET, SYS_execve, SYS_execveat, SYS_seccomp, cmsghdr,
21 iovec, msghdr, prctl, recvmsg, seccomp_data, seccomp_notif, seccomp_notif_resp,
22 seccomp_notif_sizes, sendmsg, sock_filter, sock_fprog, syscall,
23 };
24
25 const SECCOMP_RET_USER_NOTIF: c_uint = 0x7fc00000;
26 const SECCOMP_IOCTL_NOTIF_RECV: c_ulong = 0xc0502100;
27 const SECCOMP_IOCTL_NOTIF_SEND: c_ulong = 0xc0182101;
28
29 // from /usr/include/linux/audit.h, converted using bindgen
30 const __AUDIT_ARCH_64BIT: u32 = 0x80000000;
31 const __AUDIT_ARCH_LE: u32 = 0x40000000;
32
33 const AUDIT_ARCH_AARCH64: u32 = libc::EM_AARCH64 as u32 | __AUDIT_ARCH_64BIT | __AUDIT_ARCH_LE;
34 const AUDIT_ARCH_ARM: u32 = libc::EM_ARM as u32 | __AUDIT_ARCH_LE;
35 const AUDIT_ARCH_I386: u32 = libc::EM_386 as u32 | __AUDIT_ARCH_LE;
36 const AUDIT_ARCH_MIPS: u32 = libc::EM_MIPS as u32;
37 const AUDIT_ARCH_MIPSEL: u32 = libc::EM_MIPS as u32 | __AUDIT_ARCH_LE;
38 const AUDIT_ARCH_MIPS64: u32 = libc::EM_MIPS as u32 | __AUDIT_ARCH_64BIT;
39 const AUDIT_ARCH_MIPSEL64: u32 = libc::EM_MIPS as u32 | __AUDIT_ARCH_64BIT | __AUDIT_ARCH_LE;
40 const AUDIT_ARCH_PPC: u32 = libc::EM_PPC as u32;
41 const AUDIT_ARCH_PPC64: u32 = libc::EM_PPC64 as u32 | __AUDIT_ARCH_64BIT;
42 const AUDIT_ARCH_PPC64LE: u32 = libc::EM_PPC64 as u32 | __AUDIT_ARCH_64BIT | __AUDIT_ARCH_LE;
43 const AUDIT_ARCH_RISCV32: u32 = libc::EM_RISCV as u32 | __AUDIT_ARCH_LE;
44 const AUDIT_ARCH_RISCV64: u32 = libc::EM_RISCV as u32 | __AUDIT_ARCH_64BIT | __AUDIT_ARCH_LE;
45 const AUDIT_ARCH_S390X: u32 = libc::EM_S390 as u32 | __AUDIT_ARCH_64BIT;
46 const AUDIT_ARCH_X86_64: u32 = libc::EM_X86_64 as u32 | __AUDIT_ARCH_64BIT | __AUDIT_ARCH_LE;
47
48 /// # Safety
49 ///
50 /// You must follow the rules the Linux man page specifies for the chosen
51 /// seccomp operation.
52 unsafe fn seccomp<T>(operation: c_uint, flags: c_uint, args: *mut T) -> c_int {
53 // SAFETY: By function invariant.
54 unsafe { syscall(SYS_seccomp, operation, flags, args) as c_int }
55 }
56
57 struct NotifyAllocs {
58 req: *mut seccomp_notif,
59 req_size: usize,
60 resp: *mut seccomp_notif_resp,
61 }
62
63 /// Linux reserves the right to demand the memory for an object of type T
64 /// to be over-allocated; this function ensures that happens.
65 fn alloc_dynamic<T>(runtime_size: u16) -> (*mut T, usize) {
66 const {
67 assert!(size_of::<T>() > 0);
68 }
69
70 let layout = Layout::from_size_align(
71 cmp::max(runtime_size.into(), size_of::<T>()),
72 align_of::<seccomp_notif>(),
73 )
74 .unwrap();
75
76 // SAFETY: We assert that T is bigger than 0 bytes and as such the computed layout is also
77 // bigger.
78 let ptr = unsafe { std::alloc::System.alloc_zeroed(layout).cast::<T>() };
79 if ptr.is_null() {
80 handle_alloc_error(layout);
81 }
82
83 (ptr, layout.size())
84 }
85
86 fn alloc_notify_allocs() -> NotifyAllocs {
87 let mut sizes = seccomp_notif_sizes {
88 seccomp_notif: 0,
89 seccomp_notif_resp: 0,
90 seccomp_data: 0,
91 };
92 // SAFETY: A valid seccomp_notif_sizes pointer is passed in
93 if unsafe { seccomp(SECCOMP_GET_NOTIF_SIZES, 0, &mut sizes) } == -1 {
94 panic!(
95 "failed to get sizes for seccomp unotify data structures: {}",
96 io::Error::last_os_error(),
97 );
98 }
99
100 let (req, req_size) = alloc_dynamic::<seccomp_notif>(sizes.seccomp_notif);
101 let (resp, _) = alloc_dynamic::<seccomp_notif_resp>(sizes.seccomp_notif_resp);
102
103 NotifyAllocs {
104 req,
105 req_size,
106 resp,
107 }
108 }
109
110 /// Returns 'None' if the ioctl failed with E_NOENT, 'Some(())' if it succeeded.
111 /// This aborts the program in any other situation.
112 ///
113 /// # Safety
114 ///
115 /// `ioctl(fd, request, ptr)` must be safe to call
116 unsafe fn ioctl<T>(fd: BorrowedFd, request: c_ulong, ptr: *mut T) -> Option<()> {
117 // SAFETY: By function contract
118 if unsafe { libc::ioctl(fd.as_raw_fd(), request as _, ptr) } == -1 {
119 // SAFETY: Trivial
120 if unsafe { *__errno_location() } == ENOENT {
121 None
122 } else {
123 // SAFETY: Not actually unsafe
124 unsafe {
125 libc::abort();
126 }
127 }
128 } else {
129 Some(())
130 }
131 }
132
133 /// # Safety
134 ///
135 /// The argument must be a valid seccomp_unotify fd.
136 unsafe fn handle_notifications(notify_fd: OwnedFd) -> ! {
137 let NotifyAllocs {
138 req,
139 req_size,
140 resp,
141 } = alloc_notify_allocs();
142
143 // SAFETY: See individual SAFETY comments
144 let handle_syscall = |create_response: fn(&mut _)| unsafe {
145 // SECCOMP_IOCTL_NOTIF_RECV expects the target struct to be zeroed
146 // SAFETY: req is at least req_size bytes big.
147 std::ptr::write_bytes(req.cast::<u8>(), 0, req_size);
148
149 // SAFETY: A valid pointer to a seccomp_notify is passed in; notify_fd is valid.
150 ioctl(notify_fd.as_fd(), SECCOMP_IOCTL_NOTIF_RECV, req)?;
151
152 // Allow the first execve call as this is sudo itself starting the target executable.
153 // SAFETY: resp is a valid pointer to a seccomp_notify_resp.
154 (*resp).id = (*req).id;
155 create_response(&mut *resp);
156
157 // SAFETY: A valid pointer to a seccomp_notify_resp is passed in; notify_fd is valid.
158 ioctl(notify_fd.as_fd(), SECCOMP_IOCTL_NOTIF_SEND, resp)
159 };
160
161 loop {
162 if handle_syscall(|resp| {
163 resp.val = 0;
164 resp.error = 0;
165 resp.flags = SECCOMP_USER_NOTIF_FLAG_CONTINUE as _
166 })
167 .is_some()
168 {
169 break;
170 }
171 }
172
173 loop {
174 handle_syscall(|resp| {
175 resp.val = 0;
176 resp.error = -EACCES;
177 resp.flags = 0;
178 });
179 }
180 }
181
182 //We must use vectored reads with ancillary data.
183 //
184 //NOTE: some day we can witch to using send/recv_vectored_with_ancillary; see:
185 // - https://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.recv_vectored_with_ancillary
186 // - https://doc.rust-lang.org/std/os/unix/net/struct.UnixDatagram.html#method.send_vectored_with_ancillary
187 // but this is (at the time of writing) unstable.
188
189 #[repr(C)]
190 union SingleRightAnciliaryData {
191 // SAFETY: Not actually unsafe
192 buf: [u8; unsafe { CMSG_SPACE(size_of::<c_int>() as u32) as usize }],
193 _align: cmsghdr,
194 }
195
196 /// Receives a raw file descriptor from the provided UnixStream
197 fn receive_fd(rx_fd: UnixStream) -> OwnedFd {
198 let mut data = [0u8; 1];
199 let mut iov = iovec {
200 iov_base: &mut data as *mut [u8; 1] as *mut c_void,
201 iov_len: 1,
202 };
203
204 // SAFETY: msghdr can be zero-initialized
205 let mut msg: msghdr = unsafe { zeroed() };
206 msg.msg_name = ptr::null_mut();
207 msg.msg_namelen = 0;
208 msg.msg_iov = &mut iov;
209 msg.msg_iovlen = 1;
210
211 // SAFETY: SingleRightAnciliaryData can be zero-initialized.
212 let mut control: SingleRightAnciliaryData = unsafe { zeroed() };
213 // SAFETY: The buf field is valid when zero-initialized.
214 msg.msg_controllen = unsafe { control.buf.len() as _ };
215 msg.msg_control = &mut control as *mut _ as *mut c_void;
216
217 // SAFETY: A valid socket fd and a valid initialized msghdr are passed in.
218 if unsafe { recvmsg(rx_fd.as_raw_fd(), &mut msg, 0) } == -1 {
219 panic!("failed to recvmsg: {}", io::Error::last_os_error());
220 }
221
222 if msg.msg_flags & MSG_TRUNC == MSG_TRUNC {
223 unreachable!("unexpected internal error in seccomp filter");
224 }
225
226 // SAFETY: The kernel correctly initializes everything on recvmsg for this to be safe.
227 unsafe {
228 let cmsgp = CMSG_FIRSTHDR(&msg);
229 if cmsgp.is_null()
230 || (*cmsgp).cmsg_len != CMSG_LEN(size_of::<c_int>() as u32) as _
231 || (*cmsgp).cmsg_level != SOL_SOCKET
232 || (*cmsgp).cmsg_type != SCM_RIGHTS
233 {
234 unreachable!("unexpected response from Linux kernel");
235 }
236 OwnedFd::from_raw_fd(CMSG_DATA(cmsgp).cast::<c_int>().read())
237 }
238 }
239
240 fn send_fd(tx_fd: UnixStream, notify_fd: OwnedFd) -> io::Result<()> {
241 let mut data = [0u8; 1];
242 let mut iov = iovec {
243 iov_base: &mut data as *mut [u8; 1] as *mut c_void,
244 iov_len: 1,
245 };
246
247 // SAFETY: msghdr can be zero-initialized
248 let mut msg: msghdr = unsafe { zeroed() };
249 msg.msg_name = ptr::null_mut();
250 msg.msg_namelen = 0;
251 msg.msg_iov = &mut iov;
252 msg.msg_iovlen = 1;
253
254 // SAFETY: SingleRightAnciliaryData can be zero-initialized.
255 let mut control: SingleRightAnciliaryData = unsafe { zeroed() };
256 // SAFETY: The buf field is valid when zero-initialized.
257 msg.msg_controllen = unsafe { control.buf.len() as _ };
258 msg.msg_control = &mut control as *mut _ as *mut _;
259 // SAFETY: msg.msg_control is correctly initialized and this follows
260 // the contract of the various CMSG_* macros.
261 unsafe {
262 let cmsgp = CMSG_FIRSTHDR(&msg);
263 (*cmsgp).cmsg_level = SOL_SOCKET;
264 (*cmsgp).cmsg_type = SCM_RIGHTS;
265 (*cmsgp).cmsg_len = CMSG_LEN(size_of::<c_int>() as u32) as _;
266 ptr::write(CMSG_DATA(cmsgp).cast::<c_int>(), notify_fd.as_raw_fd());
267 }
268
269 // SAFETY: A valid socket fd and a valid initialized msghdr are passed in.
270 if unsafe { sendmsg(tx_fd.as_raw_fd(), &msg, 0) } == -1 {
271 Err(io::Error::last_os_error())
272 } else {
273 Ok(())
274 }
275 }
276
277 pub(crate) struct SpawnNoexecHandler(UnixStream);
278
279 impl SpawnNoexecHandler {
280 pub(super) fn spawn(self) {
281 thread::spawn(move || {
282 let notify_fd = receive_fd(self.0);
283 // SAFETY: notify_fd is a valid seccomp_unotify fd.
284 unsafe { handle_notifications(notify_fd) };
285 });
286 }
287 }
288
289 // BPF filtering is only supported (according to man seccomp) on the following architectures
290 // that are realistic on Linux.
291 const HOST_ARCH: u32 = if cfg!(target_arch = "aarch64") {
292 AUDIT_ARCH_AARCH64
293 } else if cfg!(target_arch = "arm") {
294 AUDIT_ARCH_ARM
295 } else if cfg!(target_arch = "mips") {
296 if cfg!(target_endian = "little") {
297 AUDIT_ARCH_MIPSEL
298 } else {
299 AUDIT_ARCH_MIPS
300 }
301 } else if cfg!(target_arch = "mips64") {
302 if cfg!(target_endian = "little") {
303 AUDIT_ARCH_MIPSEL64
304 } else {
305 AUDIT_ARCH_MIPS64
306 }
307 } else if cfg!(target_arch = "powerpc") {
308 AUDIT_ARCH_PPC
309 } else if cfg!(target_arch = "powerpc64") {
310 if cfg!(target_endian = "little") {
311 AUDIT_ARCH_PPC64LE
312 } else {
313 AUDIT_ARCH_PPC64
314 }
315 } else if cfg!(target_arch = "riscv32") {
316 AUDIT_ARCH_RISCV32
317 } else if cfg!(target_arch = "riscv64") {
318 AUDIT_ARCH_RISCV64
319 } else if cfg!(target_arch = "s390x") {
320 AUDIT_ARCH_S390X
321 } else if cfg!(target_arch = "x86") {
322 AUDIT_ARCH_I386
323 } else if cfg!(target_arch = "x86_64") {
324 AUDIT_ARCH_X86_64
325 } else {
326 0 // this will filter out all syscalls
327 };
328
329 // For x86-64 and aarch64 systems, it's possible to encounter them
330 // running in multi-arch mode.
331 const GUEST_ARCH: u32 = if cfg!(target_arch = "aarch64") {
332 AUDIT_ARCH_ARM
333 } else if cfg!(target_arch = "riscv64") {
334 AUDIT_ARCH_RISCV32
335 } else if cfg!(target_arch = "x86_64") {
336 AUDIT_ARCH_I386
337 } else {
338 HOST_ARCH
339 };
340
341 /// syscall numbers for the guest architecture according to the Linux syscall table
342 const SYS_execve_x86: i64 = 11;
343 const SYS_execve_arm: i64 = 11;
344 const SYS_execve_x32: i64 = 520;
345 const SYS_execve_rv32: i64 = 221;
346 const SYS_execveat_x86: i64 = 358;
347 const SYS_execveat_arm: i64 = 387;
348 const SYS_execveat_x32: i64 = 545;
349 const SYS_execveat_rv32: i64 = 281;
350
351 const GUEST_SYSCALL: (i64, i64) = if cfg!(target_arch = "aarch64") {
352 (SYS_execve_arm, SYS_execveat_arm)
353 } else if cfg!(target_arch = "riscv64") {
354 (SYS_execve_rv32, SYS_execveat_rv32)
355 } else if cfg!(target_arch = "x86_64") {
356 (SYS_execve_x86, SYS_execveat_x86)
357 } else {
358 (SYS_execve as _, SYS_execveat as _) // fallback
359 };
360
361 // Bit that is set on syscalls when using the X32 ABI; see man seccomp.
362 const __X32_SYSCALL_BIT: u32 = 0x40000000;
363
364 pub(crate) fn add_noexec_filter(command: &mut Command) -> io::Result<SpawnNoexecHandler> {
365 let (tx_fd, rx_fd) = UnixStream::pair()?;
366
367 // wrap tx_fd so it can be moved into the closure
368 let mut tx_fd = Some(tx_fd);
369
370 // SAFETY: See individual SAFETY comments
371 unsafe {
372 // SAFETY: The closure only calls async-signal-safe functions.
373 command.pre_exec(move || {
374 let tx_fd = tx_fd.take().unwrap();
375
376 let nr_offset = offset_of!(seccomp_data, nr);
377 let arch_offset = offset_of!(seccomp_data, arch);
378
379 // SAFETY: libc unnecessarily marks these functions as unsafe
380 #[rustfmt::skip]
381 let exec_filter = [
382 // Load architecture number into the accumulator
383 BPF_STMT((BPF_LD | BPF_ABS) as _, arch_offset as _),
384 // Check if we are any of the recognized architectures
385 BPF_JUMP((BPF_JMP | BPF_JEQ | BPF_K) as _, HOST_ARCH as _, 7, 0),
386 BPF_JUMP((BPF_JMP | BPF_JEQ | BPF_K) as _, GUEST_ARCH as _, 1, 0),
387 // Not a recognized architecture, forbid all syscalls
388 BPF_STMT((BPF_RET | BPF_K) as _, SECCOMP_RET_KILL_PROCESS as _),
389
390 // Guest architecture section
391 // Load syscall number into the accumulator
392 BPF_STMT((BPF_LD | BPF_W | BPF_ABS) as _, nr_offset as _),
393 // Jump to user notify for execve/execveat
394 BPF_JUMP((BPF_JMP | BPF_JEQ | BPF_K) as _, GUEST_SYSCALL.0 as _, 2, 0),
395 BPF_JUMP((BPF_JMP | BPF_JEQ | BPF_K) as _, GUEST_SYSCALL.1 as _, 1, 0),
396 // Allow non-matching syscalls
397 BPF_STMT((BPF_RET | BPF_K) as _, SECCOMP_RET_ALLOW),
398 // Notify sudo about execve/execveat syscall
399 BPF_STMT((BPF_RET | BPF_K) as _, SECCOMP_RET_USER_NOTIF as _),
400
401 // Host architecture section
402 // Load syscall number into the accumulator
403 BPF_STMT((BPF_LD | BPF_W | BPF_ABS) as _, nr_offset as _),
404 // Unset the X32_SYSCALL bit (only necessary on x86_64)
405 #[cfg(target_arch = "x86_64")]
406 BPF_STMT((BPF_ALU | BPF_AND | BPF_K) as _, !__X32_SYSCALL_BIT),
407 // On x86-64 only: check the x32 "design error" syscall numbers
408 #[cfg(target_arch = "x86_64")]
409 BPF_JUMP((BPF_JMP | BPF_JEQ | BPF_K) as _, SYS_execve_x32 as _, 4, 0),
410 #[cfg(target_arch = "x86_64")]
411 BPF_JUMP((BPF_JMP | BPF_JEQ | BPF_K) as _, SYS_execveat_x32 as _, 3, 0),
412 // Jump to user notify for execve/execveat
413 BPF_JUMP((BPF_JMP | BPF_JEQ | BPF_K) as _, SYS_execve as _, 2, 0),
414 BPF_JUMP((BPF_JMP | BPF_JEQ | BPF_K) as _, SYS_execveat as _, 1, 0),
415 // Allow non-matching syscalls
416 BPF_STMT((BPF_RET | BPF_K) as _, SECCOMP_RET_ALLOW),
417 // Notify sudo about execve/execveat syscall
418 BPF_STMT((BPF_RET | BPF_K) as _, SECCOMP_RET_USER_NOTIF as _),
419 ];
420
421 // this is used since we can't yet use "let exec_filter: [sock_filter; _] above"
422 const fn check_type<const N: usize>(_arr: &[sock_filter; N]) {}
423 check_type(&exec_filter);
424
425 let exec_fprog = sock_fprog {
426 len: exec_filter.len() as u16,
427 filter: addr_of!(exec_filter) as *mut sock_filter,
428 };
429
430 // SAFETY: Trivially safe as it doesn't touch any memory.
431 // SECCOMP_SET_MODE_FILTER will fail unless the process has
432 // CAP_SYS_ADMIN or the no_new_privs bit is set.
433 if prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) == -1 {
434 return Err(io::Error::last_os_error());
435 }
436
437 // While the man page warns against using seccomp_unotify as security
438 // mechanism, the TOCTOU problem that is described there isn't
439 // relevant here. We only SECCOMP_USER_NOTIF_FLAG_CONTINUE the first
440 // execve which is done by ourself and thus trusted.
441 // SAFETY: Passes a valid sock_fprog as argument.
442 let notify_fd = seccomp(
443 SECCOMP_SET_MODE_FILTER,
444 SECCOMP_FILTER_FLAG_NEW_LISTENER as _,
445 addr_of!(exec_fprog).cast_mut(),
446 );
447 if notify_fd < 0 {
448 return Err(io::Error::last_os_error());
449 }
450
451 send_fd(tx_fd, OwnedFd::from_raw_fd(notify_fd))?;
452
453 Ok(())
454 });
455 }
456
457 Ok(SpawnNoexecHandler(rx_fd))
458 }