procage 0.8.0

Process sandboxing for Rust on macOS (Seatbelt, without sandbox-exec) and Linux (Landlock, seccomp, namespaces)
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
417
418
419
420
421
422
423
//! The violation monitor: one per process, started on the first spawn of a
//! cage that reports violations.
//!
//! The kernel logs every Seatbelt denial to the unified log, ending with the
//! denying rule's message, which a reporting profile sets to the run's
//! marker (and the rule's kind). The monitor runs `/usr/bin/log stream` with
//! a predicate that admits only denials naming this process's marker prefix,
//! parses each line and adds the violation to the record of the run whose
//! marker it names.
//!
//! A fence is a denial too: a forked child applies a profile whose message is
//! the fence marker, is denied opening `/`, and exits. Kernel denials reach
//! the stream in the order they were logged (pinned by a kernel fact; a
//! `syslog` line from this process was measured to overtake them), so when
//! the fence's own denial arrives, every denial logged before it has too: a
//! run's record is complete once a fence made after the run ended is seen.
//!
//! `log stream` keeps running when the process that started it dies, so it
//! runs under a `/bin/sh` watchdog that kills it when the pipe from this
//! process closes. Both binaries must be root-owned, not writable by group
//! or others, and on a read-only volume (the sealed system volume) before
//! they are run.

use std::collections::{HashMap, HashSet};
use std::ffi::CString;
use std::io::{BufRead, BufReader, Read};
use std::os::unix::fs::MetadataExt;
use std::path::Path;
use std::process::{ChildStdin, Command, Stdio};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock};
use std::time::{Duration, Instant, SystemTime};

use super::{lifetime, sys};
use crate::violation::{Coverage, Record, parse};
pub(crate) use crate::violation::{Sink, lock};

/// The shell that runs the watchdog.
const SH: &str = "/bin/sh";
/// The unified-log reader.
const LOG: &str = "/usr/bin/log";
/// How long the stream may take to deliver its first fence.
const READY: Duration = Duration::from_secs(2);
/// How long a fence may take.
const FENCE: Duration = Duration::from_secs(1);
/// How long to wait for one fence before making another.
const RESEND: Duration = Duration::from_millis(100);

/// `$1` is the predicate. `log` reads nothing; the subshell reads the pipe
/// from this process (fd 3, since an asynchronous list's standard input is
/// `/dev/null`) and kills `log` when it closes; the shell waits for `log`,
/// so a `log` that exits closes the stream.
const SCRIPT: &str = "exec 3<&0
/usr/bin/log stream --style ndjson --predicate \"$1\" </dev/null 3<&- &
L=$!
(read _ <&3; kill $L) >/dev/null 2>&1 &
exec 3<&-
wait $L";

#[derive(Debug, Clone, PartialEq, Eq)]
enum Status {
    Idle,
    Starting,
    Ready,
    Down(String),
}

struct State {
    status: Status,
    /// Distinguishes helpers, so a reader of an old one cannot change state.
    generation: u64,
    /// The pipe the watchdog reads; dropping it ends the helper.
    stdin: Option<ChildStdin>,
    sinks: HashMap<String, Sink>,
    /// The pids of fences whose denial arrived.
    seen: HashSet<u32>,
}

struct Monitor {
    state: Mutex<State>,
    changed: Condvar,
}

fn monitor() -> &'static Monitor {
    static MONITOR: OnceLock<Monitor> = OnceLock::new();
    MONITOR.get_or_init(|| Monitor {
        state: Mutex::new(State {
            status: Status::Idle,
            generation: 0,
            stdin: None,
            sinks: HashMap::new(),
            seen: HashSet::new(),
        }),
        changed: Condvar::new(),
    })
}

impl Monitor {
    fn state(&self) -> MutexGuard<'_, State> {
        self.state.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// Starts the helper unless it is ready; the coverage new runs get.
    fn ensure(&self) -> Coverage {
        let mut state = self.state();
        loop {
            match &state.status {
                Status::Ready => return Coverage::Observed,
                Status::Starting => {
                    state = self.changed.wait(state).unwrap_or_else(|e| e.into_inner());
                }
                Status::Idle | Status::Down(_) => break,
            }
        }
        state.status = Status::Starting;
        state.generation += 1;
        let generation = state.generation;
        drop(state);
        let started = self.start(generation);
        let mut state = self.state();
        let coverage = match started {
            Ok(()) if state.status == Status::Ready => Coverage::Observed,
            Ok(()) => match &state.status {
                Status::Down(reason) => Coverage::Unavailable(reason.clone()),
                _ => Coverage::Unavailable("the log stream did not start".into()),
            },
            Err(reason) => {
                state.status = Status::Down(reason.clone());
                state.stdin = None;
                Coverage::Unavailable(reason)
            }
        };
        self.changed.notify_all();
        coverage
    }

