heimdall-core 0.2.0

Core Heimdall sandbox runtime orchestration and execution types.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
use std::ffi::OsString;
use std::io::{Read, Write};
use std::process::{Command, Stdio};
use std::thread;

use heimdall_sandbox_policy::AgentPolicy;

use crate::child::ChildGuard;
use crate::environment::{build_child_environment, strip_dangerous_environment};
use crate::outcome::child_outcome;
use crate::request::{EnvPolicy, ExecRequest, StdioPolicy};
use crate::{Error, Result};

#[cfg(target_os = "linux")]
use heimdall_linux_sandbox::BubblewrapRequest;
#[cfg(target_os = "macos")]
use heimdall_macos_sandbox::SeatbeltRequest;

/// Executes sandbox requests.
///
/// A zero-sized marker type that namespaces sandbox execution methods.
/// Using a type rather than free functions allows future extension (e.g.
/// injecting custom signal handlers or loggers) without changing call sites.
#[derive(Debug, Default)]
pub struct Executor;

impl Executor {
    /// Execute a sandbox request and return the child process exit code.
    ///
    /// # Errors
    ///
    /// Returns an error when validation, hardening, spawning, signal setup, or wait fails.
    pub fn execute(&self, request: &ExecRequest) -> Result<i32> {
        self.execute_with_hardener(request, heimdall_process_hardening::apply_child_hardening)
    }

    fn execute_with_hardener(
        &self,
        request: &ExecRequest,
        hardener: impl FnOnce() -> std::io::Result<()> + Send + Sync + 'static,
    ) -> Result<i32> {
        if request.needs_isolation() {
            #[cfg(target_os = "linux")]
            {
                return self.execute_with_bubblewrap(request);
            }
            #[cfg(target_os = "macos")]
            {
                return self.execute_with_seatbelt(request);
            }
            #[cfg(not(any(target_os = "linux", target_os = "macos")))]
            {
                return Err(Error::sandbox_misconfiguration(
                    "filesystem/network isolation is not supported on this platform",
                ));
            }
        }

        self.execute_direct_with_hardener(request, hardener)
    }

    fn execute_direct_with_hardener(
        &self,
        request: &ExecRequest,
        hardener: impl FnOnce() -> std::io::Result<()> + Send + Sync + 'static,
    ) -> Result<i32> {
        let child_environment = self.child_environment(request);

        let mut command = Command::new(&request.argv()[0]);
        command
            .args(&request.argv()[1..])
            .current_dir(request.cwd())
            .env_clear()
            .envs(child_environment);
        Self::configure_stdio(&mut command, request.stdio_policy());

        #[cfg(unix)]
        install_child_setup(&mut command, hardener);

        #[cfg(not(unix))]
        hardener().map_err(Error::Hardening)?;

        self.execute_command(command, request.stdio_policy())
    }

    fn child_environment(
        &self,
        request: &ExecRequest,
    ) -> Vec<(std::ffi::OsString, std::ffi::OsString)> {
        let parent_environment = std::env::vars_os().collect::<Vec<_>>();
        let child_environment = build_child_environment(
            parent_environment,
            request.allowed_env(),
            request.denied_env(),
            request.env_policy() == EnvPolicy::Blocklist,
        );
        let mut child_environment = strip_dangerous_environment(child_environment);
        append_agent_environment(&mut child_environment, request.agent_policy());
        child_environment
    }

    fn execute_command(&self, command: Command, stdio_policy: StdioPolicy) -> Result<i32> {
        self.execute_command_with_signal_target(command, stdio_policy, false)
    }

    fn execute_command_with_signal_target(
        &self,
        mut command: Command,
        stdio_policy: StdioPolicy,
        target_process_group: bool,
    ) -> Result<i32> {
        #[cfg(unix)]
        let forwarding = if target_process_group {
            crate::signal::SignalForwarding::install_for_process_group()?
        } else {
            crate::signal::SignalForwarding::install()?
        };

        let mut child = command.spawn().map_err(Error::Spawn)?;
        let output_forwarding = OutputForwarding::start(&mut child, stdio_policy);
        let mut child = ChildGuard::new(child);

        #[cfg(unix)]
        forwarding.set_child(child.id())?;

        let status = child.wait()?;
        output_forwarding.join();

        #[cfg(unix)]
        drop(forwarding);

        Ok(child_outcome(status).exit_code())
    }

