forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.7 MiB37e985dTahinli4 hours ago363 commits

check.rs506 lines, 15.4 KiBHistoryRawDownload
1use std::fs;
2use std::io;
3use std::path::{Path, PathBuf};
4use std::process::{ExitStatus, Stdio};
5
6use tokio::io::AsyncWriteExt;
7use tokio::process::Command;
8
9use crate::config::{Limits, UsernsMode};
10use crate::sandbox::helper::job_cgroup_base;
11use crate::sandbox::idmap::IdMap;
12use crate::sandbox::{SandboxRequest, new_token, strip_line};
13
14const PROBE_SCRIPT: &str = "grep '^Seccomp:' /proc/self/status; true";
15const PROBE_SUBUID_SCRIPT: &str = "grep '^Seccomp:' /proc/self/status; \
16 touch /tmp/forge-probe && chown 1000:1000 /tmp/forge-probe \
17 && stat -c 'owner %u %g' /tmp/forge-probe; true";
18const PROBE_BINARIES: &[&str] = &["sh", "grep", "touch", "chown", "stat"];
19const LIMIT_CONTROLLERS: [&str; 3] = ["cpu", "memory", "pids"];
20
21pub fn build_rootfs(root: &Path, binaries: &[&str]) -> io::Result<()> {
22 for dir in [
23 "bin",
24 "proc",
25 "dev",
26 "sys",
27 "tmp",
28 "workspace",
29 "etc",
30 "root",
31 ] {
32 fs::create_dir_all(root.join(dir))?;
33 }
34 for name in ["null", "zero", "full", "random", "urandom"] {
35 fs::write(root.join("dev").join(name), b"")?;
36 }
37 for name in ["etc/hosts", "etc/hostname", "etc/resolv.conf"] {
38 fs::write(root.join(name), b"")?;
39 }
40
41 let mut libs: Vec<PathBuf> = Vec::new();
42 for name in binaries {
43 let host = ["/usr/bin", "/bin"]
44 .iter()
45 .map(|dir| Path::new(dir).join(name))
46 .find(|p| p.exists())
47 .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, format!("{name} not found")))?;
48 let real = fs::canonicalize(&host)?;
49 fs::copy(&real, root.join("bin").join(name))?;
50 libs.extend(shared_libs(&real));
51 }
52 libs.sort();
53 libs.dedup();
54 for lib in &libs {
55 copy_into(root, lib)?;
56 }
57 Ok(())
58}
59
60fn shared_libs(binary: &Path) -> Vec<PathBuf> {
61 let Ok(out) = std::process::Command::new("ldd").arg(binary).output() else {
62 return Vec::new();
63 };
64 String::from_utf8_lossy(&out.stdout)
65 .lines()
66 .filter_map(|line| {
67 let line = line.trim();
68 let path = match line.split_once(" => ") {
69 Some((_, rest)) => rest.split(" (").next()?,
70 None => line.split(" (").next()?,
71 };
72 path.starts_with('/').then(|| PathBuf::from(path))
73 })
74 .collect()
75}
76
77fn copy_into(root: &Path, host: &Path) -> io::Result<()> {
78 let real = fs::canonicalize(host)?;
79 let dest = root.join(host.strip_prefix("/").unwrap_or(host));
80 if let Some(parent) = dest.parent() {
81 fs::create_dir_all(parent)?;
82 }
83 fs::copy(&real, &dest)?;
84 Ok(())
85}
86
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub enum Status {
89 Ok,
90 Fail,
91 Skip,
92}
93
94#[derive(Debug, Clone, PartialEq, Eq)]
95pub struct Line {
96 pub status: Status,
97 pub name: &'static str,
98 pub detail: String,
99}
100
101impl Line {
102 fn ok(name: &'static str, detail: impl Into<String>) -> Self {
103 Self {
104 status: Status::Ok,
105 name,
106 detail: detail.into(),
107 }
108 }
109
110 fn fail(name: &'static str, detail: impl Into<String>) -> Self {
111 Self {
112 status: Status::Fail,
113 name,
114 detail: detail.into(),
115 }
116 }
117
118 fn skip(name: &'static str, detail: impl Into<String>) -> Self {
119 Self {
120 status: Status::Skip,
121 name,
122 detail: detail.into(),
123 }
124 }
125}
126
127struct Probe {
128 status: ExitStatus,
129 stdout: String,
130 stderr: String,
131 token: String,
132}
133
134async fn run_probe(helper: &Path, work_dir: &Path, map: &IdMap) -> Result<Probe, String> {
135 let root = work_dir.join(format!("check-{}", std::process::id()));
136 let rootfs = root.join("rootfs");
137 let build_into = rootfs.clone();
138 let built = tokio::task::spawn_blocking(move || build_rootfs(&build_into, PROBE_BINARIES))
139 .await
140 .map_err(|e| format!("cannot build the test rootfs: {e}"))?;
141 built.map_err(|e| format!("cannot build the test rootfs: {e}"))?;
142 let workspace = root.join("workspace");
143 fs::create_dir_all(&workspace)
144 .map_err(|e| format!("cannot create {}: {e}", workspace.display()))?;
145
146 let script = if map.is_subuid() {
147 PROBE_SUBUID_SCRIPT
148 } else {
149 PROBE_SCRIPT
150 };
151 let token = new_token();
152 let request = SandboxRequest {
153 token: token.clone(),
154 job_id: "forge-check".to_owned(),
155 rootfs,
156 job_dir: root.join("job"),
157 workspace,
158 image_env: Vec::new(),
159 env: Vec::new(),
160 run: script.to_owned(),
161 network: false,
162 pasta: None,
163 limits: Limits::default(),
164 idmap: map.clone(),
165 };
166 let json = serde_json::to_vec(&request).map_err(|e| e.to_string())?;
167 let output = async {
168 let mut child = Command::new(helper)
169 .arg("__sandbox")
170 .stdin(Stdio::piped())
171 .stdout(Stdio::piped())
172 .stderr(Stdio::piped())
173 .kill_on_drop(true)
174 .spawn()?;
175 if let Some(mut stdin) = child.stdin.take() {
176 stdin.write_all(&json).await?;
177 }
178 child.wait_with_output().await
179 }
180 .await
181 .map_err(|e| format!("cannot start the sandbox helper: {e}"));
182 let _ = fs::remove_dir_all(&root);
183 let output = output?;
184 Ok(Probe {
185 status: output.status,
186 stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
187 stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
188 token,
189 })
190}
191
192fn sandbox_lines<'a>(stderr: &'a str, token: &str) -> Vec<&'a str> {
193 stderr
194 .lines()
195 .filter_map(|line| strip_line(line, token))
196 .collect()
197}
198
199fn delegated_controllers() -> Result<Vec<String>, String> {
200 let base = job_cgroup_base().map_err(|e| e.to_string())?;
201 let dir = Path::new("/sys/fs/cgroup").join(base.strip_prefix("/").unwrap_or(&base));
202 let probe = dir.join(format!("forge-check-{}", std::process::id()));
203 fs::create_dir(&probe).map_err(|e| {
204 format!(
205 "cannot create a cgroup in {}: {e}; run under systemd --user, e.g. `systemd-run --user -P forge runner check`",
206 dir.display()
207 )
208 })?;
209 let _ = fs::remove_dir(&probe);
210 let file = dir.join("cgroup.subtree_control");
211 let enabled =
212 fs::read_to_string(&file).map_err(|e| format!("cannot read {}: {e}", file.display()))?;
213 Ok(enabled.split_whitespace().map(str::to_owned).collect())
214}
215
216async fn git_line() -> Line {
217 match Command::new("git").arg("--version").output().await {
218 Ok(out) if out.status.success() => Line::ok(
219 "git",
220 String::from_utf8_lossy(&out.stdout).trim().to_owned(),
221 ),
222 Ok(out) => Line::fail("git", format!("git --version exited with {}", out.status)),
223 Err(e) => Line::fail("git", format!("git is not installed on this host: {e}")),
224 }
225}
226
227fn report(probe: Result<&Probe, &str>, controllers: Result<&[String], &str>) -> Vec<Line> {
228 let mut lines = Vec::new();
229
230 match controllers {
231 Ok(enabled) => {
232 let missing: Vec<&str> = LIMIT_CONTROLLERS
233 .iter()
234 .copied()
235 .filter(|c| !enabled.iter().any(|e| e == c))
236 .collect();
237 if missing.is_empty() {
238 lines.push(Line::ok(
239 "cgroup v2 delegation",
240 format!("controllers enabled: {}", enabled.join(" ")),
241 ));
242 } else {
243 lines.push(Line::fail(
244 "cgroup v2 delegation",
245 format!(
246 "missing {}; [limits] cannot be applied (enabled: {})",
247 missing.join(" "),
248 enabled.join(" ")
249 ),
250 ));
251 }
252 }
253 Err(reason) => lines.push(Line::fail("cgroup v2 delegation", reason)),
254 }
255
256 let probe = match probe {
257 Ok(probe) => probe,
258 Err(reason) => {
259 lines.push(Line::fail("sandbox run", reason));
260 for name in [
261 "user namespaces",
262 "overlayfs in a user namespace",
263 "resource limits",
264 "seccomp filter",
265 ] {
266 lines.push(Line::skip(name, "not tested: the probe job did not run"));
267 }
268 return lines;
269 }
270 };
271
272 let setup_errors = sandbox_lines(&probe.stderr, &probe.token);
273 let userns_error = setup_errors
274 .iter()
275 .find(|l| l.contains("user namespaces unavailable"));
276 let started = probe.stdout.lines().any(|l| l.starts_with("Seccomp:"));
277
278 if let Some(line) = userns_error {
279 lines.push(Line::fail("user namespaces", *line));
280 } else if started {
281 lines.push(Line::ok(
282 "user namespaces",
283 "unprivileged user namespaces work",
284 ));
285 } else {
286 lines.push(Line::skip(
287 "user namespaces",
288 "not tested: the probe job did not start",
289 ));
290 }
291
292 if !started {
293 let reason = setup_errors
294 .first()
295 .map(|l| (*l).to_owned())
296 .unwrap_or_else(|| format!("the probe exited with {}", probe.status));
297 lines.push(Line::fail("sandbox run", reason));
298 lines.push(Line::skip(
299 "overlayfs in a user namespace",
300 "not tested: the probe job did not start",
301 ));
302 lines.push(Line::skip(
303 "resource limits",
304 "not tested: the probe job did not start",
305 ));
306 lines.push(Line::skip(
307 "seccomp filter",
308 "not tested: the probe job did not start",
309 ));
310 return lines;
311 }
312
313 lines.push(Line::ok(
314 "sandbox run",
315 format!("probe job exited with {}", probe.status),
316 ));
317
318 match setup_errors
319 .iter()
320 .find(|l| l.starts_with("warning: overlay mount failed"))
321 {
322 Some(line) => lines.push(Line::fail(
323 "overlayfs in a user namespace",
324 format!("{line}; jobs copy the rootfs instead (slower, uses disk)"),
325 )),
326 None => lines.push(Line::ok(
327 "overlayfs in a user namespace",
328 "overlay mounts work",
329 )),
330 }
331
332 match setup_errors
333 .iter()
334 .find(|l| l.starts_with("warning: resource limits unavailable"))
335 {
336 Some(line) => lines.push(Line::fail("resource limits", *line)),
337 None => lines.push(Line::ok(
338 "resource limits",
339 "cpu, memory and pids limits apply",
340 )),
341 }
342
343 let mode = probe
344 .stdout
345 .lines()
346 .find_map(|l| l.strip_prefix("Seccomp:"))
347 .map(str::trim)
348 .unwrap_or_default();
349 if mode == "2" {
350 lines.push(Line::ok(
351 "seccomp filter",
352 "the job runs with a seccomp filter",
353 ));
354 } else {
355 lines.push(Line::fail(
356 "seccomp filter",
357 format!("the job's seccomp mode is {mode:?}, expected 2"),
358 ));
359 }
360 lines
361}
362
363fn ownership_line(probe: &Probe) -> Line {
364 const NAME: &str = "subordinate ids";
365 if !probe.stdout.lines().any(|l| l.starts_with("Seccomp:")) {
366 return Line::skip(NAME, "not tested: the probe job did not start");
367 }
368 if probe.stdout.lines().any(|l| l.trim() == "owner 1000 1000") {
369 return Line::ok(NAME, "a job can chown files to 1000:1000");
370 }
371 let reason = probe
372 .stderr
373 .lines()
374 .find(|l| strip_line(l, &probe.token).is_none() && !l.trim().is_empty())
375 .unwrap_or("no output");
376 Line::fail(
377 NAME,
378 format!("a job cannot chown 1000:1000 in /tmp: {reason}"),
379 )
380}
381
382pub async fn run(helper: &Path, work_dir: &Path, mode: UsernsMode) -> bool {
383 let work_dir = match std::path::absolute(work_dir) {
384 Ok(path) => path,
385 Err(e) => {
386 println!("FAIL work dir: {}: {e}", work_dir.display());
387 return false;
388 }
389 };
390 let map = match IdMap::resolve(mode) {
391 Ok(map) => map,
392 Err(e) => {
393 println!("FAIL user ids: {e}");
394 return false;
395 }
396 };
397 let probe = run_probe(helper, &work_dir, &map).await;
398 let controllers = delegated_controllers();
399 let mut lines = vec![Line::ok("user ids", map.describe()), git_line().await];
400 lines.extend(report(
401 probe.as_ref().map_err(String::as_str),
402 controllers.as_deref().map_err(String::as_str),
403 ));
404 if map.is_subuid() {
405 lines.push(match &probe {
406 Ok(probe) => ownership_line(probe),
407 Err(_) => Line::skip("subordinate ids", "not tested: the probe job did not run"),
408 });
409 }
410 let mut all_ok = true;
411 for line in &lines {
412 let tag = match line.status {
413 Status::Ok => "ok ",
414 Status::Fail => {
415 all_ok = false;
416 "FAIL"
417 }
418 Status::Skip => {
419 all_ok = false;
420 "skip"
421 }
422 };
423 println!("{tag} {}: {}", line.name, line.detail);
424 }
425 all_ok
426}
427
428#[cfg(test)]
429mod tests {
430 use super::*;
431 use std::os::unix::process::ExitStatusExt;
432
433 fn probe(stdout: &str, stderr: &str) -> Probe {
434 Probe {
435 status: ExitStatus::from_raw(0),
436 stdout: stdout.to_owned(),
437 stderr: stderr.to_owned(),
438 token: "t".to_owned(),
439 }
440 }
441
442 fn all() -> Vec<String> {
443 LIMIT_CONTROLLERS.iter().map(|c| (*c).to_owned()).collect()
444 }
445
446 #[test]
447 fn a_healthy_host_passes_every_check() {
448 let p = probe("Seccomp:\t2\n", "");
449 let lines = report(Ok(&p), Ok(&all()));
450 assert!(lines.iter().all(|l| l.status == Status::Ok), "{lines:?}");
451 }
452
453 #[test]
454 fn missing_userns_is_reported_with_its_reason() {
455 let p = probe("", "forge-sandbox[t]: user namespaces unavailable: EPERM\n");
456 let lines = report(Ok(&p), Ok(&all()));
457 let userns = lines
458 .iter()
459 .find(|l| l.name == "user namespaces")
460 .expect("line");
461 assert_eq!(userns.status, Status::Fail);
462 assert!(userns.detail.contains("EPERM"));
463 assert!(
464 lines
465 .iter()
466 .any(|l| l.name == "sandbox run" && l.status == Status::Fail)
467 );
468 }
469
470 #[test]
471 fn overlay_and_limit_warnings_are_failures() {
472 let p = probe(
473 "Seccomp:\t2\n",
474 "forge-sandbox[t]: warning: overlay mount failed (EPERM), copying the rootfs instead\n\
475 forge-sandbox[t]: warning: resource limits unavailable: cgroup\n",
476 );
477 let lines = report(Ok(&p), Ok(&all()));
478 let overlay = lines
479 .iter()
480 .find(|l| l.name.starts_with("overlayfs"))
481 .expect("line");
482 assert_eq!(overlay.status, Status::Fail);
483 let limits = lines
484 .iter()
485 .find(|l| l.name == "resource limits")
486 .expect("line");
487 assert_eq!(limits.status, Status::Fail);
488 }
489
490 #[test]
491 fn missing_controllers_fail_the_delegation_check() {
492 let p = probe("Seccomp:\t2\n", "");
493 let enabled = vec!["memory".to_owned()];
494 let lines = report(Ok(&p), Ok(&enabled));
495 let line = &lines[0];
496 assert_eq!(line.status, Status::Fail);
497 assert!(line.detail.contains("cpu pids"));
498 }
499
500 #[test]
501 fn a_probe_that_never_ran_skips_the_rest() {
502 let lines = report(Err("cannot build the test rootfs"), Ok(&all()));
503 assert_eq!(lines[1].status, Status::Fail);
504 assert!(lines.iter().skip(2).all(|l| l.status == Status::Skip));
505 }
506}