    /// Runs the helper and waits for it to deliver a ping.
    fn start(&self, generation: u64) -> Result<(), String> {
        for binary in [SH, LOG] {
            trusted(binary)?;
        }
        fence_bytecode()?;
        let prefix = lifetime::prefix();
        // The prefix is hex digits and dots: nothing to escape.
        let predicate = format!("sender == \"Sandbox\" AND eventMessage CONTAINS \"{prefix}\"");
        let mut command = Command::new(SH);
        command
            .args(["-c", SCRIPT, "sh", &predicate])
            .env_clear()
            .current_dir("/")
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());
        // The helper lives as long as the process: it must not keep another
        // spawn's pipe open.
        sys::inherit_only_stdio(&mut command);
        let mut child = command
            .spawn()
            .map_err(|e| format!("cannot start {SH}: {e}"))?;
        let stdout = child.stdout.take().expect("piped");
        let stderr = child.stderr.take().expect("piped");
        self.state().stdin = child.stdin.take();
        std::thread::Builder::new()
            .name("procage-violations".into())
            .spawn(move || {
                read(generation, stdout, stderr);
                // The helper ended; reap it.
                let _ = child.wait();
            })
            .map_err(|e| format!("cannot start the reader thread: {e}"))?;
        let deadline = Instant::now() + READY;
        while Instant::now() < deadline {
            if let Some(seen) = self.ping(generation, Duration::from_millis(50)) {
                if seen {
                    let mut state = self.state();
                    if state.generation == generation && state.status == Status::Starting {
                        state.status = Status::Ready;
                    }
                }
                return Ok(());
            }
        }
        self.state().stdin = None;
        Err(format!(
            "the log stream did not answer within {}s",
            READY.as_secs()
        ))
    }

    /// Makes fences and waits up to `timeout` for one's denial: `Some(true)`
    /// seen, `Some(false)` the helper went down or no fence could be made,
    /// `None` timed out. The system drops an occasional report (macOS 27:
    /// about one in 2,000), a fence's too, so a fresh fence follows every
    /// [`RESEND`]; any fence made after the run ended proves its denials
    /// arrived.
    fn ping(&self, generation: u64, timeout: Duration) -> Option<bool> {
        let Some(first) = make_fence() else {
            return Some(false);
        };
        let mut fences = vec![first];
        let deadline = Instant::now() + timeout;
        let mut resend = Instant::now() + RESEND;
        let mut state = self.state();
        let result = loop {
            if fences.iter().any(|n| state.seen.contains(n)) {
                break Some(true);
            }
            if state.generation != generation || matches!(state.status, Status::Down(_)) {
                break Some(false);
            }
            let now = Instant::now();
            let Some(left) = deadline.checked_duration_since(now) else {
                break None;
            };
            if now >= resend {
                drop(state);
                fences.extend(make_fence());
                resend = Instant::now() + RESEND;
                state = self.state();
                continue;
            }
            let wait = left.min(resend - now);
            state = self
                .changed
                .wait_timeout(state, wait)
                .unwrap_or_else(|e| e.into_inner())
                .0;
        };
        for n in &fences {
            state.seen.remove(n);
        }
        result
    }
}

/// Checks that `path` is a root-owned file, not writable by group or others,
/// on a read-only volume.
fn trusted(path: &str) -> Result<(), String> {
    let untrusted = |why: &str| Err(format!("{path} is not trusted: {why}"));
    let meta = std::fs::metadata(Path::new(path)).map_err(|e| format!("{path}: {e}"))?;
    if meta.uid() != 0 {
        return untrusted("not owned by root");
    }
    if meta.mode() & 0o022 != 0 {
        return untrusted("writable by group or others");
    }
    let c = CString::new(path).map_err(|_| format!("{path}: contains NUL"))?;
    match sys::on_read_only_volume(&c) {
        Ok(true) => Ok(()),
        Ok(false) => untrusted("not on a read-only volume"),
        Err(errno) => Err(format!("{path}: statfs failed (errno {errno})")),
    }
}

/// The message of a fence's denial.
fn fence_marker() -> String {
    format!("{}fence", lifetime::prefix())
}

/// The fence profile, compiled once: everything denied, with the fence
/// marker as the message.
fn fence_bytecode() -> Result<Arc<[u8]>, String> {
    static FENCE: OnceLock<Result<Arc<[u8]>, String>> = OnceLock::new();
    FENCE
        .get_or_init(|| {
            let lib = super::libsandbox().map_err(|e| e.to_string())?;
            let profile = format!(
                "(version 1)\n(deny default (with message \"{}\"))\n",
                fence_marker()
            );
            lib.compile(&profile, &[])
                .map(Arc::from)
                .map_err(|e| format!("cannot compile the fence profile: {e:?}"))
        })
        .clone()
}