    #[cfg(target_os = "linux")]
    fn execute_with_bubblewrap(&self, request: &ExecRequest) -> Result<i32> {
        let plan = BubblewrapRequest {
            cwd: request.cwd(),
            argv: request.argv(),
            network_mode: request.network_mode(),
            stdio_policy: match request.stdio_policy() {
                StdioPolicy::Inherit => "inherit",
                StdioPolicy::Piped => "piped",
            },
            filesystem_policy: &request.effective_filesystem_policy(),
            proc_mode: request.proc_mode(),
            agent_policy: request.agent_policy(),
        }
        .into_plan()?;
        let mut command = plan.command();
        command
            .current_dir(request.cwd())
            .env_clear()
            .envs(self.child_environment(request));
        Self::configure_stdio(&mut command, request.stdio_policy());
        install_bubblewrap_child_setup(&mut command);
        let result = self.execute_bubblewrap_command(command, request.stdio_policy());
        let cleanup_result = plan.cleanup_missing_deny_guards();
        match (result, cleanup_result) {
            (Ok(exit_code), Ok(())) => Ok(exit_code),
            (Err(error), Ok(())) | (Err(error), Err(_)) => Err(error),
            (Ok(_), Err(error)) => Err(error.into()),
        }
    }

    #[cfg(target_os = "linux")]
    fn execute_bubblewrap_command(
        &self,
        mut command: Command,
        stdio_policy: StdioPolicy,
    ) -> Result<i32> {
        let forwarding = crate::signal::SignalForwarding::install_for_bubblewrap_payload()?;

        let mut child = command.spawn().map_err(Error::Spawn)?;
        let output_forwarding = OutputForwarding::start(&mut child, stdio_policy);
        let mut child = ChildGuard::new(child);

        forwarding.set_child(child.id())?;

        let status = child.wait()?;
        output_forwarding.join();
        drop(forwarding);

        Ok(child_outcome(status).exit_code())
    }

    #[cfg(target_os = "macos")]
    fn execute_with_seatbelt(&self, request: &ExecRequest) -> Result<i32> {
        let plan = SeatbeltRequest {
            cwd: request.cwd(),
            argv: request.argv(),
            network_mode: request.network_mode(),
            filesystem_policy: &request.effective_filesystem_policy(),
            proc_mode: request.proc_mode(),
            agent_policy: request.agent_policy(),
        }
        .into_plan()?;
        let mut command = plan.command();
        command
            .current_dir(request.cwd())
            .env_clear()
            .envs(self.child_environment(request));
        Self::configure_stdio(&mut command, request.stdio_policy());
        install_seatbelt_child_setup(&mut command);
        self.execute_command_with_signal_target(command, request.stdio_policy(), true)
    }

    fn configure_stdio(command: &mut Command, stdio_policy: StdioPolicy) {
        match stdio_policy {
            StdioPolicy::Inherit => {
                command
                    .stdin(Stdio::inherit())
                    .stdout(Stdio::inherit())
                    .stderr(Stdio::inherit());
            }
            StdioPolicy::Piped => {
                command
                    .stdin(Stdio::null())
                    .stdout(Stdio::piped())
                    .stderr(Stdio::piped());
            }
        }
    }
}

fn append_agent_environment(
    environment: &mut Vec<(OsString, OsString)>,
    agent_policy: AgentPolicy,
) {
    if agent_policy.ssh_agent() {
        append_parent_environment(environment, "SSH_AUTH_SOCK");
    }
    if agent_policy.gpg_agent() {
        append_parent_environment(environment, "GPG_AGENT_INFO");
    }
    if agent_policy.age_agent() {
        append_parent_environment(environment, "AGE_AUTH_SOCK");
        append_parent_environment(environment, "GOPASS_AGE_AGENT_SOCK");
    }
}

fn append_parent_environment(environment: &mut Vec<(OsString, OsString)>, key: &str) {
    let Some(value) = std::env::var_os(key) else {
        return;
    };
    let key = OsString::from(key);
    if let Some((_, existing_value)) = environment
        .iter_mut()
        .find(|(existing_key, _)| existing_key == &key)
    {
        *existing_value = value;
    } else {
        environment.push((key, value));
    }
}

struct OutputForwarding {
    stdout: Option<thread::JoinHandle<std::io::Result<()>>>,
    stderr: Option<thread::JoinHandle<std::io::Result<()>>>,
}

impl OutputForwarding {
    fn start(child: &mut std::process::Child, stdio_policy: StdioPolicy) -> Self {
        if stdio_policy != StdioPolicy::Piped {
            return Self {
                stdout: None,
                stderr: None,
            };
        }

        let stdout = child.stdout.take().map(|mut stream| {
            thread::spawn(move || {
                let mut output = std::io::stdout().lock();
                copy_stream(&mut stream, &mut output)
            })
        });
        let stderr = child.stderr.take().map(|mut stream| {
            thread::spawn(move || {
                let mut output = std::io::stderr().lock();
                copy_stream(&mut stream, &mut output)
            })
        });

        Self { stdout, stderr }
    }

