Bind Linux sandbox paths before shell snapshot replay (#64388)

## Why

Linux filesystem rules that depend on `TMPDIR` or `HOME` need to keep
the same meaning when shell snapshot replay changes the command environment.

## What changed

Resolve `:tmpdir` entries and home-relative read-deny globs against the
prepared launch environment. Omit `:tmpdir` entries when `TMPDIR` is
unset or empty. Resolve relative temporary directories from the physical
command working directory and verify that directory before and after
bubblewrap sets up its mounts.

Preserve process confinement when resolving paths makes the filesystem
rules appear to grant full-disk access. Reject bindings that would change
the grants enforced by legacy Landlock.

## Testing

Add regression coverage for shell snapshot replay, working-directory
changes, and preservation of Linux process confinement.

GitOrigin-RevId: 07d4698ca7b30b0259193513145233ae1bdc7f19
This commit is contained in:
viyatb-oai
2026-11-27 22:29:24 +00:00
committed by copyberry
parent 372947d936
commit 5729aca45d
12 changed files with 785 additions and 30 deletions
+1
View File
@@ -5072,6 +5072,7 @@ dependencies = [
"codex-network-proxy",
"codex-otel",
"codex-protocol",
"codex-shell-command",
"codex-uds",
"codex-utils-absolute-path",
"codex-utils-cargo-bin",
@@ -128,8 +128,15 @@ async fn sandbox_request_wraps_native_argv_on_executor() {
serde_json::from_str(permission_profile_json).expect("permission profile JSON");
assert_eq!(
permission_profile,
PermissionProfile::workspace_write()
.materialize_project_roots_with_workspace_roots(std::slice::from_ref(&cwd))
PermissionProfile::workspace_write_with(
&[],
codex_protocol::permissions::NetworkSandboxPolicy::Restricted,
// This Linux launch has no TMPDIR to grant to the command.
/*exclude_tmpdir_env_var*/
true,
/*exclude_slash_tmp*/ false,
)
.materialize_project_roots_with_workspace_roots(std::slice::from_ref(&cwd))
);
let policy_directory = tempdir().expect("policy directory");
+9 -2
View File
@@ -65,6 +65,8 @@ pub(crate) const WSLG_DISTRO_ROOT: &str = "/mnt/wslg/distro";
pub(crate) struct BwrapOptions {
/// Whether to mount a fresh `/proc`; disabled by `--no-proc` or mount fallback.
pub mount_proc: bool,
/// Enter the cwd used to resolve relative TMPDIR even if PWD names a hidden alias.
pub require_command_cwd: bool,
/// Explicitly reuse the caller's PID namespace instead of creating one.
pub inherit_pid_namespace: bool,
/// How networking should be configured inside the bubblewrap sandbox.
@@ -85,6 +87,7 @@ impl Default for BwrapOptions {
fn default() -> Self {
Self {
mount_proc: true,
require_command_cwd: false,
inherit_pid_namespace: false,
network_mode: BwrapNetworkMode::FullAccess,
mask_wsl_interop: false,
@@ -331,7 +334,6 @@ fn create_bwrap_flags(
preserved_files,
synthetic_mount_targets,
} = create_filesystem_args(file_system_sandbox_policy, sandbox_policy_cwd, options)?;
let normalized_command_cwd = normalize_command_cwd_for_bwrap(command_cwd);
let mut args = Vec::new();
args.push("--new-session".to_string());
args.push("--die-with-parent".to_string());
@@ -366,7 +368,12 @@ fn create_bwrap_flags(
args.push("--proc".to_string());
args.push("/proc".to_string());
}
if normalized_command_cwd.as_path() != command_cwd {
let normalized_command_cwd = if options.require_command_cwd {
command_cwd.to_path_buf()
} else {
normalize_command_cwd_for_bwrap(command_cwd)
};
if options.require_command_cwd || normalized_command_cwd.as_path() != command_cwd {
// Bubblewrap otherwise inherits the helper's logical cwd, which can be
// a symlink alias that disappears once the sandbox only mounts
// canonical roots. Enter the canonical command cwd explicitly so
@@ -8,6 +8,7 @@ use std::io::Read;
use std::os::fd::AsRawFd;
use std::os::fd::FromRawFd;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::MetadataExt;
use std::path::Path;
use std::path::PathBuf;
use std::sync::OnceLock;
@@ -74,6 +75,10 @@ pub struct LinuxSandboxCommand {
#[arg(long = "command-cwd", hide = true)]
pub command_cwd: Option<PathBuf>,
/// Device and inode of the cwd used to bind a relative TMPDIR.
#[arg(long, hide = true, requires = "command_cwd")]
pub expected_cwd_identity: Option<String>,
/// Canonical runtime permissions for the command.
#[arg(
long = "permission-profile",
@@ -147,6 +152,7 @@ pub fn run_main() -> ! {
let LinuxSandboxCommand {
sandbox_policy_cwd,
command_cwd,
expected_cwd_identity,
permission_profile,
use_legacy_landlock,
apply_seccomp_then_exec,
@@ -159,6 +165,21 @@ pub fn run_main() -> ! {
inherit_pid_namespace,
command,
} = LinuxSandboxCommand::parse();
// Check the directory we actually entered, both on helper startup and
// after bubblewrap switches mounts. A rename can keep the inode but
// change where ".." leads, while a replacement can keep the same name.
if let Some(expected) = &expected_cwd_identity {
let actual =
fs::metadata(".").unwrap_or_else(|err| exit_with_bwrap_build_error(err.into()));
let path =
std::env::current_dir().unwrap_or_else(|err| exit_with_bwrap_build_error(err.into()));
if Some(path.as_path()) != command_cwd.as_deref()
|| *expected != format!("{}:{}", actual.dev(), actual.ino())
{
eprintln!("working directory changed after resolving relative TMPDIR");
std::process::exit(1);
}
}
let allow_network_for_proxy = managed_network.is_some();
let routing = if transparent_tcp {
ProxyRouting::TransparentTcp
@@ -350,6 +371,7 @@ pub fn run_main() -> ! {
(None, Vec::new())
};
let options = BwrapOptions {
require_command_cwd: expected_cwd_identity.is_some(),
mount_proc: !no_proc && !inherit_pid_namespace,
inherit_pid_namespace,
network_mode: if transparent_tcp {
@@ -387,6 +409,9 @@ pub fn run_main() -> ! {
proxy_route_spec,
command,
});
if let Some(expected) = expected_cwd_identity {
inner.insert(1, format!("--expected-cwd-identity={expected}"));
}
if transparent_tcp && inherit_pid_namespace {
inner.insert(1, "--inherit-pid-namespace".to_string());
}
@@ -651,6 +676,7 @@ fn build_preflight_bwrap_argv(options: BwrapOptions) -> CodexResult<crate::bwrap
Path::new("/"),
BwrapOptions {
mount_proc: true,
require_command_cwd: false,
// The alias check must see the same WSL masks as the main sandbox.
..options
},
+173 -5
View File
@@ -725,14 +725,127 @@ async fn sandbox_ignores_missing_writable_roots_under_bwrap() {
assert_eq!(output.stdout.text, "sandbox-ok");
}
#[tokio::test]
async fn relative_tmpdir_stays_bound_to_the_prepared_working_directory() -> std::io::Result<()> {
use codex_sandboxing::SandboxCommand;
use codex_sandboxing::SandboxExecutables;
use codex_sandboxing::SandboxManager;
use codex_sandboxing::SandboxSelection;
use codex_sandboxing::SandboxTransformRequest;
use codex_sandboxing::SandboxType;
use std::fs;
use std::os::unix::fs::symlink;
let temp = tempfile::tempdir()?;
let root = temp.path().canonicalize()?;
let cwd = root.join("a/current");
let moved = root.join("b/current");
let alias = root.join("alias");
fs::create_dir_all(&cwd)?;
fs::create_dir_all(root.join("b"))?;
for parent in ["a", "b"] {
let private = root.join(parent).join("private");
fs::create_dir(&private)?;
fs::write(private.join("key"), "denied")?;
}
fs::write(cwd.join("allowed"), "allowed")?;
symlink(&cwd, &alias)?;
let helper = codex_linux_sandbox_exe();
let special =
|value, access| FileSystemSandboxEntry::new(FileSystemPath::Special { value }, access);
let mut policy = FileSystemSandboxPolicy::restricted(vec![
special(FileSystemSpecialPath::Minimal, FileSystemAccessMode::Read),
special(FileSystemSpecialPath::Tmpdir, FileSystemAccessMode::Deny),
]);
let mut env = create_env_from_core_vars();
env.insert("TMPDIR".into(), "../private".into());
env.insert("PWD".into(), alias.display().to_string());
let prepare = |policy: &FileSystemSandboxPolicy| {
SandboxManager::new()
.transform(SandboxTransformRequest {
command: SandboxCommand {
program: "/bin/sh".into(),
args: vec!["-c".into(), r#"cat allowed; ! cat "$TMPDIR/key""#.into()],
cwd: AbsolutePathBuf::try_from(alias.as_path())?.into(),
env: env.clone(),
managed_network: None,
additional_permissions: None,
},
permissions: &PermissionProfile::from_runtime_permissions(
policy,
NetworkSandboxPolicy::Enabled,
),
workspace_roots: None,
selection: SandboxSelection::Explicit(SandboxType::LinuxSeccomp),
network: Default::default(),
sandbox_policy_cwd: &AbsolutePathBuf::try_from(root.as_path())?.into(),
executables: SandboxExecutables::Launcher(Some(&helper)),
use_legacy_landlock: false,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
})
.expect("prepare sandbox")
.into_direct_command()
};
let read = |path: &std::path::Path| {
FileSystemSandboxEntry::new(
AbsolutePathBuf::try_from(path).unwrap().into(),
FileSystemAccessMode::Read,
)
};
policy.entries.push(read(&helper));
let rejected = |command: &mut std::process::Command| {
let output = command.output().unwrap();
assert!(
!output.status.success() && output.stdout.is_empty(),
"{output:?}"
);
assert!(
String::from_utf8_lossy(&output.stderr).contains("working directory changed"),
"{output:?}"
);
};
let can_mount = !should_skip_bwrap_tests().await;
if can_mount {
// A mount for one file synthesizes its parent at the right path but with a different inode.
let mut file_only = policy.clone();
file_only.entries.push(read(&cwd.join("allowed")));
rejected(&mut prepare(&file_only)?);
}
policy
.entries
.extend([read(&root.join("a")), read(&root.join("b"))]);
let mut command = prepare(&policy)?;
if can_mount {
// The physical cwd is mounted even though its PWD alias is outside the readable roots.
let output = command.output()?;
assert!(output.status.success(), "{output:?}");
assert_eq!(output.stdout, b"allowed");
fs::remove_file(&alias)?;
symlink(root.join("b"), &alias)?;
assert_eq!(command.output()?.stdout, b"allowed");
}
// Moving the same directory changes where ".." leads.
fs::rename(&cwd, &moved)?;
symlink(&moved, &cwd)?;
rejected(&mut command);
// A different directory under the original name must also be rejected.
fs::remove_file(&cwd)?;
fs::create_dir(&cwd)?;
rejected(&mut command);
Ok(())
}
#[tokio::test]
async fn test_no_new_privs_is_enabled() {
let probe = [
"python3",
"-c",
"import ctypes; print(ctypes.CDLL(None).prctl(39, 0, 0, 0, 0))",
];
let output = run_cmd_output(
&[
"python3",
"-c",
"import ctypes; print(ctypes.CDLL(None).prctl(39, 0, 0, 0, 0))",
],
&probe,
&[],
// We have seen timeouts when running this test in CI on GitHub,
// so we are using a generous timeout until we can diagnose further.
@@ -741,6 +854,61 @@ async fn test_no_new_privs_is_enabled() {
.await;
assert_eq!(output.exit_code, 0);
assert_eq!(output.stdout.text, "1\n");
use FileSystemAccessMode::Deny;
use FileSystemAccessMode::Read;
use FileSystemAccessMode::Write;
let cwd = AbsolutePathBuf::current_dir().expect("cwd");
let temp = tempfile::tempdir().expect("writable tmpdir");
for (access, literal_access) in [(Deny, None), (Read, Some(Write)), (Write, Some(Read))] {
let mut entries = vec![
FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
Write,
),
FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: FileSystemSpecialPath::Tmpdir,
},
access,
),
];
// A non-root test process cannot create missing metadata mount points directly under /.
for name in codex_protocol::permissions::PROTECTED_METADATA_PATH_NAMES {
let path = AbsolutePathBuf::from_absolute_path(std::path::Path::new("/").join(name))
.expect("absolute metadata path");
entries.push(FileSystemSandboxEntry::new(path.into(), Write));
}
let mut env = create_env_from_core_vars();
env.remove("TMPDIR");
if let Some(literal_access) = literal_access {
let tmpdir = temp.path().to_str().expect("UTF-8 tmpdir");
env.insert("TMPDIR".into(), tmpdir.into());
entries.push(FileSystemSandboxEntry::new(
AbsolutePathBuf::from_absolute_path(tmpdir)
.expect("absolute tmpdir")
.into(),
literal_access,
));
}
let permissions = PermissionProfile::from_runtime_permissions(
&FileSystemSandboxPolicy::restricted(entries),
NetworkSandboxPolicy::Enabled,
);
let output = run_cmd_result_with_permission_profile_for_cwd(
&probe,
cwd.clone(),
permissions,
env,
LONG_TIMEOUT_MS,
/*use_legacy_landlock*/ false,
)
.await
.expect("restricted launch");
assert_eq!((output.exit_code, output.stdout.text.as_str()), (0, "1\n"));
}
}
#[tokio::test]
+3
View File
@@ -30,6 +30,9 @@ tokio = { workspace = true, features = ["rt", "sync"] }
tracing = { workspace = true, features = ["log"] }
which = { workspace = true }
[target.'cfg(unix)'.dependencies]
codex-shell-command = { workspace = true }
[target.'cfg(windows)'.dependencies]
codex-otel = { workspace = true }
codex-utils-home-dir = { workspace = true }
+47 -4
View File
@@ -233,9 +233,15 @@ pub(crate) enum SandboxOperation {
FileSystemHelper,
}
#[cfg(unix)]
pub(crate) use crate::linux_policy::LinuxBinding;
#[cfg(not(unix))]
pub(crate) type LinuxBinding = ();
/// The authorized profile, resolved on the host that will enforce it.
#[derive(Debug)]
pub(super) struct PreparedLaunchPolicy {
pub(super) linux_binding: Option<LinuxBinding>,
pub(super) permissions: PermissionProfile,
#[cfg(windows)]
pub(super) workspace_roots: Vec<AbsolutePathBuf>,
@@ -244,13 +250,36 @@ pub(super) struct PreparedLaunchPolicy {
impl PreparedLaunchPolicy {
/// An empty workspace list stays empty, even when the policy contains `:workspace_roots`.
pub(super) fn resolve(
permissions: PermissionProfile,
policy_cwd: &PathUri,
roots: Option<&[PathUri]>,
runtime_readable_paths: &[AbsolutePathBuf],
mut permissions: PermissionProfile,
request: &crate::SandboxTransformRequest<'_>,
operation: &SandboxOperation,
runtime_readable_paths: &[AbsolutePathBuf],
) -> io::Result<Self> {
let is_file_system_helper = matches!(operation, SandboxOperation::FileSystemHelper);
let policy_cwd = request.sandbox_policy_cwd;
let roots = request.workspace_roots;
#[cfg(unix)]
let linux = match request.selection {
crate::SandboxSelection::Explicit(backend) => backend == SandboxType::LinuxSeccomp,
crate::SandboxSelection::Platform { .. } => cfg!(target_os = "linux"),
};
let bind =
|_entries: &mut Vec<FileSystemSandboxEntry>| -> io::Result<Option<LinuxBinding>> {
#[cfg(unix)]
if linux {
return crate::linux_policy::bind_linux_policy_environment(
_entries,
&request.command.cwd,
&request.command.env,
policy_cwd,
crate::linux::uses_legacy_landlock(
request.use_legacy_landlock,
request.network.enforce_managed_network,
),
);
}
Ok(None)
};
let Some(roots) = roots else {
if is_file_system_helper || !runtime_readable_paths.is_empty() {
return Err(io::Error::new(
@@ -258,7 +287,18 @@ impl PreparedLaunchPolicy {
"runtime read access requires explicit workspace roots",
));
}
let linux_binding = match &mut permissions {
PermissionProfile::Managed {
file_system:
codex_protocol::models::ManagedFileSystemPermissions::Restricted {
entries, ..
},
..
} => bind(entries)?,
_ => None,
};
return Ok(Self {
linux_binding,
permissions,
#[cfg(windows)]
workspace_roots: Vec::new(),
@@ -277,6 +317,8 @@ impl PreparedLaunchPolicy {
}
let mut file_system =
file_system.materialize_project_roots_with_workspace_roots(&workspace_roots);
// Freeze the materialized rules before testing whether trusted helper paths need a read grant.
let linux_binding = bind(&mut file_system.entries)?;
let permissions = if is_file_system_helper {
tracing::Span::current().record("permission_entries", file_system.entries.len());
if !file_system.has_full_disk_read_access() {
@@ -319,6 +361,7 @@ impl PreparedLaunchPolicy {
)
};
Ok(Self {
linux_binding,
permissions,
#[cfg(windows)]
workspace_roots,
+2
View File
@@ -3,6 +3,8 @@ mod bwrap;
mod denial;
pub mod linux;
mod linux_pid_namespace;
#[cfg(unix)]
mod linux_policy;
mod manager;
pub mod policy_transforms;
mod sandbox_integrity;
+36 -3
View File
@@ -4,6 +4,7 @@ use crate::LinuxSandboxPidNamespace;
use crate::SandboxExecRequest;
use crate::SandboxTransformError;
use crate::manager::SandboxBackend;
use crate::manager::launch::LinuxBinding;
use codex_network_proxy::ManagedNetworkSandboxContext;
use codex_protocol::models::PermissionProfile;
use codex_utils_absolute_path::AbsolutePathBuf;
@@ -23,7 +24,7 @@ impl<'a> LinuxSandboxMode<'a> {
use_legacy_landlock: bool,
managed_network: Option<&'a ManagedNetworkSandboxContext>,
) -> Self {
if use_legacy_landlock && managed_network.is_none() {
if uses_legacy_landlock(use_legacy_landlock, managed_network.is_some()) {
Self::LegacyLandlock
} else {
Self::Bubblewrap { managed_network }
@@ -51,12 +52,18 @@ impl<'a> LinuxSandboxMode<'a> {
}
}
// Proxy routing needs bubblewrap's isolated network namespace.
pub(super) fn uses_legacy_landlock(requested: bool, enforce_managed_network: bool) -> bool {
requested && !enforce_managed_network
}
pub(super) struct Linux<'a> {
pub(super) pid_namespace: LinuxSandboxPidNamespace,
pub(super) transparent_tcp: bool,
pub(super) sandbox_exe: Option<&'a Path>,
pub(super) use_legacy_landlock: bool,
pub(super) route: Option<ManagedNetworkSandboxContext>,
pub(super) binding: Option<LinuxBinding>,
}
impl SandboxBackend for Linux<'_> {
@@ -69,19 +76,45 @@ impl SandboxBackend for Linux<'_> {
let exe = self
.sandbox_exe
.ok_or(SandboxTransformError::MissingLinuxSandboxExecutable)?;
#[cfg(unix)]
let bound_cwd = self
.binding
.as_mut()
.and_then(|binding| binding.command_cwd.take());
#[cfg(unix)]
let cwd = if let Some(bound) = &bound_cwd {
exec.cwd = codex_utils_path_uri::PathUri::from_abs_path(&bound.path);
&bound.path
} else {
cwd
};
#[cfg(unix)]
let encoded = crate::linux_policy::linux_helper_permissions(exec, self.binding.take())
.map_err(SandboxTransformError::InvalidPolicy)?;
#[cfg(unix)]
let helper_permissions = encoded.as_ref().unwrap_or(&exec.permission_profile);
#[cfg(not(unix))]
let helper_permissions = {
let _ = &self.binding;
&exec.permission_profile
};
let mode = LinuxSandboxMode::resolve(self.use_legacy_landlock, self.route.as_ref());
#[cfg(target_os = "linux")]
if crate::bwrap::is_wsl1() {
mode.ensure_supported_on_wsl1(&exec.permission_profile)?;
mode.ensure_supported_on_wsl1(helper_permissions)?;
}
let program = exe.to_string_lossy().into_owned();
let mut args = create_linux_sandbox_command_args_for_permission_profile(
std::mem::take(&mut exec.command),
cwd,
&exec.permission_profile,
helper_permissions,
policy_cwd,
mode,
);
#[cfg(unix)]
if let Some(bound) = bound_cwd {
args.insert(0, format!("--expected-cwd-identity={}", bound.identity));
}
// Only the startup opt-in requires a helper that understands PID inheritance.
if self.pid_namespace == LinuxSandboxPidNamespace::Inherit {
args.insert(0, "--inherit-pid-namespace".to_owned());
+249
View File
@@ -0,0 +1,249 @@
//! Freeze environment-dependent filesystem rules before encoding the Linux helper command.
use codex_protocol::models::PermissionProfile;
use codex_protocol::permissions::FileSystemAccessMode;
use codex_protocol::permissions::FileSystemPath;
use codex_protocol::permissions::FileSystemSandboxEntry;
use codex_protocol::permissions::FileSystemSandboxPolicy;
use codex_protocol::permissions::FileSystemSpecialPath;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathConvention;
use codex_utils_path_uri::PathUri;
use std::io;
use std::os::unix::fs::MetadataExt;
/// The directory against which a relative TMPDIR was resolved.
#[derive(Debug)]
pub(super) struct BoundCwd {
pub(super) path: AbsolutePathBuf,
pub(super) identity: String,
}
/// Linux-only bounds on a launch after binding environment-dependent paths.
#[derive(Debug)]
pub(super) struct LinuxBinding {
pub(super) command_cwd: Option<BoundCwd>,
// Keep the original ceiling only when the bound policy would exceed it.
ceiling: Option<FileSystemAccessMode>,
original_legacy: Option<FileSystemSandboxPolicy>,
}
impl LinuxBinding {
/// Decide once, after runtime grants have been added. Both sandbox selection
/// and the helper use the same decision.
pub(super) fn for_policy(self, permissions: &PermissionProfile) -> Self {
let ceiling = self.ceiling.filter(|ceiling| {
let policy = permissions.file_system_sandbox_policy();
policy.has_full_disk_write_access()
|| (!ceiling.can_read() && policy.has_full_disk_read_access())
});
Self { ceiling, ..self }
}
pub(super) fn needs_encoding(&self) -> bool {
self.ceiling.is_some()
}
}
/// Encode a real root grant as a Linux path if binding would enable the helper's
/// full-disk shortcut. Keep this representation at the helper boundary: legacy
/// policies distinguish a writable `/` from the symbolic `:root` grant.
pub(super) fn linux_helper_permissions(
exec: &crate::SandboxExecRequest,
binding: Option<LinuxBinding>,
) -> io::Result<Option<PermissionProfile>> {
let Some(binding) = binding else {
return Ok(None);
};
if !binding.needs_encoding() && binding.original_legacy.is_none() {
return Ok(None);
}
let granted = &exec.permission_profile;
let mut file_system = granted.file_system_sandbox_policy();
if let Some(ceiling) = binding.ceiling {
let full_read = file_system.has_full_disk_read_access();
let root = PathUri::from_host_native_path("/")?;
for entry in &mut file_system.entries {
if matches!(
entry.path,
FileSystemPath::Special {
value: FileSystemSpecialPath::Root
}
) && entry.access.can_read()
{
entry.path = root.clone().into();
}
}
if full_read && ceiling.can_read() {
file_system.entries.push(FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
FileSystemAccessMode::Read,
));
}
}
let network = granted.network_sandbox_policy();
if let Some(original) = &binding.original_legacy {
// Older Linux helpers in Landlock mode consume a legacy projection. Require its grants
// and metadata carveouts to survive the root encoding at the approved
// cwd and TMPDIR; an unrepresentable original must stay unrepresentable.
let cwd = exec.sandbox_policy_cwd.to_abs_path()?;
let legacy_grants = |source: &FileSystemSandboxPolicy| -> io::Result<_> {
let legacy = source.to_legacy_sandbox_policy(network, cwd.as_path())?;
let mut projected =
FileSystemSandboxPolicy::from_legacy_sandbox_policy_for_cwd(&legacy, cwd.as_path());
let _ = bind_linux_paths(
&mut projected.entries,
&exec.cwd,
&exec.env,
&exec.sandbox_policy_cwd,
)?;
Ok(projected)
};
let original_grants = legacy_grants(original)?;
let encoded_grants = legacy_grants(&file_system)?;
if !original_grants.is_semantically_equivalent_to(&encoded_grants, cwd.as_path()) {
return Err(io::Error::new(
io::ErrorKind::Unsupported,
"binding this Linux policy would change legacy Landlock grants",
));
}
}
Ok(binding.ceiling.map(|_| {
PermissionProfile::from_runtime_permissions_with_enforcement(
granted.enforcement(),
&file_system,
network,
)
}))
}
/// Give the Linux helper the paths selected by the original launch environment. In particular, a
/// relative TMPDIR belongs to the command cwd, which can differ from the sandbox policy cwd.
pub(super) fn bind_linux_policy_environment(
entries: &mut Vec<FileSystemSandboxEntry>,
command_cwd: &PathUri,
command_env: &std::collections::HashMap<String, String>,
policy_cwd: &PathUri,
legacy_landlock: bool,
) -> io::Result<Option<LinuxBinding>> {
let original = FileSystemSandboxPolicy::restricted(std::mem::take(entries));
// Freezing :tmpdir can make it alias an existing rule in either direction.
// Keep the approved policy's process confinement even if its concrete grants now look broader.
let binds_tmpdir = original.entries.iter().any(|entry| {
matches!(
&entry.path,
FileSystemPath::Special {
value: FileSystemSpecialPath::Tmpdir
}
)
});
let full_disk_access_ceiling = if !binds_tmpdir || original.has_full_disk_write_access() {
None
} else if original.has_full_disk_read_access() {
Some(FileSystemAccessMode::Read)
} else {
Some(FileSystemAccessMode::Deny)
};
let check_legacy = legacy_landlock && (binds_tmpdir || original.entries.iter().any(|entry|
matches!(&entry.path, FileSystemPath::GlobPattern { pattern } if entry.access == FileSystemAccessMode::Deny && PathConvention::Posix.home_relative_suffix(pattern).is_some())
));
// Rebinding can turn an unrepresentable legacy grant into WorkspaceWrite or
// ReadOnly even if the full-disk classification is unchanged.
let original_legacy = check_legacy.then(|| original.clone());
*entries = original.entries;
let command_cwd = bind_linux_paths(entries, command_cwd, command_env, policy_cwd)?;
let binding = (full_disk_access_ceiling.is_some() || check_legacy || command_cwd.is_some())
.then_some(LinuxBinding {
ceiling: full_disk_access_ceiling,
original_legacy,
command_cwd,
});
Ok(binding)
}
fn bind_linux_paths(
entries: &mut Vec<FileSystemSandboxEntry>,
command_cwd: &PathUri,
command_env: &std::collections::HashMap<String, String>,
policy_cwd: &PathUri,
) -> io::Result<Option<BoundCwd>> {
use codex_shell_command::shell_detect::get_user_home_path;
use std::cell::LazyCell;
use std::path::PathBuf;
let posix = PathConvention::Posix;
let invalid_path = |err| io::Error::new(io::ErrorKind::InvalidInput, err);
let env_home = command_env.get("HOME").filter(|s| !s.is_empty());
let home = LazyCell::new(|| env_home.map(PathBuf::from).or_else(get_user_home_path));
let resolve = |path: PathBuf| -> io::Result<PathUri> {
let text = path.to_str().ok_or(io::ErrorKind::InvalidInput)?;
PathUri::validate_config_path_text(text, posix).map_err(invalid_path)?;
PathUri::from_host_native_path(path)
};
let tmpdir = command_env.get("TMPDIR").filter(|s| !s.is_empty());
if tmpdir.is_none() {
entries.retain(|entry| {
!matches!(
entry.path,
FileSystemPath::Special {
value: FileSystemSpecialPath::Tmpdir
}
)
});
}
let mut resolved_cwd = None;
for entry in entries {
match &mut entry.path {
FileSystemPath::Special {
value: FileSystemSpecialPath::Tmpdir,
} => {
let value = tmpdir.ok_or(io::ErrorKind::InvalidInput)?;
let mut path = if let Some(suffix) = posix.home_relative_suffix(value)
&& let Some(home) = home.as_ref()
{
home.join(suffix.trim_start_matches('/'))
} else {
PathBuf::from(value)
};
// getcwd in the helper follows symlinks.
if path.is_relative() {
let cwd = match &resolved_cwd {
Some(cwd) => cwd,
None => {
let requested = command_cwd.to_abs_path()?;
let metadata = std::fs::metadata(&requested)?;
resolved_cwd.insert(BoundCwd {
path: requested.canonicalize()?,
identity: format!("{}:{}", metadata.dev(), metadata.ino()),
})
}
};
path = cwd.path.as_path().join(path);
}
entry.path = resolve(path)?.into();
}
FileSystemPath::GlobPattern { pattern }
if entry.access == FileSystemAccessMode::Deny =>
{
let Some(suffix) = posix.home_relative_suffix(pattern) else {
continue;
};
let home = home.as_ref().ok_or_else(|| io::Error::new(
io::ErrorKind::InvalidInput,
format!("unable to resolve deny-read glob pattern `{pattern}` without executor home"),
))?;
let directory = policy_cwd.to_abs_path()?.as_path().join(home);
PathUri::from_host_native_path(&directory)?
.validate_glob_directory(posix)
.map_err(invalid_path)?;
*pattern = resolve(directory.join(suffix.trim_start_matches('/')))?
.inferred_native_path_string();
}
_ => {}
}
}
Ok(resolved_cwd)
}
+21 -10
View File
@@ -445,7 +445,7 @@ impl SandboxManager {
/// Prepare filesystem and network enforcement for a command on the execution host.
pub fn transform(
&self,
request: SandboxTransformRequest<'_>,
mut request: SandboxTransformRequest<'_>,
) -> Result<WrappedSandboxCommand, SandboxTransformError> {
let mut runtime_readable_paths = Vec::new();
if let SandboxExecutables::Executor {
@@ -469,12 +469,10 @@ impl SandboxManager {
}
}
}
let mut command = request.command;
let SandboxNetwork {
enforce_managed_network,
proxy: network,
environment_id,
} = request.network;
let command = &mut request.command;
let network = request.network.proxy;
let environment_id = request.network.environment_id;
let enforce_managed_network = request.network.enforce_managed_network;
let is_file_system_helper = matches!(self.operation, SandboxOperation::FileSystemHelper);
if is_file_system_helper
&& (network.is_some() || enforce_managed_network || command.managed_network.is_some())
@@ -508,12 +506,24 @@ impl SandboxManager {
);
let policy = PreparedLaunchPolicy::resolve(
permissions,
request.sandbox_policy_cwd,
request.workspace_roots,
&runtime_readable_paths,
&request,
&self.operation,
&runtime_readable_paths,
)
.map_err(SandboxTransformError::InvalidPolicy)?;
let linux_binding = policy.linux_binding;
#[cfg(unix)]
let linux_binding = linux_binding.map(|binding| binding.for_policy(&policy.permissions));
#[cfg(unix)]
if let SandboxSelection::Platform { preference, .. } = &mut request.selection
&& *preference == SandboxablePreference::Auto
&& linux_binding
.as_ref()
.is_some_and(launch::LinuxBinding::needs_encoding)
{
*preference = SandboxablePreference::Require;
}
let command = request.command;
let backend = match request.selection {
SandboxSelection::Explicit(sandbox) => sandbox,
SandboxSelection::Platform {
@@ -609,6 +619,7 @@ impl SandboxManager {
sandbox_exe,
use_legacy_landlock: request.use_legacy_landlock,
route: enforce_managed_network.then(|| managed_network.unwrap_or_default()),
binding: linux_binding,
},
#[cfg(target_os = "macos")]
SandboxType::MacosSeatbelt => &mut crate::seatbelt::Seatbelt {
+209 -4
View File
@@ -633,6 +633,43 @@ async fn native_launch_preserves_borrowed_proxy_credentials() -> anyhow::Result<
assert_eq!(request.network_environment_id.as_deref(), environment_id);
assert_eq!(&request.env, expected);
}
#[cfg(unix)]
{
// The proxy masks the credential embedded in TMPDIR before Linux binds its write grant.
let raw_tmp = std::path::Path::new("/codex-snapshot-proxy-test").join(&token);
let permissions = PermissionProfile::from_runtime_permissions(
&FileSystemSandboxPolicy::restricted(vec![FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: FileSystemSpecialPath::Tmpdir,
},
FileSystemAccessMode::Write,
)]),
NetworkSandboxPolicy::Restricted,
);
let mut request = test_request(&cwd, &permissions);
request.command.env = raw;
request.selection = SandboxSelection::Explicit(SandboxType::LinuxSeccomp);
request.network = SandboxNetwork::new(
/*enforce_managed_network*/ false,
Some(&proxy),
environment_id,
);
request.executables =
SandboxExecutables::Launcher(Some(std::path::Path::new("codex-linux-sandbox")));
request
.command
.env
.insert("TMPDIR".into(), raw_tmp.display().to_string());
let launch = SandboxManager::new()
.transform(request)?
.into_command_request()?;
let masked_tmp = std::path::Path::new(&launch.env["TMPDIR"]);
assert_ne!(masked_tmp, raw_tmp);
let fs = launch.permission_profile.file_system_sandbox_policy();
let cwd = cwd.to_abs_path()?;
assert!(fs.can_write_local_path_with_cwd(masked_tmp, &cwd));
assert!(!fs.can_write_local_path_with_cwd(&raw_tmp, &cwd));
}
handle.shutdown().await
}
@@ -1092,12 +1129,15 @@ fn windows_file_system_wrapper_materializes_inner_helper() {
]),
NetworkSandboxPolicy::Restricted,
);
let request = SandboxTransformRequest {
workspace_roots: Some(std::slice::from_ref(&cwd_uri)),
..test_request(&cwd_uri, &permissions)
};
let policy = super::PreparedLaunchPolicy::resolve(
permissions,
&cwd_uri,
Some(std::slice::from_ref(&cwd_uri)),
&[],
permissions.clone(),
&request,
&super::SandboxOperation::FileSystemHelper,
&[],
)
.expect("resolve helper policy");
let mut exec_request = super::SandboxExecRequest {
@@ -1206,3 +1246,168 @@ fn restricted_token_preserves_read_only_carveouts_at_a_volume_root() -> anyhow::
assert_eq!(overrides.additional_deny_write_paths, [read_only]);
Ok(())
}
#[cfg(unix)]
#[test]
fn linux_snapshot_environment_cannot_move_a_tmpdir_grant_or_a_home_denial() -> anyhow::Result<()> {
use FileSystemAccessMode::Read;
use FileSystemAccessMode::Write;
use codex_protocol::permissions::FileSystemSandboxPolicyContext;
use codex_protocol::permissions::ReadDenyMatcher;
let dir = tempfile::tempdir()?;
let home = PathUri::from_host_native_path(dir.path().canonicalize()?)?;
let physical = home.join("real/[project]")?;
let cwd = home.join("[alias]")?;
let original = physical.join("C:/tmp[1]")?;
let backslash = physical.join(r"C:\scratch")?;
std::fs::create_dir_all(original.to_abs_path()?)?;
std::os::unix::fs::symlink(physical.to_abs_path()?, cwd.to_abs_path()?)?;
let redirected = home.join("[project]/C:/tmp[1]")?;
let permissions = PermissionProfile::from_runtime_permissions(
&FileSystemSandboxPolicy::restricted(vec![
FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: FileSystemSpecialPath::Root,
},
Read,
),
FileSystemSandboxEntry::new(
FileSystemPath::Special {
value: FileSystemSpecialPath::Tmpdir,
},
Write,
),
FileSystemSandboxEntry::new(cwd.join(".git")?.into(), Read),
FileSystemSandboxEntry::new(
FileSystemPath::GlobPattern {
pattern: "~/private/*.env".into(),
},
FileSystemAccessMode::Deny,
),
]),
NetworkSandboxPolicy::Restricted,
);
let prepare = |permissions: &PermissionProfile,
launch_home: &str,
tmpdir: Option<&str>,
use_legacy_landlock: bool| {
let mut env = HashMap::from([("HOME".into(), launch_home.into())]);
if let Some(tmpdir) = tmpdir {
env.insert("TMPDIR".into(), tmpdir.into());
}
let mut request = test_request(&cwd, permissions);
request.command.program = "sh".into();
request.command.args = vec!["-lc".into(), "pwd".into()];
request.command.env = env;
request.selection = SandboxSelection::Explicit(SandboxType::LinuxSeccomp);
request.executables =
SandboxExecutables::Launcher(Some(std::path::Path::new("codex-linux-sandbox")));
request.use_legacy_landlock = use_legacy_landlock;
SandboxManager::new().transform(request)
};
assert!(matches!(
prepare(
&permissions,
&physical.inferred_native_path_string(),
None,
/*use_legacy_landlock*/ false
),
Err(super::SandboxTransformError::InvalidPolicy(_))
));
let absolute = original.inferred_native_path_string();
let absolute_home: &str = &home.inferred_native_path_string();
// A symbolic tmpdir grant cannot authorize legacy workspace-write access to the cwd.
let cwd_tmpdir = cwd.inferred_native_path_string();
assert!(matches!(
prepare(&permissions, absolute_home, Some(&cwd_tmpdir), /*use_legacy_landlock*/ true),
Err(super::SandboxTransformError::InvalidPolicy(err)) if err.kind() == std::io::ErrorKind::InvalidInput
));
let from_parent = "../[project]/C:/tmp[1]";
let from_home = "~//real/[project]/C:/tmp[1]/.";
for (launch_home, tmpdir, target, original_access) in [
(absolute_home, Some(from_parent), &original, Write),
(absolute_home, Some("C:/tmp[1]"), &original, Write),
(absolute_home, Some(r"C:\scratch"), &backslash, Write),
(absolute_home, Some(from_home), &original, Write),
(absolute_home, Some(absolute.as_str()), &original, Write),
(absolute_home, Some(""), &original, Read),
(absolute_home, None, &original, Read),
("..", Some("~/[project]/C:/tmp[1]"), &original, Write),
] {
let mut wrapped = prepare(
&permissions,
launch_home,
tmpdir,
/*use_legacy_landlock*/ false,
)?;
let shell = ["sh".into(), "-lc".into(), "pwd".into()];
let (_, _, env) = wrapped
.shell_snapshot_replay_mut(&shell)
.expect("snapshot invocation");
for name in ["TMPDIR", "HOME"] {
env.insert(name.into(), redirected.inferred_native_path_string());
}
// Interpret the policy sent to the Linux helper with the *replay* environment.
let request = wrapped.into_command_request()?;
let json = request
.command
.windows(2)
.find(|pair| pair[0] == "--permission-profile")
.expect("Linux permission profile");
let profile: PermissionProfile = serde_json::from_str(&json[1])?;
let policy = profile.file_system_sandbox_policy();
let replay = |name: &str| PathUri::from_host_native_path(&request.env[name]);
let context = FileSystemSandboxPolicyContext {
cwd: &cwd,
workspace_roots: &[],
user_home_dir: Some(&replay("HOME")?),
temporary_directories: Some(&[replay("TMPDIR")?]),
};
assert_eq!(policy.resolve_access(&redirected, &context), Read);
assert_eq!(
policy.resolve_access(&target.join("capture-output")?, &context),
original_access
);
let deny = ReadDenyMatcher::from_context(&policy, &context).expect("home denial");
assert!(deny.is_read_denied_uri(&home.join("private/token.env")?, &context));
assert!(!deny.is_read_denied_uri(&redirected.join("private/token.env")?, &context));
}
let special =
|value, access| FileSystemSandboxEntry::new(FileSystemPath::Special { value }, access);
for (tmpdir, access) in [
("", FileSystemAccessMode::Deny),
("/", Read),
("C:/tmp[1]", FileSystemAccessMode::Deny),
] {
let permissions = PermissionProfile::from_runtime_permissions(
&FileSystemSandboxPolicy::restricted(vec![
special(FileSystemSpecialPath::Root, Write),
special(FileSystemSpecialPath::Tmpdir, access),
]),
NetworkSandboxPolicy::Enabled,
);
let prepared = prepare(
&permissions,
absolute_home,
Some(tmpdir),
/*use_legacy_landlock*/ false,
)?;
let argv = prepared.request.command;
let profile = argv
.windows(2)
.find(|pair| pair[0] == "--permission-profile")
.unwrap();
let profile: PermissionProfile = serde_json::from_str(&profile[1])?;
let file_system = profile.file_system_sandbox_policy();
assert_eq!(
(
file_system.has_full_disk_read_access(),
file_system.has_full_disk_write_access()
),
(access.can_read(), false)
);
}
Ok(())
}