/// Forks a fence and reaps it; its pid, or `None` when it could not run.
fn make_fence() -> Option<u32> {
    let lib = super::libsandbox().ok()?;
    let bytecode = fence_bytecode().ok()?;
    let mut command = Command::new("/usr/bin/true");
    command
        .env_clear()
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null());
    sys::install_fence(&mut command, lib.child_ops(), bytecode);
    let mut child = command.spawn().ok()?;
    let pid = child.id();
    // Exit 0: the open of `/` was denied, so the kernel logged it.
    let denied = child.wait().ok()?.success();
    denied.then_some(pid)
}

/// The reader thread of one helper.
fn read(generation: u64, stdout: std::process::ChildStdout, mut stderr: std::process::ChildStderr) {
    let fence = fence_marker();
    let m = monitor();
    for line in BufReader::new(stdout).lines() {
        let Ok(line) = line else { break };
        let Ok(value) = serde_json::from_str::<serde_json::Value>(&line) else {
            continue;
        };
        let Some(message) = value.get("eventMessage").and_then(|v| v.as_str()) else {
            continue;
        };
        let Some((marker, violation)) = parse(message, SystemTime::now()) else {
            continue;
        };
        if marker == fence {
            let mut state = m.state();
            if state.generation == generation {
                state.seen.insert(violation.pid);
                m.changed.notify_all();
            }
            continue;
        }
        let sink = m.state().sinks.get(marker).cloned();
        if let Some(sink) = sink {
            lock(&sink).push(violation);
        }
    }
    let mut reason = String::new();
    let _ = stderr.read_to_string(&mut reason);
    let reason = match reason.trim() {
        "" => "the log stream ended".to_string(),
        text => format!("the log stream ended: {text}"),
    };
    let mut state = m.state();
    if state.generation != generation {
        return;
    }
    state.status = Status::Down(reason.clone());
    state.stdin = None;
    for (_, sink) in state.sinks.drain() {
        lock(&sink).interrupt(&reason);
    }
    m.changed.notify_all();
}

/// Registers the run `marker`, starting the helper when needed. Returns the
/// run's record; when reporting is unavailable it says why and is not
/// registered.
pub(crate) fn register(marker: &str) -> Sink {
    let m = monitor();
    let coverage = m.ensure();
    let observed = coverage == Coverage::Observed;
    let sink = Arc::new(Mutex::new(Record::new(coverage)));
    if observed {
        m.state().sinks.insert(marker.to_string(), sink.clone());
    }
    sink
}

/// Stops routing violations to `marker`.
pub(crate) fn unregister(marker: &str) {
    monitor().state().sinks.remove(marker);
}

/// Waits until every denial logged so far has arrived; `false` when the
/// helper is down or the fence timed out.
pub(crate) fn fence() -> bool {
    let m = monitor();
    let generation = {
        let state = m.state();
        if state.status != Status::Ready {
            return false;
        }
        state.generation
    };
    m.ping(generation, FENCE) == Some(true)
}

/// Ends the helper (for tests): the reader sees the stream end.
pub(crate) fn stop() {
    monitor().state().stdin = None;
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A helper that never delivers the fence makes the wait time
    /// out after its limit instead of blocking.
    #[test]
    fn a_silent_helper_times_out() {
        let silent = Monitor {
            state: Mutex::new(State {
                status: Status::Ready,
                generation: 1,
                stdin: None,
                sinks: HashMap::new(),
                seen: HashSet::new(),
            }),
            changed: Condvar::new(),
        };
        let start = Instant::now();
        assert_eq!(silent.ping(1, Duration::from_millis(200)), None);
        let took = start.elapsed();
        assert!(
            took >= Duration::from_millis(200) && took < Duration::from_secs(2),
            "{took:?}"
        );
    }

    #[test]
    fn system_binaries_are_trusted() {
        assert_eq!(trusted(SH), Ok(()));
        assert_eq!(trusted(LOG), Ok(()));
    }

    #[test]
    fn user_files_are_not_trusted() {
        let dir = std::env::temp_dir().join(format!("procage-trust-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("log");
        std::fs::write(&file, "#!/bin/sh\n").unwrap();
        let err = trusted(file.to_str().unwrap()).unwrap_err();
        assert!(err.contains("not owned by root"), "{err}");
        let _ = std::fs::remove_dir_all(dir);
        assert!(trusted("/nonexistent/log").is_err());
    }
}