    fn join(self) {
        if let Some(stdout) = self.stdout
            && let Err(panic) = stdout.join()
        {
            std::panic::resume_unwind(panic);
        }
        if let Some(stderr) = self.stderr
            && let Err(panic) = stderr.join()
        {
            std::panic::resume_unwind(panic);
        }
    }
}

fn copy_stream(reader: &mut impl Read, writer: &mut impl Write) -> std::io::Result<()> {
    std::io::copy(reader, writer)?;
    writer.flush()
}

#[cfg(unix)]
fn install_child_setup(
    command: &mut Command,
    hardener: impl FnOnce() -> std::io::Result<()> + Send + Sync + 'static,
) {
    use std::os::unix::process::CommandExt;

    #[cfg(target_os = "linux")]
    // SAFETY: `getpid` has no preconditions.
    let parent_pid = unsafe { libc::getpid() };
    let mut hardener = Some(hardener);

    // SAFETY: the closure only calls libc/setup routines intended to run after fork and before
    // exec, and propagates `std::io::Error` values directly to `Command::spawn`.
    unsafe {
        command.pre_exec(move || {
            #[cfg(target_os = "linux")]
            heimdall_process_hardening::terminate_with_parent(parent_pid)?;

            let hardener = hardener.take().ok_or_else(|| {
                std::io::Error::other("child hardening callback was already consumed")
            })?;
            hardener()
        });
    }
}

#[cfg(target_os = "macos")]
fn install_seatbelt_child_setup(command: &mut Command) {
    use std::os::unix::process::CommandExt;

    // SAFETY: the closure only calls libc/setup routines intended to run after fork and before
    // exec, and propagates `std::io::Error` values directly to `Command::spawn`.
    unsafe {
        command.pre_exec(move || {
            // SAFETY: `setpgid(0, 0)` places the child in a fresh process group before exec.
            if libc::setpgid(0, 0) != 0 {
                return Err(std::io::Error::last_os_error());
            }
            heimdall_process_hardening::apply_child_hardening()
        });
    }
}

#[cfg(target_os = "linux")]
fn install_bubblewrap_child_setup(command: &mut Command) {
    use std::os::unix::process::CommandExt;

    #[cfg(target_os = "linux")]
    // SAFETY: `getpid` has no preconditions.
    let parent_pid = unsafe { libc::getpid() };

    // SAFETY: the closure only calls libc/setup routines intended to run after fork and before
    // exec, and propagates `std::io::Error` values directly to `Command::spawn`.
    unsafe {
        command.pre_exec(move || {
            // SAFETY: `setpgid(0, 0)` places the child in a fresh process group before exec.
            if libc::setpgid(0, 0) != 0 {
                return Err(std::io::Error::last_os_error());
            }
            heimdall_process_hardening::terminate_with_parent(parent_pid)
        });
    }
}

#[cfg(test)]
mod tests {
    use std::io;
    use std::time::{SystemTime, UNIX_EPOCH};

    use super::*;

    #[test]
    fn hardening_failure_maps_to_misconfiguration_exit_code() {
        let request = ExecRequest::new(
            std::env::current_dir().expect("current dir exists"),
            vec!["true".to_string()],
            Vec::new(),
        )
        .expect("request is valid");

        let error = Executor
            .execute_with_hardener(&request, || Err(io::Error::other("hardening failed")))
            .expect_err("hardening failure is fatal");

        assert_eq!(error.exit_code(), crate::SANDBOX_MISCONFIGURATION_EXIT_CODE);
    }

    #[test]
    fn hardening_failure_does_not_execute_child_command() {
        let stamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("system time is after Unix epoch")
            .as_nanos();
        let marker = std::env::temp_dir().join(format!("heimdall-hardening-{stamp}"));
        let script = format!("touch {}", marker.display());
        let request = ExecRequest::new(
            std::env::current_dir().expect("current dir exists"),
            vec!["sh".to_string(), "-c".to_string(), script],
            Vec::new(),
        )
        .expect("request is valid");

        let error = Executor
            .execute_with_hardener(&request, || Err(io::Error::other("hardening failed")))
            .expect_err("hardening failure is fatal");

        assert_eq!(error.exit_code(), crate::SANDBOX_MISCONFIGURATION_EXIT_CODE);
        assert!(!marker.exists());
    }
}