sbexec 0.4.0

Run untrusted build commands in a least-privilege sandbox on macOS and Linux
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
//! Audit logging — `Auditor` trait + per-OS implementations.
//!
//! The [`Auditor`] trait is intentionally separate from `SandboxBackend`:
//! audit runs *concurrently* to the sandboxed child, whereas the backend
//! is the per-invocation lifecycle. Different lifetimes, different extension
//! points (audit-log file, summary, formatters).

use std::{
    collections::HashMap,
    os::unix::fs::PermissionsExt,
    path::Path,
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
};

use sbe_core::BackendInfo;
use tokio::{
    io::{AsyncBufRead, AsyncBufReadExt},
    sync::Mutex,
};

const MAX_AUDIT_RECORD_BYTES: usize = 16 * 1024;

enum AuditRecord {
    Line(Vec<u8>),
    Dropped,
    Eof,
}

/// Start the OS-appropriate audit stream and return its handle. Pass
/// `log_path` to also append events to a file.
#[cfg_attr(
    not(any(target_os = "macos", target_os = "linux")),
    allow(unused_variables)
)]
pub async fn start(
    info: &BackendInfo,
    log_path: Option<&Path>,
    pid: u32,
) -> anyhow::Result<AuditorHandle> {
    #[cfg(target_os = "macos")]
    {
        let _ = info;
        let logger = macos::MacosLogStream::new(log_path, pid).await?;
        Ok(logger.start())
    }
    #[cfg(target_os = "linux")]
    {
        let logger = linux::LinuxSeccompLog::new(log_path, info.kernel.clone(), pid).await?;
        Ok(logger.start())
    }
    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
    {
        anyhow::bail!("audit streaming is not supported on this platform");
    }
}

#[allow(clippy::disallowed_types)] // O_NOFOLLOW/O_CLOEXEC require Unix std OpenOptions.
async fn open_audit_log(path: &Path) -> anyhow::Result<tokio::fs::File> {
    use std::os::unix::fs::OpenOptionsExt;
    let file = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .mode(0o600)
        .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC | libc::O_NONBLOCK)
        .open(path)?;
    if !file.metadata()?.is_file() {
        anyhow::bail!("audit log path is not a regular file: {}", path.display());
    }
    file.set_permissions(std::fs::Permissions::from_mode(0o600))?;
    Ok(tokio::fs::File::from_std(file))
}

async fn read_audit_record<R>(reader: &mut R) -> std::io::Result<AuditRecord>
where
    R: AsyncBufRead + Unpin,
{
    let mut output = Vec::new();
    let mut exceeded = false;
    loop {
        let available = reader.fill_buf().await?;
        if available.is_empty() {
            return if output.is_empty() && !exceeded {
                Ok(AuditRecord::Eof)
            } else if exceeded {
                Ok(AuditRecord::Dropped)
            } else {
                Ok(AuditRecord::Line(output))
            };
        }
        let consumed = available
            .iter()
            .position(|byte| *byte == b'\n')
            .map_or(available.len(), |index| index + 1);
        if !exceeded {
            if output.len().saturating_add(consumed) > MAX_AUDIT_RECORD_BYTES {
                exceeded = true;
                output.clear();
            } else {
                output.extend_from_slice(&available[..consumed]);
            }
        }
        let complete = available[..consumed].last() == Some(&b'\n');
        reader.consume(consumed);
        if complete {
            return if exceeded {
                Ok(AuditRecord::Dropped)
            } else {
                Ok(AuditRecord::Line(output))
            };
        }
    }
}

fn sanitize_event_field(value: &str) -> String {
    value
        .chars()
        .flat_map(|character| character.escape_default())
        .take(4096)
        .collect()
}

/// Cross-platform view of a single sandbox violation.
#[derive(Debug, Clone)]
pub struct SandboxEvent {
    pub operation: String,
    pub target: String,
}

/// Handle returned by [`start`]. Drop or call [`stop_and_summarize`].
pub struct AuditorHandle {
    running: Arc<AtomicBool>,
    handle: tokio::task::JoinHandle<()>,
    violation_counts: Arc<Mutex<HashMap<String, u64>>>,
}

impl AuditorHandle {
    /// Stop the audit logger and print a summary.
    pub async fn stop_and_summarize(self) {
        self.running.store(false, Ordering::Relaxed);
        let _ = self.handle.await;

        let counts = self.violation_counts.lock().await;
        if !counts.is_empty() {
            eprintln!("\n[sbe:audit] Violation summary:");
            let mut sorted: Vec<_> = counts.iter().collect();
            sorted.sort_by_key(|(_, count)| std::cmp::Reverse(**count));
            for (op, count) in sorted {
                eprintln!("  {op}: {count}");
            }
        }
    }
}

#[cfg(target_os = "macos")]
mod macos {
    use tokio::{
        io::{AsyncWriteExt, BufReader},
        process::Command,
    };
    use tracing::debug;

    use super::*;

