返回 CodeWhale
process_hardening.rs
根目录 / crates / sandbox / src / process_hardening.rs
1 //! Process hardening for Linux sandbox defense-in-depth (#2183).
2 //!
3 //! This module applies kernel-level restrictions to the codewhale-tui process
4 //! itself. These hardening measures protect the *parent* TUI process and its
5 //! descendants from information leaks and privilege-escalation vectors; they
6 //! are not a filesystem or network sandbox for child commands.
7 //!
8 //! # Ordering constraints
9 //!
10 //! `apply_process_hardening()` MUST be called **before** the Tokio runtime is
11 //! booted and **before** any worker threads are spawned. The reasons:
12 //!
13 //! 1. `PR_SET_DUMPABLE` — once set to 0, the process cannot be ptraced and
14 //! `/proc/self/` becomes root-owned. This must happen before any threads
15 //! exist, because the kernel applies dumpable state per-thread-group and
16 //! changing it after threads are live can race with `/proc` lookups.
17 //!
18 //! 2. `PR_SET_NO_NEW_PRIVS` — prevents the process and all descendants from
19 //! ever gaining new privileges via setuid/setgid/fscaps. This is
20 //! irreversible and must be applied before executing any helper binaries or
21 //! subprocesses that might (incorrectly) rely on privilege boundaries.
22 //! Because this also blocks intentional privilege gains — `sudo`, `su`,
23 //! setuid helpers — a user who runs Codewhale as a wheel/wheel-equivalent
24 //! administrator and wants the model to be able to escalate can opt out of
25 //! exactly this one measure with `CODEWHALE_NO_NEW_PRIVS=0` (#5413), and a
26 //! session whose startup sandbox mode resolves to `danger-full-access`
27 //! skips it by default so full access means what it says (#5723). The
28 //! other two measures stay on in every posture.
29 //!
30 //! 3. `RLIMIT_CORE` — disables core dumps so that sensitive in-memory data
31 //! (API keys, tokens, prompt content) is never written to disk on a crash.
32 //! Setting this before any data is loaded into memory is the safest posture.
33 //!
34 //! # Platform support
35 //!
36 //! These hardening measures are Linux-only (they use `prctl` and `setrlimit`
37 //! from the `libc` crate). On non-Linux platforms, `apply_process_hardening()`
38 //! is a no-op that logs a debug-level message.
39
40 /// Environment variable carrying the explicit no-new-privileges decision.
41 ///
42 /// `PR_SET_NO_NEW_PRIVS` is an irreversible, inherited-by-children kernel
43 /// flag, so applying it by default breaks workflows where the user *wants*
44 /// Codewhale to be able to escalate: `sudo`, `su`, setuid/fscaps helpers run
45 /// by a wheel-group administrator (#5413). Setting this variable to any
46 /// falsey value (`0`, `false`, `no`, `off`, `disabled`, or empty) skips
47 /// exactly this one measure; any other set value forces it on, and leaving it
48 /// unset lets the startup sandbox posture decide (#5723). `PR_SET_DUMPABLE`
49 /// and `RLIMIT_CORE` are never skipped.
50 #[cfg(any(test, all(target_os = "linux", not(target_env = "ohos"))))]
51 pub(crate) const NO_NEW_PRIVS_ENV: &str = "CODEWHALE_NO_NEW_PRIVS";
52
53 /// Whether a `CODEWHALE_NO_NEW_PRIVS` value requests skipping the
54 /// no-new-privileges flag. Falsey per the workspace env convention — the same
55 /// value set (`""`, `0`, `false`, `no`, `off`, `disabled`) that
56 /// `docs/CONFIGURATION.md` treats as "not set".
57 #[cfg(any(test, all(target_os = "linux", not(target_env = "ohos"))))]
58 fn is_no_new_privs_opt_out(value: &str) -> bool {
59 matches!(
60 value.trim().to_ascii_lowercase().as_str(),
61 "" | "0" | "false" | "no" | "off" | "disabled"
62 )
63 }
64
65 /// The explicit `CODEWHALE_NO_NEW_PRIVS` decision as the tri-state
66 /// `should_apply_no_new_privs` consumes: `Some(false)` opts out (falsey
67 /// value), `Some(true)` forces the flag on (any other set value), and `None`
68 /// leaves the decision to the startup posture.
69 #[cfg(any(test, all(target_os = "linux", not(target_env = "ohos"))))]
70 fn no_new_privs_env_override() -> Option<bool> {
71 std::env::var_os(NO_NEW_PRIVS_ENV)
72 .map(|value| !is_no_new_privs_opt_out(&value.to_string_lossy()))
73 }
74
75 /// Whether startup should set the kernel's irreversible no-new-privileges
76 /// flag, given the resolved startup sandbox mode and the explicit
77 /// `CODEWHALE_NO_NEW_PRIVS` override.
78 ///
79 /// Precedence (#5723):
80 ///
81 /// 1. An explicit override wins in both directions: a falsey value skips the
82 /// flag (#5413); a truthy value forces it on even under
83 /// `danger-full-access`.
84 /// 2. Otherwise a startup resolved to `danger-full-access` skips the flag so
85 /// "full access (sandbox disabled)" means it: `sudo`/`su`/setuid helpers
86 /// keep working from the agent shell.
87 /// 3. Every other — or unreadable — posture keeps the flag. Defense-in-depth
88 /// stays the default (#5413) and the decision is fail-closed.
89 ///
90 /// The mode string is normalized the same way config validation normalizes
91 /// `sandbox_mode` (`Config::validate`): trimmed, ASCII case-insensitive. An
92 /// unrecognized value keeps the flag on — it cannot silently relax into a
93 /// posture the runtime would reject.
94 #[cfg(any(test, all(target_os = "linux", not(target_env = "ohos"))))]
95 pub(crate) fn should_apply_no_new_privs(
96 resolved_startup_mode: Option<&str>,
97 env_override: Option<bool>,
98 ) -> bool {
99 if let Some(apply) = env_override {
100 return apply;
101 }
102 !resolved_startup_mode
103 .is_some_and(|mode| mode.trim().eq_ignore_ascii_case("danger-full-access"))
104 }
105
106 /// Live state of the kernel's no-new-privileges flag for this process tree.
107 ///
108 /// Returns `Some(true)`/`Some(false)` on Linux, where `PR_GET_NO_NEW_PRIVS`
109 /// reads back the irreversible flag set (or deliberately skipped) at startup,
110 /// and `None` on platforms where the flag does not exist or the query fails.
111 /// Status and denial surfaces use this to disclose the residual setuid block
112 /// truthfully instead of replaying the startup decision (#5723).
113 pub fn no_new_privs_active() -> Option<bool> {
114 #[cfg(all(target_os = "linux", not(target_env = "ohos")))]
115 {
116 // Safety: PR_GET_NO_NEW_PRIVS only reads the calling process's flag.
117 let result = unsafe { libc::prctl(libc::PR_GET_NO_NEW_PRIVS, 0i64, 0i64, 0i64, 0i64) };
118 if result < 0 { None } else { Some(result == 1) }
119 }
120 #[cfg(not(all(target_os = "linux", not(target_env = "ohos"))))]
121 {
122 None
123 }
124 }
125
126 /// Apply process-level hardening measures.
127 ///
128 /// On Linux, this:
129 /// - Sets `PR_SET_DUMPABLE` to 0 (prevents ptrace, core dumps)
130 /// - Sets `PR_SET_NO_NEW_PRIVS` to 1 (irreversible no-new-privileges), unless
131 /// `should_apply_no_new_privs` skips it: an explicit falsey
132 /// `CODEWHALE_NO_NEW_PRIVS` (#5413), or a startup sandbox mode resolved to
133 /// `danger-full-access` (#5723)
134 /// - Sets `RLIMIT_CORE` to 0 (disables core dumps)
135 ///
136 /// On non-Linux platforms this is a no-op.
137 ///
138 /// `resolved_startup_mode` is the narrow pre-parse read of the startup sandbox
139 /// mode (`CODEWHALE_SANDBOX_MODE`, else the config file's `sandbox_mode` key);
140 /// see `run_with_args` in the `codewhale-tui` crate root for the seam and its limits.
141 ///
142 /// # Panics
143 ///
144 /// Does NOT panic. Failures are logged via `tracing::warn` because the
145 /// hardening is defense-in-depth. A failure does not abort startup or change
146 /// whether a separately configured Seatbelt/bubblewrap command wrapper is
147 /// available.
148 pub fn apply_process_hardening(resolved_startup_mode: Option<&str>) {
149 #[cfg(all(target_os = "linux", not(target_env = "ohos")))]
150 {
151 apply_linux_hardening(resolved_startup_mode);
152 }
153 #[cfg(not(all(target_os = "linux", not(target_env = "ohos"))))]
154 {
155 let _ = resolved_startup_mode;
156 tracing::debug!("Process hardening skipped: not on Linux");
157 }
158 }
159
160 /// Linux-specific hardening implementation.
161 #[cfg(all(target_os = "linux", not(target_env = "ohos")))]
162 fn apply_linux_hardening(resolved_startup_mode: Option<&str>) {
163 // ── PR_SET_DUMPABLE = 0 ────────────────────────────────────────────────
164 //
165 // When dumpable is 0:
166 // - The process cannot be ptraced by non-root
167 // - /proc/<pid>/ becomes owned by root:root (mode 0400)
168 // - No core dumps are produced
169 //
170 // Pattern from openai/codex codex-rs/codex-sandbox/src/linux.rs; reimplemented.
171 //
172 // Safety: prctl with PR_SET_DUMPABLE modifies only the calling process.
173 let result = unsafe { libc::prctl(libc::PR_SET_DUMPABLE, 0i64, 0i64, 0i64, 0i64) };
174 if result != 0 {
175 let err = std::io::Error::last_os_error();
176 tracing::warn!(
177 "PR_SET_DUMPABLE failed ({}); continuing without this hardening",
178 err
179 );
180 } else {
181 tracing::debug!("PR_SET_DUMPABLE=0 applied");
182 }
183
184 // ── PR_SET_NO_NEW_PRIVS = 1 ────────────────────────────────────────────
185 //
186 // Once set, neither this process nor any descendant can ever gain new
187 // privileges via setuid, setgid, file capabilities, or LSMs like SELinux
188 // transitions. This is the strongest anti-escalation primitive the kernel
189 // offers.
190 //
191 // That strength is also the flag's one legitimate break: a wheel-group
192 // administrator running Codewhale over ssh loses `sudo`/`su`/setuid
193 // helpers for the whole process tree (#5413). Two startup-level paths skip
194 // exactly this measure, before any thread exists — the same point in
195 // startup where the flag itself is applied:
196 //
197 // - `CODEWHALE_NO_NEW_PRIVS` with a falsey value (#5413). A truthy value
198 // is the opposite explicit decision: it forces the flag on even under a
199 // `danger-full-access` startup.
200 // - A startup sandbox mode resolved to `danger-full-access` (#5723):
201 // "full access (sandbox disabled)" must mean it, so the agent shell's
202 // `sudo`/setuid workflows keep working. Every narrower posture keeps
203 // the flag as defense-in-depth.
204 //
205 // Pattern from openai/codex codex-rs/codex-sandbox/src/linux.rs; reimplemented.
206 //
207 // Safety: prctl with PR_SET_NO_NEW_PRIVS modifies only the calling process
208 // and its future descendants.
209 let env_override = no_new_privs_env_override();
210 if should_apply_no_new_privs(resolved_startup_mode, env_override) {
211 let result = unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1i64, 0i64, 0i64, 0i64) };
212 if result != 0 {
213 let err = std::io::Error::last_os_error();
214 tracing::warn!(
215 "PR_SET_NO_NEW_PRIVS failed ({}); continuing without this hardening",
216 err
217 );
218 } else {
219 tracing::debug!("PR_SET_NO_NEW_PRIVS=1 applied");
220 }
221 } else if env_override == Some(false) {
222 tracing::info!(
223 target: "sandbox",
224 "PR_SET_NO_NEW_PRIVS skipped via {NO_NEW_PRIVS_ENV}: setuid/sudo escalation is \
225 allowed for this process tree"
226 );
227 } else {
228 tracing::info!(
229 target: "sandbox",
230 "PR_SET_NO_NEW_PRIVS skipped: startup sandbox mode resolved to danger-full-access \
231 (#5723); setuid/sudo escalation is allowed for this process tree"
232 );
233 }
234
235 // ── RLIMIT_CORE = 0 ────────────────────────────────────────────────────
236 //
237 // Disables core dumps at the rlimit level. In combination with
238 // PR_SET_DUMPABLE=0, this provides a belt-and-suspenders guarantee that
239 // no core file will ever be written.
240 //
241 // Safety: setrlimit modifies resource limits for the calling process only.
242 let rlim_core = libc::rlimit {
243 rlim_cur: 0,
244 rlim_max: 0,
245 };
246 let result = unsafe { libc::setrlimit(libc::RLIMIT_CORE, &raw const rlim_core) };
247 if result != 0 {
248 let err = std::io::Error::last_os_error();
249 tracing::warn!(
250 "RLIMIT_CORE failed ({}); continuing without this hardening",
251 err
252 );
253 } else {
254 tracing::debug!("RLIMIT_CORE=0 applied");
255 }
256 }
257
258 #[cfg(test)]
259 mod tests {
260 use super::*;
261
262 #[test]
263 fn test_apply_process_hardening_does_not_panic() {
264 // This test exists to ensure the function can be called without
265 // panicking, even on platforms where hardening is a no-op.
266 apply_process_hardening(None);
267 }
268
269 #[test]
270 fn no_new_privs_opt_out_accepts_exactly_the_falsey_values() {
271 // The workspace env convention: "", 0, false, no, off, disabled.
272 for value in ["", "0", "false", "no", "off", "disabled"] {
273 assert!(
274 is_no_new_privs_opt_out(value),
275 "{value:?} should opt out of PR_SET_NO_NEW_PRIVS"
276 );
277 // Case and surrounding whitespace must not change the answer.
278 assert!(is_no_new_privs_opt_out(&format!(
279 " {} ",
280 value.to_uppercase()
281 )));
282 }
283 }
284
285 #[test]
286 fn no_new_privs_opt_out_rejects_truthy_and_garbage_values() {
287 // Anything else — including a typo — keeps the hardening on, so the
288 // opt-out can never be entered by accident.
289 for value in [
290 "1",
291 "true",
292 "yes",
293 "on",
294 "enabled",
295 "maybe",
296 "0x0",
297 "false-ish",
298 "off!",
299 ] {
300 assert!(
301 !is_no_new_privs_opt_out(value),
302 "{value:?} should NOT opt out of PR_SET_NO_NEW_PRIVS"
303 );
304 }
305 }
306
307 #[test]
308 fn no_new_privs_env_wiring_reads_the_documented_variable() {
309 // The env is process-global and tests run in parallel threads, so the
310 // wiring is asserted structurally: the constant is the documented
311 // name, and the reader is a pure projection of var_os over that
312 // constant. Setting/removing the variable here would race every other
313 // test in the process.
314 assert_eq!(NO_NEW_PRIVS_ENV, "CODEWHALE_NO_NEW_PRIVS");
315 let projected = std::env::var_os(NO_NEW_PRIVS_ENV)
316 .map(|value| !is_no_new_privs_opt_out(&value.to_string_lossy()));
317 assert_eq!(projected, no_new_privs_env_override());
318 }
319
320 #[test]
321 fn should_apply_no_new_privs_defaults_on_without_full_access_startup() {
322 // No posture information at all, and every narrower posture, keeps
323 // the defense-in-depth default (#5413).
324 for mode in [
325 None,
326 Some("read-only"),
327 Some("workspace-write"),
328 Some("external-sandbox"),
329 ] {
330 assert!(
331 should_apply_no_new_privs(mode, None),
332 "{mode:?} must keep PR_SET_NO_NEW_PRIVS"
333 );
334 }
335 }
336
337 #[test]
338 fn should_apply_no_new_privs_skips_for_danger_full_access_startup() {
339 // The product decision behind #5723: "full access (sandbox disabled)"
340 // must mean it, so the irreversible setuid block is relaxed when the
341 // startup posture resolves to danger-full-access.
342 assert!(!should_apply_no_new_privs(Some("danger-full-access"), None));
343 // Mode strings are normalized the way config validation normalizes
344 // them: surrounding whitespace and ASCII case do not matter.
345 assert!(!should_apply_no_new_privs(
346 Some(" Danger-Full-Access "),
347 None
348 ));
349 }
350
351 #[test]
352 fn should_apply_no_new_privs_env_override_wins_over_posture() {
353 // Explicit override beats posture in both directions (#5413, #5723):
354 // falsey opts out under a narrow posture, truthy forces the flag on
355 // under full access.
356 assert!(!should_apply_no_new_privs(
357 Some("workspace-write"),
358 Some(false)
359 ));
360 assert!(!should_apply_no_new_privs(None, Some(false)));
361 assert!(should_apply_no_new_privs(
362 Some("danger-full-access"),
363 Some(true)
364 ));
365 assert!(should_apply_no_new_privs(
366 Some("workspace-write"),
367 Some(true)
368 ));
369 }
370
371 #[test]
372 fn should_apply_no_new_privs_is_fail_closed_for_unknown_modes() {
373 // A mode string the runtime would reject as invalid must never relax
374 // the flag by accident.
375 for mode in ["danger_full_access", "full-access", "yolo", "", "danger"] {
376 assert!(
377 should_apply_no_new_privs(Some(mode), None),
378 "{mode:?} must keep PR_SET_NO_NEW_PRIVS"
379 );
380 }
381 }
382 }
383
384 /// Kernel-flag proof. `PR_SET_NO_NEW_PRIVS` is irreversible and inherited by
385 /// descendants, so the decision can only be observed end-to-end in a fresh
386 /// child process: the child applies hardening under one posture and reports
387 /// the kernel's own record through `PR_GET_NO_NEW_PRIVS`. These tests exist only
388 /// on Linux; on other hosts `apply_process_hardening` is a no-op and the flag
389 /// does not exist.
390 #[cfg(all(test, target_os = "linux", not(target_env = "ohos")))]
391 mod linux_flag_tests {
392 use super::*;
393
394 const CHILD_ENV: &str = "CODEWHALE_NNP_TEST_CHILD";
395 const CHILD_MODE_ENV: &str = "CODEWHALE_NNP_TEST_MODE";
396
397 /// Child-process entry point. Run directly (child env marker unset) it is
398 /// a trivial pass; run under the parent tests below it applies hardening
399 /// with the posture named by `CODEWHALE_NNP_TEST_MODE` and prints the
400 /// kernel-recorded flag as `NNP=0|1`.
401 #[test]
402 fn no_new_privs_child_reports_kernel_flag() {
403 if std::env::var_os(CHILD_ENV).is_none() {
404 return;
405 }
406 let mode = std::env::var(CHILD_MODE_ENV).ok();
407 apply_process_hardening(mode.as_deref());
408 // Read the flag back through PR_GET_NO_NEW_PRIVS, not
409 // /proc/self/status: no_new_privs is per-task and /proc/self/status
410 // shows the *main* thread's flag, while libtest runs this test on a
411 // spawned thread — the /proc read always reports 0 here.
412 let flag = no_new_privs_active().expect("PR_GET_NO_NEW_PRIVS reads the flag on Linux");
413 println!("NNP={}", if flag { "1" } else { "0" });
414 }
415
416 fn run_child(mode: Option<&str>, env_override: Option<&str>) -> String {
417 let output = std::process::Command::new(std::env::current_exe().expect("test binary"))
418 .args(["no_new_privs_child_reports_kernel_flag", "--nocapture"])
419 .env(CHILD_ENV, "1")
420 // The ambient developer/CI environment must not leak into the
421 // matrix: the child decides from exactly the inputs passed here.
422 .env_remove(NO_NEW_PRIVS_ENV)
423 .env_remove(CHILD_MODE_ENV)
424 .envs(mode.map(|m| (CHILD_MODE_ENV, m)))
425 .envs(env_override.map(|v| (NO_NEW_PRIVS_ENV, v)))
426 .output()
427 .expect("spawn child test process");
428 assert!(
429 output.status.success(),
430 "child failed: status={:?} stderr={}",
431 output.status.code(),
432 String::from_utf8_lossy(&output.stderr)
433 );
434 String::from_utf8_lossy(&output.stdout).into_owned()
435 }
436
437 fn ratchet_expectation(expected: &'static str, row: &str) -> &'static str {
438 if expected == "0" && no_new_privs_active() == Some(true) {
439 eprintln!(
440 "{row}: parent already holds NoNewPrivs, which children cannot clear; \
441 asserting the child keeps NNP=1 instead of NNP=0"
442 );
443 return "1";
444 }
445 expected
446 }
447
448 #[test]
449 fn no_new_privs_flag_tracks_startup_posture_in_child_processes() {
450 // Never recurse when this test binary is itself the spawned child.
451 if std::env::var_os(CHILD_ENV).is_some() {
452 return;
453 }
454 for (mode, expected) in [
455 (None, "1"),
456 (Some("workspace-write"), "1"),
457 (Some("read-only"), "1"),
458 (Some("external-sandbox"), "1"),
459 (Some("danger-full-access"), "0"),
460 ] {
461 let expected = ratchet_expectation(expected, &format!("mode {mode:?}"));
462 let stdout = run_child(mode, None);
463 assert!(
464 stdout.contains(&format!("NNP={expected}")),
465 "mode {mode:?}: expected NoNewPrivs={expected}, got:\n{stdout}"
466 );
467 }
468 }
469
470 #[test]
471 fn no_new_privs_env_override_beats_posture_in_child_processes() {
472 if std::env::var_os(CHILD_ENV).is_some() {
473 return;
474 }
475 for (mode, override_value, expected) in [
476 // Explicit truthy forces the flag on even under full access.
477 ("danger-full-access", "1", "1"),
478 // Explicit falsey opts out under a narrow posture (#5413).
479 ("workspace-write", "0", "0"),
480 ] {
481 let expected = ratchet_expectation(
482 expected,
483 &format!("mode {mode:?} with {NO_NEW_PRIVS_ENV}={override_value}"),
484 );
485 let stdout = run_child(Some(mode), Some(override_value));
486 assert!(
487 stdout.contains(&format!("NNP={expected}")),
488 "mode {mode:?} with {NO_NEW_PRIVS_ENV}={override_value}: \
489 expected NoNewPrivs={expected}, got:\n{stdout}"
490 );
491 }
492 }
493 }
494
494 lines RUST