Lightweight coding agent that runs in your terminal
Rust
Reject sandbox-writable bubblewrap executables from PATH (#51211)
viyatb-oai7aa8f5104963
diff --git a/codex-rs/app-server/src/lib.rs b/codex-rs/app-server/src/lib.rsindex bf1bb93285..08ebe50862 100644--- a/codex-rs/app-server/src/lib.rs+++ b/codex-rs/app-server/src/lib.rs@@ -686,9 +686,10 @@ pub async fn run_main_with_transport_options(range: None,});}- if let Some(warning) =- codex_core::config::system_bwrap_warning(config.permissions.permission_profile())- {+ if let Some(warning) = codex_core::config::system_bwrap_warning(+ &config.permissions.effective_permission_profile(),+ &config.cwd,+ ) {config_warnings.push(ConfigWarningNotification {summary: warning,details: None,diff --git a/codex-rs/cli/tests/exec_server/pid_namespace_tests.rs b/codex-rs/cli/tests/exec_server/pid_namespace_tests.rsindex 57ce4074b4..0139c7f6b1 100644--- a/codex-rs/cli/tests/exec_server/pid_namespace_tests.rs+++ b/codex-rs/cli/tests/exec_server/pid_namespace_tests.rs@@ -14,7 +14,10 @@ use pretty_assertions::assert_eq;#[tokio::test]async fn pid_inheritance_is_startup_only_for_process_and_filesystem_helpers() -> Result<()> {- let Some(bwrap) = codex_sandboxing::find_system_bwrap_in_path() else {+ let Some(bwrap) = codex_sandboxing::find_system_bwrap_in_path(+ &PermissionProfile::read_only().file_system_sandbox_policy(),+ &std::env::current_dir()?,+ ) else {eprintln!("skipping PID namespace test: no system bubblewrap");return Ok(());};diff --git a/codex-rs/exec-server/tests/exec_process.rs b/codex-rs/exec-server/tests/exec_process.rsindex 4c942b01ac..dba1c7c640 100644--- a/codex-rs/exec-server/tests/exec_process.rs+++ b/codex-rs/exec-server/tests/exec_process.rs@@ -211,8 +211,10 @@ async fn shell_snapshot_v2_filters_profile_exports_and_stays_in_memory(shell_name: &str,) -> Result<()> {if use_sandbox- && let Some(warning) =- codex_sandboxing::system_bwrap_warning(&PermissionProfile::read_only())+ && let Some(warning) = codex_sandboxing::system_bwrap_warning(+ &PermissionProfile::read_only(),+ &std::env::current_dir()?,+ ){eprintln!("skipping sandbox test: {warning}");return Ok(());@@ -485,8 +487,10 @@ async fn shell_snapshot_v2_capture_failure_falls_back_and_retries(failure: CaptureFailure,) -> Result<()> {if use_remote- && let Some(warning) =- codex_sandboxing::system_bwrap_warning(&PermissionProfile::workspace_write())+ && let Some(warning) = codex_sandboxing::system_bwrap_warning(+ &PermissionProfile::workspace_write(),+ &std::env::current_dir()?,+ ){eprintln!("skipping sandbox test: {warning}");return Ok(());@@ -636,7 +640,10 @@ async fn shell_snapshot_v2_capture_failure_falls_back_and_retries(#[cfg(unix)]#[tokio::test(flavor = "multi_thread", worker_threads = 2)]async fn remote_sandboxed_process_preserves_custom_arg0() -> Result<()> {- if let Some(warning) = codex_sandboxing::system_bwrap_warning(&PermissionProfile::read_only()) {+ if let Some(warning) = codex_sandboxing::system_bwrap_warning(+ &PermissionProfile::read_only(),+ &std::env::current_dir()?,+ ) {eprintln!("skipping bwrap test: {warning}");return Ok(());}@@ -740,7 +747,10 @@ async fn assert_exec_process_starts_and_exits(use_remote: bool) -> Result<()> {#[cfg(target_os = "linux")]#[tokio::test(flavor = "multi_thread", worker_threads = 2)]async fn remote_process_keeps_sandbox_helper_visible_with_restricted_reads() -> Result<()> {- if let Some(warning) = codex_sandboxing::system_bwrap_warning(&PermissionProfile::read_only()) {+ if let Some(warning) = codex_sandboxing::system_bwrap_warning(+ &PermissionProfile::read_only(),+ &std::env::current_dir()?,+ ) {eprintln!("skipping bwrap test: {warning}");return Ok(());}@@ -802,7 +812,10 @@ async fn remote_process_keeps_sandbox_helper_visible_with_restricted_reads() ->#[cfg(target_os = "linux")]#[tokio::test(flavor = "multi_thread", worker_threads = 2)]async fn remote_tty_process_uses_configured_sandbox_helper_with_hostile_path() -> Result<()> {- if let Some(warning) = codex_sandboxing::system_bwrap_warning(&PermissionProfile::read_only()) {+ if let Some(warning) = codex_sandboxing::system_bwrap_warning(+ &PermissionProfile::read_only(),+ &std::env::current_dir()?,+ ) {eprintln!("skipping bwrap test: {warning}");return Ok(());}@@ -873,7 +886,10 @@ async fn remote_tty_process_uses_configured_sandbox_helper_with_hostile_path() -#[cfg(unix)]#[tokio::test(flavor = "multi_thread", worker_threads = 2)]async fn remote_process_preserves_empty_workspace_roots() -> Result<()> {- if let Some(warning) = codex_sandboxing::system_bwrap_warning(&PermissionProfile::read_only()) {+ if let Some(warning) = codex_sandboxing::system_bwrap_warning(+ &PermissionProfile::read_only(),+ &std::env::current_dir()?,+ ) {eprintln!("skipping bwrap test: {warning}");return Ok(());}diff --git a/codex-rs/exec-server/tests/exec_process/shell_snapshot.rs b/codex-rs/exec-server/tests/exec_process/shell_snapshot.rsindex 56bb200bbf..7d022116b1 100644--- a/codex-rs/exec-server/tests/exec_process/shell_snapshot.rs+++ b/codex-rs/exec-server/tests/exec_process/shell_snapshot.rs@@ -108,8 +108,10 @@ async fn shell_snapshot_concurrent_replays_keep_independent_readers(let deny_fd_path = sandbox_mode == SnapshotSandbox::DenyFdPath;let use_sandbox = sandbox_mode != SnapshotSandbox::None;if use_sandbox- && let Some(warning) =- codex_sandboxing::system_bwrap_warning(&PermissionProfile::read_only())+ && let Some(warning) = codex_sandboxing::system_bwrap_warning(+ &PermissionProfile::read_only(),+ &std::env::current_dir()?,+ ){eprintln!("skipping sandbox test: {warning}");return Ok(());diff --git a/codex-rs/exec/src/lib.rs b/codex-rs/exec/src/lib.rsindex 9899772fe2..90733404ad 100644--- a/codex-rs/exec/src/lib.rs+++ b/codex-rs/exec/src/lib.rs@@ -1177,8 +1177,10 @@ async fn run_exec_session(args: ExecRunArgs) -> anyhow::Result<()> {// is using.event_processor.print_config_summary(&config, &prompt_summary, &session_configured);if !json_mode- && let Some(message) =- codex_core::config::system_bwrap_warning(config.permissions.permission_profile())+ && let Some(message) = codex_core::config::system_bwrap_warning(+ &config.permissions.effective_permission_profile(),+ &config.cwd,+ ){event_processor.process_warning(message);}diff --git a/codex-rs/linux-sandbox/src/launcher.rs b/codex-rs/linux-sandbox/src/launcher.rsindex b72cfede17..84df99c936 100644--- a/codex-rs/linux-sandbox/src/launcher.rs+++ b/codex-rs/linux-sandbox/src/launcher.rs@@ -11,6 +11,7 @@ use crate::bundled_bwrap;use crate::bundled_bwrap::BundledBwrapLauncher;use crate::exec_util::argv_to_cstrings;use crate::exec_util::make_files_inheritable;+use codex_protocol::permissions::FileSystemSandboxPolicy;use codex_sandboxing::find_system_bwrap_in_path;use codex_utils_absolute_path::AbsolutePathBuf;@@ -35,6 +36,8 @@ struct SystemBwrapCapabilities {supports_ro_bind_fd: bool,}+static LAUNCHER: OnceLock<BubblewrapLauncher> = OnceLock::new();+pub(crate) fn exec_bwrap(mut argv: Vec<String>, preserved_files: Vec<File>) -> ! {if argv.iter()@@ -129,22 +132,28 @@ fn translate_legacy_bwrap_fd_mounts(argv: &mut Vec<String>) -> Result<(), StringOk(())}-fn preferred_bwrap_launcher() -> BubblewrapLauncher {- static LAUNCHER: OnceLock<BubblewrapLauncher> = OnceLock::new();- LAUNCHER- .get_or_init(|| {- if let Some(path) = find_system_bwrap_in_path()- && let Some(launcher) = system_bwrap_launcher_for_path(&path)- {- return BubblewrapLauncher::System(launcher);- }+pub(crate) fn initialize_bwrap_launcher(+ file_system_policy: &FileSystemSandboxPolicy,+ sandbox_policy_cwd: &Path,+) {+ LAUNCHER.get_or_init(|| {+ if let Some(path) = find_system_bwrap_in_path(file_system_policy, sandbox_policy_cwd)+ && let Some(launcher) = system_bwrap_launcher_for_path(&path)+ {+ return BubblewrapLauncher::System(launcher);+ }- match bundled_bwrap::launcher() {- Some(launcher) => BubblewrapLauncher::Bundled(launcher),- None => BubblewrapLauncher::Unavailable,- }- })- .clone()+ match bundled_bwrap::launcher() {+ Some(launcher) => BubblewrapLauncher::Bundled(launcher),+ None => BubblewrapLauncher::Unavailable,+ }+ });+}++fn preferred_bwrap_launcher() -> &'static BubblewrapLauncher {+ LAUNCHER.get().unwrap_or_else(|| {+ panic!("bubblewrap launcher must be initialized with the command's permissions")+ })}fn system_bwrap_launcher_for_path(system_bwrap_path: &Path) -> Option<SystemBwrapLauncher> {diff --git a/codex-rs/linux-sandbox/src/linux_run_main.rs b/codex-rs/linux-sandbox/src/linux_run_main.rsindex 8ef516589c..5c08c8c39a 100644--- a/codex-rs/linux-sandbox/src/linux_run_main.rs+++ b/codex-rs/linux-sandbox/src/linux_run_main.rs@@ -27,6 +27,7 @@ use crate::bwrap::WSLG_DISTRO_ROOT;use crate::bwrap::create_bwrap_command_args;use crate::landlock::apply_permission_profile_to_current_thread;use crate::launcher::exec_bwrap;+use crate::launcher::initialize_bwrap_launcher;use crate::launcher::preferred_bwrap_supports_argv0;use crate::proxy_routing::activate_proxy_routes_in_netns;use crate::proxy_routing::prepare_host_proxy_route_spec;@@ -428,6 +429,9 @@ fn run_bwrap_with_proc_fallback() -> ! {let command_cwd = command_cwd.unwrap_or(sandbox_policy_cwd);+ // Select before the preflight, whose synthetic policy omits writable roots.+ initialize_bwrap_launcher(file_system_sandbox_policy, sandbox_policy_cwd);+if options.mount_proc&& !preflight_proc_mount_support(options).unwrap_or_else(|err| exit_with_bwrap_build_error(err))diff --git a/codex-rs/linux-sandbox/tests/suite/bwrap_path.rs b/codex-rs/linux-sandbox/tests/suite/bwrap_path.rsnew file mode 100644index 0000000000..33a3788633--- /dev/null+++ b/codex-rs/linux-sandbox/tests/suite/bwrap_path.rs@@ -0,0 +1,134 @@+//! Writable PATH candidates must never run while constructing the sandbox.++#![cfg(target_os = "linux")]++use codex_protocol::models::PermissionProfile;+use codex_protocol::permissions::NetworkSandboxPolicy;+use codex_utils_absolute_path::AbsolutePathBuf;+use codex_utils_cargo_bin::cargo_bin;+use codex_utils_cargo_bin::write_executable;+use pretty_assertions::assert_eq;+use std::os::unix::fs::PermissionsExt;+use std::process::Command;++#[test]+fn child_workdir_does_not_probe_or_launch_writable_parent_bwrap() {+ // Bazel can mount the default temp directory noexec.+ let temp = tempfile::tempdir_in(std::env::current_dir().expect("current directory"))+ .or_else(|_| tempfile::tempdir())+ .expect("create fixture");+ let workspace = temp.path().join("workspace");+ let cwd = workspace.join("service");+ let bin = workspace.join("bin");+ let marker = temp.path().join("outside-workspace");+ std::fs::create_dir_all(&cwd).expect("create cwd");+ std::fs::create_dir_all(&bin).expect("create bin");+ let fake_bwrap = bin.join("bwrap");+ std::fs::write(+ &fake_bwrap,+ "#!/bin/sh\n: > \"$BWRAP_PROBE_MARKER\"\nprintf '%s\\n' '--as-pid-1 --perms --argv0 --ro-bind-fd'\n",+ )+ .expect("write fake bwrap");+ std::fs::set_permissions(&fake_bwrap, std::fs::Permissions::from_mode(0o755))+ .expect("make fake bwrap executable");+ let policy = PermissionProfile::read_only()+ .file_system_sandbox_policy()+ .with_additional_writable_roots(+ &workspace,+ &[AbsolutePathBuf::try_from(workspace.clone()).expect("absolute workspace")],+ );+ let profile =+ PermissionProfile::from_runtime_permissions(&policy, NetworkSandboxPolicy::Restricted);+ let profile_json = serde_json::to_string(&profile).expect("serialize profile");+ let trusted_path = std::env::var_os("PATH").expect("PATH is set");+ let run = |search_path: &std::ffi::OsStr, script: &str| {+ Command::new(cargo_bin("codex-linux-sandbox").expect("resolve sandbox binary"))+ .arg("--sandbox-policy-cwd")+ .arg(&workspace)+ .arg("--command-cwd")+ .arg(&cwd)+ .arg("--permission-profile")+ .arg(&profile_json)+ .args(["--", "/bin/sh", "-c", script])+ .current_dir(&cwd)+ .env("PATH", search_path)+ .env("BWRAP_PROBE_MARKER", &marker)+ .output()+ .expect("run sandbox")+ };+ let baseline = run(&trusted_path, "printf sandboxed");+ let stderr = String::from_utf8_lossy(&baseline.stderr);+ if !baseline.status.success()+ && [+ "bubblewrap is unavailable",+ "No permissions to create a new namespace",+ "setting up uid map: Permission denied",+ ]+ .iter()+ .any(|message| stderr.contains(message))+ {+ eprintln!(+ "sandbox unavailable: {}",+ String::from_utf8_lossy(&baseline.stderr)+ );+ return;+ }+ assert_eq!(baseline.status.success(), true, "{baseline:?}");+ let denied_write = run(&trusted_path, ": > \"$BWRAP_PROBE_MARKER\"");+ assert_eq!(denied_write.status.success(), false, "{denied_write:?}");+ assert!(+ !marker.exists(),+ "sandbox must deny the outside-workspace write"+ );+ let hostile_path = std::env::join_paths(+ [bin]+ .into_iter()+ .chain(std::env::split_paths(&trusted_path)),+ )+ .expect("join PATH");+ let output = run(&hostile_path, "printf sandboxed");+ assert!(!marker.exists(), "writable bwrap ran before confinement");+ assert_eq!(output.status.success(), true, "{output:?}");+ assert_eq!(output.stdout, b"sandboxed");+}++#[test]+fn full_disk_write_with_managed_network_does_not_probe_writable_bwrap() {+ let temp = tempfile::tempdir_in(std::env::current_dir().unwrap()).unwrap();+ let bin = temp.path().join("bin");+ let cwd = temp.path().join("cwd");+ std::fs::create_dir(&bin).unwrap();+ std::fs::create_dir(&cwd).unwrap();+ let bwrap = bin.join("bwrap");+ write_executable(&bwrap, "#!/bin/sh\n: > \"$BWRAP_PROBE_MARKER\"\nexit 1\n").unwrap();+ let run = |profile: &PermissionProfile, marker: &std::path::Path| {+ Command::new(cargo_bin("codex-linux-sandbox").expect("resolve sandbox binary"))+ .arg("--sandbox-policy-cwd")+ .arg(&cwd)+ .arg("--permission-profile")+ .arg(serde_json::to_string(profile).unwrap())+ .args(["--managed-network", "{}", "--", "/bin/true"])+ .current_dir(&cwd)+ .env_clear()+ .env("PATH", &bin)+ .env("HTTP_PROXY", "http://127.0.0.1:9")+ .env("BWRAP_PROBE_MARKER", marker)+ .output()+ .unwrap()+ };+ // Confirm this host reaches the capability probe without needing working+ // namespaces or bundled bubblewrap. Both invocations use managed networking.+ let control_marker = temp.path().join("control");+ let control = run(&PermissionProfile::read_only(), &control_marker);+ assert!(+ control_marker.exists(),+ "probe was not reached: {control:?}"+ );++ let marker = temp.path().join("unrestricted");+ let output = run(&PermissionProfile::Disabled, &marker);+ assert!(+ !marker.exists(),+ "writable bwrap ran before network confinement: {output:?}"+ );+}diff --git a/codex-rs/linux-sandbox/tests/suite/managed_proxy.rs b/codex-rs/linux-sandbox/tests/suite/managed_proxy.rsindex 02b5d0cad8..49f47f342a 100644--- a/codex-rs/linux-sandbox/tests/suite/managed_proxy.rs+++ b/codex-rs/linux-sandbox/tests/suite/managed_proxy.rs@@ -315,7 +315,10 @@ async fn proc_mount_denial_preserves_legacy_fallback_and_explicit_pid_inheritancreturn;}- let Some(system_bwrap) = codex_sandboxing::find_system_bwrap_in_path() else {+ let Some(system_bwrap) = codex_sandboxing::find_system_bwrap_in_path(+ &PermissionProfile::read_only().file_system_sandbox_policy(),+ &std::env::current_dir().expect("current directory"),+ ) else {eprintln!("skipping PID namespace test: no system bubblewrap is available");return;};@@ -461,7 +464,10 @@ async fn unsupported_system_bwrap_falls_back_to_bundled_bwrap() {return;}- let Some(system_bwrap) = codex_sandboxing::find_system_bwrap_in_path() else {+ let Some(system_bwrap) = codex_sandboxing::find_system_bwrap_in_path(+ &PermissionProfile::read_only().file_system_sandbox_policy(),+ &std::env::current_dir().expect("current directory"),+ ) else {eprintln!("skipping system bwrap fallback test: no system bubblewrap is available");return;};diff --git a/codex-rs/linux-sandbox/tests/suite/mod.rs b/codex-rs/linux-sandbox/tests/suite/mod.rsindex e24b787861..8044edf2ad 100644--- a/codex-rs/linux-sandbox/tests/suite/mod.rs+++ b/codex-rs/linux-sandbox/tests/suite/mod.rs@@ -1,4 +1,5 @@// Aggregates all former standalone integration tests as modules.mod bundled_bwrap;+mod bwrap_path;mod landlock;mod managed_proxy;diff --git a/codex-rs/linux-sandbox/tests/suite/root_metadata_tests.rs b/codex-rs/linux-sandbox/tests/suite/root_metadata_tests.rsindex 8e190470a4..fe7d4dcc20 100644--- a/codex-rs/linux-sandbox/tests/suite/root_metadata_tests.rs+++ b/codex-rs/linux-sandbox/tests/suite/root_metadata_tests.rs@@ -18,7 +18,10 @@ async fn root_metadata_symlinks_cannot_reopen_approved_denials() {if should_skip_bwrap_tests().await {return;}- let Some(bwrap) = codex_sandboxing::find_system_bwrap_in_path() else {+ let Some(bwrap) = codex_sandboxing::find_system_bwrap_in_path(+ &PermissionProfile::read_only().file_system_sandbox_policy(),+ &std::env::current_dir().expect("current directory"),+ ) else {eprintln!("skipping root metadata test: system bubblewrap is unavailable");return;};diff --git a/codex-rs/sandboxing/src/bwrap.rs b/codex-rs/sandboxing/src/bwrap.rsindex 633487136a..ebf7f8d60e 100644--- a/codex-rs/sandboxing/src/bwrap.rs+++ b/codex-rs/sandboxing/src/bwrap.rs@@ -1,8 +1,13 @@use crate::policy_transforms::should_require_platform_sandbox;use codex_protocol::models::PermissionProfile;+use codex_protocol::permissions::FileSystemSandboxPolicy;+use codex_utils_absolute_path::AbsolutePathBuf;+use std::ffi::CString;use std::io::ErrorKind;use std::io::Read;use std::os::fd::AsRawFd;+use std::os::unix::ffi::OsStrExt;+use std::os::unix::fs::MetadataExt;use std::path::Path;use std::path::PathBuf;use std::process::Command;@@ -37,12 +42,18 @@ const SYSTEM_BWRAP_PROBE_TIMEOUT: Duration = Duration::from_millis(500);const SYSTEM_BWRAP_PROBE_POLL_INTERVAL: Duration = Duration::from_millis(50);const SYSTEM_BWRAP_PROBE_STDERR_LIMIT_BYTES: u64 = 64 * 1024;-pub fn system_bwrap_warning(permission_profile: &PermissionProfile) -> Option<String> {+pub fn system_bwrap_warning(+ permission_profile: &PermissionProfile,+ sandbox_policy_cwd: &Path,+) -> Option<String> {if !should_warn_about_system_bwrap(permission_profile) {return None;}- let system_bwrap_path = find_system_bwrap_in_path();+ let system_bwrap_path = find_system_bwrap_in_path(+ &permission_profile.file_system_sandbox_policy(),+ sandbox_policy_cwd,+ );system_bwrap_warning_for_path(system_bwrap_path.as_deref())}@@ -165,24 +176,97 @@ fn is_user_namespace_failure(output: &Output) -> bool {.any(|failure| stderr.contains(failure))}-pub fn find_system_bwrap_in_path() -> Option<PathBuf> {+pub fn find_system_bwrap_in_path(+ file_system_policy: &FileSystemSandboxPolicy,+ sandbox_policy_cwd: &Path,+) -> Option<PathBuf> {+ find_pre_sandbox_executable_in_path(+ SYSTEM_BWRAP_PROGRAM,+ file_system_policy,+ sandbox_policy_cwd,+ )+}++/// Finds the first canonical PATH executable for use before sandbox construction.+/// Skips candidates under a non-root process cwd and candidates the current user+/// can modify or replace through writes allowed by the filesystem policy.+pub fn find_pre_sandbox_executable_in_path(+ program: &str,+ file_system_policy: &FileSystemSandboxPolicy,+ sandbox_policy_cwd: &Path,+) -> Option<PathBuf> {let search_path = std::env::var_os("PATH")?;let cwd = std::env::current_dir().ok()?;- find_system_bwrap_in_search_paths(std::env::split_paths(&search_path), &cwd)+ find_executable_in_search_paths(+ program,+ std::env::split_paths(&search_path),+ &cwd,+ file_system_policy,+ sandbox_policy_cwd,+ )}-fn find_system_bwrap_in_search_paths(+fn find_executable_in_search_paths(+ program: &str,search_paths: impl IntoIterator<Item = PathBuf>,cwd: &Path,+ file_system_policy: &FileSystemSandboxPolicy,+ sandbox_policy_cwd: &Path,) -> Option<PathBuf> {let search_path = std::env::join_paths(search_paths).ok()?;let cwd = std::fs::canonicalize(cwd).unwrap_or_else(|_| cwd.to_path_buf());let cwd_is_root = cwd.parent().is_none();- which::which_in_all(SYSTEM_BWRAP_PROGRAM, Some(search_path), &cwd)+ // Full-disk policies intentionally have no enumerated writable roots.+ let full_disk_write = file_system_policy.has_full_disk_write_access();+ let writable_roots = file_system_policy+ .get_writable_roots_with_cwd_inheriting_root_metadata(sandbox_policy_cwd)+ .into_iter()+ .map(|mut root| {+ if let Ok(canonical) = std::fs::canonicalize(&root.root)+ && let Ok(canonical) = AbsolutePathBuf::from_absolute_path_checked(canonical)+ {+ for subpath in &mut root.read_only_subpaths {+ if let Ok(relative) = subpath.as_path().strip_prefix(root.root.as_path()) {+ *subpath = canonical.join(relative);+ }+ }+ root.root = canonical;+ }+ root+ })+ .collect::<Vec<_>>();+ let policy_can_write = |path: &Path| {+ full_disk_write+ || writable_roots+ .iter()+ .any(|root| root.is_path_writable(path))+ };+ which::which_in_all(program, Some(search_path), &cwd).ok()?.find_map(|path| {let path = std::fs::canonicalize(path).ok()?;- if !cwd_is_root && path.starts_with(&cwd) {+ // Preserve read-only carveouts, but also check ancestors: a protected+ // file can still be replaced by renaming a writable parent directory.+ // Host-protected installations remain usable even with full-disk writes.+ if (!cwd_is_root && path.starts_with(&cwd))+ || (policy_can_write(&path) && current_user_can_modify(&path))+ || path.ancestors().any(|component| {+ let Some(parent) = component.parent() else {+ return false;+ };+ // Read-only carveouts are bind mounts and cannot themselves+ // be renamed/unlinked. Continue checking above them, since a+ // mutable ancestor could still redirect the installation path.+ let is_read_only_mount = writable_roots.iter().any(|root| {+ root.read_only_subpaths+ .iter()+ .any(|path| path.as_path() == component)+ });+ policy_can_write(parent)+ && !is_read_only_mount+ && current_user_can_modify(parent)+ })+ {None} else {Some(path)@@ -190,6 +274,40 @@ fn find_system_bwrap_in_search_paths(})}+fn current_user_can_modify(path: &Path) -> bool {+ let Ok(metadata) = std::fs::metadata(path) else {+ return true;+ };+ // Owners can chmod a currently read-only file or directory before writing it.+ // SAFETY: geteuid has no preconditions.+ if metadata.uid() == unsafe { libc::geteuid() } {+ return true;+ }+ let Ok(path) = CString::new(path.as_os_str().as_bytes()) else {+ return true;+ };+ // Ask the kernel to check effective credentials, including POSIX ACLs. Older+ // libc faccessat emulation ignores ACLs, which could misclassify a writable path.+ // SAFETY: path is a live, NUL-terminated string, and no pointer is retained.+ if unsafe {+ libc::syscall(+ libc::SYS_faccessat2,+ libc::AT_FDCWD,+ path.as_ptr(),+ libc::W_OK,+ libc::AT_EACCESS,+ )+ } == 0+ {+ return true;+ }+ // Unknown errors must not turn an unverified candidate into a trusted one.+ !matches!(+ std::io::Error::last_os_error().raw_os_error(),+ Some(libc::EACCES | libc::EROFS)+ )+}+#[cfg(test)]#[path = "bwrap_tests.rs"]mod tests;diff --git a/codex-rs/sandboxing/src/bwrap_tests.rs b/codex-rs/sandboxing/src/bwrap_tests.rsindex b64f9ff0cf..1c08e044db 100644--- a/codex-rs/sandboxing/src/bwrap_tests.rs+++ b/codex-rs/sandboxing/src/bwrap_tests.rs@@ -1,4 +1,7 @@use super::*;+use codex_protocol::permissions::FileSystemAccessMode;+use codex_protocol::permissions::FileSystemSandboxEntry;+use codex_utils_absolute_path::AbsolutePathBuf;use pretty_assertions::assert_eq;use std::path::Path;use std::path::PathBuf;@@ -127,7 +130,13 @@ fn finds_first_executable_bwrap_in_joined_search_path() {let search_path = std::env::join_paths([first_dir, second_dir]).expect("join search path");assert_eq!(- find_system_bwrap_in_search_paths(std::env::split_paths(&search_path), &cwd),+ find_executable_in_search_paths(+ "bwrap",+ std::env::split_paths(&search_path),+ &cwd,+ &PermissionProfile::read_only().file_system_sandbox_policy(),+ &cwd,+ ),Some(expected_bwrap));}@@ -144,7 +153,13 @@ fn skips_workspace_local_bwrap_in_joined_search_path() {let search_path = std::env::join_paths([cwd.clone(), trusted_dir]).expect("join search path");assert_eq!(- find_system_bwrap_in_search_paths(std::env::split_paths(&search_path), &cwd),+ find_executable_in_search_paths(+ "bwrap",+ std::env::split_paths(&search_path),+ &cwd,+ &PermissionProfile::read_only().file_system_sandbox_policy(),+ &cwd,+ ),Some(expected_bwrap));}@@ -158,9 +173,175 @@ fn root_cwd_does_not_hide_system_bwrap_candidates() {let search_path = std::env::join_paths([bin_dir]).expect("join search path");assert_eq!(- find_system_bwrap_in_search_paths(std::env::split_paths(&search_path), Path::new("/")),+ find_executable_in_search_paths(+ "bwrap",+ std::env::split_paths(&search_path),+ Path::new("/"),+ &PermissionProfile::read_only().file_system_sandbox_policy(),+ Path::new("/"),+ ),Some(expected_bwrap));+ assert_eq!(+ find_executable_in_search_paths(+ "bwrap",+ std::env::split_paths(&search_path),+ Path::new("/"),+ &PermissionProfile::Disabled.file_system_sandbox_policy(),+ Path::new("/"),+ ),+ None,+ );+}++#[test]+fn skips_bwrap_in_writable_roots_outside_command_cwd() {+ let temp_dir = tempdir().expect("temp dir");+ let workspace = temp_dir.path().join("workspace");+ let cwd = workspace.join("service");+ let workspace_bin = workspace.join("bin");+ let extra_root = temp_dir.path().join("extra");+ let trusted_dir = temp_dir.path().join("trusted");+ for dir in [&cwd, &workspace_bin, &extra_root, &trusted_dir] {+ std::fs::create_dir_all(dir).expect("create directory");+ }+ write_named_fake_bwrap_in(&workspace_bin);+ write_named_fake_bwrap_in(&extra_root);+ let expected_bwrap = write_named_fake_bwrap_in(&trusted_dir);+ let writable_roots = vec![workspace, extra_root.clone()];+ let policy = PermissionProfile::read_only()+ .file_system_sandbox_policy()+ .with_additional_writable_roots(+ &cwd,+ &writable_roots+ .into_iter()+ .map(|path| AbsolutePathBuf::try_from(path).unwrap())+ .collect::<Vec<_>>(),+ );+ let search_paths = vec![workspace_bin, extra_root];++ assert_eq!(+ find_executable_in_search_paths("bwrap", search_paths.clone(), &cwd, &policy, &cwd),+ None,+ );+ assert_eq!(+ find_executable_in_search_paths(+ "bwrap",+ search_paths.into_iter().chain([trusted_dir]),+ &cwd,+ &policy,+ &cwd,+ ),+ Some(expected_bwrap),+ );+}++#[test]+fn skips_bwrap_in_symlinked_writable_root() {+ let temp_dir = tempdir().expect("temp dir");+ let workspace = temp_dir.path().join("workspace");+ let cwd = workspace.join("service");+ let workspace_bin = workspace.join("bin");+ let alias = temp_dir.path().join("alias");+ std::fs::create_dir_all(&cwd).expect("create cwd");+ std::fs::create_dir_all(&workspace_bin).expect("create bin");+ std::os::unix::fs::symlink(&workspace, &alias).expect("create workspace alias");+ write_named_fake_bwrap_in(&workspace_bin);+ let policy = PermissionProfile::read_only()+ .file_system_sandbox_policy()+ .with_additional_writable_roots(&cwd, &[AbsolutePathBuf::try_from(alias).unwrap()]);++ assert_eq!(+ find_executable_in_search_paths("bwrap", [workspace_bin], &cwd, &policy, &cwd),+ None,+ );+}++#[test]+fn full_disk_write_rejects_owned_bwrap_even_when_chmod_read_only() {+ use std::os::unix::fs::PermissionsExt;++ let temp = tempdir().unwrap();+ let bin = temp.path().join("bin");+ std::fs::create_dir(&bin).unwrap();+ let bwrap = write_named_fake_bwrap_in(&bin);+ std::fs::set_permissions(&bwrap, std::fs::Permissions::from_mode(0o555)).unwrap();+ let policy = PermissionProfile::Disabled.file_system_sandbox_policy();++ assert_eq!(+ find_executable_in_search_paths("bwrap", [bin], Path::new("/"), &policy, Path::new("/")),+ None,+ );+}++#[test]+fn read_only_bwrap_carveout_does_not_trust_a_replaceable_parent() {+ let temp = tempdir().unwrap();+ let bin = temp.path().join("bin");+ std::fs::create_dir(&bin).unwrap();+ let bwrap = write_named_fake_bwrap_in(&bin);+ let policy = FileSystemSandboxPolicy::restricted(vec![+ FileSystemSandboxEntry::new(+ AbsolutePathBuf::try_from(temp.path()).unwrap().into(),+ FileSystemAccessMode::Write,+ ),+ FileSystemSandboxEntry::new(+ AbsolutePathBuf::try_from(bwrap).unwrap().into(),+ FileSystemAccessMode::Read,+ ),+ ]);++ assert_eq!(+ find_executable_in_search_paths("bwrap", [bin], Path::new("/"), &policy, Path::new("/")),+ None,+ );+}++#[test]+fn root_write_preserves_a_read_only_system_installation() {+ use codex_protocol::permissions::FileSystemPath;+ use codex_protocol::permissions::FileSystemSpecialPath;++ let temp = tempdir().unwrap();+ // Use a system executable as a discovery-only candidate. Never execute it.+ let system_binary = std::fs::canonicalize("/bin/true").unwrap();+ let protected_root = system_binary+ .ancestors()+ .find(|path| path.parent() == Some(Path::new("/")))+ .unwrap();+ std::os::unix::fs::symlink(&system_binary, temp.path().join("bwrap")).unwrap();+ let policy = FileSystemSandboxPolicy::restricted(vec![+ FileSystemSandboxEntry::new(+ FileSystemPath::Special {+ value: FileSystemSpecialPath::Root,+ },+ FileSystemAccessMode::Write,+ ),+ FileSystemSandboxEntry::new(+ AbsolutePathBuf::try_from(protected_root).unwrap().into(),+ FileSystemAccessMode::Read,+ ),+ ]);++ for policy in [+ policy,+ PermissionProfile::Disabled.file_system_sandbox_policy(),+ ] {+ // Root can modify the system installation unless the policy protects it.+ // SAFETY: geteuid has no preconditions.+ let can_modify_system =+ policy.has_full_disk_write_access() && unsafe { libc::geteuid() } == 0;+ assert_eq!(+ find_executable_in_search_paths(+ "bwrap",+ [temp.path().to_path_buf()],+ Path::new("/"),+ &policy,+ Path::new("/"),+ ),+ (!can_modify_system).then(|| system_binary.clone()),+ );+ }}fn write_fake_bwrap(contents: &str) -> tempfile::TempPath {diff --git a/codex-rs/sandboxing/src/lib.rs b/codex-rs/sandboxing/src/lib.rsindex 9e54454e3d..e65ead4d5e 100644--- a/codex-rs/sandboxing/src/lib.rs+++ b/codex-rs/sandboxing/src/lib.rs@@ -14,6 +14,8 @@ mod windows;#[cfg(windows)]mod windows_mxc;+#[cfg(target_os = "linux")]+pub use bwrap::find_pre_sandbox_executable_in_path;#[cfg(target_os = "linux")]pub use bwrap::find_system_bwrap_in_path;#[cfg(target_os = "linux")]@@ -59,6 +61,7 @@ use codex_protocol::error::CodexErr;#[cfg(not(target_os = "linux"))]pub fn system_bwrap_warning(_permission_profile: &codex_protocol::models::PermissionProfile,+ _sandbox_policy_cwd: &std::path::Path,) -> Option<String> {None}diff --git a/codex-rs/tui/src/app/startup_prompts.rs b/codex-rs/tui/src/app/startup_prompts.rsindex d0f3b31669..1203f9eb43 100644--- a/codex-rs/tui/src/app/startup_prompts.rs+++ b/codex-rs/tui/src/app/startup_prompts.rs@@ -101,9 +101,10 @@ pub(super) fn project_config_warning(config: &Config) -> Option<String> {}pub(super) fn emit_system_bwrap_warning(app_event_tx: &AppEventSender, config: &Config) {- let Some(message) =- codex_sandboxing::system_bwrap_warning(config.permissions.permission_profile())- else {+ let Some(message) = codex_sandboxing::system_bwrap_warning(+ &config.permissions.effective_permission_profile(),+ &config.cwd,+ ) else {return;};