1#![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
83pub const TOOL_ENV: &str = "REVERIE_PRELOAD_TOOL";
85pub const LIB_ENV: &str = "REVERIE_PRELOAD_LIB";
87
88#[derive(Clone, Copy, Debug, Eq, PartialEq)]
93pub enum BuiltinTool {
94 Passthrough,
97 SpoofGetpid,
100}
101
102pub 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
131struct SpoofGetpidDispatcher;
133
134impl SyscallDispatcher for SpoofGetpidDispatcher {
135 fn dispatch(&self, event: &mut SyscallEvent) {
136 if event.number() == libc::SYS_getpid {
138 event.set_result(SPOOF_PID);
139 return;
140 }
141 PassthroughDispatcher::new().dispatch(event);
142 }
143}
144
145pub 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
164pub unsafe fn install_builtin(tool: BuiltinTool) -> io::Result<()> {
170 let config = RuntimeConfig::default();
171 unsafe { install(tool.into_dispatcher(), &InProcessSeccomp, &config) }
172}
173
174pub 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
191pub 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
225pub 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#[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}