Skip to main content

reverie_process/
lib.rs

1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 * All rights reserved.
4 *
5 * This source code is licensed under the BSD-style license found in the
6 * LICENSE file in the root directory of this source tree.
7 */
8
9//! A drop-in replacement for `std::process::Command` that provides the ability
10//! to set up namespaces, a seccomp filter, and more.
11
12#![deny(missing_docs)]
13#![deny(rustdoc::broken_intra_doc_links)]
14#![cfg(target_os = "linux")]
15#![cfg_attr(feature = "nightly", feature(internal_output_capture))]
16
17mod builder;
18mod child;
19mod clone;
20mod container;
21mod env;
22mod error;
23mod exit_status;
24mod fd;
25mod id_map;
26#[doc(hidden)]
27pub mod launch_window;
28mod mount;
29mod namespace;
30mod net;
31mod pid;
32mod pinned_mount;
33mod pty;
34pub mod seccomp;
35mod spawn;
36mod stdio;
37mod util;
38
39use std::ffi::CString;
40use std::io;
41
42pub use child::Child;
43pub use child::Output;
44pub use container::ChildCleanupObservation;
45pub use container::ChildParentResourceStartContext;
46pub use container::ChildStartContext;
47pub use container::Container;
48pub use container::DeferredContainerRun;
49pub use container::LinuxMonotonicDeadline;
50pub use container::MAX_STARTUP_FDS;
51pub use container::OwnedContainerCleanup;
52pub use container::OwnedDecodeFailure;
53pub use container::OwnedDeferredContainerRun;
54pub use container::OwnedFinalization;
55pub use container::OwnedFinalize;
56pub use container::OwnedReapedResult;
57pub use container::OwnedRunFailure;
58pub use container::ParentResourcePublication;
59pub use container::ParentResourceStartContext;
60pub use container::ParentResourceStartupFailure;
61pub use container::ParentResourceStartupPhase;
62pub use container::ParentResourceStartupResult;
63pub use container::ParentStartContext;
64pub use container::RunError;
65pub use container::StartupError;
66pub use container::StartupOwnedFailure;
67pub use container::StartupRunError;
68pub use error::Context;
69pub use error::Error;
70pub use exit_status::ExitStatus;
71pub use mount::Bind;
72pub use mount::Mount;
73pub use mount::MountFlags;
74pub use mount::MountParseError;
75pub use namespace::Namespace;
76// Re-export Signal since it is used by `Child::signal`.
77pub use nix::sys::signal::Signal;
78pub use pid::Pid;
79pub use pinned_mount::PinnedMountSource;
80pub use pty::Pty;
81pub use pty::PtyChild;
82pub use stdio::ChildStderr;
83pub use stdio::ChildStdin;
84pub use stdio::ChildStdout;
85pub use stdio::Stdio;
86use syscalls::Errno;
87
88/// Trusted terminal execution entry using the command's exact prepared vectors.
89///
90/// Successful kernel exec never returns. An entry must also terminate through
91/// its own admitted gate on failure; it cannot return into the ordinary spawn
92/// error path after publishing an inherited filter.
93pub type TerminalExecve = unsafe extern "C" fn(
94    *const libc::c_char,
95    *const *const libc::c_char,
96    *const *const libc::c_char,
97) -> !;
98
99/// A builder for spawning a process.
100// See the builder.rs for documentation of each field.
101pub struct Command {
102    program: CString,
103    args: util::CStringArray,
104    pre_exec: Vec<Box<dyn FnMut() -> Result<(), Errno> + Send + Sync>>,
105    terminal_execve: Option<TerminalExecve>,
106    container: Container,
107}
108
109impl Command {
110    /// Converts [`std::process::Command`] into [`Command`]. Note that this is a
111    /// very basic and *lossy* conversion.
112    ///
113    /// This only preserves the
114    ///  - program path,
115    ///  - arguments,
116    ///  - environment variables,
117    ///  - and working directory.
118    ///
119    /// # Caveats
120    ///
121    /// Since [`std::process::Command`] is rather opaque and doesn't provide
122    /// access to all fields, this will *not* preserve:
123    ///  - stdio handles,
124    ///  - `env_clear`,
125    ///  - any `pre_exec` callbacks,
126    ///  - `arg0` (if not the same as `program`),
127    ///  - `uid`, `gid`, or `groups`.
128    pub fn from_std_lossy(cmd: &std::process::Command) -> Command {
129        let mut result = Command::new(cmd.get_program());
130        result.args(cmd.get_args());
131
132        for (key, value) in cmd.get_envs() {
133            match value {
134                Some(value) => result.env(key, value),
135                None => result.env_remove(key),
136            };
137        }
138
139        if let Some(dir) = cmd.get_current_dir() {
140            result.current_dir(dir);
141        }
142
143        result
144    }
145
146    /// Converts this command to [`std::process::Command`].
147    ///
148    /// This fails if the command contains container configuration that cannot
149    /// be represented by [`std::process::Command`], rather than silently
150    /// discarding that configuration. This includes namespaces, mounts,
151    /// seccomp filters, pseudoterminals, and CPU affinity.
152    pub fn try_into_std(self) -> io::Result<std::process::Command> {
153        let blockers = self.container.std_conversion_blockers();
154        if self.terminal_execve.is_some() {
155            return Err(io::Error::new(
156                io::ErrorKind::InvalidInput,
157                "cannot convert a command with a terminal execution entry",
158            ));
159        }
160        if !blockers.is_empty() {
161            return Err(io::Error::new(
162                io::ErrorKind::InvalidInput,
163                format!(
164                    "cannot convert to std::process::Command without losing: {}",
165                    blockers.join(", ")
166                ),
167            ));
168        }
169
170        Ok(self.into_std())
171    }
172
173    /// Converts this command to [`std::process::Command`], refusing to discard
174    /// any container configuration.
175    ///
176    /// This compatibility shim preserves the former return type for callers
177    /// whose commands are representable. It panics instead of silently losing
178    /// unsupported configuration. New callers should use [`Self::try_into_std`]
179    /// to handle that refusal explicitly.
180    pub fn into_std_lossy(self) -> std::process::Command {
181        self.try_into_std().unwrap_or_else(|error| {
182            panic!("Command::into_std_lossy refused unsupported configuration: {error}")
183        })
184    }
185
186    fn into_std(self) -> std::process::Command {
187        use std::ffi::OsStr;
188        use std::os::unix::ffi::OsStrExt;
189
190        // Keep this exhaustive: adding Command state must fail to compile until
191        // the standard-command conversion explicitly preserves or refuses it.
192        let Self {
193            program,
194            args,
195            pre_exec,
196            terminal_execve,
197            container,
198        } = self;
199
200        assert!(
201            terminal_execve.is_none(),
202            "terminal entry requires the native command owner"
203        );
204        let mut result = std::process::Command::new(OsStr::from_bytes(program.to_bytes()));
205        result.args(
206            args.iter()
207                .skip(1)
208                .map(|arg| OsStr::from_bytes(arg.to_bytes())),
209        );
210
211        if container.env.is_cleared() {
212            result.env_clear();
213        }
214
215        for (key, value) in container.get_envs() {
216            match value {
217                Some(value) => result.env(key, value),
218                None => result.env_remove(key),
219            };
220        }
221
222        if let Some(dir) = container.get_current_dir() {
223            result.current_dir(dir);
224        }
225
226        #[cfg(unix)]
227        {
228            use std::os::unix::process::CommandExt;
229
230            result.arg0(OsStr::from_bytes(args.get(0).to_bytes()));
231
232            for mut f in pre_exec {
233                unsafe {
234                    result.pre_exec(move || f().map_err(Into::into));
235                }
236            }
237        }
238
239        result.stdin(container.stdin);
240        result.stdout(container.stdout);
241        result.stderr(container.stderr);
242
243        result
244    }
245}
246
247/// Names the unit test that a fresh single-test process was started to run; it
248/// is set only in that process, never in the libtest harness process.
249#[cfg(test)]
250pub(crate) const ISOLATED_TEST_MARKER: &str = "REVERIE_PROCESS_ISOLATED_TEST";
251
252/// Runs the calling unit test in a fresh single-test process.
253///
254/// Returns `true` in the libtest harness process, after the fresh process has
255/// run the test body and passed; the caller must then return without running
256/// the body itself. Returns `false` inside the fresh process, where the caller
257/// runs the body. Use it as the first statement of every test that creates a
258/// child process:
259///
260/// ```ignore
261/// if crate::test_runs_in_own_process() {
262///     return;
263/// }
264/// ```
265///
266/// The children these tests create are made with a raw `clone` that shares
267/// neither the file-descriptor table nor glibc's `atfork` handlers, and most of
268/// them never `execve`. Such a child therefore receives a copy of every
269/// descriptor open anywhere in the process that runs the test, including the
270/// pipe ends and pidfds of tests running on other libtest threads, and a copy
271/// of every userspace lock another thread held at the instant of the clone.
272/// That is why the `Container` entry points require a single-threaded caller.
273/// The multi-threaded libtest harness breaks that requirement: another test's
274/// child can hold this test's pipe ends open (so a closed reader raises no
275/// `SIGPIPE` and a drain to end-of-file waits forever), a startup child counts
276/// another test's pidfd, a closed descriptor number is reused by another
277/// thread, and a panicking child can block forever on an allocator lock that
278/// one of libtest's own threads held at the clone. A mutex around the tests
279/// cannot stop libtest's own threads from allocating. The fresh process runs
280/// with `--test-threads=1`, where the only other thread is libtest's main
281/// thread blocked in a channel receive, which is the documented
282/// single-threaded setting.
283#[cfg(test)]
284#[must_use]
285pub(crate) fn test_runs_in_own_process() -> bool {
286    let thread = std::thread::current();
287    let name = thread
288        .name()
289        .expect("libtest names each test thread after its test")
290        .to_owned();
291    if let Some(marker) = std::env::var_os(ISOLATED_TEST_MARKER) {
292        assert_eq!(
293            marker.to_str(),
294            Some(name.as_str()),
295            "the isolated test process ran a test other than the one it was started for"
296        );
297        return false;
298    }
299    let output = std::process::Command::new(std::env::current_exe().unwrap())
300        .args([name.as_str(), "--exact", "--test-threads=1", "--nocapture"])
301        .env(ISOLATED_TEST_MARKER, &name)
302        .stdin(std::process::Stdio::null())
303        .output()
304        .unwrap();
305    let stdout = String::from_utf8_lossy(&output.stdout);
306    print!("{stdout}");
307    eprint!("{}", String::from_utf8_lossy(&output.stderr));
308    assert!(
309        output.status.success(),
310        "the isolated process for {name} failed: {:?}",
311        output.status
312    );
313    assert!(
314        stdout.contains("test result: ok. 1 passed; 0 failed;"),
315        "the isolated process for {name} did not run exactly that one test"
316    );
317    true
318}
319
320#[cfg(test)]
321mod tests {
322    use std::collections::BTreeMap;
323    use std::fs;
324    use std::path::Path;
325    use std::str::from_utf8;
326
327    use super::*;
328    use crate::ExitStatus;
329
330    #[tokio::test]
331    async fn spawn() {
332        if crate::test_runs_in_own_process() {
333            return;
334        }
335        assert_eq!(
336            Command::new("true").spawn().unwrap().wait().await.unwrap(),
337            ExitStatus::Exited(0)
338        );
339
340        assert_eq!(
341            Command::new("false").spawn().unwrap().wait().await.unwrap(),
342            ExitStatus::Exited(1)
343        );
344    }
345
346    #[test]
347    fn wait_blocking() {
348        if crate::test_runs_in_own_process() {
349            return;
350        }
351        assert_eq!(
352            Command::new("true")
353                .spawn()
354                .unwrap()
355                .wait_blocking()
356                .unwrap(),
357            ExitStatus::Exited(0)
358        );
359
360        assert_eq!(
361            Command::new("false")
362                .spawn()
363                .unwrap()
364                .wait_blocking()
365                .unwrap(),
366            ExitStatus::Exited(1)
367        );
368    }
369
370    #[tokio::test]
371    async fn spawn_fail() {
372        if crate::test_runs_in_own_process() {
373            return;
374        }
375        assert_eq!(
376            Command::new("/iprobablydonotexist").spawn().unwrap_err(),
377            Error::new(Errno::ENOENT, Context::Exec)
378        );
379    }
380
381    #[tokio::test]
382    async fn double_wait() {
383        if crate::test_runs_in_own_process() {
384            return;
385        }
386        let mut child = Command::new("true").spawn().unwrap();
387        assert_eq!(child.wait().await.unwrap(), ExitStatus::Exited(0));
388        assert_eq!(child.wait().await.unwrap(), ExitStatus::Exited(0));
389    }
390
391    #[tokio::test]
392    async fn output() {
393        if crate::test_runs_in_own_process() {
394            return;
395        }
396        let output = Command::new("echo")
397            .arg("foo")
398            .arg("bar")
399            .output()
400            .await
401            .unwrap();
402        assert_eq!(output.stdout, b"foo bar\n");
403        assert_eq!(output.stderr, b"");
404        assert_eq!(output.status, ExitStatus::Exited(0));
405    }
406
407    fn parse_proc_status(stdout: &[u8]) -> BTreeMap<&str, &str> {
408        from_utf8(stdout)
409            .unwrap()
410            .trim_end()
411            .split('\n')
412            .map(|line| {
413                let (first, second) = line.split_once(':').unwrap();
414                (first, second.trim())
415            })
416            .collect()
417    }
418
419    #[tokio::test]
420    async fn uid_namespace() {
421        if crate::test_runs_in_own_process() {
422            return;
423        }
424        let output = Command::new("cat")
425            .arg("/proc/self/status")
426            .map_root()
427            .output()
428            .await
429            .unwrap();
430        assert_eq!(output.status, ExitStatus::Exited(0));
431
432        let proc_status = parse_proc_status(&output.stdout);
433
434        // We should be root user inside of the container.
435        assert_eq!(proc_status["Uid"], "0\t0\t0\t0");
436    }
437
438    #[tokio::test]
439    async fn pid_namespace() {
440        if crate::test_runs_in_own_process() {
441            return;
442        }
443        let output = Command::new("cat")
444            .arg("/proc/self/status")
445            .map_root()
446            .unshare(Namespace::PID)
447            .output()
448            .await
449            .unwrap();
450        assert_eq!(output.status, ExitStatus::Exited(0));
451
452        let proc_status = parse_proc_status(&output.stdout);
453
454        assert_eq!(proc_status["NSpid"].split('\t').nth(1), Some("1"),);
455
456        // Note that, since we haven't mounted a fresh /proc into the container,
457        // the child still sees what the parent sees and so the PID will *not*
458        // be 1.
459        assert_ne!(proc_status["Pid"], "1");
460    }
461
462    #[tokio::test]
463    async fn mount_proc() {
464        if crate::test_runs_in_own_process() {
465            return;
466        }
467        let output = Command::new("cat")
468            .arg("/proc/self/status")
469            .map_root()
470            .unshare(Namespace::PID)
471            .mount(Mount::proc())
472            .output()
473            .await
474            .unwrap();
475        assert_eq!(output.status, ExitStatus::Exited(0));
476
477        let proc_status = parse_proc_status(&output.stdout);
478
479        // With /proc mounted, the child really believes it is the root process.
480        assert_eq!(proc_status["NSpid"], "1");
481        assert_eq!(proc_status["Pid"], "1");
482    }
483
484    #[tokio::test]
485    async fn mount_proc_with_readonly_fallback() {
486        if crate::test_runs_in_own_process() {
487            return;
488        }
489        let proc = tempfile::tempdir().unwrap();
490        let proc_path = proc.path().to_str().unwrap();
491        let output = Command::new("sh")
492            .arg("-c")
493            .arg(
494                "cat \"$REVERIE_PROC_PATH/mounts\"; echo __STATUS__; \
495                 exec cat \"$REVERIE_PROC_PATH/self/status\"",
496            )
497            .env("REVERIE_PROC_PATH", proc_path)
498            .map_root()
499            .unshare(Namespace::PID)
500            .mount(
501                Mount::new(proc.path())
502                    .fstype("proc")
503                    .allow_readonly_fallback(),
504            )
505            .output()
506            .await
507            .unwrap();
508        assert_eq!(output.status, ExitStatus::Exited(0));
509
510        let stdout = from_utf8(&output.stdout).unwrap();
511        let (mounts, status) = stdout.split_once("__STATUS__\n").unwrap();
512        let proc_options = mounts
513            .lines()
514            .find_map(|line| {
515                let mut fields = line.split_whitespace();
516                let _source = fields.next()?;
517                let target = fields.next()?;
518                let fstype = fields.next()?;
519                let options = fields.next()?;
520                (target == proc_path && fstype == "proc").then_some(options)
521            })
522            .unwrap();
523        assert!(
524            proc_options
525                .split(',')
526                .any(|option| option == "ro" || option == "rw")
527        );
528        println!("nested_proc_options={proc_options}");
529
530        let proc_status = parse_proc_status(status.as_bytes());
531        assert_eq!(proc_status["NSpid"], "1");
532        assert_eq!(proc_status["Pid"], "1");
533    }
534
535    #[tokio::test]
536    async fn hostname() {
537        if crate::test_runs_in_own_process() {
538            return;
539        }
540        let output = Command::new("cat")
541            .arg("/proc/sys/kernel/hostname")
542            .map_root()
543            .hostname("foobar.local")
544            .output()
545            .await
546            .unwrap();
547        assert_eq!(output.status, ExitStatus::Exited(0));
548
549        let hostname = from_utf8(&output.stdout).unwrap().trim();
550
551        assert_eq!(hostname, "foobar.local");
552    }
553
554    #[tokio::test]
555    async fn domainname() {
556        if crate::test_runs_in_own_process() {
557            return;
558        }
559        let output = Command::new("cat")
560            .arg("/proc/sys/kernel/domainname")
561            .map_root()
562            .domainname("foobar")
563            .output()
564            .await
565            .unwrap();
566
567        assert_eq!(output.status, ExitStatus::Exited(0));
568
569        let domainname = from_utf8(&output.stdout).unwrap().trim();
570
571        assert_eq!(domainname, "foobar");
572    }
573
574    #[tokio::test]
575    async fn pty() {
576        if crate::test_runs_in_own_process() {
577            return;
578        }
579        use tokio::io::AsyncReadExt;
580
581        let mut pty = Pty::open().unwrap();
582        let pty_child = pty.child().unwrap();
583
584        let mut tty = pty_child.terminal_params().unwrap();
585        // Prevent post-processing of output so `\n` isn't translated to `\r\n`.
586        tty.c_oflag &= !libc::OPOST;
587        pty_child.set_terminal_params(&tty).unwrap();
588
589        pty_child.set_window_size(40, 80).unwrap();
590
591        // stty is in coreutils and should be available on most systems.
592        let mut child = Command::new("stty")
593            .arg("size")
594            .pty(pty_child)
595            .spawn()
596            .unwrap();
597
598        // NOTE: read_to_end returns an EIO error once the child has exited.
599        let mut buf = Vec::new();
600        assert!(pty.read_to_end(&mut buf).await.is_err());
601
602        assert_eq!(from_utf8(&buf).unwrap(), "40 80\n");
603
604        assert_eq!(child.wait().await.unwrap(), ExitStatus::SUCCESS);
605    }
606
607    #[tokio::test]
608    async fn mount_devpts_basic() {
609        if crate::test_runs_in_own_process() {
610            return;
611        }
612        let output = Command::new("ls")
613            .arg("/dev/pts")
614            .map_root()
615            .mount(Mount::devpts("/dev/pts"))
616            .output()
617            .await
618            .unwrap();
619
620        assert_eq!(output.status, ExitStatus::Exited(0));
621
622        // Should be totally empty except for `/dev/pts/ptmx` since we mounted a
623        // new devpts.
624        assert_eq!(output.stderr, b"");
625        assert_eq!(output.stdout, b"ptmx\n");
626    }
627
628    #[tokio::test]
629    async fn mount_devpts_isolated() {
630        if crate::test_runs_in_own_process() {
631            return;
632        }
633        let output = Command::new("ls")
634            .arg("/dev/pts")
635            .map_root()
636            .mount(Mount::devpts("/dev/pts").data("newinstance,ptmxmode=0666"))
637            .mount(Mount::bind("/dev/pts/ptmx", "/dev/ptmx"))
638            .output()
639            .await
640            .unwrap();
641
642        assert_eq!(output.status, ExitStatus::Exited(0));
643
644        // Should be totally empty except for `/dev/pts/ptmx` since we mounted a
645        // new devpts.
646        assert_eq!(output.stderr, b"");
647        assert_eq!(output.stdout, b"ptmx\n");
648    }
649
650    #[tokio::test]
651    async fn mount_tmpfs() {
652        if crate::test_runs_in_own_process() {
653            return;
654        }
655        let mount = "type=tmpfs,target=/tmp"
656            .parse::<Mount>()
657            .expect("tmpfs mount syntax should parse");
658        let output = Command::new("ls")
659            .arg("/tmp")
660            .map_root()
661            .mount(mount)
662            .output()
663            .await
664            .unwrap();
665
666        assert_eq!(output.status, ExitStatus::Exited(0));
667
668        // Should be totally empty since we mounted a new tmpfs.
669        assert_eq!(output.stderr, b"");
670        assert_eq!(output.stdout, b"");
671    }
672
673    #[tokio::test]
674    async fn mount_and_move_tmpfs() {
675        if crate::test_runs_in_own_process() {
676            return;
677        }
678        let tmpfs = tempfile::tempdir().unwrap();
679
680        // Create a temporary directory that will be the only thing to remain in
681        // the `/tmp` mount.
682        let persistent = tempfile::tempdir().unwrap();
683        fs::write(persistent.path().join("foobar"), b"").unwrap();
684
685        let output = Command::new("ls")
686            .arg("/tmp")
687            .map_root()
688            .mount(Mount::tmpfs(tmpfs.path()))
689            // Bind-mount a directory from our upper /tmp to our new /tmp.
690            .mount(Mount::bind(persistent.path(), tmpfs.path().join("my-dir")).touch_target())
691            // Move our newly-created tmpfs to hide the upper /tmp folder.
692            .mount(Mount::rename(tmpfs.path(), Path::new("/tmp")))
693            .output()
694            .await
695            .unwrap();
696
697        assert_eq!(output.status, ExitStatus::Exited(0));
698
699        // The only thing there should be our bind-mounted directory.
700        assert_eq!(output.stderr, b"");
701        assert_eq!(output.stdout, b"my-dir\n");
702    }
703
704    #[tokio::test]
705    async fn mount_bind() {
706        if crate::test_runs_in_own_process() {
707            return;
708        }
709        let temp = tempfile::tempdir().unwrap();
710        let a = temp.path().join("a");
711        let b = temp.path().join("b");
712
713        fs::create_dir(&a).unwrap();
714        fs::create_dir(&b).unwrap();
715
716        fs::write(a.join("foobar"), "im a test").unwrap();
717
718        let output = Command::new("ls")
719            .arg(&b)
720            .map_root()
721            .mount(Mount::bind(&a, &b))
722            .output()
723            .await
724            .unwrap();
725
726        assert_eq!(output.status, ExitStatus::Exited(0));
727        assert_eq!(output.stdout, b"foobar\n");
728        assert_eq!(output.stderr, b"");
729    }
730
731    #[tokio::test]
732    async fn mount_bind_readonly_rejects_writes() {
733        if crate::test_runs_in_own_process() {
734            return;
735        }
736        let temp = tempfile::tempdir().unwrap();
737        let source = temp.path().join("source");
738        let target = temp.path().join("target");
739        fs::create_dir(&source).unwrap();
740        fs::create_dir(&target).unwrap();
741        fs::write(source.join("data"), "original").unwrap();
742
743        let output = Command::new("sh")
744            .args(["-c", "printf changed > \"$TARGET\""])
745            .env("TARGET", target.join("data"))
746            .map_root()
747            .mount(Mount::bind(&source, &target).readonly())
748            .output()
749            .await
750            .unwrap();
751
752        assert_ne!(output.status, ExitStatus::Exited(0));
753        assert_eq!(fs::read(source.join("data")).unwrap(), b"original");
754    }
755
756    #[tokio::test]
757    async fn local_networking_ping() {
758        if crate::test_runs_in_own_process() {
759            return;
760        }
761        const CHILD_ENV: &str = "REVERIE_PROCESS_LOOPBACK_TEST_CHILD";
762
763        if std::env::var_os(CHILD_ENV).is_some() {
764            let socket = std::net::UdpSocket::bind("[::1]:0").unwrap();
765            let address = socket.local_addr().unwrap();
766            assert_eq!(socket.send_to(b"ping", address).unwrap(), 4);
767
768            let mut buffer = [0; 4];
769            let (length, source) = socket.recv_from(&mut buffer).unwrap();
770            assert_eq!(source, address);
771            assert_eq!(&buffer[..length], b"ping");
772            return;
773        }
774
775        let output = Command::new(std::env::current_exe().unwrap())
776            .arg("--exact")
777            .arg("tests::local_networking_ping")
778            .env(CHILD_ENV, "1")
779            .map_root()
780            .local_networking_only()
781            .output()
782            .await
783            .unwrap();
784
785        assert_eq!(output.status, ExitStatus::Exited(0), "{:?}", output);
786    }
787
788    #[tokio::test]
789    async fn local_networking_loopback_flags() {
790        if crate::test_runs_in_own_process() {
791            return;
792        }
793        let output = Command::new("cat")
794            .arg("/sys/class/net/lo/flags")
795            .map_root()
796            .local_networking_only()
797            .output()
798            .await
799            .unwrap();
800
801        assert_eq!(output.status, ExitStatus::Exited(0), "{:?}", output);
802        assert_eq!(output.stdout, b"0x9\n", "{:?}", output);
803    }
804
805    /// Show that processes in two separate network namespaces can bind to the
806    /// same port.
807    #[tokio::test]
808    async fn port_isolation() {
809        if crate::test_runs_in_own_process() {
810            return;
811        }
812        use std::thread::sleep;
813        use std::time::Duration;
814
815        let mut command = Command::new("nc");
816        command
817            .arg("-l")
818            .arg("127.0.0.1")
819            // Can bind to a low port without real root inside the namespace.
820            .arg("80")
821            .stdin(Stdio::null())
822            .stdout(Stdio::piped())
823            .stderr(Stdio::piped())
824            .map_root()
825            .local_networking_only();
826
827        let server1 = match command.spawn() {
828            // If netcat is not installed just exit successfully.
829            Err(error) if error.errno() == Errno::ENOENT => return,
830            other => other,
831        }
832        .unwrap();
833
834        let server2 = command.spawn().unwrap();
835
836        // Give them both time to start up.
837        sleep(Duration::from_millis(100));
838
839        // Stop them with a signal that cannot be ignored. A test binary launched
840        // as a background shell job inherits SIGINT as ignored, and that
841        // disposition survives exec into nc.
842        server1.signal(Signal::SIGKILL).unwrap();
843        server2.signal(Signal::SIGKILL).unwrap();
844
845        let (output1, output2) = tokio::join!(
846            tokio::time::timeout(Duration::from_secs(1), server1.wait_with_output()),
847            tokio::time::timeout(Duration::from_secs(1), server2.wait_with_output()),
848        );
849        let output1 = output1
850            .expect("port_isolation: server 1 did not exit within 1 second after SIGKILL")
851            .unwrap();
852        let output2 = output2
853            .expect("port_isolation: server 2 did not exit within 1 second after SIGKILL")
854            .unwrap();
855
856        // Without network isolation, one of the servers would exit with an
857        // "Address already in use" (exit status 2) error.
858        assert_eq!(
859            output1.status,
860            ExitStatus::Signaled(Signal::SIGKILL, false),
861            "{:?}",
862            output1
863        );
864        assert_eq!(
865            output2.status,
866            ExitStatus::Signaled(Signal::SIGKILL, false),
867            "{:?}",
868            output2
869        );
870    }
871
872    /// Make sure we can call `.local_networking_only` more than once.
873    #[tokio::test]
874    async fn local_networking_there_can_be_only_one() {
875        if crate::test_runs_in_own_process() {
876            return;
877        }
878        let output = Command::new("true")
879            .map_root()
880            .local_networking_only()
881            // If calling this twice mounted /sys twice, then we'd get a "Device
882            // or resource busy" error.
883            .local_networking_only()
884            .output()
885            .await
886            .unwrap();
887        assert_eq!(output.status, ExitStatus::Exited(0), "{:?}", output);
888        assert_eq!(output.stdout, b"", "{:?}", output);
889        assert_eq!(output.stderr, b"", "{:?}", output);
890    }
891
892    #[test]
893    fn from_std_lossy() {
894        if crate::test_runs_in_own_process() {
895            return;
896        }
897        let mut stdcmd = std::process::Command::new("echo");
898        stdcmd.args(["arg1", "arg2"]);
899        stdcmd.current_dir("/foo/bar");
900        stdcmd.env_clear();
901        stdcmd.env("FOO", "1");
902        stdcmd.env("BAR", "2");
903
904        let cmd = Command::from_std_lossy(&stdcmd);
905
906        assert_eq!(cmd.get_program(), "echo");
907        assert_eq!(cmd.get_arg0(), "echo");
908        assert_eq!(cmd.get_args().collect::<Vec<_>>(), ["arg1", "arg2"]);
909
910        let envs = cmd
911            .get_envs()
912            .filter_map(|(k, v)| Some((k.to_str()?, v.and_then(|v| v.to_str()))))
913            .collect::<Vec<_>>();
914        assert_eq!(envs, [("BAR", Some("2")), ("FOO", Some("1"))]);
915    }
916
917    #[test]
918    fn into_std_lossy_compatibility() {
919        if crate::test_runs_in_own_process() {
920            return;
921        }
922        let mut cmd = Command::new("env");
923        cmd.args(["-0"]);
924        cmd.current_dir("/foo/bar");
925        cmd.env_clear();
926        cmd.env("FOO", "1");
927        cmd.env("BAR", "2");
928
929        let stdcmd = cmd.into_std_lossy();
930
931        assert_eq!(stdcmd.get_program(), "env");
932        assert_eq!(stdcmd.get_args().collect::<Vec<_>>(), ["-0"]);
933
934        let envs = stdcmd
935            .get_envs()
936            .filter_map(|(k, v)| Some((k.to_str()?, v.and_then(|v| v.to_str()))))
937            .collect::<Vec<_>>();
938
939        assert_eq!(envs, [("BAR", Some("2")), ("FOO", Some("1"))]);
940    }
941
942    #[test]
943    fn try_into_std_refuses_container_configuration() {
944        if crate::test_runs_in_own_process() {
945            return;
946        }
947        use syscalls::Sysno;
948
949        use super::seccomp::Action;
950        use super::seccomp::FilterBuilder;
951
952        let filter = FilterBuilder::new()
953            .default_action(Action::Allow)
954            .syscalls([(Sysno::brk, Action::KillProcess)])
955            .build();
956        let mut command = Command::new("true");
957        command.seccomp(filter);
958        let error = command.try_into_std().unwrap_err();
959        assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
960        assert_eq!(
961            error.to_string(),
962            "cannot convert to std::process::Command without losing: seccomp filter"
963        );
964
965        let filter = FilterBuilder::new()
966            .default_action(Action::Allow)
967            .syscalls([(Sysno::brk, Action::KillProcess)])
968            .build();
969        let mut command = Command::new("true");
970        command.seccomp(filter);
971        let panic =
972            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| command.into_std_lossy()))
973                .unwrap_err();
974        let message = panic
975            .downcast_ref::<String>()
976            .map(String::as_str)
977            .or_else(|| panic.downcast_ref::<&str>().copied())
978            .expect("legacy conversion panic must carry a string diagnostic");
979        assert_eq!(
980            message,
981            "Command::into_std_lossy refused unsupported configuration: cannot convert to std::process::Command without losing: seccomp filter"
982        );
983
984        let mut command = Command::new("true");
985        command.unshare(Namespace::MOUNT);
986        let error = command.try_into_std().unwrap_err();
987        assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
988        assert_eq!(
989            error.to_string(),
990            "cannot convert to std::process::Command without losing: Linux namespaces"
991        );
992
993        let mut command = Command::new("true");
994        command.container.affinity(0);
995        let error = command.try_into_std().unwrap_err();
996        assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
997        assert_eq!(
998            error.to_string(),
999            "cannot convert to std::process::Command without losing: CPU affinity"
1000        );
1001    }
1002
1003    #[tokio::test]
1004    async fn seccomp() {
1005        if crate::test_runs_in_own_process() {
1006            return;
1007        }
1008        use syscalls::Sysno;
1009
1010        use super::seccomp::*;
1011
1012        let filter = FilterBuilder::new()
1013            .default_action(Action::Allow)
1014            .syscalls([(Sysno::brk, Action::KillProcess)])
1015            .build();
1016
1017        let output = Command::new("cat")
1018            .arg("/proc/self/status")
1019            .seccomp(filter)
1020            .output()
1021            .await
1022            .unwrap();
1023        assert!(
1024            matches!(output.status, ExitStatus::Signaled(Signal::SIGSYS, _)),
1025            "Expected Signaled(SIGSYS, _), got {:?}",
1026            output.status
1027        );
1028    }
1029
1030    /// The launcher's `execve` must reach the kernel with the argument
1031    /// registers that `execve` ignores (arg3..arg5: r10, r8 and r9) set to
1032    /// zero. A ptrace tracer records all six argument registers at the seccomp
1033    /// stop, so whatever the launcher's own code last left in them would
1034    /// otherwise enter the recorded launch as host-dependent state.
1035    ///
1036    /// A SIGSYS handler observes the registers at the `execve` instruction:
1037    /// the filter traps `execve`, the handler reports the three registers
1038    /// through a pipe, and the child exits before any exec happens. The
1039    /// `pre_exec` callback leaves a recognizable value in those registers, the
1040    /// way arbitrary launcher code can.
1041    #[cfg(target_arch = "x86_64")]
1042    #[tokio::test]
1043    async fn exec_zeroes_unused_argument_registers() {
1044        if crate::test_runs_in_own_process() {
1045            return;
1046        }
1047        use std::sync::atomic::AtomicI32;
1048        use std::sync::atomic::Ordering;
1049
1050        use syscalls::Sysno;
1051
1052        use super::seccomp::*;
1053
1054        const POISON: u64 = 0x5a5a_0000_0000_0030;
1055        static REPORT_FD: AtomicI32 = AtomicI32::new(-1);
1056
1057        extern "C" fn on_sigsys(
1058            _sig: libc::c_int,
1059            _info: *mut libc::siginfo_t,
1060            ctx: *mut libc::c_void,
1061        ) {
1062            // SAFETY: SA_SIGINFO handlers receive a valid ucontext_t.
1063            let gregs = unsafe { &(*(ctx as *const libc::ucontext_t)).uc_mcontext.gregs };
1064            let words = [
1065                gregs[libc::REG_R10 as usize] as u64,
1066                gregs[libc::REG_R8 as usize] as u64,
1067                gregs[libc::REG_R9 as usize] as u64,
1068            ];
1069            let fd = REPORT_FD.load(Ordering::Relaxed);
1070            // SAFETY: write and _exit are async-signal-safe.
1071            unsafe {
1072                libc::write(fd, words.as_ptr() as *const libc::c_void, 24);
1073                libc::_exit(0);
1074            }
1075        }
1076
1077        let mut fds = [0; 2];
1078        assert_eq!(unsafe { libc::pipe(fds.as_mut_ptr()) }, 0);
1079        let (reader, writer) = (fds[0], fds[1]);
1080        REPORT_FD.store(writer, Ordering::Relaxed);
1081
1082        let filter = FilterBuilder::new()
1083            .default_action(Action::Allow)
1084            .syscalls([(Sysno::execve, Action::Trap)])
1085            .build();
1086
1087        let mut command = Command::new("/bin/true");
1088        command.seccomp(filter);
1089        // SAFETY: the callback only calls async-signal-safe sigaction and
1090        // writes registers; it does not allocate.
1091        unsafe {
1092            command.pre_exec(|| {
1093                let mut action: libc::sigaction = std::mem::zeroed();
1094                action.sa_sigaction = on_sigsys as *const () as usize;
1095                action.sa_flags = libc::SA_SIGINFO;
1096                if libc::sigaction(libc::SIGSYS, &action, std::ptr::null_mut()) != 0 {
1097                    return Err(Errno::last());
1098                }
1099                std::arch::asm!(
1100                    "mov r8, {poison}",
1101                    "mov r9, {poison}",
1102                    "mov r10, {poison}",
1103                    poison = in(reg) POISON,
1104                    out("r8") _,
1105                    out("r9") _,
1106                    out("r10") _,
1107                );
1108                Ok(())
1109            });
1110        }
1111
1112        let status = command.spawn().unwrap().wait().await.unwrap();
1113        unsafe { libc::close(writer) };
1114        let mut words = [0u64; 3];
1115        let n = unsafe { libc::read(reader, words.as_mut_ptr() as *mut libc::c_void, 24) };
1116        unsafe { libc::close(reader) };
1117
1118        assert_eq!(status, ExitStatus::SUCCESS);
1119        assert_eq!(
1120            n, 24,
1121            "the SIGSYS handler did not report the execve registers"
1122        );
1123        assert_eq!(
1124            words,
1125            [0, 0, 0],
1126            "execve reached the kernel with leftover launcher registers \
1127             [r10, r8, r9] = [{:#x}, {:#x}, {:#x}]",
1128            words[0],
1129            words[1],
1130            words[2],
1131        );
1132    }
1133
1134    /// `Command` resolves its program the way glibc's `execvpe(3)` does: the
1135    /// `PATH` of the spawning process (default `/bin:/usr/bin`), an empty entry
1136    /// meaning the current directory, `EACCES` remembered while the search
1137    /// continues past `ENOENT` and `ENOTDIR`, any other error ending the
1138    /// search, and a script without a shebang (`ENOEXEC`) run through
1139    /// `/bin/sh`. The expected values are glibc's results, so this passes
1140    /// whether the launcher calls glibc's `execvpe` or reimplements its search.
1141    #[tokio::test]
1142    async fn exec_path_search_matches_glibc_execvpe() {
1143        if crate::test_runs_in_own_process() {
1144            return;
1145        }
1146        use std::os::unix::fs::PermissionsExt;
1147
1148        const NAME: &str = "reverie-exec-probe";
1149
1150        // The directory holding this test binary is on a mount that allows
1151        // exec, which the script cases need; a temporary directory may not be.
1152        let exe = std::env::current_exe().unwrap();
1153        let scratch = tempfile::tempdir_in(exe.parent().unwrap()).unwrap();
1154        let make_dir = |name: &str| {
1155            let dir = scratch.path().join(name);
1156            fs::create_dir(&dir).unwrap();
1157            dir
1158        };
1159        let empty = make_dir("empty");
1160        let not_executable = make_dir("not-executable");
1161        let script = make_dir("script");
1162        let symlink_loop = make_dir("symlink-loop");
1163        let regular_file = scratch.path().join("regular-file");
1164        fs::write(&regular_file, "").unwrap();
1165
1166        let write_probe = |dir: &Path, mode: u32| {
1167            let path = dir.join(NAME);
1168            fs::write(&path, "exit 7\n").unwrap();
1169            fs::set_permissions(&path, fs::Permissions::from_mode(mode)).unwrap();
1170        };
1171        write_probe(&not_executable, 0o644);
1172        // No shebang: `execve` fails with ENOEXEC and the shell runs it.
1173        write_probe(&script, 0o755);
1174        std::os::unix::fs::symlink(NAME, symlink_loop.join(NAME)).unwrap();
1175
1176        // The search reads PATH from this process, not from the child's
1177        // environment. This test runs alone in its own process.
1178        let set_path = |entries: &[&Path]| {
1179            let value = entries
1180                .iter()
1181                .map(|entry| entry.to_str().unwrap())
1182                .collect::<Vec<_>>()
1183                .join(":");
1184            unsafe { std::env::set_var("PATH", value) };
1185        };
1186        let exec_error = |errno| Error::new(errno, Context::Exec);
1187
1188        assert_eq!(
1189            Command::new("").spawn().unwrap_err(),
1190            exec_error(Errno::ENOENT),
1191            "an empty program name"
1192        );
1193        assert_eq!(
1194            Command::new("x".repeat(libc::NAME_MAX as usize + 1))
1195                .spawn()
1196                .unwrap_err(),
1197            exec_error(Errno::ENAMETOOLONG),
1198            "a program name longer than NAME_MAX"
1199        );
1200
1201        set_path(&[&empty]);
1202        assert_eq!(
1203            Command::new(NAME).spawn().unwrap_err(),
1204            exec_error(Errno::ENOENT),
1205            "a program that is on no PATH entry"
1206        );
1207
1208        set_path(&[&not_executable, &empty]);
1209        assert_eq!(
1210            Command::new(NAME).spawn().unwrap_err(),
1211            exec_error(Errno::EACCES),
1212            "EACCES from an earlier entry outranks a later ENOENT"
1213        );
1214
1215        set_path(&[&symlink_loop, &script]);
1216        assert_eq!(
1217            Command::new(NAME).spawn().unwrap_err(),
1218            exec_error(Errno::ELOOP),
1219            "an error other than EACCES, ENOENT or ENOTDIR ends the search"
1220        );
1221
1222        set_path(&[&not_executable, &regular_file, &script]);
1223        assert_eq!(
1224            Command::new(NAME).spawn().unwrap().wait().await.unwrap(),
1225            ExitStatus::Exited(7),
1226            "the search continues past EACCES and ENOTDIR to a script without a shebang"
1227        );
1228
1229        set_path(&[&empty, Path::new("")]);
1230        assert_eq!(
1231            Command::new(NAME)
1232                .current_dir(&script)
1233                .spawn()
1234                .unwrap()
1235                .wait()
1236                .await
1237                .unwrap(),
1238            ExitStatus::Exited(7),
1239            "an empty PATH entry means the current directory"
1240        );
1241
1242        assert_eq!(
1243            Command::new(script.join(NAME))
1244                .spawn()
1245                .unwrap()
1246                .wait()
1247                .await
1248                .unwrap(),
1249            ExitStatus::Exited(7),
1250            "a name containing a slash is executed without a search"
1251        );
1252
1253        unsafe { std::env::remove_var("PATH") };
1254        assert_eq!(
1255            Command::new("true").spawn().unwrap().wait().await.unwrap(),
1256            ExitStatus::Exited(0),
1257            "an unset PATH defaults to /bin:/usr/bin"
1258        );
1259    }
1260
1261    #[tokio::test]
1262    async fn seccomp_notify() {
1263        if crate::test_runs_in_own_process() {
1264            return;
1265        }
1266        use std::collections::HashMap;
1267
1268        use futures::future::Either;
1269        use futures::future::select;
1270        use futures::stream::TryStreamExt;
1271        use syscalls::Sysno;
1272
1273        use super::seccomp::*;
1274
1275        let filter = FilterBuilder::new()
1276            .default_action(Action::Notify)
1277            .syscalls([
1278                // FIXME: Because the first execve happens when the child is
1279                // spawned, we must allow this through. Otherwise, the
1280                // `.spawn()` below will deadlock because we can't process
1281                // seccomp notifications until after it returns.
1282                (Sysno::execve, Action::Allow),
1283            ])
1284            .build();
1285
1286        let mut child = Command::new("cat")
1287            .arg("/proc/self/status")
1288            .seccomp(filter)
1289            .seccomp_notify()
1290            .stdout(Stdio::null())
1291            .spawn()
1292            .unwrap();
1293
1294        let mut summary = HashMap::new();
1295
1296        let exit_status = {
1297            let seccomp_notif = child.seccomp_notif.take();
1298
1299            let notifier = async {
1300                if let Some(mut notifier) = seccomp_notif {
1301                    while let Some(notif) = notifier.try_next().await.unwrap() {
1302                        *summary.entry(Sysno::from(notif.data.nr)).or_insert(0u64) += 1;
1303
1304                        // Simply let the syscall through.
1305                        let resp = seccomp_notif_resp {
1306                            id: notif.id,
1307                            val: 0,
1308                            error: 0,
1309                            flags: SECCOMP_USER_NOTIF_FLAG_CONTINUE,
1310                        };
1311                        notifier.send(&resp).unwrap();
1312                    }
1313                }
1314            };
1315
1316            let exit_status = child.wait();
1317
1318            futures::pin_mut!(notifier);
1319            futures::pin_mut!(exit_status);
1320
1321            match select(notifier, exit_status).await {
1322                Either::Left((_, _)) => unreachable!(),
1323                Either::Right((exit_status, _)) => exit_status.unwrap(),
1324            }
1325        };
1326
1327        assert_eq!(exit_status, ExitStatus::SUCCESS);
1328
1329        assert!(summary[&Sysno::read] > 0);
1330        assert!(summary[&Sysno::write] > 0);
1331        assert!(summary[&Sysno::close] > 0);
1332    }
1333}