1use std::ffi::{OsStr, OsString};
73
74use super::layering::Layering;
75use super::seccomp;
76use super::{
77 AccessMode, AllowedPath, NetworkAccess, NetworkSupport, ProxyListener, SandboxEnforcer,
78 SandboxPolicy, WrappedCommand, canonicalize_paths,
79};
80use crate::error::SandboxError;
81
82const SOCKET_DIRECTORIES: &[&str] = &["/run", "/tmp", "/var/tmp", "/dev/shm"];
85
86pub const INFO_FD: i32 = 65;
89
90pub const BLOCK_FD: i32 = 66;
93
94pub const SECCOMP_FD: i32 = 64;
99
100pub struct LinuxEnforcer;
134
135impl LinuxEnforcer {
136 pub fn new() -> Self {
138 Self
139 }
140
141 pub fn generate_args(policy: &SandboxPolicy) -> Vec<String> {
166 Self::generate_args_from_paths(
167 &policy.allowed_paths,
168 &policy.network,
169 policy.allow_process_spawn,
170 )
171 }
172
173 fn generate_args_from_paths(
175 paths: &[AllowedPath],
176 network: &NetworkAccess,
177 allow_process_spawn: bool,
178 ) -> Vec<String> {
179 let mut args = Vec::with_capacity(16);
180
181 args.push("--die-with-parent".to_string());
183
184 args.push("--unshare-pid".to_string());
186
187 if network.restricts() {
189 args.push("--unshare-net".to_string());
190 }
191 if let NetworkAccess::Proxied { .. } = network {
192 args.extend(
193 ["--info-fd", &INFO_FD.to_string(), "--block-fd", &BLOCK_FD.to_string()]
194 .map(str::to_string),
195 );
196 }
197
198 args.push("--new-session".to_string());
201
202 if !allow_process_spawn {
204 args.push("--seccomp".to_string());
205 args.push(SECCOMP_FD.to_string());
206 }
207
208 let mut covered: Vec<&str> = Vec::new();
213 for (path, mode) in Layering::new(paths).mounts() {
214 let path_str = path.to_string_lossy().to_string();
215 match mode {
216 AccessMode::ReadOnly => {
217 args.push("--ro-bind".to_string());
218 args.push(path_str.clone());
219 args.push(path_str);
220 }
221 AccessMode::ReadWrite => {
222 args.push("--bind".to_string());
223 args.push(path_str.clone());
224 args.push(path_str);
225 }
226 }
227 if !network.restricts() {
228 continue;
229 }
230 for directory in SOCKET_DIRECTORIES {
231 let target = std::path::Path::new(directory);
232 let below = target != path && target.starts_with(path);
233 if below
234 && !covered.contains(directory)
235 && std::fs::symlink_metadata(target).is_ok_and(|m| m.is_dir())
236 {
237 args.push("--tmpfs".to_string());
238 args.push((*directory).to_string());
239 covered.push(directory);
240 }
241 }
242 }
243 for directory in covered {
244 args.push("--remount-ro".to_string());
245 args.push(directory.to_string());
246 }
247
248 args
249 }
250}
251
252impl Default for LinuxEnforcer {
253 fn default() -> Self {
254 Self::new()
255 }
256}
257
258impl SandboxEnforcer for LinuxEnforcer {
259 fn name(&self) -> &str {
260 "bubblewrap"
261 }
262
263 fn network_support(&self) -> NetworkSupport {
264 NetworkSupport { denied: true, proxied: cfg!(feature = "egress-proxy") }
265 }
266
267 fn proxy_listener(&self) -> ProxyListener {
268 ProxyListener::SandboxLoopback
269 }
270
271 fn probe(&self) -> Result<(), SandboxError> {
272 let result = std::process::Command::new("bwrap")
274 .arg("--version")
275 .stdout(std::process::Stdio::null())
276 .stderr(std::process::Stdio::null())
277 .status();
278
279 match result {
280 Ok(status) if status.success() => {
281 let ns_check = std::process::Command::new("bwrap")
288 .args(["--ro-bind", "/", "/", "--unshare-user", "--", "/bin/true"])
289 .stdout(std::process::Stdio::null())
290 .stderr(std::process::Stdio::null())
291 .status();
292
293 match ns_check {
294 Ok(s) if s.success() => Ok(()),
295 _ => Err(SandboxError::EnforcerUnavailable {
296 enforcer: "bubblewrap".to_string(),
297 message: "user namespaces are not available. Check that \
298 `kernel.unprivileged_userns_clone` sysctl is set to 1."
299 .to_string(),
300 }),
301 }
302 }
303 Ok(_) => Err(SandboxError::EnforcerUnavailable {
304 enforcer: "bubblewrap".to_string(),
305 message: "bwrap binary found but returned an error. \
306 Verify installation is complete."
307 .to_string(),
308 }),
309 Err(e) => Err(SandboxError::EnforcerUnavailable {
310 enforcer: "bubblewrap".to_string(),
311 message: format!(
312 "bwrap binary not found: {e}. Install bubblewrap: \
313 `apt install bubblewrap` (Debian/Ubuntu) or \
314 `dnf install bubblewrap` (Fedora/RHEL)."
315 ),
316 }),
317 }
318 }
319
320 fn wrap_command(
321 &self,
322 program: &OsStr,
323 args: &[OsString],
324 policy: &SandboxPolicy,
325 ) -> Result<WrappedCommand, SandboxError> {
326 self.network_support().check(self.name(), &policy.network)?;
327
328 let canonicalized_paths = canonicalize_paths(&policy.allowed_paths)?;
330 if policy.network.restricts() {
331 refuse_socket_directories(&canonicalized_paths, &policy.network)?;
332 }
333
334 let bwrap_args = Self::generate_args_from_paths(
336 &canonicalized_paths,
337 &policy.network,
338 policy.allow_process_spawn,
339 );
340
341 let mut wrapped_args: Vec<OsString> = bwrap_args.into_iter().map(OsString::from).collect();
343 wrapped_args.push(OsString::from("--"));
344 wrapped_args.push(program.to_owned());
345 wrapped_args.extend_from_slice(args);
346
347 Ok(WrappedCommand { program: OsString::from("bwrap"), args: wrapped_args })
348 }
349
350 fn configure_command(
357 &self,
358 cmd: &mut tokio::process::Command,
359 policy: &SandboxPolicy,
360 ) -> Result<(), SandboxError> {
361 use std::io::Write;
362 use std::os::fd::{AsRawFd, OwnedFd};
363
364 if let NetworkAccess::Proxied { endpoint } = policy.network {
365 let failed = |error: std::io::Error| SandboxError::EnforcerFailed {
366 enforcer: "bubblewrap".to_string(),
367 message: format!("failed to prepare the egress proxy's descriptors: {error}"),
368 };
369 let (info_reader, info_writer) = std::io::pipe().map_err(failed)?;
370 let (block_reader, block_writer) = std::io::pipe().map_err(failed)?;
371 let (info_fd, block_fd) = (OwnedFd::from(info_writer), OwnedFd::from(block_reader));
372 unsafe {
375 cmd.pre_exec(move || {
376 install_fd(info_fd.as_raw_fd(), INFO_FD)?;
377 install_fd(block_fd.as_raw_fd(), BLOCK_FD)
378 });
379 }
380 std::thread::Builder::new()
381 .name("adk-sandbox-egress-namespace".to_string())
382 .spawn(move || namespace::attach_listener(info_reader, block_writer, endpoint.port))
383 .map_err(failed)?;
384 }
385
386 if policy.allow_process_spawn {
387 return Ok(());
388 }
389
390 let abi = seccomp::Abi::native().ok_or_else(|| SandboxError::EnforcerFailed {
391 enforcer: "bubblewrap".to_string(),
392 message: format!(
393 "no process-creation seccomp filter exists for {}; allow process spawning in \
394 the policy or run on x86_64 or aarch64",
395 std::env::consts::ARCH
396 ),
397 })?;
398 let program = seccomp::encode(&seccomp::deny_process_creation(abi));
399
400 let failed = |error: std::io::Error| SandboxError::EnforcerFailed {
401 enforcer: "bubblewrap".to_string(),
402 message: format!("failed to prepare the seccomp program descriptor: {error}"),
403 };
404 let (reader, mut writer) = std::io::pipe().map_err(failed)?;
407 writer.write_all(&program).map_err(failed)?;
408 drop(writer);
409 let program_fd = OwnedFd::from(reader);
410
411 unsafe {
415 cmd.pre_exec(move || install_fd(program_fd.as_raw_fd(), SECCOMP_FD));
416 }
417 Ok(())
418 }
419}
420
421fn install_fd(source: i32, target: i32) -> std::io::Result<()> {
426 let result = unsafe {
428 if source == target {
429 libc::fcntl(source, libc::F_SETFD, 0)
431 } else {
432 libc::dup2(source, target)
433 }
434 };
435 if result == -1 { Err(std::io::Error::last_os_error()) } else { Ok(()) }
436}
437
438#[cfg(feature = "egress-proxy")]
440mod namespace {
441 use std::fs::File;
442 use std::io::{Read, Write};
443 use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
444 use std::os::unix::net::UnixStream;
445 use std::os::unix::process::CommandExt;
446
447 pub(super) fn attach_listener(
450 info: std::io::PipeReader,
451 mut block: std::io::PipeWriter,
452 port: u16,
453 ) {
454 let attached =
455 child_pid(info).and_then(|pid| listen_in_namespace(pid, port)).and_then(|listener| {
456 if crate::egress_proxy::deliver_namespace_listener(port, listener) {
457 Ok(())
458 } else {
459 Err(std::io::Error::other("no egress proxy waits for this call"))
460 }
461 });
462 if let Err(error) = attached {
463 tracing::warn!(
464 error = %error,
465 sandbox.proxy_port = port,
466 "the egress proxy listener could not be placed in the sandbox; the program \
467 reaches no network"
468 );
469 }
470 let _ = block.write_all(b"1");
471 }
472
473 fn child_pid(mut info: std::io::PipeReader) -> std::io::Result<u32> {
475 let mut text = Vec::new();
476 let mut chunk = [0u8; 512];
477 while !text.contains(&b'}') {
478 match info.read(&mut chunk)? {
479 0 => break,
480 n => text.extend_from_slice(&chunk[..n]),
481 }
482 if text.len() > 64 * 1024 {
483 break;
484 }
485 }
486 let text = String::from_utf8_lossy(&text);
487 text.split("\"child-pid\"")
488 .nth(1)
489 .and_then(|rest| {
490 let digits: String = rest
491 .trim_start_matches(|c: char| c == ':' || c.is_whitespace())
492 .chars()
493 .take_while(char::is_ascii_digit)
494 .collect();
495 digits.parse().ok()
496 })
497 .ok_or_else(|| {
498 std::io::Error::other(format!("bubblewrap reported no child-pid: {text}"))
499 })
500 }
501
502 fn listen_in_namespace(pid: u32, port: u16) -> std::io::Result<std::net::TcpListener> {
505 let user = File::open(format!("/proc/{pid}/ns/user"))?;
506 let net = File::open(format!("/proc/{pid}/ns/net"))?;
507 let (parent, child) = UnixStream::pair()?;
508 let (user_fd, net_fd, child_fd) = (user.as_raw_fd(), net.as_raw_fd(), child.as_raw_fd());
509 let mut helper = std::process::Command::new("true");
510 helper
511 .stdin(std::process::Stdio::null())
512 .stdout(std::process::Stdio::null())
513 .stderr(std::process::Stdio::null());
514 unsafe {
517 helper.pre_exec(move || {
518 if libc::setns(user_fd, libc::CLONE_NEWUSER) == -1
519 || libc::setns(net_fd, libc::CLONE_NEWNET) == -1
520 {
521 return Err(std::io::Error::last_os_error());
522 }
523 wait_for_loopback()?;
524 let listener = bind_loopback(port)?;
525 send_fd(child_fd, listener)
526 });
527 }
528 let status = helper.status()?;
529 if !status.success() {
530 return Err(std::io::Error::other(format!("the namespace helper ended with {status}")));
531 }
532 drop((user, net, child));
533 let fd = receive_fd(&parent)?;
534 Ok(std::net::TcpListener::from(fd))
535 }
536
537 unsafe fn wait_for_loopback() -> std::io::Result<()> {
544 const ATTEMPTS: u32 = 2_500;
546 let pause = libc::timespec { tv_sec: 0, tv_nsec: 2_000_000 };
547 unsafe {
549 let socket = libc::socket(libc::AF_INET, libc::SOCK_DGRAM | libc::SOCK_CLOEXEC, 0);
550 if socket == -1 {
551 return Err(std::io::Error::last_os_error());
552 }
553 let mut request: libc::ifreq = std::mem::zeroed();
554 for (slot, byte) in request.ifr_name.iter_mut().zip(b"lo\0") {
555 *slot = *byte as libc::c_char;
556 }
557 let mut outcome = Err(std::io::Error::from_raw_os_error(libc::ETIMEDOUT));
558 for _ in 0..ATTEMPTS {
559 if libc::ioctl(socket, libc::SIOCGIFFLAGS as _, &raw mut request) == -1 {
560 outcome = Err(std::io::Error::last_os_error());
561 break;
562 }
563 if request.ifr_ifru.ifru_flags & libc::IFF_UP as libc::c_short != 0 {
564 outcome = Ok(());
565 break;
566 }
567 libc::nanosleep(&raw const pause, std::ptr::null_mut());
568 }
569 libc::close(socket);
570 outcome
571 }
572 }
573
574 unsafe fn bind_loopback(port: u16) -> std::io::Result<libc::c_int> {
576 unsafe {
578 let socket = libc::socket(libc::AF_INET, libc::SOCK_STREAM | libc::SOCK_CLOEXEC, 0);
579 if socket == -1 {
580 return Err(std::io::Error::last_os_error());
581 }
582 let address = libc::sockaddr_in {
583 sin_family: libc::AF_INET as libc::sa_family_t,
584 sin_port: port.to_be(),
585 sin_addr: libc::in_addr {
586 s_addr: u32::from(std::net::Ipv4Addr::LOCALHOST).to_be(),
587 },
588 sin_zero: [0; 8],
589 };
590 let length = std::mem::size_of::<libc::sockaddr_in>() as libc::socklen_t;
591 if libc::bind(socket, (&raw const address).cast(), length) == -1
592 || libc::listen(socket, 128) == -1
593 {
594 let error = std::io::Error::last_os_error();
595 libc::close(socket);
596 return Err(error);
597 }
598 Ok(socket)
599 }
600 }
601
602 unsafe fn send_fd(socket: libc::c_int, fd: libc::c_int) -> std::io::Result<()> {
604 unsafe {
607 let mut byte = [0u8; 1];
608 let mut iov = libc::iovec { iov_base: byte.as_mut_ptr().cast(), iov_len: 1 };
609 let mut control = [0u64; 8];
610 let mut message: libc::msghdr = std::mem::zeroed();
611 message.msg_iov = &mut iov;
612 message.msg_iovlen = 1;
613 message.msg_control = control.as_mut_ptr().cast();
614 message.msg_controllen =
615 libc::CMSG_SPACE(std::mem::size_of::<libc::c_int>() as u32) as _;
616 let header = libc::CMSG_FIRSTHDR(&message);
617 (*header).cmsg_level = libc::SOL_SOCKET;
618 (*header).cmsg_type = libc::SCM_RIGHTS;
619 (*header).cmsg_len = libc::CMSG_LEN(std::mem::size_of::<libc::c_int>() as u32) as _;
620 std::ptr::write_unaligned(libc::CMSG_DATA(header).cast::<libc::c_int>(), fd);
621 if libc::sendmsg(socket, &message, 0) == -1 {
622 return Err(std::io::Error::last_os_error());
623 }
624 Ok(())
625 }
626 }
627
628 fn receive_fd(socket: &UnixStream) -> std::io::Result<OwnedFd> {
630 unsafe {
632 let mut byte = [0u8; 1];
633 let mut iov = libc::iovec { iov_base: byte.as_mut_ptr().cast(), iov_len: 1 };
634 let mut control = [0u64; 8];
635 let mut message: libc::msghdr = std::mem::zeroed();
636 message.msg_iov = &mut iov;
637 message.msg_iovlen = 1;
638 message.msg_control = control.as_mut_ptr().cast();
639 message.msg_controllen = std::mem::size_of_val(&control) as _;
640 if libc::recvmsg(socket.as_raw_fd(), &mut message, libc::MSG_CMSG_CLOEXEC) == -1 {
641 return Err(std::io::Error::last_os_error());
642 }
643 let header = libc::CMSG_FIRSTHDR(&message);
644 if header.is_null()
645 || (*header).cmsg_level != libc::SOL_SOCKET
646 || (*header).cmsg_type != libc::SCM_RIGHTS
647 {
648 return Err(std::io::Error::other("the namespace helper sent no listener"));
649 }
650 let fd = std::ptr::read_unaligned(libc::CMSG_DATA(header).cast::<libc::c_int>());
651 Ok(OwnedFd::from_raw_fd(fd))
652 }
653 }
654}
655
656#[cfg(not(feature = "egress-proxy"))]
659mod namespace {
660 use std::io::Write;
661
662 pub(super) fn attach_listener(
663 _info: std::io::PipeReader,
664 mut block: std::io::PipeWriter,
665 _port: u16,
666 ) {
667 let _ = block.write_all(b"1");
668 }
669}
670
671fn refuse_socket_directories(
674 paths: &[AllowedPath],
675 network: &NetworkAccess,
676) -> Result<(), SandboxError> {
677 let run = std::path::Path::new("/run");
678 for entry in paths {
679 let shared = SOCKET_DIRECTORIES
680 .iter()
681 .any(|directory| entry.path == std::path::Path::new(directory));
682 let mut budget = 4096;
684 if shared || (entry.path.starts_with(run) && holds_socket(&entry.path, &mut budget)) {
685 return Err(SandboxError::Unenforceable {
686 enforcer: "bubblewrap".to_string(),
687 requirement: format!(
688 "network access {network} while granting '{}': Unix sockets there (Docker, \
689 D-Bus, systemd, SSH agents) stay reachable through a bind mount; grant a \
690 directory below it that holds none",
691 entry.path.display()
692 ),
693 });
694 }
695 }
696 Ok(())
697}
698
699fn holds_socket(path: &std::path::Path, budget: &mut usize) -> bool {
702 use std::os::unix::fs::FileTypeExt;
703 let Ok(metadata) = std::fs::symlink_metadata(path) else { return true };
704 if metadata.file_type().is_socket() {
705 return true;
706 }
707 if !metadata.is_dir() {
708 return false;
709 }
710 let Ok(entries) = std::fs::read_dir(path) else { return true };
711 for entry in entries {
712 if *budget == 0 {
713 return true;
714 }
715 *budget -= 1;
716 let Ok(entry) = entry else { return true };
717 let Ok(kind) = entry.file_type() else { return true };
718 if kind.is_socket() || (kind.is_dir() && holds_socket(&entry.path(), budget)) {
719 return true;
720 }
721 }
722 false
723}
724
725#[cfg(test)]
730mod tests {
731 use super::*;
732 use crate::sandbox::SandboxPolicyBuilder;
733
734 #[test]
735 fn test_generate_args_deny_all() {
736 let policy = SandboxPolicyBuilder::new().build();
737 let args = LinuxEnforcer::generate_args(&policy);
738
739 assert_eq!(args[0], "--die-with-parent");
740 assert_eq!(args[1], "--unshare-pid");
741 assert!(args.contains(&"--unshare-net".to_string()));
742 assert!(args.contains(&"--new-session".to_string()));
743 assert!(
744 args.windows(2).any(|pair| pair[0] == "--seccomp" && pair[1] == SECCOMP_FD.to_string())
745 );
746 assert!(!args.contains(&"--ro-bind".to_string()));
748 assert!(!args.contains(&"--bind".to_string()));
749 }
750
751 #[test]
752 fn test_generate_args_read_only_path() {
753 let policy = SandboxPolicyBuilder::new().allow_read("/usr/lib").build();
754 let args = LinuxEnforcer::generate_args(&policy);
755
756 let ro_idx = args.iter().position(|a| a == "--ro-bind").unwrap();
757 assert_eq!(args[ro_idx + 1], "/usr/lib");
758 assert_eq!(args[ro_idx + 2], "/usr/lib");
759 assert!(!args.contains(&"--bind".to_string()));
760 }
761
762 #[test]
763 fn test_generate_args_read_write_path() {
764 let policy = SandboxPolicyBuilder::new().allow_read_write("/tmp/work").build();
765 let args = LinuxEnforcer::generate_args(&policy);
766
767 let bind_idx = args.iter().position(|a| a == "--bind").unwrap();
768 assert_eq!(args[bind_idx + 1], "/tmp/work");
769 assert_eq!(args[bind_idx + 2], "/tmp/work");
770 assert!(!args.contains(&"--ro-bind".to_string()));
771 }
772
773 #[test]
774 fn test_generate_args_network_allowed() {
775 let policy = SandboxPolicyBuilder::new().allow_network().build();
776 let args = LinuxEnforcer::generate_args(&policy);
777
778 assert!(!args.contains(&"--unshare-net".to_string()));
779 }
780
781 #[test]
782 fn test_generate_args_network_denied() {
783 let policy = SandboxPolicyBuilder::new().build();
784 let args = LinuxEnforcer::generate_args(&policy);
785
786 assert!(args.contains(&"--unshare-net".to_string()));
787 }
788
789 #[test]
790 fn test_generate_args_process_spawn_allowed() {
791 let policy = SandboxPolicyBuilder::new().allow_process_spawn().build();
792 let args = LinuxEnforcer::generate_args(&policy);
793
794 assert!(!args.contains(&"--seccomp".to_string()));
795 }
796
797 #[test]
800 fn every_policy_starts_a_new_session() {
801 for allow_process_spawn in [false, true] {
802 for network in [NetworkAccess::Denied, NetworkAccess::Open] {
803 let args =
804 LinuxEnforcer::generate_args_from_paths(&[], &network, allow_process_spawn);
805 assert_eq!(
806 args.iter().filter(|arg| *arg == "--new-session").count(),
807 1,
808 "spawn={allow_process_spawn} network={network}: {args:?}"
809 );
810 }
811 }
812 }
813
814 #[test]
815 fn test_generate_args_process_spawn_denied() {
816 let policy = SandboxPolicyBuilder::new().build();
817 let args = LinuxEnforcer::generate_args(&policy);
818
819 assert!(args.contains(&"--new-session".to_string()));
820 let seccomp = args.iter().position(|arg| arg == "--seccomp").expect("--seccomp present");
821 assert_eq!(args[seccomp + 1], SECCOMP_FD.to_string());
822 }
823
824 #[test]
825 fn configure_command_is_a_no_op_when_spawning_is_allowed() {
826 let policy = SandboxPolicyBuilder::new().allow_process_spawn().build();
827 let mut cmd = tokio::process::Command::new("true");
828
829 LinuxEnforcer::new().configure_command(&mut cmd, &policy).expect("nothing to configure");
830 }
831
832 #[test]
833 fn configure_command_installs_the_filter_on_supported_architectures() {
834 let policy = SandboxPolicyBuilder::new().build();
835 let mut cmd = tokio::process::Command::new("true");
836
837 let result = LinuxEnforcer::new().configure_command(&mut cmd, &policy);
838 if seccomp::Abi::native().is_some() {
839 result.expect("the filter is prepared on a supported architecture");
840 } else {
841 assert!(matches!(result, Err(SandboxError::EnforcerFailed { .. })), "{result:?}");
842 }
843 }
844
845 #[test]
846 fn test_generate_args_starts_with_die_with_parent() {
847 let policy = SandboxPolicyBuilder::new()
848 .allow_read("/tmp")
849 .allow_network()
850 .allow_process_spawn()
851 .build();
852 let args = LinuxEnforcer::generate_args(&policy);
853
854 assert_eq!(args[0], "--die-with-parent");
855 }
856
857 #[test]
858 fn test_generate_args_no_empty_strings() {
859 let policy = SandboxPolicyBuilder::new()
860 .allow_read("/usr/lib")
861 .allow_read_write("/tmp")
862 .allow_network()
863 .build();
864 let args = LinuxEnforcer::generate_args(&policy);
865
866 for arg in &args {
867 assert!(!arg.is_empty(), "found empty string in bwrap args");
868 }
869 }
870
871 #[test]
872 fn test_name() {
873 let enforcer = LinuxEnforcer::new();
874 assert_eq!(enforcer.name(), "bubblewrap");
875 }
876
877 #[test]
880 fn proxied_network_access_needs_the_egress_proxy() {
881 let endpoint = super::super::ProxyEndpoint { port: 3128 };
882 let policy = SandboxPolicyBuilder::new().proxied(endpoint).build();
883
884 let result = LinuxEnforcer::new().wrap_command(OsStr::new("true"), &[], &policy);
885
886 if cfg!(feature = "egress-proxy") {
887 let args: Vec<String> = result
888 .expect("Proxied is enforced with the egress proxy")
889 .args
890 .iter()
891 .map(|arg| arg.to_string_lossy().into_owned())
892 .collect();
893 for flag in [
894 vec!["--unshare-net".to_string()],
895 vec!["--info-fd".to_string(), INFO_FD.to_string()],
896 vec!["--block-fd".to_string(), BLOCK_FD.to_string()],
897 ] {
898 assert!(
899 args.windows(flag.len()).any(|w| w == flag.as_slice()),
900 "{flag:?} in {args:?}"
901 );
902 }
903 } else {
904 assert!(matches!(result, Err(SandboxError::Unenforceable { .. })), "{result:?}");
905 }
906 }
907
908 #[test]
911 fn socket_directories_are_refused_under_denied_network() {
912 let enforcer = LinuxEnforcer::new();
913 for path in ["/run", "/tmp"] {
914 let denied = SandboxPolicyBuilder::new().allow_read(path).build();
915 let result = enforcer.wrap_command(OsStr::new("true"), &[], &denied);
916 assert!(
917 matches!(result, Err(SandboxError::Unenforceable { .. })),
918 "{path}: {result:?}"
919 );
920
921 let open = SandboxPolicyBuilder::new().allow_read(path).allow_network().build();
922 assert!(enforcer.wrap_command(OsStr::new("true"), &[], &open).is_ok(), "{path}");
923 }
924 let narrow = SandboxPolicyBuilder::new().allow_read("/usr").build();
925 assert!(enforcer.wrap_command(OsStr::new("true"), &[], &narrow).is_ok());
926 }
927
928 #[test]
931 fn a_granted_root_covers_the_socket_directories_under_denied_network() {
932 let workspace = tempfile::tempdir().expect("tempdir");
933 let workspace = std::fs::canonicalize(workspace.path()).expect("canonical");
934 let paths = [
935 AllowedPath { path: std::path::PathBuf::from("/"), mode: AccessMode::ReadOnly },
936 AllowedPath { path: workspace.clone(), mode: AccessMode::ReadWrite },
937 ];
938 let args = LinuxEnforcer::generate_args_from_paths(&paths, &NetworkAccess::Denied, true);
939 let position = |needle: &[&str]| args.windows(needle.len()).position(|w| w == needle);
940 let root = position(&["--ro-bind", "/", "/"]).expect("the root is bound");
941 let run = position(&["--tmpfs", "/run"]).expect("/run is covered");
942 let tmp = position(&["--tmpfs", "/tmp"]).expect("/tmp is covered");
943 let workspace = workspace.to_string_lossy().into_owned();
944 let bound = position(&["--bind", &workspace, &workspace]).expect("the workspace is bound");
945 assert!(root < run && run < bound && tmp < bound, "{args:?}");
946 assert!(position(&["--remount-ro", "/run"]).is_some_and(|ro| ro > bound), "{args:?}");
947
948 let open = LinuxEnforcer::generate_args_from_paths(&paths, &NetworkAccess::Open, true);
949 assert!(!open.iter().any(|arg| arg == "--tmpfs"), "{open:?}");
950 }
951
952 #[test]
953 fn test_wrap_command_nonexistent_path_fails() {
954 let enforcer = LinuxEnforcer::new();
955 let policy =
956 SandboxPolicyBuilder::new().allow_read("/nonexistent/path/that/does/not/exist").build();
957
958 let result = enforcer.wrap_command(OsStr::new("echo"), &[], &policy);
959
960 assert!(result.is_err());
961 let err = result.unwrap_err();
962 assert!(
963 matches!(err, SandboxError::PolicyViolation(_)),
964 "expected PolicyViolation, got: {err:?}"
965 );
966 }
967}