Skip to main content

reverie_preload/
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//! Shared LD_PRELOAD + seccomp/SIGSYS instrumentation runtime for Reverie's
10//! ld-preload backends (e9patch and liteinst).
11//!
12//! This crate factors the primitives every ld-preload backend needs out of any
13//! one backend so they are written and reviewed **once**:
14//!
15//! * [`seccomp`] — the trap-everything-but-the-trusted-gate BPF filter;
16//! * [`trap`] — the trusted syscall gate, the `SIGSYS` handler, and dispatcher
17//!   registration;
18//! * [`dispatch`] — the [`SyscallDispatcher`] seam
19//!   and the shared fail-closed [`PassthroughDispatcher`];
20//! * [`fork`] — fork-following (the filter is inherited atomically; only
21//!   per-process state must be reset);
22//! * [`signal`] — signal multiplexing / reserved-signal policy;
23//! * [`sync`] — the async-signal-safe [`SpinMutex`](sync::SpinMutex) the
24//!   in-guest tool hosts use for RPC and per-thread state;
25//! * [`lifecycle`] — the [`LifecycleController`]
26//!   seam that makes switching to a hybrid in-process-trap + ptrace backend an
27//!   additive change rather than a rewrite;
28//! * [`rpc`] (feature `coordinator-rpc`) — a synchronous coordinator RPC client
29//!   wire-compatible with the async `reverie-rpc-transport`;
30//! * [`tool_host`] (feature `coordinator-rpc`) — the backend-agnostic driver
31//!   that polls an in-guest Reverie tool's `async` handlers with a no-op waker
32//!   and carries the shared `ERESTARTSYS` restart protocol.
33//!
34//! # Coverage boundaries
35//!
36//! Established by the `research-ldpreload-derisking` task and enforced here:
37//! this runtime is for **trusted, dynamically linked, non-`AT_SECURE`, no-exec**
38//! x86-64 guests. It does not cover vDSO fast paths, the ~40 loader/startup
39//! syscalls before the constructor runs, static binaries, or `execve`. `fork`
40//! *is* fully covered because the kernel inherits the filter atomically.
41//!
42//! # Two ways to use it
43//!
44//! * **As a library (`rlib`):** e9patch/liteinst embed the runtime, register a
45//!   custom [`SyscallDispatcher`], and call
46//!   [`install`].
47//! * **As a standalone `LD_PRELOAD` (`cdylib`):** set `REVERIE_PRELOAD_TOOL` and
48//!   preload `libreverie_preload.so`; the constructor installs a built-in tool.
49
50#![forbid(unsafe_op_in_unsafe_fn)]
51
52#[cfg(not(all(target_os = "linux", target_arch = "x86_64")))]
53compile_error!("reverie-preload requires Linux x86-64");
54
55pub mod dispatch;
56pub mod fmt;
57pub mod fork;
58pub mod lifecycle;
59pub mod seccomp;
60pub mod signal;
61pub mod sync;
62pub mod trap;
63
64#[cfg(feature = "coordinator-rpc")]
65pub mod rpc;
66
67#[cfg(feature = "coordinator-rpc")]
68pub mod tool_host;
69
70use std::env;
71use std::ffi::OsStr;
72use std::io;
73use std::path::PathBuf;
74use std::process::Command;
75
76use crate::dispatch::PassthroughDispatcher;
77use crate::dispatch::SyscallDispatcher;
78use crate::dispatch::SyscallEvent;
79use crate::lifecycle::InProcessSeccomp;
80use crate::lifecycle::LifecycleController;
81use crate::lifecycle::RuntimeConfig;
82
83/// Environment variable selecting a built-in tool for the standalone cdylib.
84pub const TOOL_ENV: &str = "REVERIE_PRELOAD_TOOL";
85/// Environment variable overriding the located preload library path.
86pub const LIB_ENV: &str = "REVERIE_PRELOAD_LIB";
87
88/// The built-in tools the standalone `LD_PRELOAD` cdylib can install.
89///
90/// Real backends register their own [`SyscallDispatcher`]; these exist so the
91/// `.so` is useful and testable on its own.
92#[derive(Clone, Copy, Debug, Eq, PartialEq)]
93pub enum BuiltinTool {
94    /// Forward every syscall (with the shared fail-closed guards). Proves the
95    /// trap path end to end without altering guest behavior.
96    Passthrough,
97    /// Forward everything except `getpid`, which returns [`SPOOF_PID`]. Proves
98    /// the trap can *mutate* a syscall result.
99    SpoofGetpid,
100}
101
102/// The value [`BuiltinTool::SpoofGetpid`] returns for `getpid`.
103pub const SPOOF_PID: i64 = 424_242;
104
105impl BuiltinTool {
106    fn as_str(self) -> &'static str {
107        match self {
108            Self::Passthrough => "passthrough",
109            Self::SpoofGetpid => "spoof-getpid",
110        }
111    }
112
113    fn parse(value: &OsStr) -> Option<Self> {
114        if value == OsStr::new("passthrough") {
115            Some(Self::Passthrough)
116        } else if value == OsStr::new("spoof-getpid") {
117            Some(Self::SpoofGetpid)
118        } else {
119            None
120        }
121    }
122
123    fn into_dispatcher(self) -> Box<dyn SyscallDispatcher> {
124        match self {
125            Self::Passthrough => Box::new(PassthroughDispatcher::new()),
126            Self::SpoofGetpid => Box::new(SpoofGetpidDispatcher),
127        }
128    }
129}
130
131/// A demo dispatcher that spoofs `getpid` and forwards everything else.
132struct SpoofGetpidDispatcher;
133
134impl SyscallDispatcher for SpoofGetpidDispatcher {
135    fn dispatch(&self, event: &mut SyscallEvent) {
136        // AUTONOMOUS-BOT-IMPLEMENTED
137        if event.number() == libc::SYS_getpid {
138            event.set_result(SPOOF_PID);
139            return;
140        }
141        PassthroughDispatcher::new().dispatch(event);
142    }
143}
144
145/// Install the runtime with a caller-provided dispatcher and controller.
146///
147/// This is the library entry point for e9patch/liteinst. Registers `dispatcher`,
148/// then installs `controller` (which puts the SIGSYS handler and seccomp filter
149/// in place).
150///
151/// # Safety
152///
153/// Installs process-global, irreversible state. Call exactly once, before
154/// untrusted application threads start.
155pub unsafe fn install(
156    dispatcher: Box<dyn SyscallDispatcher>,
157    controller: &dyn LifecycleController,
158    config: &RuntimeConfig,
159) -> io::Result<()> {
160    trap::set_dispatcher(dispatcher);
161    unsafe { controller.install(config) }
162}
163
164/// Install a built-in tool with the default in-process controller.
165///
166/// # Safety
167///
168/// See [`install`].
169pub unsafe fn install_builtin(tool: BuiltinTool) -> io::Result<()> {
170    let config = RuntimeConfig::default();
171    unsafe { install(tool.into_dispatcher(), &InProcessSeccomp, &config) }
172}
173
174/// Read [`TOOL_ENV`] and, if it names a built-in tool, install the runtime.
175///
176/// Absent env var → the preload is inert (returns `Ok(())`), so an unrelated
177/// process that happens to have the `.so` on `LD_PRELOAD` is unaffected.
178pub fn initialize_from_environment() -> io::Result<()> {
179    let Some(value) = env::var_os(TOOL_ENV) else {
180        return Ok(());
181    };
182    let tool = BuiltinTool::parse(&value).ok_or_else(|| {
183        io::Error::new(
184            io::ErrorKind::InvalidInput,
185            format!("unsupported {TOOL_ENV} value {value:?}"),
186        )
187    })?;
188    unsafe { install_builtin(tool) }
189}
190
191/// Locate the preload cdylib beside the current executable, or via [`LIB_ENV`].
192pub fn preload_library_path() -> io::Result<PathBuf> {
193    if let Some(path) = env::var_os(LIB_ENV) {
194        let path = PathBuf::from(path);
195        return path.is_file().then_some(path).ok_or_else(|| {
196            io::Error::new(io::ErrorKind::NotFound, format!("{LIB_ENV} is not a file"))
197        });
198    }
199
200    let executable = env::current_exe()?;
201    let parent = executable.parent().ok_or_else(|| {
202        io::Error::new(io::ErrorKind::NotFound, "current executable has no parent")
203    })?;
204    [
205        parent.join("libreverie_preload.so"),
206        parent.join("deps/libreverie_preload.so"),
207        parent
208            .parent()
209            .unwrap_or(parent)
210            .join("libreverie_preload.so"),
211    ]
212    .into_iter()
213    .find(|path| path.is_file())
214    .ok_or_else(|| {
215        io::Error::new(
216            io::ErrorKind::NotFound,
217            format!(
218                "cannot find libreverie_preload.so beside {}",
219                executable.display()
220            ),
221        )
222    })
223}
224
225/// Configure `command` to load the runtime and select a built-in `tool`.
226///
227/// Prepends the located cdylib to `LD_PRELOAD` and sets [`TOOL_ENV`].
228pub fn configure_command(command: &mut Command, tool: BuiltinTool) -> io::Result<()> {
229    let mut preload = preload_library_path()?.into_os_string();
230    if let Some(existing) = env::var_os("LD_PRELOAD").filter(|value| !value.is_empty()) {
231        preload.push(OsStr::new(":"));
232        preload.push(existing);
233    }
234    command
235        .env("LD_PRELOAD", preload)
236        .env(TOOL_ENV, tool.as_str());
237    Ok(())
238}
239
240// TODO-HUMAN-REVIEW(#100): this constructor installs process-wide
241// signal and seccomp state. Only a human reviewer may clear this marker.
242/// Constructor entry point invoked by the dynamic loader for the cdylib.
243///
244/// # Safety
245///
246/// The loader must call this exactly once before application threads start.
247#[unsafe(no_mangle)]
248pub unsafe extern "C" fn reverie_preload_initialize() {
249    if let Err(error) = initialize_from_environment() {
250        eprintln!("reverie-preload initialization failed: {error}");
251        unsafe {
252            libc::_exit(127);
253        }
254    }
255}
256
257#[cfg(feature = "preload-constructor")]
258#[used]
259#[unsafe(link_section = ".init_array")]
260static REVERIE_PRELOAD_INIT: unsafe extern "C" fn() = reverie_preload_initialize;
261
262#[cfg(test)]
263mod tests {
264    use super::*;
265
266    #[test]
267    fn builtin_tool_names_round_trip() {
268        for tool in [BuiltinTool::Passthrough, BuiltinTool::SpoofGetpid] {
269            let name = tool.as_str();
270            assert_eq!(BuiltinTool::parse(OsStr::new(name)), Some(tool));
271        }
272        assert_eq!(BuiltinTool::parse(OsStr::new("nope")), None);
273    }
274
275    #[test]
276    fn spoof_dispatcher_keeps_shared_fail_closed_guards() {
277        let dispatcher = SpoofGetpidDispatcher;
278        let mut mask_args = [0; 6];
279        mask_args[0] = libc::SIG_BLOCK as u64;
280        mask_args[1] = 0xdead_beef;
281        let mut mask = SyscallEvent::new(libc::SYS_rt_sigprocmask, mask_args, 0);
282        dispatcher.dispatch(&mut mask);
283        assert_eq!(mask.result(), Some(-i64::from(libc::EPERM)));
284
285        let mut exec = SyscallEvent::new(libc::SYS_execve, [0; 6], 0);
286        dispatcher.dispatch(&mut exec);
287        assert_eq!(exec.result(), Some(-i64::from(libc::ENOTSUP)));
288    }
289}