    /// macOS `sandboxd` log stream auditor.
    pub struct MacosLogStream {
        running: Arc<AtomicBool>,
        log_file: Option<tokio::fs::File>,
        violation_counts: Arc<Mutex<HashMap<String, u64>>>,
        pid: u32,
    }

    impl MacosLogStream {
        pub async fn new(log_path: Option<&Path>, pid: u32) -> anyhow::Result<Self> {
            let log_file = match log_path {
                Some(p) => Some(open_audit_log(p).await?),
                None => None,
            };

            Ok(Self {
                running: Arc::new(AtomicBool::new(true)),
                log_file,
                violation_counts: Arc::new(Mutex::new(HashMap::new())),
                pid,
            })
        }

        pub fn start(mut self) -> AuditorHandle {
            let running = Arc::clone(&self.running);
            let counts = Arc::clone(&self.violation_counts);

            let handle = tokio::spawn(async move {
                if let Err(e) = self.stream_logs().await {
                    debug!(error = %e, "audit log stream ended");
                }
            });

            AuditorHandle {
                running,
                handle,
                violation_counts: counts,
            }
        }

        async fn stream_logs(&mut self) -> anyhow::Result<()> {
            let predicate = format!(
                "process == \"sandboxd\" AND eventMessage CONTAINS[c] \"({})\"",
                self.pid
            );
            let mut child = Command::new("/usr/bin/log")
                .args(["stream", "--style", "compact", "--predicate", &predicate])
                .stdout(std::process::Stdio::piped())
                .stderr(std::process::Stdio::null())
                .spawn()?;

            let stdout = child
                .stdout
                .take()
                .ok_or_else(|| anyhow::anyhow!("no stdout from log stream"))?;
            let mut reader = BufReader::new(stdout);

            while self.running.load(Ordering::Relaxed) {
                let line = tokio::select! {
                    result = read_audit_record(&mut reader) => {
                        match result {
                            Ok(AuditRecord::Line(line)) => String::from_utf8_lossy(&line).into_owned(),
                            Ok(AuditRecord::Dropped) => {
                                let mut counts = self.violation_counts.lock().await;
                                *counts.entry("audit-record-dropped".to_owned()).or_insert(0) += 1;
                                continue;
                            }
                            Ok(AuditRecord::Eof) => break,
                            Err(e) => {
                                debug!(error = %e, "error reading log stream");
                                break;
                            }
                        }
                    }
                    _ = tokio::time::sleep(std::time::Duration::from_millis(100)) => {
                        if !self.running.load(Ordering::Relaxed) {
                            break;
                        }
                        continue;
                    }
                };

                if let Some(event) = parse_macos_event(&line, self.pid) {
                    let operation = sanitize_event_field(&event.operation);
                    let target = sanitize_event_field(&event.target);
                    let formatted = format!("[sbe:audit] DENIED {operation} {target}\n");
                    eprint!("{formatted}");

                    if let Some(ref mut f) = self.log_file {
                        let _ = f.write_all(formatted.as_bytes()).await;
                    }

                    let mut counts = self.violation_counts.lock().await;
                    *counts.entry(event.operation).or_insert(0) += 1;
                }
            }

            let _ = child.kill().await;

            Ok(())
        }
    }

    fn parse_macos_event(line: &str, pid: u32) -> Option<SandboxEvent> {
        if !line.contains("deny") || !line.contains(&format!("({pid})")) {
            return None;
        }

        let operation = if line.contains("file-write") {
            "file-write"
        } else if line.contains("file-read") {
            "file-read"
        } else if line.contains("network") {
            "network"
        } else if line.contains("process-exec") {
            "process-exec"
        } else {
            "other"
        };

        let target = line
            .rsplit_once(' ')
            .map(|(_, t)| t.to_owned())
            .unwrap_or_default();

        Some(SandboxEvent {
            operation: operation.to_owned(),
            target,
        })
    }
}

#[cfg(target_os = "linux")]
mod linux {
    use anyhow::Context as _;
    use tokio::{
        fs::File,
        io::{AsyncWriteExt, BufReader},
    };
    use tracing::debug;

    use super::*;

    /// Linux `/dev/kmsg` reader filtered to the current pid for seccomp
    /// audit lines. Best-effort: requires CAP_SYSLOG on locked-down hosts.
    pub struct LinuxSeccompLog {
        running: Arc<AtomicBool>,
        source: Option<File>,
        log_file: Option<tokio::fs::File>,
        kernel: String,
        violation_counts: Arc<Mutex<HashMap<String, u64>>>,
        pid: u32,
    }

    impl LinuxSeccompLog {
        pub async fn new(
            log_path: Option<&Path>,
            kernel: String,
            pid: u32,
        ) -> anyhow::Result<Self> {
            let source = File::open("/dev/kmsg")
                .await
                .context("open /dev/kmsg for Linux audit")?;
            let log_file = match log_path {
                Some(p) => Some(open_audit_log(p).await?),
                None => None,
            };

            Ok(Self {
                running: Arc::new(AtomicBool::new(true)),
                source: Some(source),
                log_file,
                kernel,
                violation_counts: Arc::new(Mutex::new(HashMap::new())),
                pid,
            })
        }

        pub fn start(mut self) -> AuditorHandle {
            let running = Arc::clone(&self.running);
            let counts = Arc::clone(&self.violation_counts);

            let handle = tokio::spawn(async move {
                if let Err(e) = self.stream_kmsg().await {
                    debug!(error = %e, kernel = %self.kernel, "audit log stream ended");
                }
            });

            AuditorHandle {
                running,
                handle,
                violation_counts: counts,
            }
        }

        async fn stream_kmsg(&mut self) -> anyhow::Result<()> {
            let file = self
                .source
                .take()
                .ok_or_else(|| anyhow::anyhow!("Linux audit source already consumed"))?;
            let mut reader = BufReader::new(file);

            while self.running.load(Ordering::Relaxed) {
                let line = tokio::select! {
                    result = read_audit_record(&mut reader) => match result {
                        Ok(AuditRecord::Line(line)) => String::from_utf8_lossy(&line).into_owned(),
                        Ok(AuditRecord::Dropped) => {
                            let mut counts = self.violation_counts.lock().await;
                            *counts.entry("audit-record-dropped".to_owned()).or_insert(0) += 1;
                            continue;
                        }
                        Ok(AuditRecord::Eof) => break,
                        Err(_) => break,
                    },
                    _ = tokio::time::sleep(std::time::Duration::from_millis(150)) => {
                        if !self.running.load(Ordering::Relaxed) {
                            break;
                        }
                        continue;
                    }
                };

                if let Some(event) = parse_kmsg_event(&line, self.pid) {
                    let operation = sanitize_event_field(&event.operation);
                    let target = sanitize_event_field(&event.target);
                    let formatted = format!("[sbe:audit] DENIED {operation} {target}\n");
                    eprint!("{formatted}");

                    if let Some(ref mut f) = self.log_file {
                        let _ = f.write_all(formatted.as_bytes()).await;
                    }

                    let mut counts = self.violation_counts.lock().await;
                    *counts.entry(event.operation).or_insert(0) += 1;
                }
            }
            Ok(())
        }
    }

    fn parse_kmsg_event(line: &str, pid: u32) -> Option<SandboxEvent> {
        // Kernel seccomp audit lines look like:
        //   "audit: type=1326 audit(...): auid=... syscall=44 comm=\"foo\" exe=\"...\""
        // We match on `audit(` and `seccomp` keywords.
        if !line.contains("audit")
            || (!line.contains(&format!("pid={pid}")) && !line.contains(&format!("ppid={pid}")))
        {
            return None;
        }
        if line.contains("syscall=") {
            let syscall = line
                .split_once("syscall=")
                .and_then(|(_, rest)| rest.split_whitespace().next())
                .unwrap_or("?");
            let exe = line
                .split_once("exe=")
                .and_then(|(_, rest)| rest.split('"').nth(1))
                .unwrap_or("");
            return Some(SandboxEvent {
                operation: format!("seccomp:{syscall}"),
                target: exe.to_owned(),
            });
        }
        if line.contains("LANDLOCK") || line.contains("landlock") {
            return Some(SandboxEvent {
                operation: "landlock".to_owned(),
                target: line.trim().to_owned(),
            });
        }
        None
    }
}

#[cfg(test)]
mod tests {
    use tokio::io::AsyncWriteExt as _;

    use super::*;

    #[tokio::test]
    async fn oversized_audit_record_is_dropped_without_desynchronizing() {
        let (mut writer, reader) = tokio::io::duplex(MAX_AUDIT_RECORD_BYTES * 2);
        tokio::spawn(async move {
            writer
                .write_all(&vec![b'x'; MAX_AUDIT_RECORD_BYTES + 1])
                .await
                .unwrap();
            writer.write_all(b"\nvalid\n").await.unwrap();
        });
        let mut reader = tokio::io::BufReader::new(reader);
        assert!(matches!(
            read_audit_record(&mut reader).await.unwrap(),
            AuditRecord::Dropped
        ));
        let AuditRecord::Line(line) = read_audit_record(&mut reader).await.unwrap() else {
            panic!("expected line after dropped record");
        };
        assert_eq!(line, b"valid\n");
    }

    #[tokio::test]
    async fn audit_log_is_private_and_refuses_symlinks() {
        let directory = tempfile::tempdir().unwrap();
        let log = directory.path().join("audit.log");
        drop(open_audit_log(&log).await.unwrap());
        assert_eq!(
            tokio::fs::metadata(&log)
                .await
                .unwrap()
                .permissions()
                .mode()
                & 0o777,
            0o600
        );

        let target = directory.path().join("target.log");
        tokio::fs::write(&target, "sentinel").await.unwrap();
        let link = directory.path().join("link.log");
        std::os::unix::fs::symlink(&target, &link).unwrap();
        assert!(open_audit_log(&link).await.is_err());
        assert_eq!(tokio::fs::read_to_string(target).await.unwrap(), "sentinel");
    }
}