Base: codex-main originale (prima del fork aKode)
This commit is contained in:
13
codex-rs/linux-sandbox/BUILD.bazel
Normal file
13
codex-rs/linux-sandbox/BUILD.bazel
Normal file
@@ -0,0 +1,13 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "linux-sandbox",
|
||||
crate_name = "codex_linux_sandbox",
|
||||
extra_binaries = [
|
||||
"//codex-rs/bwrap:bwrap",
|
||||
],
|
||||
rustc_env_files = select({
|
||||
"@platforms//os:linux": ["//codex-rs/bwrap:bwrap-sha256-env"],
|
||||
"//conditions:default": [],
|
||||
}),
|
||||
)
|
||||
50
codex-rs/linux-sandbox/Cargo.toml
Normal file
50
codex-rs/linux-sandbox/Cargo.toml
Normal file
@@ -0,0 +1,50 @@
|
||||
[package]
|
||||
name = "codex-linux-sandbox"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "codex-linux-sandbox"
|
||||
path = "src/main.rs"
|
||||
|
||||
[lib]
|
||||
name = "codex_linux_sandbox"
|
||||
path = "src/lib.rs"
|
||||
doctest = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
clap = { workspace = true, features = ["derive"] }
|
||||
codex-install-context = { workspace = true }
|
||||
codex-network-proxy = { workspace = true }
|
||||
codex-process-hardening = { workspace = true }
|
||||
codex-protocol = { workspace = true }
|
||||
codex-sandboxing = { workspace = true }
|
||||
codex-uds = { workspace = true }
|
||||
codex-utils-absolute-path = { workspace = true }
|
||||
ignore = { workspace = true }
|
||||
landlock = { workspace = true }
|
||||
libc = { workspace = true }
|
||||
rustix = { workspace = true }
|
||||
seccompiler = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
sha2 = { workspace = true }
|
||||
url = { workspace = true }
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dev-dependencies]
|
||||
codex-core = { workspace = true }
|
||||
codex-utils-cargo-bin = { workspace = true }
|
||||
pretty_assertions = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
test-case = "3.3.1"
|
||||
tokio = { workspace = true, features = [
|
||||
"io-std",
|
||||
"macros",
|
||||
"process",
|
||||
"rt-multi-thread",
|
||||
"signal",
|
||||
] }
|
||||
124
codex-rs/linux-sandbox/README.md
Normal file
124
codex-rs/linux-sandbox/README.md
Normal file
@@ -0,0 +1,124 @@
|
||||
# codex-linux-sandbox
|
||||
|
||||
This crate is responsible for producing:
|
||||
|
||||
- a `codex-linux-sandbox` standalone executable for Linux that is bundled with the Node.js version of the Codex CLI
|
||||
- a lib crate that exposes the business logic of the executable as `run_main()` so that
|
||||
- the `codex-exec` CLI can check if its arg0 is `codex-linux-sandbox` and, if so, execute as if it were `codex-linux-sandbox`
|
||||
- this should also be true of the `codex` multitool CLI
|
||||
|
||||
The helper uses bubblewrap for filesystem and namespace isolation, and seccomp
|
||||
for syscall filtering. `src/seccomp.rs` installs `PR_SET_NO_NEW_PRIVS` and the
|
||||
seccomp filters; it also retains the legacy Landlock filesystem implementation.
|
||||
`src/linux_run_main.rs` coordinates these stages through `LinuxSandboxCommand`.
|
||||
End-to-end coverage lives in `tests/suite/sandbox.rs` and the other suite modules.
|
||||
|
||||
On Linux, Codex prefers the first `bwrap` found on `PATH`
|
||||
outside the current working directory whenever it is available. If `bwrap` is
|
||||
present but too old to support
|
||||
`--argv0`, the helper keeps using system bubblewrap and switches to a
|
||||
no-`--argv0` compatibility path for the inner re-exec. If `bwrap` is missing,
|
||||
the helper falls back to the bundled `codex-resources/bwrap` binary shipped
|
||||
with Codex.
|
||||
Codex also surfaces a startup warning when `bwrap` is missing so users know it
|
||||
is falling back to the bundled helper. Codex surfaces the same startup warning
|
||||
path when bubblewrap cannot create user namespaces. WSL2 follows the normal
|
||||
Linux bubblewrap path. WSL1 is not supported for bubblewrap sandboxing because
|
||||
it cannot create the required user namespaces, so Codex rejects sandboxed shell
|
||||
commands that would enter the bubblewrap path.
|
||||
|
||||
**Current Behavior**
|
||||
|
||||
- Legacy `SandboxPolicy` / `sandbox_mode` configs remain supported.
|
||||
- Bubblewrap is the default filesystem sandbox.
|
||||
- If `bwrap` is present on `PATH` outside the current working directory, the
|
||||
helper uses it.
|
||||
- If `bwrap` is present but too old to support `--argv0`, the helper uses a
|
||||
no-`--argv0` compatibility path for the inner re-exec.
|
||||
- If `bwrap` is missing, the helper falls back to the bundled
|
||||
`codex-resources/bwrap` path.
|
||||
- If `bwrap` is missing, Codex also surfaces a startup warning instead of
|
||||
printing directly from the sandbox helper.
|
||||
- If bubblewrap cannot create user namespaces, Codex surfaces a startup warning
|
||||
instead of waiting for a runtime sandbox failure.
|
||||
- WSL2 uses the normal Linux bubblewrap path.
|
||||
- WSL1 is not supported for bubblewrap sandboxing; Codex rejects sandboxed
|
||||
shell commands that would require the bubblewrap path before invoking `bwrap`.
|
||||
- Filesystem-restricted execution requires bubblewrap. The legacy Landlock
|
||||
option is rejected for these policies because it cannot isolate app-server
|
||||
Unix sockets. Disable `features.use_legacy_landlock` when upgrading.
|
||||
- Split-only filesystem policies that do not round-trip through the legacy
|
||||
`SandboxPolicy` model stay on bubblewrap so nested read-only or denied
|
||||
carveouts are preserved.
|
||||
- When bubblewrap is active, the helper applies `PR_SET_NO_NEW_PRIVS` and a
|
||||
seccomp filter in-process after establishing the filesystem view. Restricted
|
||||
network policies block network syscalls; filesystem-restricted policies with
|
||||
otherwise unrestricted networking still block `AF_VSOCK` sockets. All filter
|
||||
modes block `io_uring` to prevent bypassing socket-family restrictions.
|
||||
- When bubblewrap is active, the filesystem is read-only by default via `--ro-bind / /`.
|
||||
- When bubblewrap is active, writable roots are layered with `--bind <root> <root>`.
|
||||
- When bubblewrap is active, protected subpaths under writable roots (for
|
||||
example `.git`,
|
||||
resolved `gitdir:`, and `.codex`) are re-applied as read-only via `--ro-bind`.
|
||||
- When bubblewrap is active, overlapping split-policy
|
||||
entries are applied in path-specificity order so narrower writable children
|
||||
can reopen broader read-only or denied parents while narrower denied subpaths
|
||||
still win. For example, `/repo = write`, `/repo/a = none`, `/repo/a/b = write`
|
||||
keeps `/repo` writable, denies `/repo/a`, and reopens `/repo/a/b` as
|
||||
writable again.
|
||||
- When bubblewrap is active, unreadable glob entries are expanded before
|
||||
launching the sandbox and matching files are masked in bubblewrap:
|
||||
|
||||
```text
|
||||
Prefer: rg --files --hidden --no-ignore --glob <pattern> -- <search-root>
|
||||
Fallback: internal globset walker when rg is not installed
|
||||
Failure: any other rg failure aborts sandbox construction
|
||||
```
|
||||
|
||||
Users can cap the scan depth per permissions profile:
|
||||
|
||||
```toml
|
||||
[permissions.workspace.filesystem]
|
||||
glob_scan_max_depth = 2
|
||||
|
||||
[permissions.workspace.filesystem.":workspace_roots"]
|
||||
"**/*.env" = "none"
|
||||
```
|
||||
|
||||
- When bubblewrap is active, symlink-in-path and non-existent protected paths inside
|
||||
writable roots are blocked by mounting `/dev/null` on the symlink or first
|
||||
missing component.
|
||||
- When bubblewrap is active, the helper explicitly isolates the user namespace via
|
||||
`--unshare-user`. By default it also creates a PID namespace via `--unshare-pid`.
|
||||
- When bubblewrap is active and network is restricted without proxy routing, the helper also
|
||||
isolates the network namespace via `--unshare-net`.
|
||||
- In managed proxy mode, the helper uses `--unshare-net` plus an internal
|
||||
TCP->UDS->TCP routing bridge so tool traffic reaches only configured proxy
|
||||
endpoints.
|
||||
- In managed proxy mode, after the bridge is live, seccomp allows IP sockets
|
||||
inside the isolated network namespace and blocks new standalone `AF_UNIX`
|
||||
sockets unless `dangerously_allow_all_unix_sockets` is granted. Unix socket
|
||||
pairs remain allowed for communication between related processes.
|
||||
- When bubblewrap is active, it mounts a fresh `/proc` via `--proc /proc` by default.
|
||||
If that mount is denied, it retains the inherited `/proc` and still creates a
|
||||
PID namespace, preserving the existing fallback. `--no-proc` also retains the
|
||||
inherited `/proc` without disabling PID isolation. In these cases, process IDs
|
||||
inside the sandbox can differ from those exposed by `/proc`. Default invocations
|
||||
send no new helper flags and remain compatible with older helpers.
|
||||
- Trusted provisioning of a dedicated environment can start
|
||||
`codex exec-server --linux-sandbox-pid-namespace=inherit`. This startup-only
|
||||
setting applies to both process and filesystem helpers; repository config and
|
||||
command environment variables cannot enable it. The helper receives the new
|
||||
`--inherit-pid-namespace` option, which requires an updated helper; deploy the
|
||||
helper and startup flag together.
|
||||
Inheritance reuses the caller's PID namespace and `/proc` together, omitting
|
||||
`--unshare-pid` and `--as-pid-1`. This preserves process lookups but allows
|
||||
sandboxed commands to signal other same-UID processes, including the executor.
|
||||
With `:minimal`, the existing `/proc` is bound read-only, preserving its
|
||||
container masks; explicit filesystem denials are applied afterward.
|
||||
Filesystem, user, IPC, network, seccomp, and existing container `/proc` masks
|
||||
remain in force. The default `isolate` mode retains PID isolation.
|
||||
|
||||
**Notes**
|
||||
|
||||
- The CLI surface is `codex sandbox`; the host OS selects the sandbox backend.
|
||||
3
codex-rs/linux-sandbox/build.rs
Normal file
3
codex-rs/linux-sandbox/build.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-env-changed=CODEX_BWRAP_SHA256");
|
||||
}
|
||||
74
codex-rs/linux-sandbox/src/bazel_bwrap.rs
Normal file
74
codex-rs/linux-sandbox/src/bazel_bwrap.rs
Normal file
@@ -0,0 +1,74 @@
|
||||
use std::ffi::OsString;
|
||||
#[cfg(debug_assertions)]
|
||||
use std::fs::File;
|
||||
#[cfg(debug_assertions)]
|
||||
use std::io::BufRead;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
const BAZEL_BWRAP_ENV_VAR: &str = "CARGO_BIN_EXE_bwrap";
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
pub(crate) fn candidate(cwd: &Path, env: impl Fn(&str) -> Option<OsString>) -> Option<PathBuf> {
|
||||
if option_env!("BAZEL_PACKAGE").is_none() || !runfiles_env_present(&env) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let raw = PathBuf::from(env(BAZEL_BWRAP_ENV_VAR)?);
|
||||
if raw.is_absolute() {
|
||||
return Some(raw);
|
||||
}
|
||||
resolve_runfile(raw.to_str()?, cwd, &env)
|
||||
}
|
||||
|
||||
#[cfg(not(debug_assertions))]
|
||||
pub(crate) fn candidate(_cwd: &Path, _env: impl Fn(&str) -> Option<OsString>) -> Option<PathBuf> {
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
fn runfiles_env_present(env: &impl Fn(&str) -> Option<OsString>) -> bool {
|
||||
env("RUNFILES_DIR").is_some()
|
||||
|| env("TEST_SRCDIR").is_some()
|
||||
|| env("RUNFILES_MANIFEST_FILE").is_some()
|
||||
}
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
fn resolve_runfile(
|
||||
logical_path: &str,
|
||||
cwd: &Path,
|
||||
env: &impl Fn(&str) -> Option<OsString>,
|
||||
) -> Option<PathBuf> {
|
||||
let mut logical_paths = vec![logical_path.to_string()];
|
||||
if let Some(workspace) = env("TEST_WORKSPACE").and_then(|value| value.into_string().ok())
|
||||
&& !workspace.is_empty()
|
||||
{
|
||||
logical_paths.push(format!("{workspace}/{logical_path}"));
|
||||
}
|
||||
|
||||
for root_env in ["RUNFILES_DIR", "TEST_SRCDIR"] {
|
||||
let Some(root) = env(root_env) else {
|
||||
continue;
|
||||
};
|
||||
let root = cwd.join(root);
|
||||
for logical_path in &logical_paths {
|
||||
let candidate = root.join(logical_path);
|
||||
if candidate.exists() {
|
||||
return Some(candidate);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let manifest = cwd.join(env("RUNFILES_MANIFEST_FILE")?);
|
||||
let file = File::open(manifest).ok()?;
|
||||
for line in std::io::BufReader::new(file).lines().map_while(Result::ok) {
|
||||
let Some((key, value)) = line.split_once(' ') else {
|
||||
continue;
|
||||
};
|
||||
if logical_paths.iter().any(|logical_path| logical_path == key) {
|
||||
return Some(cwd.join(value));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
223
codex-rs/linux-sandbox/src/bundled_bwrap.rs
Normal file
223
codex-rs/linux-sandbox/src/bundled_bwrap.rs
Normal file
@@ -0,0 +1,223 @@
|
||||
use std::ffi::CStr;
|
||||
use std::ffi::CString;
|
||||
use std::ffi::OsString;
|
||||
use std::fs::File;
|
||||
use std::io::Read;
|
||||
use std::os::fd::AsRawFd;
|
||||
use std::os::raw::c_char;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use crate::bazel_bwrap;
|
||||
use crate::exec_util::argv_to_cstrings;
|
||||
use crate::exec_util::make_files_inheritable;
|
||||
use codex_install_context::InstallContext;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use sha2::Digest as _;
|
||||
use sha2::Sha256;
|
||||
|
||||
const SHA256_HEX_LEN: usize = 64;
|
||||
const NULL_SHA256_DIGEST: [u8; 32] = [0; 32];
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct BundledBwrapLauncher {
|
||||
program: AbsolutePathBuf,
|
||||
}
|
||||
|
||||
pub(crate) fn launcher() -> Option<BundledBwrapLauncher> {
|
||||
let current_exe = std::env::current_exe().ok()?;
|
||||
find_program(
|
||||
InstallContext::current(),
|
||||
¤t_exe,
|
||||
Path::new("."),
|
||||
|key| std::env::var_os(key),
|
||||
)
|
||||
.map(|program| BundledBwrapLauncher { program })
|
||||
}
|
||||
|
||||
/// Discover the bundled fallback for an explicit launcher and its environment.
|
||||
pub fn find_bundled_bwrap_for_exe(
|
||||
exe: &Path,
|
||||
command_cwd: &Path,
|
||||
env: impl Fn(&str) -> Option<OsString>,
|
||||
) -> Option<AbsolutePathBuf> {
|
||||
let exe = std::fs::canonicalize(exe).ok()?;
|
||||
let context = InstallContext::from_exe(
|
||||
/*is_macos*/ false,
|
||||
Some(&exe),
|
||||
/*method_override*/ None,
|
||||
);
|
||||
find_program(&context, &exe, command_cwd, env)
|
||||
}
|
||||
|
||||
fn find_program(
|
||||
context: &InstallContext,
|
||||
exe: &Path,
|
||||
cwd: &Path,
|
||||
env: impl Fn(&str) -> Option<OsString>,
|
||||
) -> Option<AbsolutePathBuf> {
|
||||
find_for_install_context(context)
|
||||
.or_else(|| find_legacy_for_exe(exe, bazel_bwrap::candidate(cwd, env)))
|
||||
}
|
||||
|
||||
impl BundledBwrapLauncher {
|
||||
pub(crate) fn exec(&self, argv: Vec<String>, preserved_files: Vec<File>) -> ! {
|
||||
let bwrap_file = File::open(self.program.as_path()).unwrap_or_else(|err| {
|
||||
panic!(
|
||||
"failed to open bundled bubblewrap {}: {err}",
|
||||
self.program.as_path().display()
|
||||
)
|
||||
});
|
||||
if let Err(err) = verify_digest(&bwrap_file, expected_sha256(), self.program.as_path()) {
|
||||
eprintln!("{err}");
|
||||
std::process::exit(crate::BUNDLED_BWRAP_DIGEST_VERIFICATION_FAILURE_EXIT_CODE);
|
||||
}
|
||||
|
||||
make_files_inheritable(&preserved_files);
|
||||
|
||||
let fd_path = format!("/proc/self/fd/{}", bwrap_file.as_raw_fd());
|
||||
let program_cstring = CString::new(fd_path.as_str())
|
||||
.unwrap_or_else(|err| panic!("invalid bundled bubblewrap fd path: {err}"));
|
||||
let cstrings = argv_to_cstrings(&argv);
|
||||
let mut argv_ptrs: Vec<*const c_char> = cstrings
|
||||
.iter()
|
||||
.map(CString::as_c_str)
|
||||
.map(CStr::as_ptr)
|
||||
.collect();
|
||||
argv_ptrs.push(std::ptr::null());
|
||||
|
||||
// SAFETY: `program_cstring` and every entry in `argv_ptrs` are valid C
|
||||
// strings for the duration of the call. On success `execv` does not return.
|
||||
unsafe {
|
||||
libc::execv(program_cstring.as_ptr(), argv_ptrs.as_ptr());
|
||||
}
|
||||
let err = std::io::Error::last_os_error();
|
||||
panic!(
|
||||
"failed to exec bundled bubblewrap {} via {fd_path}: {err}",
|
||||
self.program.as_path().display()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn find_for_install_context(context: &InstallContext) -> Option<AbsolutePathBuf> {
|
||||
context
|
||||
.bundled_resource("bwrap")
|
||||
.filter(|path| is_executable_file(path))
|
||||
}
|
||||
|
||||
fn find_legacy_for_exe(exe: &Path, bazel_candidate: Option<PathBuf>) -> Option<AbsolutePathBuf> {
|
||||
legacy_candidates_for_exe(exe, bazel_candidate)
|
||||
.into_iter()
|
||||
.find(|candidate| is_executable_file(candidate))
|
||||
.map(|path| {
|
||||
AbsolutePathBuf::from_absolute_path(&path).unwrap_or_else(|err| {
|
||||
panic!(
|
||||
"failed to normalize bundled bubblewrap path {}: {err}",
|
||||
path.display()
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn legacy_candidates_for_exe(exe: &Path, bazel_candidate: Option<PathBuf>) -> Vec<PathBuf> {
|
||||
let Some(exe_dir) = exe.parent() else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let mut candidates = Vec::new();
|
||||
candidates.push(exe_dir.join("codex-resources").join("bwrap"));
|
||||
if let Some(package_target_dir) = exe_dir.parent() {
|
||||
candidates.push(package_target_dir.join("codex-resources").join("bwrap"));
|
||||
}
|
||||
candidates.push(exe_dir.join("bwrap"));
|
||||
if let Some(path) = bazel_candidate {
|
||||
candidates.push(path);
|
||||
}
|
||||
candidates
|
||||
}
|
||||
|
||||
fn is_executable_file(path: &Path) -> bool {
|
||||
let Ok(metadata) = path.metadata() else {
|
||||
return false;
|
||||
};
|
||||
metadata.is_file() && metadata.permissions().mode() & 0o111 != 0
|
||||
}
|
||||
|
||||
fn expected_sha256() -> Option<[u8; 32]> {
|
||||
static EXPECTED: OnceLock<Option<[u8; 32]>> = OnceLock::new();
|
||||
*EXPECTED.get_or_init(|| {
|
||||
let raw_digest = option_env!("CODEX_BWRAP_SHA256")?;
|
||||
let digest = parse_sha256_hex(raw_digest)
|
||||
.unwrap_or_else(|err| panic!("invalid CODEX_BWRAP_SHA256 value: {err}"));
|
||||
(digest != NULL_SHA256_DIGEST).then_some(digest)
|
||||
})
|
||||
}
|
||||
|
||||
fn verify_digest(file: &File, expected: Option<[u8; 32]>, path: &Path) -> Result<(), String> {
|
||||
let Some(expected) = expected else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let mut file = file
|
||||
.try_clone()
|
||||
.map_err(|err| format!("failed to clone bundled bubblewrap fd: {err}"))?;
|
||||
let mut hasher = Sha256::new();
|
||||
let mut buffer = [0_u8; 8192];
|
||||
loop {
|
||||
let read = file.read(&mut buffer).map_err(|err| {
|
||||
format!(
|
||||
"failed to read bundled bubblewrap {} for digest verification: {err}",
|
||||
path.display()
|
||||
)
|
||||
})?;
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
hasher.update(&buffer[..read]);
|
||||
}
|
||||
|
||||
let actual: [u8; 32] = hasher.finalize().into();
|
||||
if actual == expected {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
Err(format!(
|
||||
"bundled bubblewrap digest mismatch for {}: expected sha256:{}, got sha256:{}",
|
||||
path.display(),
|
||||
bytes_to_hex(&expected),
|
||||
bytes_to_hex(&actual),
|
||||
))
|
||||
}
|
||||
|
||||
fn parse_sha256_hex(raw: &str) -> Result<[u8; 32], String> {
|
||||
if raw.len() != SHA256_HEX_LEN {
|
||||
return Err(format!(
|
||||
"expected {SHA256_HEX_LEN} hex characters, got {}",
|
||||
raw.len()
|
||||
));
|
||||
}
|
||||
|
||||
let mut digest = [0_u8; 32];
|
||||
for (index, byte) in digest.iter_mut().enumerate() {
|
||||
let start = index * 2;
|
||||
*byte = u8::from_str_radix(&raw[start..start + 2], 16)
|
||||
.map_err(|err| format!("invalid hex byte at offset {start}: {err}"))?;
|
||||
}
|
||||
Ok(digest)
|
||||
}
|
||||
|
||||
fn bytes_to_hex(bytes: &[u8; 32]) -> String {
|
||||
const HEX: &[u8; 16] = b"0123456789abcdef";
|
||||
let mut hex = String::with_capacity(SHA256_HEX_LEN);
|
||||
for byte in bytes {
|
||||
hex.push(HEX[(byte >> 4) as usize] as char);
|
||||
hex.push(HEX[(byte & 0x0f) as usize] as char);
|
||||
}
|
||||
hex
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "bundled_bwrap_tests.rs"]
|
||||
mod tests;
|
||||
125
codex-rs/linux-sandbox/src/bundled_bwrap_tests.rs
Normal file
125
codex-rs/linux-sandbox/src/bundled_bwrap_tests.rs
Normal file
@@ -0,0 +1,125 @@
|
||||
//! Verify bundled bubblewrap discovery and executable digest validation.
|
||||
|
||||
use super::*;
|
||||
use codex_install_context::CodexPackageLayout;
|
||||
use codex_install_context::InstallContext;
|
||||
use codex_install_context::InstallMethod;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::fs;
|
||||
use tempfile::NamedTempFile;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[test]
|
||||
fn finds_package_layout_bwrap_from_install_context() {
|
||||
let temp_dir = tempdir().expect("temp dir");
|
||||
let package_dir = temp_dir.path();
|
||||
let bin_dir = package_dir.join("bin");
|
||||
let resources_dir = package_dir.join("codex-resources");
|
||||
let expected_bwrap = resources_dir.join("bwrap");
|
||||
fs::create_dir_all(&bin_dir).expect("create bin dir");
|
||||
write_executable(&expected_bwrap);
|
||||
|
||||
let context = InstallContext {
|
||||
method: InstallMethod::Other,
|
||||
package_layout: Some(CodexPackageLayout {
|
||||
package_dir: AbsolutePathBuf::from_absolute_path(package_dir).expect("absolute"),
|
||||
bin_dir: AbsolutePathBuf::from_absolute_path(&bin_dir).expect("absolute"),
|
||||
resources_dir: Some(
|
||||
AbsolutePathBuf::from_absolute_path(&resources_dir).expect("absolute"),
|
||||
),
|
||||
path_dir: None,
|
||||
}),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
find_for_install_context(&context),
|
||||
Some(AbsolutePathBuf::from_absolute_path(&expected_bwrap).expect("absolute"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_legacy_standalone_bundled_bwrap_next_to_exe_resources() {
|
||||
let temp_dir = tempdir().expect("temp dir");
|
||||
let exe = temp_dir.path().join("codex");
|
||||
let expected_bwrap = temp_dir.path().join("codex-resources").join("bwrap");
|
||||
write_executable(&exe);
|
||||
write_executable(&expected_bwrap);
|
||||
|
||||
assert_eq!(
|
||||
find_legacy_for_exe(&exe, /*bazel_candidate*/ None),
|
||||
Some(AbsolutePathBuf::from_absolute_path(&expected_bwrap).expect("absolute"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_npm_bundled_bwrap_next_to_target_vendor_dir() {
|
||||
let temp_dir = tempdir().expect("temp dir");
|
||||
let target_dir = temp_dir.path().join("vendor/x86_64-unknown-linux-musl");
|
||||
let exe = target_dir.join("codex").join("codex");
|
||||
let expected_bwrap = target_dir.join("codex-resources").join("bwrap");
|
||||
write_executable(&exe);
|
||||
write_executable(&expected_bwrap);
|
||||
|
||||
assert_eq!(
|
||||
find_legacy_for_exe(&exe, /*bazel_candidate*/ None),
|
||||
Some(AbsolutePathBuf::from_absolute_path(&expected_bwrap).expect("absolute"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_adjacent_dev_bwrap() {
|
||||
let temp_dir = tempdir().expect("temp dir");
|
||||
let exe = temp_dir.path().join("codex");
|
||||
let expected_bwrap = temp_dir.path().join("bwrap");
|
||||
write_executable(&exe);
|
||||
write_executable(&expected_bwrap);
|
||||
|
||||
assert_eq!(
|
||||
find_legacy_for_exe(&exe, /*bazel_candidate*/ None),
|
||||
Some(AbsolutePathBuf::from_absolute_path(&expected_bwrap).expect("absolute"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn digest_verification_skips_missing_expected_digest() {
|
||||
let file = NamedTempFile::new().expect("temp file");
|
||||
fs::write(file.path(), b"contents").expect("write file");
|
||||
|
||||
verify_digest(file.as_file(), /*expected*/ None, file.path())
|
||||
.expect("missing digest should skip verification");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn digest_verification_accepts_matching_digest() {
|
||||
let file = NamedTempFile::new().expect("temp file");
|
||||
fs::write(file.path(), b"contents").expect("write file");
|
||||
let expected: [u8; 32] = Sha256::digest(b"contents").into();
|
||||
|
||||
verify_digest(file.as_file(), Some(expected), file.path())
|
||||
.expect("matching digest should verify");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn digest_verification_rejects_mismatched_digest() {
|
||||
let file = NamedTempFile::new().expect("temp file");
|
||||
fs::write(file.path(), b"contents").expect("write file");
|
||||
|
||||
let err = verify_digest(file.as_file(), Some([0xab; 32]), file.path())
|
||||
.expect_err("mismatched digest should fail");
|
||||
assert!(err.contains("bundled bubblewrap digest mismatch"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_sha256_hex_digest() {
|
||||
assert_eq!(parse_sha256_hex(&"ab".repeat(32)), Ok([0xab; 32]));
|
||||
assert_eq!(parse_sha256_hex(&"00".repeat(32)), Ok(NULL_SHA256_DIGEST));
|
||||
assert!(parse_sha256_hex("ab").is_err());
|
||||
assert!(parse_sha256_hex(&format!("{}xx", "00".repeat(31))).is_err());
|
||||
}
|
||||
|
||||
fn write_executable(path: &Path) {
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent).expect("create parent dir");
|
||||
}
|
||||
codex_utils_cargo_bin::write_executable(path, "").expect("write executable");
|
||||
}
|
||||
1398
codex-rs/linux-sandbox/src/bwrap.rs
Normal file
1398
codex-rs/linux-sandbox/src/bwrap.rs
Normal file
File diff suppressed because it is too large
Load Diff
1645
codex-rs/linux-sandbox/src/bwrap_tests.rs
Normal file
1645
codex-rs/linux-sandbox/src/bwrap_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
238
codex-rs/linux-sandbox/src/bwrap_wslg_tests.rs
Normal file
238
codex-rs/linux-sandbox/src/bwrap_wslg_tests.rs
Normal file
@@ -0,0 +1,238 @@
|
||||
//! Regression coverage for excluding WSLg's duplicate filesystem view.
|
||||
|
||||
use super::*;
|
||||
use codex_protocol::protocol::FileSystemSandboxEntry;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test_case::test_case(FileSystemAccessMode::Read; "read_root")]
|
||||
#[test_case::test_case(FileSystemAccessMode::Write; "write_root")]
|
||||
fn wslg_mask_follows_filesystem_grants_and_denials(root_access: FileSystemAccessMode) {
|
||||
let temp_dir = tempfile::TempDir::new().expect("temp dir");
|
||||
let denied = temp_dir.path().join("denied.txt");
|
||||
fs::write(&denied, "fixture").expect("write fixture");
|
||||
let denied = AbsolutePathBuf::from_absolute_path(denied).expect("absolute fixture");
|
||||
let workspace =
|
||||
AbsolutePathBuf::from_absolute_path(temp_dir.path()).expect("absolute workspace");
|
||||
|
||||
for denied_path in [
|
||||
FileSystemPath::from(denied.clone()),
|
||||
FileSystemPath::GlobPattern {
|
||||
pattern: format!("{}/*.txt", temp_dir.path().display()),
|
||||
},
|
||||
] {
|
||||
let policy = FileSystemSandboxPolicy::restricted(vec![
|
||||
FileSystemSandboxEntry {
|
||||
path: FileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::Root,
|
||||
},
|
||||
access: root_access,
|
||||
missing_path_behavior: None,
|
||||
},
|
||||
FileSystemSandboxEntry {
|
||||
path: workspace.clone().into(),
|
||||
access: FileSystemAccessMode::Write,
|
||||
missing_path_behavior: None,
|
||||
},
|
||||
FileSystemSandboxEntry {
|
||||
path: denied_path,
|
||||
access: FileSystemAccessMode::Deny,
|
||||
missing_path_behavior: None,
|
||||
},
|
||||
]);
|
||||
for mount_proc in [true, false] {
|
||||
for network_mode in [BwrapNetworkMode::FullAccess, BwrapNetworkMode::Isolated] {
|
||||
let args = create_bwrap_command_args(
|
||||
vec!["/bin/true".to_string()],
|
||||
&policy,
|
||||
temp_dir.path(),
|
||||
temp_dir.path(),
|
||||
BwrapOptions {
|
||||
mount_proc,
|
||||
network_mode,
|
||||
mask_wslg_distro: true,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.expect("create restricted bwrap args")
|
||||
.args;
|
||||
let mask = args
|
||||
.windows(6)
|
||||
.position(|args| {
|
||||
args == [
|
||||
"--perms",
|
||||
"000",
|
||||
"--tmpfs",
|
||||
WSLG_DISTRO_ROOT,
|
||||
"--remount-ro",
|
||||
WSLG_DISTRO_ROOT,
|
||||
]
|
||||
})
|
||||
.expect("unreadable, read-only WSLg mask");
|
||||
let last_grant = args
|
||||
.iter()
|
||||
.rposition(|arg| arg == "--bind" || arg == "--ro-bind")
|
||||
.expect("filesystem grant");
|
||||
let denial = args
|
||||
.iter()
|
||||
.rposition(|arg| arg == &path_to_string(denied.as_path()))
|
||||
.expect("denied file mask");
|
||||
assert!(last_grant < mask && denial < mask);
|
||||
assert!(args.windows(2).any(|args| {
|
||||
args == [if mount_proc { "--proc" } else { "--tmpfs" }, "/proc"]
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wslg_mask_is_omitted_when_policy_already_hides_an_ancestor() {
|
||||
for denied in ["/mnt", "/mnt/wslg", WSLG_DISTRO_ROOT] {
|
||||
let mut policy = FileSystemSandboxPolicy::read_only();
|
||||
policy.entries.push(FileSystemSandboxEntry {
|
||||
path: AbsolutePathBuf::from_absolute_path(denied)
|
||||
.expect("absolute denied directory")
|
||||
.into(),
|
||||
access: FileSystemAccessMode::Deny,
|
||||
missing_path_behavior: None,
|
||||
});
|
||||
let mut commands = Vec::new();
|
||||
for mask_wslg_distro in [false, true] {
|
||||
commands.push(
|
||||
create_bwrap_command_args(
|
||||
vec!["/bin/true".to_string()],
|
||||
&policy,
|
||||
Path::new("/"),
|
||||
Path::new("/"),
|
||||
BwrapOptions {
|
||||
mask_wslg_distro,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.expect("create bwrap args with denied ancestor")
|
||||
.args,
|
||||
);
|
||||
}
|
||||
assert_eq!(commands[0], commands[1]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unrestricted_filesystem_preserves_wslg_with_or_without_network_isolation() {
|
||||
for network_mode in [BwrapNetworkMode::FullAccess, BwrapNetworkMode::Isolated] {
|
||||
let mut commands = Vec::new();
|
||||
for mask_wslg_distro in [false, true] {
|
||||
commands.push(
|
||||
create_bwrap_command_args(
|
||||
vec!["/bin/true".to_string()],
|
||||
&FileSystemSandboxPolicy::unrestricted(),
|
||||
Path::new("/"),
|
||||
Path::new("/"),
|
||||
BwrapOptions {
|
||||
network_mode,
|
||||
mask_wslg_distro,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.expect("create unrestricted bwrap args")
|
||||
.args,
|
||||
);
|
||||
}
|
||||
assert_eq!(commands[0], commands[1]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test_case::test_case("grant_read"; "read_grant")]
|
||||
#[test_case::test_case("grant_write"; "write_grant")]
|
||||
#[test_case::test_case("policy_cwd"; "policy_cwd")]
|
||||
#[test_case::test_case("command_cwd"; "command_cwd")]
|
||||
#[test_case::test_case("executable"; "executable")]
|
||||
fn explicit_wslg_alias_paths_are_rejected(source: &str) {
|
||||
let alias = Path::new(WSLG_DISTRO_ROOT).join("project");
|
||||
let mut policy = FileSystemSandboxPolicy::read_only();
|
||||
if source.starts_with("grant_") {
|
||||
policy.entries.push(FileSystemSandboxEntry {
|
||||
path: AbsolutePathBuf::from_absolute_path(&alias)
|
||||
.expect("absolute alias")
|
||||
.into(),
|
||||
access: if source == "grant_write" {
|
||||
FileSystemAccessMode::Write
|
||||
} else {
|
||||
FileSystemAccessMode::Read
|
||||
},
|
||||
missing_path_behavior: None,
|
||||
});
|
||||
}
|
||||
let executable = if source == "executable" {
|
||||
alias.as_path()
|
||||
} else {
|
||||
Path::new("/bin/true")
|
||||
};
|
||||
let policy_cwd = if source == "policy_cwd" {
|
||||
alias.as_path()
|
||||
} else {
|
||||
Path::new("/")
|
||||
};
|
||||
let command_cwd = if source == "command_cwd" {
|
||||
alias.as_path()
|
||||
} else {
|
||||
Path::new("/")
|
||||
};
|
||||
let error = create_bwrap_command_args(
|
||||
vec![path_to_string(executable)],
|
||||
&policy,
|
||||
policy_cwd,
|
||||
command_cwd,
|
||||
BwrapOptions {
|
||||
mask_wslg_distro: true,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.expect_err("explicit alias must be rejected before mounts are built");
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
format!(
|
||||
"Fatal error: restricted sandboxes do not support paths under {WSLG_DISTRO_ROOT}: {}; use the corresponding path under the primary filesystem root instead",
|
||||
alias.display()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wslg_masks_remain_when_glob_skips_directory_symlinks() {
|
||||
let temp = tempfile::tempdir().expect("temp directory");
|
||||
// '/' is an ancestor on every test host; no WSL mount is needed. Only
|
||||
// inspect arguments: never launch this synthetic filesystem policy.
|
||||
let relative_root: PathBuf =
|
||||
std::iter::repeat_n("..", temp.path().components().count() - 1).collect();
|
||||
std::os::unix::fs::symlink(relative_root, temp.path().join("alias")).expect("relative symlink");
|
||||
let mut policy = FileSystemSandboxPolicy::read_only();
|
||||
policy.entries.push(FileSystemSandboxEntry {
|
||||
path: FileSystemPath::GlobPattern {
|
||||
pattern: format!("{}/alias*", temp.path().display()),
|
||||
},
|
||||
access: FileSystemAccessMode::Deny,
|
||||
missing_path_behavior: None,
|
||||
});
|
||||
let args = create_bwrap_command_args(
|
||||
vec!["/bin/true".to_string()],
|
||||
&policy,
|
||||
Path::new("/"),
|
||||
Path::new("/"),
|
||||
BwrapOptions {
|
||||
mask_wslg_distro: true,
|
||||
mount_proc: false,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.expect("skipped glob links still need the WSLg mask")
|
||||
.args;
|
||||
assert!(args.windows(4).any(|args| args
|
||||
== [
|
||||
"--tmpfs",
|
||||
WSLG_DISTRO_ROOT,
|
||||
"--remount-ro",
|
||||
WSLG_DISTRO_ROOT
|
||||
]));
|
||||
assert!(args.windows(2).any(|args| args == ["--tmpfs", "/proc"]));
|
||||
}
|
||||
256
codex-rs/linux-sandbox/src/daemon_mounts.rs
Normal file
256
codex-rs/linux-sandbox/src/daemon_mounts.rs
Normal file
@@ -0,0 +1,256 @@
|
||||
//! Find host mount aliases that need the privileged socket directory mask.
|
||||
//! Mount roots describe filesystem identity; canonical paths alone miss bind mounts.
|
||||
//! Btrfs subvolume device numbers can differ from the containing mount's device.
|
||||
|
||||
use rustix::fs::AtFlags;
|
||||
use rustix::fs::StatxFlags;
|
||||
use rustix::fs::fstatfs;
|
||||
use rustix::fs::statx;
|
||||
use std::collections::BTreeSet;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::os::fd::AsRawFd;
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum SocketFilesystem {
|
||||
Btrfs,
|
||||
Other,
|
||||
}
|
||||
|
||||
pub(crate) fn daemon_socket_mask_paths(
|
||||
directory: &Path,
|
||||
masked_root: Option<&Path>,
|
||||
) -> io::Result<BTreeSet<PathBuf>> {
|
||||
let directory_file = fs::File::open(directory)?;
|
||||
let device = directory_file.metadata()?.dev();
|
||||
let filesystem =
|
||||
if fstatfs(&directory_file).is_ok_and(|stat| stat.f_type == libc::BTRFS_SUPER_MAGIC) {
|
||||
SocketFilesystem::Btrfs
|
||||
} else {
|
||||
SocketFilesystem::Other
|
||||
};
|
||||
let mount_id = fs::read_to_string(format!("/proc/self/fdinfo/{}", directory_file.as_raw_fd()))
|
||||
.ok()
|
||||
.and_then(|fdinfo| {
|
||||
fdinfo
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix("mnt_id:"))
|
||||
.and_then(|id| id.trim().parse::<u64>().ok())
|
||||
})
|
||||
.or_else(|| {
|
||||
// Query the same open directory, using the ID shared with mountinfo.
|
||||
// Older kernels may succeed without returning the requested field.
|
||||
statx(&directory_file, "", AtFlags::EMPTY_PATH, StatxFlags::MNT_ID)
|
||||
.ok()
|
||||
.filter(|stat| stat.stx_mask & StatxFlags::MNT_ID.bits() != 0)
|
||||
.map(|stat| stat.stx_mnt_id)
|
||||
})
|
||||
.map(|id| id.to_string());
|
||||
check_mounts(
|
||||
directory,
|
||||
&format!("{}:{}", libc::major(device), libc::minor(device)),
|
||||
filesystem,
|
||||
mount_id.as_deref(),
|
||||
&fs::read("/proc/self/mountinfo")?,
|
||||
masked_root,
|
||||
)
|
||||
}
|
||||
|
||||
fn check_mounts(
|
||||
directory: &Path,
|
||||
device: &str,
|
||||
filesystem: SocketFilesystem,
|
||||
mount_id: Option<&str>,
|
||||
mountinfo: &[u8],
|
||||
masked_root: Option<&Path>,
|
||||
) -> io::Result<BTreeSet<PathBuf>> {
|
||||
let invalid = || io::Error::other("cannot establish app-server socket mount isolation");
|
||||
let mut mounts = Vec::new();
|
||||
for line in mountinfo
|
||||
.split(|byte| *byte == b'\n')
|
||||
.filter(|line| !line.is_empty())
|
||||
{
|
||||
let mut fields = line.split(|byte| *byte == b' ');
|
||||
let prefix: Vec<_> = fields.by_ref().take(5).collect();
|
||||
let [id, parent, mount_device, root, destination] = prefix.as_slice() else {
|
||||
return Err(invalid());
|
||||
};
|
||||
let destination = mount_path(destination)?;
|
||||
let mount_filesystem = fields
|
||||
.skip_while(|field| *field != b"-")
|
||||
.nth(1)
|
||||
.ok_or_else(invalid)?;
|
||||
mounts.push((
|
||||
*id,
|
||||
*parent,
|
||||
*mount_device,
|
||||
*root,
|
||||
destination,
|
||||
mount_filesystem,
|
||||
));
|
||||
}
|
||||
let selected_index = mount_id
|
||||
.map(|mount_id| {
|
||||
let mut matching = mounts
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, (id, ..))| *id == mount_id.as_bytes());
|
||||
let (index, (_, _, mount_device, _, _, mount_filesystem)) =
|
||||
matching.next().ok_or_else(invalid)?;
|
||||
if matching.next().is_some()
|
||||
|| (*mount_device != device.as_bytes()
|
||||
&& (filesystem != SocketFilesystem::Btrfs || *mount_filesystem != b"btrfs"))
|
||||
{
|
||||
return Err(invalid());
|
||||
}
|
||||
Ok(index)
|
||||
})
|
||||
.transpose()?;
|
||||
// Btrfs reports a per-subvolume st_dev, while mountinfo uses the superblock
|
||||
// device. Only the verified descriptor's mount ID can authorize that mismatch.
|
||||
// Retain both device identities when looking for aliases.
|
||||
let mount_device = selected_index
|
||||
.map(|index| mounts[index].2)
|
||||
.unwrap_or(device.as_bytes());
|
||||
let mounts = mounts
|
||||
.into_iter()
|
||||
.map(|(id, parent, candidate_device, root, destination, _)| {
|
||||
// Only roots on the socket filesystem can identify aliases. Other
|
||||
// filesystems can use non-path roots such as nsfs `mnt:[inode]`, but
|
||||
// their destinations still matter for ancestry and nested-mount checks.
|
||||
let root = (candidate_device == device.as_bytes() || candidate_device == mount_device)
|
||||
.then(|| mount_path(root))
|
||||
.transpose()?;
|
||||
Ok((id, parent, candidate_device, root, destination))
|
||||
})
|
||||
.collect::<io::Result<Vec<_>>>()?;
|
||||
let (location, containing_mount) = if let Some((mount_id, index)) = mount_id.zip(selected_index)
|
||||
{
|
||||
// fdinfo/statx identifies the opened mount, which may have been covered
|
||||
// by another mount before we read mountinfo.
|
||||
let selected = &mounts[index];
|
||||
let (_, _, _, root, destination) = selected;
|
||||
let root = root.as_ref().ok_or_else(invalid)?;
|
||||
let relative = directory.strip_prefix(destination).map_err(|_| invalid())?;
|
||||
let mut current = Some(selected);
|
||||
let mut visible_child: Option<&Path> = None;
|
||||
let mut visited = BTreeSet::new();
|
||||
while let Some((id, parent, _, _, destination)) = current {
|
||||
if !visited.insert(id)
|
||||
|| mounts.iter().any(|(child_id, child_parent, _, _, child)| {
|
||||
child_id != id
|
||||
&& child_parent == id
|
||||
&& directory.starts_with(child)
|
||||
&& !visible_child.is_some_and(|visible| child.starts_with(visible))
|
||||
})
|
||||
{
|
||||
return Err(invalid());
|
||||
}
|
||||
if id == parent {
|
||||
break;
|
||||
}
|
||||
// Follow the selected branch towards the namespace root. Sibling
|
||||
// mounts below this branch are hidden; mounts above it cover it.
|
||||
visible_child = Some(destination);
|
||||
current = mounts.iter().find(|(id, ..)| id == parent);
|
||||
}
|
||||
(root.join(relative), Some((mount_id, destination)))
|
||||
} else {
|
||||
// Without a mount ID, require every possible containing mount to agree
|
||||
// on the backing location, and do not assume any aliases are hidden.
|
||||
let locations: BTreeSet<_> = mounts
|
||||
.iter()
|
||||
.filter_map(|(_, _, _, root, destination)| {
|
||||
let root = root.as_ref()?;
|
||||
directory
|
||||
.strip_prefix(destination)
|
||||
.ok()
|
||||
.map(|relative| root.join(relative))
|
||||
})
|
||||
.collect();
|
||||
if locations.len() != 1 {
|
||||
return Err(invalid());
|
||||
}
|
||||
(locations.into_iter().next().ok_or_else(invalid)?, None)
|
||||
};
|
||||
let mut mask_paths = BTreeSet::from([directory.to_path_buf()]);
|
||||
for (id, _, _, root, destination) in &mounts {
|
||||
// Nested mounts can introduce another filesystem (or an individual socket) under the mask.
|
||||
let nested = destination != directory && destination.starts_with(directory);
|
||||
let alias = if let Some(root) = root {
|
||||
if let Ok(relative) = location.strip_prefix(root) {
|
||||
Some((destination.join(relative), !relative.as_os_str().is_empty()))
|
||||
} else if root.starts_with(&location) {
|
||||
Some((destination.clone(), false))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let exposed_alias = alias.filter(|(path, _)| {
|
||||
// An ancestor's path beneath this mount is hidden by it. Keep
|
||||
// checking other mounts, including aliases mounted beneath it.
|
||||
let hidden = containing_mount.is_some_and(|(mount_id, containing_mount)| {
|
||||
*id != mount_id.as_bytes()
|
||||
&& containing_mount.starts_with(destination)
|
||||
&& path.starts_with(containing_mount)
|
||||
});
|
||||
!path.starts_with(directory)
|
||||
&& !masked_root.is_some_and(|root| path.starts_with(root))
|
||||
&& !hidden
|
||||
});
|
||||
if nested
|
||||
|| exposed_alias
|
||||
.as_ref()
|
||||
.is_some_and(|(_, can_mask)| !can_mask)
|
||||
{
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
format!(
|
||||
"app-server socket directory has an unsupported host mount at {}; remove the bind-mount alias or nested mount before starting the sandbox",
|
||||
destination.display()
|
||||
),
|
||||
));
|
||||
}
|
||||
if let Some((path, _)) = exposed_alias {
|
||||
// An alias of an ancestor exposes the whole directory, so apply the
|
||||
// same mask there. Direct directory/socket aliases and nested mounts
|
||||
// remain unsupported because a later bind could reopen the mask.
|
||||
mask_paths.insert(path);
|
||||
}
|
||||
}
|
||||
Ok(mask_paths)
|
||||
}
|
||||
|
||||
fn mount_path(encoded: &[u8]) -> io::Result<PathBuf> {
|
||||
let mut decoded = Vec::new();
|
||||
let mut bytes = encoded.iter().copied();
|
||||
while let Some(byte) = bytes.next() {
|
||||
decoded.push(if byte == b'\\' {
|
||||
let digits: Vec<_> = bytes.by_ref().take(3).collect();
|
||||
match digits.as_slice() {
|
||||
b"040" => b' ',
|
||||
b"011" => b'\t',
|
||||
b"012" => b'\n',
|
||||
b"134" => b'\\',
|
||||
_ => return Err(io::Error::other("invalid mountinfo path escape")),
|
||||
}
|
||||
} else {
|
||||
byte
|
||||
});
|
||||
}
|
||||
let path = PathBuf::from(std::ffi::OsString::from_vec(decoded));
|
||||
if !path.is_absolute() {
|
||||
return Err(io::Error::other("mountinfo path is not absolute"));
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "daemon_mounts_tests.rs"]
|
||||
mod tests;
|
||||
324
codex-rs/linux-sandbox/src/daemon_mounts_tests.rs
Normal file
324
codex-rs/linux-sandbox/src/daemon_mounts_tests.rs
Normal file
@@ -0,0 +1,324 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use test_case::test_case;
|
||||
|
||||
// Most cases have no independently masked subtree.
|
||||
fn check_mounts(
|
||||
directory: &Path,
|
||||
device: &str,
|
||||
mount_id: Option<&str>,
|
||||
mountinfo: &[u8],
|
||||
) -> io::Result<BTreeSet<PathBuf>> {
|
||||
super::check_mounts(
|
||||
directory,
|
||||
device,
|
||||
SocketFilesystem::Other,
|
||||
mount_id,
|
||||
mountinfo,
|
||||
/*masked_root*/ None,
|
||||
)
|
||||
}
|
||||
|
||||
fn check_btrfs_mounts(mount_id: &str, mountinfo: &[u8]) -> io::Result<BTreeSet<PathBuf>> {
|
||||
super::check_mounts(
|
||||
Path::new("/tmp/codex-daemon-1000"),
|
||||
"0:2",
|
||||
SocketFilesystem::Btrfs,
|
||||
Some(mount_id),
|
||||
mountinfo,
|
||||
/*masked_root*/ None,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn btrfs_bind_mount_masks_aliases_for_both_device_numbers() {
|
||||
let mounts = b"1 0 0:1 / / rw - btrfs disk rw\n\
|
||||
2 1 0:1 /var/lib/system-tmp /tmp rw shared:1 - btrfs disk rw\n\
|
||||
3 1 0:1 /var/lib/system-tmp /mount-device-alias rw - btrfs disk rw\n\
|
||||
4 1 0:2 /var/lib/system-tmp /stat-device-alias rw - btrfs disk rw\n\
|
||||
5 1 0:3 mnt:[1234] /run/example.mnt rw - nsfs nsfs rw\n";
|
||||
assert_eq!(
|
||||
check_btrfs_mounts("2", mounts).unwrap(),
|
||||
BTreeSet::from([
|
||||
PathBuf::from("/tmp/codex-daemon-1000"),
|
||||
PathBuf::from("/var/lib/system-tmp/codex-daemon-1000"),
|
||||
PathBuf::from("/mount-device-alias/codex-daemon-1000"),
|
||||
PathBuf::from("/stat-device-alias/codex-daemon-1000"),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
#[test_case(SocketFilesystem::Other, "btrfs", Some("1"); "unverified descriptor filesystem")]
|
||||
#[test_case(SocketFilesystem::Btrfs, "ext4", Some("1"); "inconsistent mount filesystem")]
|
||||
#[test_case(SocketFilesystem::Btrfs, "btrfs", None; "unavailable mount id")]
|
||||
#[test_case(SocketFilesystem::Btrfs, "btrfs", Some("missing"); "missing mount id")]
|
||||
fn device_mismatch_requires_verified_btrfs_mount(
|
||||
filesystem: SocketFilesystem,
|
||||
mount_filesystem: &str,
|
||||
mount_id: Option<&str>,
|
||||
) {
|
||||
let mounts = format!("1 0 0:1 / / rw - {mount_filesystem} disk rw\n");
|
||||
assert_eq!(
|
||||
super::check_mounts(
|
||||
Path::new("/tmp/codex-daemon-1000"),
|
||||
"0:2",
|
||||
filesystem,
|
||||
mount_id,
|
||||
mounts.as_bytes(),
|
||||
/*masked_root*/ None,
|
||||
)
|
||||
.map_err(|error| error.kind()),
|
||||
Err(io::ErrorKind::Other),
|
||||
);
|
||||
}
|
||||
|
||||
#[test_case("0:1", "/@/tmp/codex-daemon-1000", "/alias"; "mount device directory alias")]
|
||||
#[test_case("0:2", "/@/tmp/codex-daemon-1000/rpc.sock", "/alias.sock"; "stat device socket alias")]
|
||||
fn btrfs_device_mismatch_still_rejects_unsafe_mounts(device: &str, root: &str, destination: &str) {
|
||||
let mounts = format!(
|
||||
"1 0 0:1 /@ / rw - btrfs disk rw\n\
|
||||
2 1 {device} {root} {destination} rw - btrfs disk rw\n"
|
||||
);
|
||||
assert_eq!(
|
||||
check_btrfs_mounts("1", mounts.as_bytes()).map_err(|error| error.kind()),
|
||||
Err(io::ErrorKind::PermissionDenied),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn btrfs_device_mismatch_rejects_duplicate_mount_id() {
|
||||
let mounts = b"1 0 0:1 /@ / rw - btrfs disk rw\n\
|
||||
1 0 0:1 /@ / rw - btrfs disk rw\n";
|
||||
assert_eq!(
|
||||
check_btrfs_mounts("1", mounts).map_err(|error| error.kind()),
|
||||
Err(io::ErrorKind::Other),
|
||||
);
|
||||
}
|
||||
|
||||
#[test_case("/tmp", "/host-tmp", true; "ancestor alias")]
|
||||
#[test_case("/tmp/codex-daemon-1000", "/alias", false; "directory alias")]
|
||||
#[test_case("/tmp/codex-daemon-1000/rpc.sock", "/alias.sock", false; "socket alias")]
|
||||
#[test_case("/", "/host", true; "root alias")]
|
||||
#[test_case("/workspace", "/project", true; "unrelated project bind")]
|
||||
#[test_case("/tmp", "/tmp", true; "same location")]
|
||||
#[test_case("/tmp", "/host\\040tmp", true; "escaped alias")]
|
||||
#[test_case("/other", "/tmp/codex-daemon-1000/nested", false; "nested mount")]
|
||||
fn accepts_only_mounts_that_can_keep_the_directory_masked(
|
||||
root: &str,
|
||||
destination: &str,
|
||||
allowed: bool,
|
||||
) {
|
||||
let mounts =
|
||||
format!("1 0 0:1 / / rw - ext4 disk rw\n2 1 0:1 {root} {destination} rw - ext4 disk rw\n");
|
||||
let visible_mount = if destination == "/tmp" { "2" } else { "1" };
|
||||
for mount_id in [Some(visible_mount), None] {
|
||||
assert_eq!(
|
||||
check_mounts(
|
||||
Path::new("/tmp/codex-daemon-1000"),
|
||||
"0:1",
|
||||
mount_id,
|
||||
mounts.as_bytes()
|
||||
)
|
||||
.is_ok(),
|
||||
allowed,
|
||||
"mount_id: {mount_id:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test_case("0:2", "mnt:[4026532835]", "/run/snapd/ns/example.mnt", Ok(()); "unrelated mount namespace")]
|
||||
#[test_case("0:2", "net:[4026531840]", "/run/netns/example", Ok(()); "unrelated network namespace")]
|
||||
#[test_case("0:2", "mnt:[4026532835]", "/tmp/codex-daemon-1000/ns", Err(io::ErrorKind::PermissionDenied); "nested namespace mount")]
|
||||
#[test_case("0:1", "mnt:[4026532835]", "/run/snapd/ns/example.mnt", Err(io::ErrorKind::Other); "non-path root on socket filesystem")]
|
||||
#[test_case("0:2", "mnt:[4026532835]", "relative/ns", Err(io::ErrorKind::Other); "relative destination")]
|
||||
#[test_case("0:2", "mnt:[4026532835]", "/run/snapd/ns/\\invalid", Err(io::ErrorKind::Other); "invalid destination escape")]
|
||||
fn validates_namespace_mounts_by_device_and_destination(
|
||||
device: &str,
|
||||
root: &str,
|
||||
destination: &str,
|
||||
expected: Result<(), io::ErrorKind>,
|
||||
) {
|
||||
let mounts = format!(
|
||||
"1 0 0:1 / / rw - ext4 disk rw\n2 1 {device} {root} {destination} rw - nsfs nsfs rw\n"
|
||||
);
|
||||
for mount_id in [Some("1"), None] {
|
||||
assert_eq!(
|
||||
check_mounts(
|
||||
Path::new("/tmp/codex-daemon-1000"),
|
||||
"0:1",
|
||||
mount_id,
|
||||
mounts.as_bytes()
|
||||
)
|
||||
.map(|_| ())
|
||||
.map_err(|error| error.kind()),
|
||||
expected,
|
||||
"mount_id: {mount_id:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unrelated_namespace_mount_does_not_hide_a_socket_alias() {
|
||||
let mounts = b"1 0 0:1 / / rw - ext4 disk rw\n\
|
||||
2 1 0:2 net:[4026531840] /run/netns/example rw - nsfs nsfs rw\n\
|
||||
3 1 0:1 /tmp/codex-daemon-1000 /alias rw - ext4 disk rw\n";
|
||||
for mount_id in [Some("1"), None] {
|
||||
assert_eq!(
|
||||
check_mounts(Path::new("/tmp/codex-daemon-1000"), "0:1", mount_id, mounts)
|
||||
.map_err(|error| error.kind()),
|
||||
Err(io::ErrorKind::PermissionDenied),
|
||||
"mount_id: {mount_id:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn masks_alias_when_tmp_is_itself_a_bind_mount() {
|
||||
let mounts = b"1 0 0:1 / / rw - ext4 disk rw\n2 1 0:1 /backing/tmp /tmp rw - ext4 disk rw\n";
|
||||
let expected = BTreeSet::from([
|
||||
PathBuf::from("/tmp/codex-daemon-1000"),
|
||||
PathBuf::from("/backing/tmp/codex-daemon-1000"),
|
||||
]);
|
||||
assert_eq!(
|
||||
check_mounts(
|
||||
Path::new("/tmp/codex-daemon-1000"),
|
||||
"0:1",
|
||||
Some("2"),
|
||||
mounts
|
||||
)
|
||||
.unwrap(),
|
||||
expected
|
||||
);
|
||||
// A hidden deeper mount must not override the actual /tmp backing location.
|
||||
let hidden = [
|
||||
mounts.as_slice(),
|
||||
b"3 1 0:1 /tmp/codex-daemon-1000 /tmp/codex-daemon-1000 rw - ext4 disk rw\n",
|
||||
]
|
||||
.concat();
|
||||
assert_eq!(
|
||||
check_mounts(
|
||||
Path::new("/tmp/codex-daemon-1000"),
|
||||
"0:1",
|
||||
Some("2"),
|
||||
&hidden
|
||||
)
|
||||
.unwrap(),
|
||||
expected
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_private_tmp_filesystem_and_resolves_stacked_mounts() {
|
||||
let mounts = "1 0 0:1 / / rw - ext4 disk rw\n2 1 0:2 / /tmp rw - tmpfs tmpfs rw\n";
|
||||
let directory = Path::new("/tmp/codex-daemon-1000");
|
||||
assert!(check_mounts(directory, "0:2", Some("2"), mounts.as_bytes()).is_ok());
|
||||
assert!(check_mounts(directory, "0:2", /*mount_id*/ None, mounts.as_bytes()).is_ok());
|
||||
// Missing or inconsistent precise IDs must not fall back to the otherwise
|
||||
// acceptable conservative interpretation.
|
||||
assert!(check_mounts(directory, "0:2", Some("missing"), mounts.as_bytes()).is_err());
|
||||
assert!(check_mounts(directory, "0:2", Some("1"), mounts.as_bytes()).is_err());
|
||||
assert!(check_mounts(directory, "0:3", /*mount_id*/ None, mounts.as_bytes()).is_err());
|
||||
let stacked = format!("{mounts}3 2 0:2 /other /tmp rw - tmpfs tmpfs rw\n");
|
||||
assert!(check_mounts(directory, "0:2", Some("3"), stacked.as_bytes()).is_ok());
|
||||
assert!(check_mounts(directory, "0:2", /*mount_id*/ None, stacked.as_bytes()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_open_mount_that_has_been_covered() {
|
||||
let directory = Path::new("/tmp/codex-daemon-1000");
|
||||
let mounts = "1 0 0:1 / / rw - ext4 disk rw\n\
|
||||
2 1 0:1 /tmp/private-old/tmp /tmp rw - ext4 disk rw\n\
|
||||
3 2 0:1 /tmp/private-new/tmp /tmp rw - ext4 disk rw\n";
|
||||
assert!(check_mounts(directory, "0:1", Some("2"), mounts.as_bytes()).is_err());
|
||||
assert!(check_mounts(directory, "0:1", Some("3"), mounts.as_bytes()).is_ok());
|
||||
let exposed = format!(
|
||||
"{mounts}4 1 0:1 /tmp/private-new/tmp/codex-daemon-1000 /outside rw - ext4 disk rw\n"
|
||||
);
|
||||
for mount_id in [Some("2"), Some("3"), None] {
|
||||
assert!(check_mounts(directory, "0:1", mount_id, exposed.as_bytes()).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_mount_hidden_by_an_ancestor_overmount() {
|
||||
let directory = Path::new("/tmp/private/codex-daemon-1000");
|
||||
let mounts = "1 0 0:1 / / rw - ext4 disk rw\n\
|
||||
2 1 0:2 / /tmp rw - tmpfs tmpfs rw\n\
|
||||
3 2 0:3 / /tmp/private rw - tmpfs tmpfs rw\n";
|
||||
assert!(check_mounts(directory, "0:3", Some("3"), mounts.as_bytes()).is_ok());
|
||||
let covered = format!("{mounts}4 2 0:2 /other /tmp rw - tmpfs tmpfs rw\n");
|
||||
assert!(check_mounts(directory, "0:3", Some("3"), covered.as_bytes()).is_err());
|
||||
assert!(check_mounts(directory, "0:2", Some("4"), covered.as_bytes()).is_ok());
|
||||
}
|
||||
|
||||
#[test_case("/tmp/systemd-private-service/tmp", "/"; "tmp on root filesystem")]
|
||||
#[test_case("/systemd-private-service/tmp", "/tmp"; "tmp on separate filesystem")]
|
||||
fn accepts_private_tmp_bind_and_maskable_aliases(root: &str, parent: &str) {
|
||||
let directory = Path::new("/tmp/codex-daemon-1000");
|
||||
let mounts =
|
||||
format!("1 0 0:1 / {parent} rw - ext4 disk rw\n2 1 0:1 {root} /tmp rw - ext4 disk rw\n");
|
||||
assert!(check_mounts(directory, "0:1", Some("2"), mounts.as_bytes()).is_ok());
|
||||
// PrivateTmp remains ambiguous when neither fdinfo nor statx supplies an ID.
|
||||
assert!(check_mounts(directory, "0:1", /*mount_id*/ None, mounts.as_bytes()).is_err());
|
||||
|
||||
// A real alias beneath /tmp needs a mask; a direct socket alias remains unsupported.
|
||||
for (alias_root, destination, can_mask) in [
|
||||
(root.to_owned(), "/tmp/exposed", true),
|
||||
(
|
||||
format!("{root}/codex-daemon-1000/rpc.sock"),
|
||||
"/tmp/alias.sock",
|
||||
false,
|
||||
),
|
||||
("/".to_owned(), "/host", true),
|
||||
] {
|
||||
let exposed = format!("{mounts}3 2 0:1 {alias_root} {destination} rw - ext4 disk rw\n");
|
||||
assert_eq!(
|
||||
check_mounts(directory, "0:1", Some("2"), exposed.as_bytes()).is_ok(),
|
||||
can_mask
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn masked_wslg_alias_does_not_skip_other_socket_masks() {
|
||||
let mounts = "1 0 0:1 / / rw - ext4 disk rw\n2 1 0:1 / /mnt/wslg/distro rw - ext4 disk rw\n";
|
||||
let directory = Path::new("/tmp/codex-daemon-1000");
|
||||
let mask = Some(Path::new(crate::bwrap::WSLG_DISTRO_ROOT));
|
||||
let exposed = format!("{mounts}3 1 0:1 /tmp /host-tmp rw - ext4 disk rw\n");
|
||||
for mount_id in [Some("1"), None] {
|
||||
assert_eq!(
|
||||
check_mounts(directory, "0:1", mount_id, mounts.as_bytes()).unwrap(),
|
||||
BTreeSet::from([
|
||||
directory.to_path_buf(),
|
||||
PathBuf::from("/mnt/wslg/distro/tmp/codex-daemon-1000"),
|
||||
])
|
||||
);
|
||||
assert_eq!(
|
||||
super::check_mounts(
|
||||
directory,
|
||||
"0:1",
|
||||
SocketFilesystem::Other,
|
||||
mount_id,
|
||||
mounts.as_bytes(),
|
||||
mask
|
||||
)
|
||||
.unwrap(),
|
||||
BTreeSet::from([directory.to_path_buf()])
|
||||
);
|
||||
assert_eq!(
|
||||
super::check_mounts(
|
||||
directory,
|
||||
"0:1",
|
||||
SocketFilesystem::Other,
|
||||
mount_id,
|
||||
exposed.as_bytes(),
|
||||
mask
|
||||
)
|
||||
.unwrap(),
|
||||
BTreeSet::from([
|
||||
directory.to_path_buf(),
|
||||
PathBuf::from("/host-tmp/codex-daemon-1000"),
|
||||
])
|
||||
);
|
||||
}
|
||||
}
|
||||
44
codex-rs/linux-sandbox/src/exec_util.rs
Normal file
44
codex-rs/linux-sandbox/src/exec_util.rs
Normal file
@@ -0,0 +1,44 @@
|
||||
use std::ffi::CString;
|
||||
use std::fs::File;
|
||||
use std::os::fd::AsRawFd;
|
||||
|
||||
pub(crate) fn argv_to_cstrings(argv: &[String]) -> Vec<CString> {
|
||||
let mut cstrings: Vec<CString> = Vec::with_capacity(argv.len());
|
||||
for arg in argv {
|
||||
match CString::new(arg.as_str()) {
|
||||
Ok(value) => cstrings.push(value),
|
||||
Err(err) => panic!("failed to convert argv to CString: {err}"),
|
||||
}
|
||||
}
|
||||
cstrings
|
||||
}
|
||||
|
||||
pub(crate) fn make_files_inheritable(files: &[File]) {
|
||||
for file in files {
|
||||
clear_cloexec(file.as_raw_fd());
|
||||
}
|
||||
}
|
||||
|
||||
fn clear_cloexec(fd: libc::c_int) {
|
||||
// SAFETY: `fd` is an owned descriptor kept alive by `files`.
|
||||
let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };
|
||||
if flags < 0 {
|
||||
let err = std::io::Error::last_os_error();
|
||||
panic!("failed to read fd flags for preserved bubblewrap file descriptor {fd}: {err}");
|
||||
}
|
||||
let cleared_flags = flags & !libc::FD_CLOEXEC;
|
||||
if cleared_flags == flags {
|
||||
return;
|
||||
}
|
||||
|
||||
// SAFETY: `fd` is valid and we are only clearing FD_CLOEXEC.
|
||||
let result = unsafe { libc::fcntl(fd, libc::F_SETFD, cleared_flags) };
|
||||
if result < 0 {
|
||||
let err = std::io::Error::last_os_error();
|
||||
panic!("failed to clear CLOEXEC for preserved bubblewrap file descriptor {fd}: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "exec_util_tests.rs"]
|
||||
mod tests;
|
||||
35
codex-rs/linux-sandbox/src/exec_util_tests.rs
Normal file
35
codex-rs/linux-sandbox/src/exec_util_tests.rs
Normal file
@@ -0,0 +1,35 @@
|
||||
//! Verify preserved file descriptors remain inheritable across exec.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::NamedTempFile;
|
||||
|
||||
#[test]
|
||||
fn preserved_files_are_made_inheritable() {
|
||||
let file = NamedTempFile::new().expect("temp file");
|
||||
set_cloexec(file.as_file().as_raw_fd());
|
||||
|
||||
make_files_inheritable(std::slice::from_ref(file.as_file()));
|
||||
|
||||
assert_eq!(fd_flags(file.as_file().as_raw_fd()) & libc::FD_CLOEXEC, 0);
|
||||
}
|
||||
|
||||
fn set_cloexec(fd: libc::c_int) {
|
||||
let flags = fd_flags(fd);
|
||||
// SAFETY: `fd` is valid for the duration of the test.
|
||||
let result = unsafe { libc::fcntl(fd, libc::F_SETFD, flags | libc::FD_CLOEXEC) };
|
||||
if result < 0 {
|
||||
let err = std::io::Error::last_os_error();
|
||||
panic!("failed to set CLOEXEC for test fd {fd}: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
fn fd_flags(fd: libc::c_int) -> libc::c_int {
|
||||
// SAFETY: `fd` is valid for the duration of the test.
|
||||
let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };
|
||||
if flags < 0 {
|
||||
let err = std::io::Error::last_os_error();
|
||||
panic!("failed to read fd flags for test fd {fd}: {err}");
|
||||
}
|
||||
flags
|
||||
}
|
||||
91
codex-rs/linux-sandbox/src/fd_mount.rs
Normal file
91
codex-rs/linux-sandbox/src/fd_mount.rs
Normal file
@@ -0,0 +1,91 @@
|
||||
//! Authenticate descriptor-backed mounts before sandboxed code can inherit them.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::fs;
|
||||
use std::fs::File;
|
||||
use std::io;
|
||||
use std::os::fd::AsRawFd;
|
||||
use std::os::fd::FromRawFd;
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
use std::path::Path;
|
||||
|
||||
pub(crate) fn verify_fd_mounts(mounts: &[String]) -> io::Result<()> {
|
||||
let mut claimed_descriptors = HashSet::with_capacity(mounts.len());
|
||||
|
||||
for mount in mounts {
|
||||
let (descriptor, destination) = mount.split_once(':').ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!("descriptor-backed mount must contain FD:DEST: {mount}"),
|
||||
)
|
||||
})?;
|
||||
let descriptor = descriptor.parse::<libc::c_int>().map_err(|_| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!("descriptor-backed mount has an invalid descriptor: {mount}"),
|
||||
)
|
||||
})?;
|
||||
if descriptor <= libc::STDERR_FILENO {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!("descriptor-backed mount cannot use a standard descriptor: {descriptor}"),
|
||||
));
|
||||
}
|
||||
if !claimed_descriptors.insert(descriptor) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!("descriptor-backed mount reuses descriptor {descriptor}"),
|
||||
));
|
||||
}
|
||||
|
||||
// The launcher transfers each distinct descriptor exactly once across
|
||||
// bubblewrap, so first confirm it is live before assuming ownership.
|
||||
let flags = unsafe { libc::fcntl(descriptor, libc::F_GETFD) };
|
||||
if flags < 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
// SAFETY: the launcher transferred this live descriptor to this stage,
|
||||
// and the set above prevents claiming the same descriptor twice.
|
||||
let file = unsafe { File::from_raw_fd(descriptor) };
|
||||
let result =
|
||||
unsafe { libc::fcntl(file.as_raw_fd(), libc::F_SETFD, flags | libc::FD_CLOEXEC) };
|
||||
if result < 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
|
||||
let destination = Path::new(destination);
|
||||
if !destination.is_absolute() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!(
|
||||
"descriptor-backed mount destination must be absolute: {}",
|
||||
destination.display()
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
let descriptor_metadata = file.metadata()?;
|
||||
let destination_metadata = fs::symlink_metadata(destination)?;
|
||||
if (descriptor_metadata.dev(), descriptor_metadata.ino())
|
||||
!= (destination_metadata.dev(), destination_metadata.ino())
|
||||
{
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
format!(
|
||||
"descriptor-backed mount does not match its destination: {}",
|
||||
destination.display()
|
||||
),
|
||||
));
|
||||
}
|
||||
|
||||
// Closing immediately prevents a writable host directory descriptor
|
||||
// from reaching bridge workers or the sandboxed command.
|
||||
drop(file);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "fd_mount_tests.rs"]
|
||||
mod tests;
|
||||
130
codex-rs/linux-sandbox/src/fd_mount_tests.rs
Normal file
130
codex-rs/linux-sandbox/src/fd_mount_tests.rs
Normal file
@@ -0,0 +1,130 @@
|
||||
//! Check mount validation and cleanup without assuming closed descriptor numbers stay unused.
|
||||
|
||||
use super::verify_fd_mounts;
|
||||
use pretty_assertions::assert_eq;
|
||||
use pretty_assertions::assert_ne;
|
||||
use std::fs::File;
|
||||
use std::fs::Metadata;
|
||||
use std::os::fd::IntoRawFd;
|
||||
use std::os::fd::RawFd;
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
|
||||
// Another test can reuse the number after closure; only the original directory is a leak.
|
||||
#[track_caller]
|
||||
fn assert_inherited_descriptor_closed(descriptor: RawFd, inherited: &Metadata) {
|
||||
match std::fs::metadata(format!("/proc/self/fd/{descriptor}")) {
|
||||
Ok(current) => assert_ne!(
|
||||
(current.dev(), current.ino()),
|
||||
(inherited.dev(), inherited.ino()),
|
||||
"the inherited directory descriptor must be closed"
|
||||
),
|
||||
Err(error) => assert_eq!(error.kind(), std::io::ErrorKind::NotFound),
|
||||
}
|
||||
}
|
||||
|
||||
/// A matching mount authenticates its original inode and closes the inherited descriptor.
|
||||
#[test]
|
||||
fn matching_mount_closes_inherited_descriptor() {
|
||||
let root = tempfile::tempdir().expect("temporary directory should be created");
|
||||
let descriptor = File::open(root.path())
|
||||
.expect("directory descriptor should open")
|
||||
.into_raw_fd();
|
||||
let descriptor_path = format!("/proc/self/fd/{descriptor}");
|
||||
let inherited = std::fs::metadata(&descriptor_path)
|
||||
.expect("inherited descriptor metadata should be accessible");
|
||||
let marker = format!("{descriptor}:{}", root.path().display());
|
||||
|
||||
verify_fd_mounts(&[marker]).expect("matching mount should verify");
|
||||
|
||||
assert_inherited_descriptor_closed(descriptor, &inherited);
|
||||
}
|
||||
|
||||
/// A swapped destination fails closed without leaking the original descriptor.
|
||||
#[test]
|
||||
fn mismatched_mount_closes_inherited_descriptor() {
|
||||
let source = tempfile::tempdir().expect("source directory should be created");
|
||||
let destination = tempfile::tempdir().expect("destination directory should be created");
|
||||
let descriptor = File::open(source.path())
|
||||
.expect("source directory descriptor should open")
|
||||
.into_raw_fd();
|
||||
let descriptor_path = format!("/proc/self/fd/{descriptor}");
|
||||
let inherited = std::fs::metadata(&descriptor_path)
|
||||
.expect("inherited descriptor metadata should be accessible");
|
||||
let marker = format!("{descriptor}:{}", destination.path().display());
|
||||
|
||||
let error = verify_fd_mounts(&[marker]).expect_err("different inodes must be rejected");
|
||||
|
||||
assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
|
||||
assert_inherited_descriptor_closed(descriptor, &inherited);
|
||||
}
|
||||
|
||||
/// A symlink to the original inode is not itself the authenticated mount.
|
||||
#[test]
|
||||
fn symlinked_mount_destination_closes_inherited_descriptor() {
|
||||
let root = tempfile::tempdir().expect("temporary directory should be created");
|
||||
let source = root.path().join("source");
|
||||
let destination = root.path().join("destination");
|
||||
std::fs::create_dir(&source).expect("source directory should be created");
|
||||
std::os::unix::fs::symlink(&source, &destination)
|
||||
.expect("mount destination symlink should be created");
|
||||
let descriptor = File::open(&source)
|
||||
.expect("source directory descriptor should open")
|
||||
.into_raw_fd();
|
||||
let descriptor_path = format!("/proc/self/fd/{descriptor}");
|
||||
let inherited = std::fs::metadata(&descriptor_path)
|
||||
.expect("inherited descriptor metadata should be accessible");
|
||||
let marker = format!("{descriptor}:{}", destination.display());
|
||||
|
||||
let error = verify_fd_mounts(&[marker]).expect_err("symlinked mounts must be rejected");
|
||||
|
||||
assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
|
||||
assert_inherited_descriptor_closed(descriptor, &inherited);
|
||||
}
|
||||
|
||||
/// Malformed mount markers cannot claim standard streams or relative destinations.
|
||||
#[test]
|
||||
fn malformed_mount_markers_are_rejected() {
|
||||
for marker in [
|
||||
"missing-separator",
|
||||
"invalid:/tmp",
|
||||
"0:/tmp",
|
||||
"1:/tmp",
|
||||
"2:/tmp",
|
||||
] {
|
||||
let error = verify_fd_mounts(&[marker.to_string()])
|
||||
.expect_err("malformed mount marker must be rejected");
|
||||
assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);
|
||||
}
|
||||
|
||||
let root = tempfile::tempdir().expect("temporary directory should be created");
|
||||
let descriptor = File::open(root.path())
|
||||
.expect("directory descriptor should open")
|
||||
.into_raw_fd();
|
||||
let descriptor_path = format!("/proc/self/fd/{descriptor}");
|
||||
let inherited = std::fs::metadata(&descriptor_path)
|
||||
.expect("inherited descriptor metadata should be accessible");
|
||||
let error = verify_fd_mounts(&[format!("{descriptor}:relative")])
|
||||
.expect_err("relative mount destinations must be rejected");
|
||||
|
||||
assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);
|
||||
assert_inherited_descriptor_closed(descriptor, &inherited);
|
||||
}
|
||||
|
||||
/// A transferred descriptor can be consumed only once even if a marker is repeated.
|
||||
#[test]
|
||||
fn duplicate_mount_descriptors_are_rejected() {
|
||||
let root = tempfile::tempdir().expect("temporary directory should be created");
|
||||
let descriptor = File::open(root.path())
|
||||
.expect("directory descriptor should open")
|
||||
.into_raw_fd();
|
||||
let descriptor_path = format!("/proc/self/fd/{descriptor}");
|
||||
let inherited = std::fs::metadata(&descriptor_path)
|
||||
.expect("inherited descriptor metadata should be accessible");
|
||||
let marker = format!("{descriptor}:{}", root.path().display());
|
||||
|
||||
let error = verify_fd_mounts(&[marker.clone(), marker])
|
||||
.expect_err("a mount descriptor must not be consumed twice");
|
||||
|
||||
assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);
|
||||
assert_inherited_descriptor_closed(descriptor, &inherited);
|
||||
}
|
||||
252
codex-rs/linux-sandbox/src/launcher.rs
Normal file
252
codex-rs/linux-sandbox/src/launcher.rs
Normal file
@@ -0,0 +1,252 @@
|
||||
use std::ffi::CStr;
|
||||
use std::ffi::CString;
|
||||
use std::fs::File;
|
||||
use std::os::raw::c_char;
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
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;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
enum BubblewrapLauncher {
|
||||
System(SystemBwrapLauncher),
|
||||
Bundled(BundledBwrapLauncher),
|
||||
Unavailable,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
struct SystemBwrapLauncher {
|
||||
program: AbsolutePathBuf,
|
||||
supports_argv0: bool,
|
||||
supports_ro_bind_fd: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
struct SystemBwrapCapabilities {
|
||||
supports_argv0: bool,
|
||||
supports_perms: bool,
|
||||
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()
|
||||
.take_while(|arg| arg.as_str() != "--")
|
||||
.any(|arg| arg == "--unshare-pid")
|
||||
{
|
||||
argv.insert(1, "--as-pid-1".to_string());
|
||||
}
|
||||
|
||||
match preferred_bwrap_launcher() {
|
||||
BubblewrapLauncher::System(launcher) => {
|
||||
if !launcher.supports_ro_bind_fd {
|
||||
translate_legacy_bwrap_fd_mounts(&mut argv)
|
||||
.unwrap_or_else(|error| panic!("invalid legacy bubblewrap fd mount: {error}"));
|
||||
}
|
||||
exec_system_bwrap(&launcher.program, argv, preserved_files)
|
||||
}
|
||||
BubblewrapLauncher::Bundled(launcher) => launcher.exec(argv, preserved_files),
|
||||
BubblewrapLauncher::Unavailable => {
|
||||
panic!(
|
||||
"bubblewrap is unavailable: no system bwrap was found on PATH and no bundled \
|
||||
codex-resources/bwrap binary was found next to the Codex executable"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn translate_legacy_bwrap_fd_mounts(argv: &mut Vec<String>) -> Result<(), String> {
|
||||
let command_separator = argv
|
||||
.iter()
|
||||
.position(|argument| argument == "--")
|
||||
.ok_or_else(|| "bubblewrap argv is missing the command separator '--'".to_string())?;
|
||||
let mut verification_args = Vec::new();
|
||||
let mut verified_fds = Vec::new();
|
||||
let mut argument_index = 0;
|
||||
|
||||
while argument_index < command_separator {
|
||||
if argv[argument_index] != "--ro-bind-fd" {
|
||||
argument_index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
let fd_argument = argv
|
||||
.get(argument_index + 1)
|
||||
.filter(|_| argument_index + 1 < command_separator)
|
||||
.ok_or_else(|| "--ro-bind-fd is missing its file descriptor".to_string())?;
|
||||
let fd = fd_argument
|
||||
.parse::<libc::c_int>()
|
||||
.map_err(|_| format!("invalid --ro-bind-fd file descriptor: {fd_argument}"))?;
|
||||
if fd <= libc::STDERR_FILENO {
|
||||
return Err(format!(
|
||||
"--ro-bind-fd file descriptor must not use standard descriptors: {fd}"
|
||||
));
|
||||
}
|
||||
if verified_fds.contains(&fd) {
|
||||
return Err(format!("duplicate --ro-bind-fd file descriptor: {fd}"));
|
||||
}
|
||||
|
||||
let destination = argv
|
||||
.get(argument_index + 2)
|
||||
.filter(|_| argument_index + 2 < command_separator)
|
||||
.ok_or_else(|| "--ro-bind-fd is missing its mount destination".to_string())?;
|
||||
if !Path::new(destination).is_absolute() {
|
||||
return Err(format!(
|
||||
"--ro-bind-fd mount destination must be absolute: {destination}"
|
||||
));
|
||||
}
|
||||
|
||||
verification_args.push("--verify-fd-mount".to_string());
|
||||
verification_args.push(format!("{fd}:{destination}"));
|
||||
verified_fds.push(fd);
|
||||
argv[argument_index] = "--ro-bind".to_string();
|
||||
argv[argument_index + 1] = format!("/proc/self/fd/{fd}");
|
||||
argument_index += 3;
|
||||
}
|
||||
|
||||
if verification_args.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let inner_command = command_separator + 1;
|
||||
if argv.get(inner_command).is_none() {
|
||||
return Err("bubblewrap argv is missing the inner command after '--'".to_string());
|
||||
}
|
||||
if !argv[inner_command + 1..]
|
||||
.iter()
|
||||
.take_while(|argument| argument.as_str() != "--")
|
||||
.any(|argument| argument == "--apply-seccomp-then-exec")
|
||||
{
|
||||
return Err("descriptor-backed mounts require the trusted inner sandbox stage".to_string());
|
||||
}
|
||||
argv.splice(inner_command + 1..inner_command + 1, verification_args);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
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> {
|
||||
system_bwrap_launcher_for_path_with_probe(system_bwrap_path, system_bwrap_capabilities)
|
||||
}
|
||||
|
||||
fn system_bwrap_launcher_for_path_with_probe(
|
||||
system_bwrap_path: &Path,
|
||||
system_bwrap_capabilities: impl FnOnce(&Path) -> Option<SystemBwrapCapabilities>,
|
||||
) -> Option<SystemBwrapLauncher> {
|
||||
if !system_bwrap_path.is_file() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let Some(SystemBwrapCapabilities {
|
||||
supports_argv0,
|
||||
supports_perms: true,
|
||||
supports_ro_bind_fd,
|
||||
}) = system_bwrap_capabilities(system_bwrap_path)
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let system_bwrap_path = match AbsolutePathBuf::from_absolute_path(system_bwrap_path) {
|
||||
Ok(path) => path,
|
||||
Err(err) => panic!(
|
||||
"failed to normalize system bubblewrap path {}: {err}",
|
||||
system_bwrap_path.display()
|
||||
),
|
||||
};
|
||||
Some(SystemBwrapLauncher {
|
||||
program: system_bwrap_path,
|
||||
supports_argv0,
|
||||
supports_ro_bind_fd,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn preferred_bwrap_supports_argv0() -> bool {
|
||||
match preferred_bwrap_launcher() {
|
||||
BubblewrapLauncher::System(launcher) => launcher.supports_argv0,
|
||||
BubblewrapLauncher::Bundled(_) | BubblewrapLauncher::Unavailable => true,
|
||||
}
|
||||
}
|
||||
|
||||
fn system_bwrap_capabilities(system_bwrap_path: &Path) -> Option<SystemBwrapCapabilities> {
|
||||
// bubblewrap added `--argv0` in v0.9.0:
|
||||
// https://github.com/containers/bubblewrap/releases/tag/v0.9.0
|
||||
// Older distro packages (for example Ubuntu 20.04/22.04) ship builds that
|
||||
// reject `--argv0`, so use the system binary's no-argv0 compatibility path
|
||||
// in that case.
|
||||
let output = match Command::new(system_bwrap_path).arg("--help").output() {
|
||||
Ok(output) => output,
|
||||
Err(_) => return None,
|
||||
};
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
if !stdout.contains("--as-pid-1") && !stderr.contains("--as-pid-1") {
|
||||
return None;
|
||||
}
|
||||
Some(SystemBwrapCapabilities {
|
||||
supports_argv0: stdout.contains("--argv0") || stderr.contains("--argv0"),
|
||||
supports_perms: stdout.contains("--perms") || stderr.contains("--perms"),
|
||||
supports_ro_bind_fd: stdout.contains("--ro-bind-fd") || stderr.contains("--ro-bind-fd"),
|
||||
})
|
||||
}
|
||||
|
||||
fn exec_system_bwrap(
|
||||
program: &AbsolutePathBuf,
|
||||
argv: Vec<String>,
|
||||
preserved_files: Vec<File>,
|
||||
) -> ! {
|
||||
// System bwrap runs across an exec boundary, so preserved fds must survive exec.
|
||||
make_files_inheritable(&preserved_files);
|
||||
|
||||
let program_path = program.as_path().display().to_string();
|
||||
let program = CString::new(program.as_path().as_os_str().as_bytes())
|
||||
.unwrap_or_else(|err| panic!("invalid system bubblewrap path: {err}"));
|
||||
let cstrings = argv_to_cstrings(&argv);
|
||||
let mut argv_ptrs: Vec<*const c_char> = cstrings
|
||||
.iter()
|
||||
.map(CString::as_c_str)
|
||||
.map(CStr::as_ptr)
|
||||
.collect();
|
||||
argv_ptrs.push(std::ptr::null());
|
||||
|
||||
// SAFETY: `program` and every entry in `argv_ptrs` are valid C strings for
|
||||
// the duration of the call. On success `execv` does not return.
|
||||
unsafe {
|
||||
libc::execv(program.as_ptr(), argv_ptrs.as_ptr());
|
||||
}
|
||||
let err = std::io::Error::last_os_error();
|
||||
panic!("failed to exec system bubblewrap {program_path}: {err}");
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "launcher_tests.rs"]
|
||||
mod tests;
|
||||
223
codex-rs/linux-sandbox/src/launcher_tests.rs
Normal file
223
codex-rs/linux-sandbox/src/launcher_tests.rs
Normal file
@@ -0,0 +1,223 @@
|
||||
//! Verify system bubblewrap selection and legacy fd mount translation.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::NamedTempFile;
|
||||
|
||||
#[test]
|
||||
fn prefers_system_bwrap_when_help_lists_argv0() {
|
||||
let fake_bwrap = NamedTempFile::new().expect("temp file");
|
||||
let fake_bwrap_path = fake_bwrap.path();
|
||||
let expected = AbsolutePathBuf::from_absolute_path(fake_bwrap_path).expect("absolute");
|
||||
|
||||
assert_eq!(
|
||||
system_bwrap_launcher_for_path_with_probe(fake_bwrap_path, |_| {
|
||||
Some(SystemBwrapCapabilities {
|
||||
supports_argv0: true,
|
||||
supports_perms: true,
|
||||
supports_ro_bind_fd: true,
|
||||
})
|
||||
}),
|
||||
Some(SystemBwrapLauncher {
|
||||
program: expected,
|
||||
supports_argv0: true,
|
||||
supports_ro_bind_fd: true,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prefers_system_bwrap_when_system_bwrap_lacks_argv0() {
|
||||
let fake_bwrap = NamedTempFile::new().expect("temp file");
|
||||
let fake_bwrap_path = fake_bwrap.path();
|
||||
|
||||
assert_eq!(
|
||||
system_bwrap_launcher_for_path_with_probe(fake_bwrap_path, |_| {
|
||||
Some(SystemBwrapCapabilities {
|
||||
supports_argv0: false,
|
||||
supports_perms: true,
|
||||
supports_ro_bind_fd: false,
|
||||
})
|
||||
}),
|
||||
Some(SystemBwrapLauncher {
|
||||
program: AbsolutePathBuf::from_absolute_path(fake_bwrap_path).expect("absolute"),
|
||||
supports_argv0: false,
|
||||
supports_ro_bind_fd: false,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_system_bwrap_when_system_bwrap_lacks_perms() {
|
||||
let fake_bwrap = NamedTempFile::new().expect("temp file");
|
||||
|
||||
assert_eq!(
|
||||
system_bwrap_launcher_for_path_with_probe(fake_bwrap.path(), |_| {
|
||||
Some(SystemBwrapCapabilities {
|
||||
supports_argv0: false,
|
||||
supports_perms: false,
|
||||
supports_ro_bind_fd: false,
|
||||
})
|
||||
}),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_fd_backed_read_only_mount_support_in_system_bwrap_help() {
|
||||
let temp_dir = tempfile::tempdir().expect("temp directory");
|
||||
let fake_bwrap_path = temp_dir.path().join("bwrap");
|
||||
codex_utils_cargo_bin::write_executable(
|
||||
&fake_bwrap_path,
|
||||
"#!/bin/sh\nprintf '%s\\n' '--as-pid-1' '--perms' '--argv0' '--ro-bind-fd'\n",
|
||||
)
|
||||
.expect("write fake bubblewrap");
|
||||
|
||||
assert_eq!(
|
||||
system_bwrap_capabilities(&fake_bwrap_path),
|
||||
Some(SystemBwrapCapabilities {
|
||||
supports_argv0: true,
|
||||
supports_perms: true,
|
||||
supports_ro_bind_fd: true,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn translates_fd_mounts_for_legacy_system_bubblewrap() {
|
||||
let mut argv = vec![
|
||||
"bwrap".to_string(),
|
||||
"--ro-bind-fd".to_string(),
|
||||
"7".to_string(),
|
||||
"/tmp/socket-root".to_string(),
|
||||
"--".to_string(),
|
||||
"/usr/bin/codex-linux-sandbox".to_string(),
|
||||
"--apply-seccomp-then-exec".to_string(),
|
||||
"--".to_string(),
|
||||
"echo".to_string(),
|
||||
"--ro-bind-fd".to_string(),
|
||||
];
|
||||
|
||||
translate_legacy_bwrap_fd_mounts(&mut argv).expect("fd mount should translate");
|
||||
|
||||
assert_eq!(
|
||||
argv,
|
||||
vec![
|
||||
"bwrap".to_string(),
|
||||
"--ro-bind".to_string(),
|
||||
"/proc/self/fd/7".to_string(),
|
||||
"/tmp/socket-root".to_string(),
|
||||
"--".to_string(),
|
||||
"/usr/bin/codex-linux-sandbox".to_string(),
|
||||
"--verify-fd-mount".to_string(),
|
||||
"7:/tmp/socket-root".to_string(),
|
||||
"--apply-seccomp-then-exec".to_string(),
|
||||
"--".to_string(),
|
||||
"echo".to_string(),
|
||||
"--ro-bind-fd".to_string(),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn translates_multiple_fd_mounts_for_legacy_system_bubblewrap() {
|
||||
let mut argv = vec![
|
||||
"bwrap".to_string(),
|
||||
"--ro-bind-fd".to_string(),
|
||||
"7".to_string(),
|
||||
"/tmp/first".to_string(),
|
||||
"--ro-bind-fd".to_string(),
|
||||
"9".to_string(),
|
||||
"/tmp/second:with-colon".to_string(),
|
||||
"--".to_string(),
|
||||
"codex-linux-sandbox".to_string(),
|
||||
"--apply-seccomp-then-exec".to_string(),
|
||||
"--".to_string(),
|
||||
"true".to_string(),
|
||||
];
|
||||
|
||||
translate_legacy_bwrap_fd_mounts(&mut argv).expect("fd mounts should translate");
|
||||
|
||||
assert_eq!(
|
||||
argv,
|
||||
vec![
|
||||
"bwrap".to_string(),
|
||||
"--ro-bind".to_string(),
|
||||
"/proc/self/fd/7".to_string(),
|
||||
"/tmp/first".to_string(),
|
||||
"--ro-bind".to_string(),
|
||||
"/proc/self/fd/9".to_string(),
|
||||
"/tmp/second:with-colon".to_string(),
|
||||
"--".to_string(),
|
||||
"codex-linux-sandbox".to_string(),
|
||||
"--verify-fd-mount".to_string(),
|
||||
"7:/tmp/first".to_string(),
|
||||
"--verify-fd-mount".to_string(),
|
||||
"9:/tmp/second:with-colon".to_string(),
|
||||
"--apply-seccomp-then-exec".to_string(),
|
||||
"--".to_string(),
|
||||
"true".to_string(),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_malformed_legacy_bubblewrap_fd_mounts() {
|
||||
for (fd, destination) in [
|
||||
("invalid", "/tmp/socket-root"),
|
||||
("2", "/tmp/socket-root"),
|
||||
("7", "relative/socket-root"),
|
||||
] {
|
||||
let mut argv = vec![
|
||||
"bwrap".to_string(),
|
||||
"--ro-bind-fd".to_string(),
|
||||
fd.to_string(),
|
||||
destination.to_string(),
|
||||
"--".to_string(),
|
||||
"codex-linux-sandbox".to_string(),
|
||||
];
|
||||
|
||||
assert!(translate_legacy_bwrap_fd_mounts(&mut argv).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_fd_mounts_without_the_trusted_inner_sandbox_stage() {
|
||||
let mut argv = vec![
|
||||
"bwrap".to_string(),
|
||||
"--ro-bind-fd".to_string(),
|
||||
"7".to_string(),
|
||||
"/tmp/socket-root".to_string(),
|
||||
"--".to_string(),
|
||||
"/bin/true".to_string(),
|
||||
"--".to_string(),
|
||||
"--apply-seccomp-then-exec".to_string(),
|
||||
];
|
||||
|
||||
assert!(translate_legacy_bwrap_fd_mounts(&mut argv).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_duplicate_legacy_bubblewrap_fd_mounts() {
|
||||
let mut argv = vec![
|
||||
"bwrap".to_string(),
|
||||
"--ro-bind-fd".to_string(),
|
||||
"7".to_string(),
|
||||
"/tmp/first".to_string(),
|
||||
"--ro-bind-fd".to_string(),
|
||||
"7".to_string(),
|
||||
"/tmp/second".to_string(),
|
||||
"--".to_string(),
|
||||
"codex-linux-sandbox".to_string(),
|
||||
];
|
||||
|
||||
assert!(translate_legacy_bwrap_fd_mounts(&mut argv).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_system_bwrap_when_system_bwrap_is_missing() {
|
||||
assert_eq!(
|
||||
system_bwrap_launcher_for_path(Path::new("/definitely/not/a/bwrap")),
|
||||
None
|
||||
);
|
||||
}
|
||||
48
codex-rs/linux-sandbox/src/lib.rs
Normal file
48
codex-rs/linux-sandbox/src/lib.rs
Normal file
@@ -0,0 +1,48 @@
|
||||
//! Linux sandbox helper entry point.
|
||||
//!
|
||||
//! On Linux, `codex-linux-sandbox` applies:
|
||||
//! - in-process restrictions (`no_new_privs` + seccomp), and
|
||||
//! - bubblewrap for filesystem isolation.
|
||||
#[cfg(target_os = "linux")]
|
||||
mod bazel_bwrap;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod bundled_bwrap;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod bwrap;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod daemon_mounts;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod exec_util;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod fd_mount;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod launcher;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod linux_run_main;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod proxy_lifecycle;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod proxy_routing;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod seccomp;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod wslg;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub use bundled_bwrap::find_bundled_bwrap_for_exe;
|
||||
#[cfg(target_os = "linux")]
|
||||
pub use bwrap::expand_unreadable_globs;
|
||||
|
||||
/// Exit status returned when bundled bubblewrap fails digest verification.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub const BUNDLED_BWRAP_DIGEST_VERIFICATION_FAILURE_EXIT_CODE: i32 = 8;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub fn run_main() -> ! {
|
||||
linux_run_main::run_main();
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
pub fn run_main() -> ! {
|
||||
panic!("codex-linux-sandbox is only supported on Linux");
|
||||
}
|
||||
1201
codex-rs/linux-sandbox/src/linux_run_main.rs
Normal file
1201
codex-rs/linux-sandbox/src/linux_run_main.rs
Normal file
File diff suppressed because it is too large
Load Diff
711
codex-rs/linux-sandbox/src/linux_run_main_tests.rs
Normal file
711
codex-rs/linux-sandbox/src/linux_run_main_tests.rs
Normal file
@@ -0,0 +1,711 @@
|
||||
#[cfg(test)]
|
||||
use super::*;
|
||||
#[cfg(test)]
|
||||
use crate::linux_run_main::install_bwrap_signal_forwarders;
|
||||
#[cfg(test)]
|
||||
use crate::linux_run_main::wait_for_bwrap_child;
|
||||
#[cfg(test)]
|
||||
use codex_network_proxy::ManagedNetworkSandboxContext;
|
||||
#[cfg(test)]
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
#[cfg(test)]
|
||||
use codex_protocol::protocol::FileSystemSandboxPolicy;
|
||||
#[cfg(test)]
|
||||
use codex_protocol::protocol::NetworkSandboxPolicy;
|
||||
#[cfg(test)]
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
#[cfg(test)]
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn read_only_permission_profile() -> PermissionProfile {
|
||||
PermissionProfile::read_only()
|
||||
}
|
||||
|
||||
fn read_only_file_system_policy() -> FileSystemSandboxPolicy {
|
||||
read_only_permission_profile().file_system_sandbox_policy()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_proc_mount_invalid_argument_failure() {
|
||||
let stderr = "bwrap: Can't mount proc on /newroot/proc: Invalid argument";
|
||||
assert!(is_proc_mount_failure(stderr));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_proc_mount_operation_not_permitted_failure() {
|
||||
let stderr = "bwrap: Can't mount proc on /newroot/proc: Operation not permitted";
|
||||
assert!(is_proc_mount_failure(stderr));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_proc_mount_permission_denied_failure() {
|
||||
let stderr = "bwrap: Can't mount proc on /newroot/proc: Permission denied";
|
||||
assert!(is_proc_mount_failure(stderr));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_non_proc_mount_errors() {
|
||||
let stderr = "bwrap: Can't bind mount /dev/null: Operation not permitted";
|
||||
assert!(!is_proc_mount_failure(stderr));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inserts_bwrap_argv0_before_command_separator() {
|
||||
let file_system_sandbox_policy = read_only_file_system_policy();
|
||||
let mut argv = build_bwrap_argv(
|
||||
vec!["/bin/true".to_string()],
|
||||
&file_system_sandbox_policy,
|
||||
Path::new("/"),
|
||||
Path::new("/"),
|
||||
BwrapOptions {
|
||||
mount_proc: true,
|
||||
network_mode: BwrapNetworkMode::FullAccess,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.expect("build bwrap argv")
|
||||
.args;
|
||||
apply_inner_command_argv0_for_launcher(
|
||||
&mut argv,
|
||||
/*supports_argv0*/ true,
|
||||
"/tmp/codex-arg0-session/codex-linux-sandbox".to_string(),
|
||||
);
|
||||
let separator = argv.iter().position(|arg| arg == "--").unwrap();
|
||||
assert_eq!(
|
||||
&argv[separator - 2..],
|
||||
["--argv0", "codex-linux-sandbox", "--", "/bin/true"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_inner_command_path_when_bwrap_lacks_argv0() {
|
||||
let file_system_sandbox_policy = read_only_file_system_policy();
|
||||
let mut argv = build_bwrap_argv(
|
||||
vec!["/bin/true".to_string()],
|
||||
&file_system_sandbox_policy,
|
||||
Path::new("/"),
|
||||
Path::new("/"),
|
||||
BwrapOptions {
|
||||
mount_proc: true,
|
||||
network_mode: BwrapNetworkMode::FullAccess,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.expect("build bwrap argv")
|
||||
.args;
|
||||
apply_inner_command_argv0_for_launcher(
|
||||
&mut argv,
|
||||
/*supports_argv0*/ false,
|
||||
"/tmp/codex-arg0-session/codex-linux-sandbox".to_string(),
|
||||
);
|
||||
|
||||
assert!(!argv.iter().any(|arg| arg == "--argv0"));
|
||||
assert!(
|
||||
argv.windows(2)
|
||||
.any(|window| { window == ["--", "/tmp/codex-arg0-session/codex-linux-sandbox"] })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_bwrap_helper_command_not_nested_user_command_when_current_exe_appears_later() {
|
||||
let nested_current_exe = std::env::current_exe()
|
||||
.expect("current exe")
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
let mut argv = vec![
|
||||
"bwrap".to_string(),
|
||||
"--".to_string(),
|
||||
"/tmp/helper-symlink".to_string(),
|
||||
"--sandbox-policy-cwd".to_string(),
|
||||
"/tmp/cwd".to_string(),
|
||||
"--".to_string(),
|
||||
nested_current_exe.clone(),
|
||||
"--codex-run-as-apply-patch".to_string(),
|
||||
"patch".to_string(),
|
||||
];
|
||||
|
||||
apply_inner_command_argv0_for_launcher(
|
||||
&mut argv,
|
||||
/*supports_argv0*/ false,
|
||||
"/tmp/argv0-fallback-helper".to_string(),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
argv,
|
||||
vec![
|
||||
"bwrap".to_string(),
|
||||
"--".to_string(),
|
||||
"/tmp/argv0-fallback-helper".to_string(),
|
||||
"--sandbox-policy-cwd".to_string(),
|
||||
"/tmp/cwd".to_string(),
|
||||
"--".to_string(),
|
||||
nested_current_exe,
|
||||
"--codex-run-as-apply-patch".to_string(),
|
||||
"patch".to_string(),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inserts_unshare_net_when_network_isolation_requested() {
|
||||
let file_system_sandbox_policy = read_only_file_system_policy();
|
||||
let argv = build_bwrap_argv(
|
||||
vec!["/bin/true".to_string()],
|
||||
&file_system_sandbox_policy,
|
||||
Path::new("/"),
|
||||
Path::new("/"),
|
||||
BwrapOptions {
|
||||
mount_proc: true,
|
||||
network_mode: BwrapNetworkMode::Isolated,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.expect("build bwrap argv")
|
||||
.args;
|
||||
assert!(argv.contains(&"--unshare-net".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inserts_unshare_net_when_proxy_only_network_mode_requested() {
|
||||
let file_system_sandbox_policy = read_only_file_system_policy();
|
||||
let argv = build_bwrap_argv(
|
||||
vec!["/bin/true".to_string()],
|
||||
&file_system_sandbox_policy,
|
||||
Path::new("/"),
|
||||
Path::new("/"),
|
||||
BwrapOptions {
|
||||
mount_proc: true,
|
||||
network_mode: BwrapNetworkMode::ProxyOnly,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.expect("build bwrap argv")
|
||||
.args;
|
||||
assert!(argv.contains(&"--unshare-net".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn masks_wsl_interop_with_full_network_and_restricted_filesystem() {
|
||||
let argv = build_bwrap_argv(
|
||||
vec!["/bin/true".to_string()],
|
||||
&read_only_file_system_policy(),
|
||||
Path::new("/"),
|
||||
Path::new("/"),
|
||||
BwrapOptions {
|
||||
network_mode: BwrapNetworkMode::FullAccess,
|
||||
mask_wsl_interop: true,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.expect("build bwrap argv")
|
||||
.args;
|
||||
|
||||
assert!(argv.windows(2).any(|args| args == ["--tmpfs", "/run/WSL"]));
|
||||
assert!(!argv.iter().any(|arg| arg == "--unshare-net"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn masks_inherited_procfs_when_wsl_interop_is_masked_without_fresh_proc() {
|
||||
let argv = build_bwrap_argv(
|
||||
vec!["/bin/true".to_string()],
|
||||
&read_only_file_system_policy(),
|
||||
Path::new("/"),
|
||||
Path::new("/"),
|
||||
BwrapOptions {
|
||||
mount_proc: false,
|
||||
network_mode: BwrapNetworkMode::FullAccess,
|
||||
mask_wsl_interop: true,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.expect("build bwrap argv")
|
||||
.args;
|
||||
|
||||
assert!(argv.windows(2).any(|args| args == ["--tmpfs", "/run/WSL"]));
|
||||
assert!(argv.windows(2).any(|args| args == ["--tmpfs", "/proc"]));
|
||||
assert!(!argv.windows(2).any(|args| args == ["--proc", "/proc"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proxy_only_mode_takes_precedence_over_full_network_policy() {
|
||||
let mode = bwrap_network_mode(
|
||||
NetworkSandboxPolicy::Enabled,
|
||||
/*allow_network_for_proxy*/ true,
|
||||
);
|
||||
assert_eq!(mode, BwrapNetworkMode::ProxyOnly);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_only_filesystem_policy_requires_direct_runtime_enforcement() {
|
||||
let temp_dir = tempfile::TempDir::new().expect("tempdir");
|
||||
let docs = temp_dir.path().join("docs");
|
||||
std::fs::create_dir_all(&docs).expect("create docs");
|
||||
let docs = AbsolutePathBuf::from_absolute_path(&docs).expect("absolute docs");
|
||||
let policy = FileSystemSandboxPolicy::restricted(vec![
|
||||
codex_protocol::permissions::FileSystemSandboxEntry {
|
||||
path: codex_protocol::permissions::FileSystemPath::Special {
|
||||
value: codex_protocol::permissions::FileSystemSpecialPath::project_roots(
|
||||
/*subpath*/ None,
|
||||
),
|
||||
},
|
||||
access: codex_protocol::permissions::FileSystemAccessMode::Write,
|
||||
missing_path_behavior: None,
|
||||
},
|
||||
codex_protocol::permissions::FileSystemSandboxEntry {
|
||||
path: docs.into(),
|
||||
access: codex_protocol::permissions::FileSystemAccessMode::Read,
|
||||
missing_path_behavior: None,
|
||||
},
|
||||
]);
|
||||
|
||||
assert!(
|
||||
policy.needs_direct_runtime_enforcement(NetworkSandboxPolicy::Restricted, temp_dir.path(),)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn root_write_read_only_carveout_requires_direct_runtime_enforcement() {
|
||||
let temp_dir = tempfile::TempDir::new().expect("tempdir");
|
||||
let docs = temp_dir.path().join("docs");
|
||||
std::fs::create_dir_all(&docs).expect("create docs");
|
||||
let docs = AbsolutePathBuf::from_absolute_path(&docs).expect("absolute docs");
|
||||
let policy = FileSystemSandboxPolicy::restricted(vec![
|
||||
codex_protocol::permissions::FileSystemSandboxEntry {
|
||||
path: codex_protocol::permissions::FileSystemPath::Special {
|
||||
value: codex_protocol::permissions::FileSystemSpecialPath::Root,
|
||||
},
|
||||
access: codex_protocol::permissions::FileSystemAccessMode::Write,
|
||||
missing_path_behavior: None,
|
||||
},
|
||||
codex_protocol::permissions::FileSystemSandboxEntry {
|
||||
path: docs.into(),
|
||||
access: codex_protocol::permissions::FileSystemAccessMode::Read,
|
||||
missing_path_behavior: None,
|
||||
},
|
||||
]);
|
||||
|
||||
assert!(
|
||||
policy.needs_direct_runtime_enforcement(NetworkSandboxPolicy::Restricted, temp_dir.path(),)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_proxy_preflight_argv_unshares_network() {
|
||||
let mode = bwrap_network_mode(
|
||||
NetworkSandboxPolicy::Enabled,
|
||||
/*allow_network_for_proxy*/ true,
|
||||
);
|
||||
let argv = build_preflight_bwrap_argv(BwrapOptions {
|
||||
network_mode: mode,
|
||||
..Default::default()
|
||||
})
|
||||
.expect("build preflight argv")
|
||||
.args;
|
||||
assert!(argv.iter().any(|arg| arg == "--"));
|
||||
assert!(argv.iter().any(|arg| arg == "--unshare-net"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proc_mount_preflight_does_not_bind_the_full_filesystem() {
|
||||
let argv = build_preflight_bwrap_argv(BwrapOptions::default())
|
||||
.expect("build preflight argv")
|
||||
.args;
|
||||
|
||||
assert!(argv.windows(2).any(|window| window == ["--tmpfs", "/"]));
|
||||
assert!(argv.windows(2).any(|window| window == ["--proc", "/proc"]));
|
||||
assert!(
|
||||
!argv
|
||||
.windows(3)
|
||||
.any(|window| window == ["--ro-bind", "/", "/"])
|
||||
);
|
||||
assert!(!argv.windows(3).any(|window| window == ["--bind", "/", "/"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proc_mount_preflight_preserves_wsl_masks() {
|
||||
let argv = build_preflight_bwrap_argv(BwrapOptions {
|
||||
mask_wsl_interop: true,
|
||||
mask_wslg_distro: true,
|
||||
..Default::default()
|
||||
})
|
||||
.expect("build WSL preflight argv")
|
||||
.args;
|
||||
|
||||
assert!(argv.windows(2).any(|window| window == ["--proc", "/proc"]));
|
||||
assert!(
|
||||
argv.windows(2)
|
||||
.any(|window| window == ["--tmpfs", WSL_INTEROP_DIR])
|
||||
);
|
||||
assert!(argv.windows(6).any(|window| {
|
||||
window
|
||||
== [
|
||||
"--perms",
|
||||
"000",
|
||||
"--tmpfs",
|
||||
WSLG_DISTRO_ROOT,
|
||||
"--remount-ro",
|
||||
WSLG_DISTRO_ROOT,
|
||||
]
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_synthetic_mount_targets_removes_only_empty_mount_targets() {
|
||||
let temp_dir = tempfile::TempDir::new().expect("tempdir");
|
||||
let empty_file = temp_dir.path().join(".git");
|
||||
let empty_dir = temp_dir.path().join(".agents");
|
||||
let non_empty_file = temp_dir.path().join("non-empty");
|
||||
let missing_file = temp_dir.path().join(".missing");
|
||||
std::fs::write(&empty_file, "").expect("write empty file");
|
||||
std::fs::create_dir(&empty_dir).expect("create empty dir");
|
||||
std::fs::write(&non_empty_file, "keep").expect("write nonempty file");
|
||||
|
||||
let registrations = register_synthetic_mount_targets(&[
|
||||
crate::bwrap::SyntheticMountTarget::missing(&empty_file),
|
||||
crate::bwrap::SyntheticMountTarget::missing_empty_directory(&empty_dir),
|
||||
crate::bwrap::SyntheticMountTarget::missing(&non_empty_file),
|
||||
crate::bwrap::SyntheticMountTarget::missing(&missing_file),
|
||||
]);
|
||||
cleanup_synthetic_mount_targets(®istrations);
|
||||
|
||||
assert!(!empty_file.exists());
|
||||
assert!(!empty_dir.exists());
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&non_empty_file).expect("read nonempty file"),
|
||||
"keep"
|
||||
);
|
||||
assert!(!missing_file.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn synthetic_mount_registry_root_is_unique_to_effective_user() {
|
||||
let effective_uid = unsafe { libc::geteuid() };
|
||||
assert_eq!(
|
||||
synthetic_mount_registry_root(),
|
||||
std::env::temp_dir()
|
||||
.canonicalize()
|
||||
.expect("resolve temp directory")
|
||||
.join(format!(
|
||||
"codex-bwrap-synthetic-mount-targets-{effective_uid}"
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_synthetic_mount_targets_waits_for_other_active_registrations() {
|
||||
let temp_dir = tempfile::TempDir::new().expect("tempdir");
|
||||
let empty_dir = temp_dir.path().join(".git");
|
||||
std::fs::create_dir(&empty_dir).expect("create empty dir");
|
||||
let target = crate::bwrap::SyntheticMountTarget::missing_empty_directory(&empty_dir);
|
||||
|
||||
let registrations = register_synthetic_mount_targets(std::slice::from_ref(&target));
|
||||
let active_marker = registrations[0].marker_dir.join("1");
|
||||
std::fs::write(&active_marker, "").expect("write active marker");
|
||||
|
||||
cleanup_synthetic_mount_targets(®istrations);
|
||||
assert!(empty_dir.exists());
|
||||
|
||||
std::fs::remove_file(active_marker).expect("remove active marker");
|
||||
let registrations = register_synthetic_mount_targets(std::slice::from_ref(&target));
|
||||
cleanup_synthetic_mount_targets(®istrations);
|
||||
|
||||
assert!(!empty_dir.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_synthetic_mount_targets_removes_transient_file_after_concurrent_owner_exits() {
|
||||
let temp_dir = tempfile::TempDir::new().expect("tempdir");
|
||||
let empty_file = temp_dir.path().join(".git");
|
||||
let first_target = crate::bwrap::SyntheticMountTarget::missing(&empty_file);
|
||||
|
||||
let first_registrations = register_synthetic_mount_targets(&[first_target]);
|
||||
std::fs::write(&empty_file, "").expect("write transient empty file");
|
||||
let active_marker = first_registrations[0].marker_dir.join("1");
|
||||
std::fs::write(&active_marker, SYNTHETIC_MOUNT_MARKER_SYNTHETIC).expect("write active marker");
|
||||
let metadata = std::fs::symlink_metadata(&empty_file).expect("stat empty file");
|
||||
let second_target =
|
||||
crate::bwrap::SyntheticMountTarget::existing_empty_file(&empty_file, &metadata);
|
||||
let second_registrations = register_synthetic_mount_targets(&[second_target]);
|
||||
|
||||
cleanup_synthetic_mount_targets(&first_registrations);
|
||||
assert!(empty_file.exists());
|
||||
|
||||
std::fs::remove_file(active_marker).expect("remove active marker");
|
||||
cleanup_synthetic_mount_targets(&second_registrations);
|
||||
|
||||
assert!(!empty_file.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cleanup_synthetic_mount_targets_preserves_real_pre_existing_empty_file() {
|
||||
let temp_dir = tempfile::TempDir::new().expect("tempdir");
|
||||
let empty_file = temp_dir.path().join(".git");
|
||||
std::fs::write(&empty_file, "").expect("write pre-existing empty file");
|
||||
let metadata = std::fs::symlink_metadata(&empty_file).expect("stat empty file");
|
||||
let first_target =
|
||||
crate::bwrap::SyntheticMountTarget::existing_empty_file(&empty_file, &metadata);
|
||||
let second_target =
|
||||
crate::bwrap::SyntheticMountTarget::existing_empty_file(&empty_file, &metadata);
|
||||
|
||||
let first_registrations = register_synthetic_mount_targets(&[first_target]);
|
||||
let second_registrations = register_synthetic_mount_targets(&[second_target]);
|
||||
|
||||
cleanup_synthetic_mount_targets(&first_registrations);
|
||||
cleanup_synthetic_mount_targets(&second_registrations);
|
||||
|
||||
assert!(empty_file.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bwrap_signal_forwarder_terminates_child_and_keeps_parent_alive() {
|
||||
let supervisor_pid = unsafe { libc::fork() };
|
||||
assert!(supervisor_pid >= 0, "failed to fork supervisor");
|
||||
|
||||
if supervisor_pid == 0 {
|
||||
run_bwrap_signal_forwarder_test_supervisor();
|
||||
}
|
||||
|
||||
let status = wait_for_bwrap_child(supervisor_pid);
|
||||
assert!(libc::WIFEXITED(status), "supervisor status: {status}");
|
||||
assert_eq!(libc::WEXITSTATUS(status), 0);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn run_bwrap_signal_forwarder_test_supervisor() -> ! {
|
||||
let child_pid = unsafe { libc::fork() };
|
||||
if child_pid < 0 {
|
||||
unsafe {
|
||||
libc::_exit(2);
|
||||
}
|
||||
}
|
||||
|
||||
if child_pid == 0 {
|
||||
loop {
|
||||
unsafe {
|
||||
libc::pause();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
install_bwrap_signal_forwarders(child_pid);
|
||||
unsafe {
|
||||
libc::raise(libc::SIGTERM);
|
||||
}
|
||||
|
||||
let status = wait_for_bwrap_child(child_pid);
|
||||
let child_terminated_by_sigterm =
|
||||
libc::WIFSIGNALED(status) && libc::WTERMSIG(status) == libc::SIGTERM;
|
||||
unsafe {
|
||||
libc::_exit(if child_terminated_by_sigterm { 0 } else { 1 });
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_proxy_inner_command_includes_route_spec() {
|
||||
let permission_profile = read_only_permission_profile();
|
||||
for managed_network in [
|
||||
ManagedNetworkSandboxContext::default(),
|
||||
ManagedNetworkSandboxContext {
|
||||
loopback_ports: vec![8080, 9090],
|
||||
allow_local_binding: true,
|
||||
allow_unix_sockets: vec!["/tmp/daemon.sock".to_string()],
|
||||
dangerously_allow_all_unix_sockets: true,
|
||||
},
|
||||
] {
|
||||
let args = build_inner_seccomp_command(InnerSeccompCommandArgs {
|
||||
sandbox_policy_cwd: Path::new("/tmp"),
|
||||
command_cwd: Some(Path::new("/tmp/link")),
|
||||
permission_profile: &permission_profile,
|
||||
managed_network: Some(managed_network.clone()),
|
||||
proxy_route_spec: Some("{\"routes\":[]}".to_string()),
|
||||
command: vec!["/bin/true".to_string()],
|
||||
});
|
||||
|
||||
assert!(args.iter().any(|arg| arg == "--proxy-route-spec"));
|
||||
assert!(args.iter().any(|arg| arg == "{\"routes\":[]}"));
|
||||
let parsed = LinuxSandboxCommand::try_parse_from(args)
|
||||
.expect("inner command should preserve the managed network policy");
|
||||
assert_eq!(parsed.managed_network, Some(managed_network));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_network_policy_alone_enables_proxy_mode() {
|
||||
let parsed = LinuxSandboxCommand::try_parse_from([
|
||||
"codex-linux-sandbox",
|
||||
"--sandbox-policy-cwd",
|
||||
"/tmp",
|
||||
"--managed-network",
|
||||
"{}",
|
||||
"--",
|
||||
"/bin/true",
|
||||
])
|
||||
.expect("managed network context should enable proxy mode on its own");
|
||||
assert_eq!(
|
||||
parsed.managed_network,
|
||||
Some(ManagedNetworkSandboxContext::default())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_managed_network_policy_is_rejected() {
|
||||
let error = LinuxSandboxCommand::try_parse_from([
|
||||
"codex-linux-sandbox",
|
||||
"--sandbox-policy-cwd",
|
||||
"/tmp",
|
||||
"--managed-network",
|
||||
"{\"dangerouslyAllowAllUnixSockets\":\"true\"}",
|
||||
"--",
|
||||
"/bin/true",
|
||||
])
|
||||
.expect_err("managed network policy should reject a non-boolean grant");
|
||||
assert_eq!(error.kind(), clap::error::ErrorKind::ValueValidation);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inner_command_includes_permission_profile_flag() {
|
||||
let permission_profile = read_only_permission_profile();
|
||||
let args = build_inner_seccomp_command(InnerSeccompCommandArgs {
|
||||
sandbox_policy_cwd: Path::new("/tmp"),
|
||||
command_cwd: Some(Path::new("/tmp/link")),
|
||||
permission_profile: &permission_profile,
|
||||
managed_network: None,
|
||||
proxy_route_spec: None,
|
||||
command: vec!["/bin/true".to_string()],
|
||||
});
|
||||
|
||||
assert!(args.iter().any(|arg| arg == "--permission-profile"));
|
||||
assert!(
|
||||
args.windows(2)
|
||||
.any(|window| { window == ["--command-cwd", "/tmp/link"] })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_managed_inner_command_omits_route_spec() {
|
||||
let permission_profile = read_only_permission_profile();
|
||||
let args = build_inner_seccomp_command(InnerSeccompCommandArgs {
|
||||
sandbox_policy_cwd: Path::new("/tmp"),
|
||||
command_cwd: Some(Path::new("/tmp/link")),
|
||||
permission_profile: &permission_profile,
|
||||
managed_network: None,
|
||||
proxy_route_spec: None,
|
||||
command: vec!["/bin/true".to_string()],
|
||||
});
|
||||
|
||||
assert!(!args.iter().any(|arg| arg == "--proxy-route-spec"));
|
||||
let parsed = LinuxSandboxCommand::try_parse_from(args)
|
||||
.expect("unmanaged inner command should preserve ordinary sandbox mode");
|
||||
assert_eq!(parsed.managed_network, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_proxy_inner_command_requires_route_spec() {
|
||||
let result = std::panic::catch_unwind(|| {
|
||||
let permission_profile = read_only_permission_profile();
|
||||
build_inner_seccomp_command(InnerSeccompCommandArgs {
|
||||
sandbox_policy_cwd: Path::new("/tmp"),
|
||||
command_cwd: Some(Path::new("/tmp/link")),
|
||||
permission_profile: &permission_profile,
|
||||
managed_network: Some(ManagedNetworkSandboxContext::default()),
|
||||
proxy_route_spec: None,
|
||||
command: vec!["/bin/true".to_string()],
|
||||
})
|
||||
});
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_permission_profile_derives_runtime_policies() {
|
||||
let permission_profile = read_only_permission_profile();
|
||||
let resolved = resolve_permission_profile(Some(permission_profile.clone()))
|
||||
.expect("profile should resolve");
|
||||
|
||||
assert_eq!(resolved.permission_profile, permission_profile);
|
||||
assert_eq!(
|
||||
resolved.file_system_sandbox_policy,
|
||||
read_only_file_system_policy()
|
||||
);
|
||||
assert_eq!(
|
||||
resolved.network_sandbox_policy,
|
||||
NetworkSandboxPolicy::Restricted
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_permission_profile_preserves_direct_runtime_profile() {
|
||||
let temp_dir = tempfile::TempDir::new().expect("tempdir");
|
||||
let docs = temp_dir.path().join("docs");
|
||||
std::fs::create_dir_all(&docs).expect("create docs");
|
||||
let docs = AbsolutePathBuf::from_absolute_path(&docs).expect("absolute docs");
|
||||
let file_system_sandbox_policy = FileSystemSandboxPolicy::restricted(vec![
|
||||
codex_protocol::permissions::FileSystemSandboxEntry {
|
||||
path: codex_protocol::permissions::FileSystemPath::Special {
|
||||
value: codex_protocol::permissions::FileSystemSpecialPath::Root,
|
||||
},
|
||||
access: codex_protocol::permissions::FileSystemAccessMode::Read,
|
||||
missing_path_behavior: None,
|
||||
},
|
||||
codex_protocol::permissions::FileSystemSandboxEntry {
|
||||
path: docs.into(),
|
||||
access: codex_protocol::permissions::FileSystemAccessMode::Write,
|
||||
missing_path_behavior: None,
|
||||
},
|
||||
]);
|
||||
let permission_profile = PermissionProfile::from_runtime_permissions(
|
||||
&file_system_sandbox_policy,
|
||||
NetworkSandboxPolicy::Restricted,
|
||||
);
|
||||
let resolved = resolve_permission_profile(Some(permission_profile.clone()))
|
||||
.expect("profile should resolve");
|
||||
|
||||
assert_eq!(resolved.permission_profile, permission_profile);
|
||||
assert_eq!(
|
||||
resolved.file_system_sandbox_policy,
|
||||
file_system_sandbox_policy
|
||||
);
|
||||
assert_eq!(
|
||||
resolved.network_sandbox_policy,
|
||||
NetworkSandboxPolicy::Restricted
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_permission_profile_rejects_missing_configuration() {
|
||||
let err = resolve_permission_profile(/*permission_profile*/ None)
|
||||
.expect_err("missing profile should fail");
|
||||
|
||||
assert_eq!(err, ResolvePermissionProfileError::MissingConfiguration);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_seccomp_then_exec_with_legacy_landlock_panics() {
|
||||
let result = std::panic::catch_unwind(|| {
|
||||
ensure_inner_stage_mode_is_valid(
|
||||
/*apply_seccomp_then_exec*/ true, /*use_legacy_landlock*/ true,
|
||||
)
|
||||
});
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "filesystem-restricted execution requires bubblewrap")]
|
||||
fn legacy_landlock_cannot_bypass_daemon_socket_isolation() {
|
||||
ensure_legacy_landlock_mode_supports_policy(
|
||||
/*use_legacy_landlock*/ true,
|
||||
&read_only_file_system_policy(),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_inner_stage_modes_do_not_panic() {
|
||||
ensure_inner_stage_mode_is_valid(
|
||||
/*apply_seccomp_then_exec*/ false, /*use_legacy_landlock*/ false,
|
||||
);
|
||||
ensure_inner_stage_mode_is_valid(
|
||||
/*apply_seccomp_then_exec*/ false, /*use_legacy_landlock*/ true,
|
||||
);
|
||||
ensure_inner_stage_mode_is_valid(
|
||||
/*apply_seccomp_then_exec*/ true, /*use_legacy_landlock*/ false,
|
||||
);
|
||||
}
|
||||
6
codex-rs/linux-sandbox/src/main.rs
Normal file
6
codex-rs/linux-sandbox/src/main.rs
Normal file
@@ -0,0 +1,6 @@
|
||||
/// Note that the cwd, env, and command args are preserved in the ultimate call
|
||||
/// to `execv`, so the caller is responsible for ensuring those values are
|
||||
/// correct.
|
||||
fn main() -> ! {
|
||||
codex_linux_sandbox::run_main()
|
||||
}
|
||||
227
codex-rs/linux-sandbox/src/proxy_lifecycle.rs
Normal file
227
codex-rs/linux-sandbox/src/proxy_lifecycle.rs
Normal file
@@ -0,0 +1,227 @@
|
||||
//! Manage privileged bridge processes and transfer their loopback TCP listeners.
|
||||
//!
|
||||
//! Received descriptors are CLOEXEC and owned even when validation rejects them.
|
||||
//! Shape validation does not authenticate the sender: the caller must retain exclusive
|
||||
//! control of the anonymous channel and close bootstrap descriptors before untrusted execution.
|
||||
|
||||
use rustix::io::retry_on_intr;
|
||||
use rustix::net::RecvAncillaryBuffer;
|
||||
use rustix::net::RecvAncillaryMessage;
|
||||
use rustix::net::RecvFlags;
|
||||
use rustix::net::ReturnFlags;
|
||||
use rustix::net::SendAncillaryBuffer;
|
||||
use rustix::net::SendAncillaryMessage;
|
||||
use rustix::net::SendFlags;
|
||||
use rustix::net::SocketType;
|
||||
use rustix::net::ipproto;
|
||||
use rustix::net::sockopt;
|
||||
use std::io;
|
||||
use std::io::IoSlice;
|
||||
use std::io::IoSliceMut;
|
||||
use std::mem::MaybeUninit;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::net::SocketAddr;
|
||||
use std::net::TcpListener;
|
||||
use std::os::fd::AsFd;
|
||||
use std::os::fd::AsRawFd;
|
||||
use std::os::fd::FromRawFd;
|
||||
use std::os::fd::OwnedFd;
|
||||
use std::os::unix::net::UnixStream;
|
||||
|
||||
const LISTENER_MESSAGE: u8 = 1;
|
||||
|
||||
pub(crate) fn send_listener(channel: &UnixStream, listener: &TcpListener) -> io::Result<()> {
|
||||
let descriptors = [listener.as_fd()];
|
||||
let mut space = [MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(1))];
|
||||
let mut control = SendAncillaryBuffer::new(&mut space);
|
||||
if !control.push(SendAncillaryMessage::ScmRights(&descriptors)) {
|
||||
return Err(io::Error::other("missing proxy listener control header"));
|
||||
}
|
||||
// rustix surfaces EINTR on both its libc and raw-syscall backends.
|
||||
// Retry interrupted sends so a handled signal does not abort the handoff.
|
||||
let sent = retry_on_intr(|| {
|
||||
rustix::net::sendmsg(
|
||||
channel,
|
||||
&[IoSlice::new(&[LISTENER_MESSAGE])],
|
||||
&mut control,
|
||||
SendFlags::NOSIGNAL,
|
||||
)
|
||||
})?;
|
||||
if sent != 1 {
|
||||
return Err(io::Error::other("failed to transfer proxy listener"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn receive_listener(channel: &UnixStream) -> io::Result<TcpListener> {
|
||||
let mut byte = [0_u8];
|
||||
let mut space = [MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(1))];
|
||||
let mut control = RecvAncillaryBuffer::new(&mut space);
|
||||
// rustix surfaces EINTR on both its libc and raw-syscall backends.
|
||||
// Retry interrupted receives so a handled signal does not abort the handoff.
|
||||
let message = retry_on_intr(|| {
|
||||
rustix::net::recvmsg(
|
||||
channel,
|
||||
&mut [IoSliceMut::new(&mut byte)],
|
||||
&mut control,
|
||||
RecvFlags::CMSG_CLOEXEC,
|
||||
)
|
||||
})?;
|
||||
|
||||
// Alignment headroom can fit extra descriptors. Own all of them before checking
|
||||
// the count; rustix also closes any descriptors left undrained on error paths.
|
||||
let mut descriptors = Vec::new();
|
||||
let mut unexpected_message = false;
|
||||
for ancillary in control.drain() {
|
||||
match ancillary {
|
||||
RecvAncillaryMessage::ScmRights(received) => descriptors.extend(received),
|
||||
_ => unexpected_message = true,
|
||||
}
|
||||
}
|
||||
if message.bytes != 1
|
||||
|| byte != [LISTENER_MESSAGE]
|
||||
|| message
|
||||
.flags
|
||||
.intersects(ReturnFlags::CTRUNC | ReturnFlags::TRUNC)
|
||||
|| unexpected_message
|
||||
|| descriptors.len() != 1
|
||||
{
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"invalid proxy listener handoff",
|
||||
));
|
||||
}
|
||||
|
||||
let listener = TcpListener::from(descriptors.remove(/*index*/ 0));
|
||||
if sockopt::socket_type(&listener)? != SocketType::STREAM
|
||||
|| sockopt::socket_protocol(&listener)? != Some(ipproto::TCP)
|
||||
|| !sockopt::socket_acceptconn(&listener)?
|
||||
{
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"proxy handoff requires a TCP listener",
|
||||
));
|
||||
}
|
||||
if !matches!(listener.local_addr()?, SocketAddr::V4(address)
|
||||
if *address.ip() == Ipv4Addr::LOCALHOST && address.port() != 0)
|
||||
{
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"proxy listener must be bound to IPv4 loopback",
|
||||
));
|
||||
}
|
||||
Ok(listener)
|
||||
}
|
||||
|
||||
pub(crate) fn harden_bridge_process(expected_parent_pid: libc::pid_t) -> io::Result<()> {
|
||||
detach_bridge_stdio()?;
|
||||
set_parent_death_signal(expected_parent_pid)?;
|
||||
codex_process_hardening::disable_process_dumping()
|
||||
}
|
||||
|
||||
fn set_parent_death_signal(expected_parent_pid: libc::pid_t) -> io::Result<()> {
|
||||
let res = unsafe { libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM) };
|
||||
if res != 0 {
|
||||
Err(io::Error::last_os_error())
|
||||
} else if unsafe { libc::getppid() } != expected_parent_pid {
|
||||
Err(io::Error::other("parent process already exited"))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn detach_bridge_stdio() -> io::Result<()> {
|
||||
let null_read_fd = unsafe { libc::open(c"/dev/null".as_ptr(), libc::O_RDONLY) };
|
||||
if null_read_fd < 0 {
|
||||
let err = io::Error::last_os_error();
|
||||
if unsafe { libc::fcntl(libc::STDIN_FILENO, libc::F_GETFD) } < 0 {
|
||||
return Err(err);
|
||||
}
|
||||
return redirect_bridge_output(libc::STDIN_FILENO);
|
||||
}
|
||||
|
||||
let null_write_fd = unsafe { libc::open(c"/dev/null".as_ptr(), libc::O_WRONLY) };
|
||||
if null_write_fd < 0 {
|
||||
if unsafe { libc::dup2(null_read_fd, libc::STDIN_FILENO) } < 0 {
|
||||
let err = io::Error::last_os_error();
|
||||
if null_read_fd > libc::STDERR_FILENO {
|
||||
let _ = close_fd(null_read_fd);
|
||||
}
|
||||
return Err(err);
|
||||
}
|
||||
let result = redirect_bridge_output(null_read_fd);
|
||||
if null_read_fd > libc::STDERR_FILENO {
|
||||
let _ = close_fd(null_read_fd);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
for (source_fd, stream_fd) in [
|
||||
(null_read_fd, libc::STDIN_FILENO),
|
||||
(null_write_fd, libc::STDOUT_FILENO),
|
||||
(null_write_fd, libc::STDERR_FILENO),
|
||||
] {
|
||||
if unsafe { libc::dup2(source_fd, stream_fd) } < 0 {
|
||||
let err = io::Error::last_os_error();
|
||||
if null_read_fd > libc::STDERR_FILENO {
|
||||
let _ = close_fd(null_read_fd);
|
||||
}
|
||||
if null_write_fd > libc::STDERR_FILENO {
|
||||
let _ = close_fd(null_write_fd);
|
||||
}
|
||||
return Err(err);
|
||||
}
|
||||
}
|
||||
|
||||
if null_read_fd > libc::STDERR_FILENO {
|
||||
close_fd(null_read_fd)?;
|
||||
}
|
||||
if null_write_fd > libc::STDERR_FILENO {
|
||||
close_fd(null_write_fd)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn redirect_bridge_output(source_fd: libc::c_int) -> io::Result<()> {
|
||||
for stream_fd in [libc::STDOUT_FILENO, libc::STDERR_FILENO] {
|
||||
if unsafe { libc::dup2(source_fd, stream_fd) } < 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn move_fd_above_stdio(fd: OwnedFd) -> io::Result<OwnedFd> {
|
||||
if fd.as_raw_fd() > libc::STDERR_FILENO {
|
||||
return Ok(fd);
|
||||
}
|
||||
|
||||
// SAFETY: F_DUPFD_CLOEXEC takes an integer lower bound, not a pointer;
|
||||
// `fd` owns the live descriptor throughout the call.
|
||||
let relocated_fd = unsafe {
|
||||
libc::fcntl(
|
||||
fd.as_raw_fd(),
|
||||
libc::F_DUPFD_CLOEXEC,
|
||||
libc::STDERR_FILENO + 1,
|
||||
)
|
||||
};
|
||||
if relocated_fd < 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
|
||||
// SAFETY: F_DUPFD_CLOEXEC returned a new descriptor; the original owner drops here.
|
||||
Ok(unsafe { OwnedFd::from_raw_fd(relocated_fd) })
|
||||
}
|
||||
|
||||
pub(crate) fn close_fd(fd: libc::c_int) -> io::Result<()> {
|
||||
let res = unsafe { libc::close(fd) };
|
||||
if res < 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "proxy_lifecycle_tests.rs"]
|
||||
mod tests;
|
||||
124
codex-rs/linux-sandbox/src/proxy_lifecycle_tests.rs
Normal file
124
codex-rs/linux-sandbox/src/proxy_lifecycle_tests.rs
Normal file
@@ -0,0 +1,124 @@
|
||||
//! Verify listener ownership, handoff validation, and descriptor cleanup on rejection.
|
||||
|
||||
use super::LISTENER_MESSAGE;
|
||||
use super::receive_listener;
|
||||
use super::send_listener;
|
||||
use pretty_assertions::assert_eq;
|
||||
use rustix::io::FdFlags;
|
||||
use rustix::io::fcntl_getfd;
|
||||
use rustix::net::SendAncillaryBuffer;
|
||||
use rustix::net::SendAncillaryMessage;
|
||||
use rustix::net::SendFlags;
|
||||
use std::io;
|
||||
use std::io::IoSlice;
|
||||
use std::io::Read;
|
||||
use std::io::Write;
|
||||
use std::mem::MaybeUninit;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::net::TcpListener;
|
||||
use std::net::TcpStream;
|
||||
use std::os::fd::AsFd;
|
||||
use std::os::fd::BorrowedFd;
|
||||
use std::os::unix::net::UnixStream;
|
||||
use std::time::Duration;
|
||||
use test_case::test_case;
|
||||
|
||||
#[test]
|
||||
fn transferred_listener_survives_sender_close_and_is_cloexec() -> io::Result<()> {
|
||||
let (sender, receiver) = UnixStream::pair()?;
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))?;
|
||||
let address = listener.local_addr()?;
|
||||
send_listener(&sender, &listener)?;
|
||||
drop(listener);
|
||||
drop(sender);
|
||||
|
||||
let listener = receive_listener(&receiver)?;
|
||||
let flags = fcntl_getfd(&listener)?;
|
||||
assert_eq!(
|
||||
(listener.local_addr()?, flags & FdFlags::CLOEXEC),
|
||||
(address, FdFlags::CLOEXEC)
|
||||
);
|
||||
let mut client = TcpStream::connect(address)?;
|
||||
client.write_all(b"proxy")?;
|
||||
let (mut accepted, _) = listener.accept()?;
|
||||
let mut bytes = [0; 5];
|
||||
accepted.read_exact(&mut bytes)?;
|
||||
assert_eq!(bytes, *b"proxy");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test_case(1; "non_listener")]
|
||||
#[test_case(2; "extra_descriptors")]
|
||||
// Eight descriptors exceed the receive buffer even with alignment headroom.
|
||||
#[test_case(8; "truncated_control_message")]
|
||||
fn malformed_handoff_closes_all_received_descriptors(count: usize) -> io::Result<()> {
|
||||
let (sender, receiver) = UnixStream::pair()?;
|
||||
let mut peers = Vec::new();
|
||||
let mut passed = Vec::new();
|
||||
for _ in 0..count {
|
||||
let (peer, descriptor) = UnixStream::pair()?;
|
||||
peer.set_read_timeout(Some(Duration::from_secs(/*secs*/ 1)))?;
|
||||
peers.push(peer);
|
||||
passed.push(descriptor);
|
||||
}
|
||||
let descriptors = passed.iter().map(AsFd::as_fd).collect::<Vec<_>>();
|
||||
send_descriptors(&sender, LISTENER_MESSAGE, &descriptors)?;
|
||||
drop(passed);
|
||||
assert!(receive_listener(&receiver).is_err());
|
||||
for mut peer in peers {
|
||||
assert_eq!(peer.read(&mut [0])?, 0);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_missing_descriptors_and_invalid_payloads() -> io::Result<()> {
|
||||
let (mut sender, receiver) = UnixStream::pair()?;
|
||||
sender.write_all(&[LISTENER_MESSAGE])?;
|
||||
assert!(receive_listener(&receiver).is_err());
|
||||
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))?;
|
||||
send_descriptors(&sender, /*payload*/ 0, &[listener.as_fd()])?;
|
||||
assert!(receive_listener(&receiver).is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test_case(2; "extra_descriptors")]
|
||||
#[test_case(8; "truncated_control_message")]
|
||||
fn rejects_extra_descriptors_even_when_first_is_a_listener(count: usize) -> io::Result<()> {
|
||||
let (sender, receiver) = UnixStream::pair()?;
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))?;
|
||||
send_descriptors(&sender, LISTENER_MESSAGE, &vec![listener.as_fd(); count])?;
|
||||
assert!(receive_listener(&receiver).is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_listener_bound_to_all_interfaces() -> io::Result<()> {
|
||||
let (sender, receiver) = UnixStream::pair()?;
|
||||
let listener = TcpListener::bind((Ipv4Addr::UNSPECIFIED, 0))?;
|
||||
send_listener(&sender, &listener)?;
|
||||
assert!(receive_listener(&receiver).is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn send_descriptors(
|
||||
channel: &UnixStream,
|
||||
payload: u8,
|
||||
descriptors: &[BorrowedFd<'_>],
|
||||
) -> io::Result<()> {
|
||||
let message = SendAncillaryMessage::ScmRights(descriptors);
|
||||
let mut space = vec![MaybeUninit::uninit(); message.size()];
|
||||
let mut control = SendAncillaryBuffer::new(&mut space);
|
||||
assert!(control.push(message));
|
||||
let sent = rustix::io::retry_on_intr(|| {
|
||||
rustix::net::sendmsg(
|
||||
channel,
|
||||
&[IoSlice::new(&[payload])],
|
||||
&mut control,
|
||||
SendFlags::NOSIGNAL,
|
||||
)
|
||||
})?;
|
||||
assert_eq!(sent, 1);
|
||||
Ok(())
|
||||
}
|
||||
491
codex-rs/linux-sandbox/src/proxy_routing.rs
Normal file
491
codex-rs/linux-sandbox/src/proxy_routing.rs
Normal file
@@ -0,0 +1,491 @@
|
||||
use crate::proxy_lifecycle::close_fd;
|
||||
use crate::proxy_lifecycle::harden_bridge_process;
|
||||
use crate::proxy_lifecycle::move_fd_above_stdio;
|
||||
use crate::proxy_lifecycle::receive_listener;
|
||||
use crate::proxy_lifecycle::send_listener;
|
||||
use codex_network_proxy::PROXY_ATTRIBUTION_TOKEN_ENV_KEY;
|
||||
use codex_network_proxy::write_attribution_frame;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::HashMap;
|
||||
use std::fs::File;
|
||||
use std::io;
|
||||
use std::io::Read;
|
||||
use std::io::Write;
|
||||
use std::net::IpAddr;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::net::Shutdown;
|
||||
use std::net::SocketAddr;
|
||||
use std::net::TcpListener;
|
||||
use std::net::TcpStream;
|
||||
use std::os::fd::AsRawFd;
|
||||
use std::os::fd::FromRawFd;
|
||||
use std::os::fd::OwnedFd;
|
||||
use std::os::unix::net::UnixStream;
|
||||
use std::time::Duration;
|
||||
use url::Url;
|
||||
|
||||
const PROXY_ENV_KEYS: &[&str] = &[
|
||||
"HTTP_PROXY",
|
||||
"HTTPS_PROXY",
|
||||
"WS_PROXY",
|
||||
"WSS_PROXY",
|
||||
"ALL_PROXY",
|
||||
"FTP_PROXY",
|
||||
"YARN_HTTP_PROXY",
|
||||
"YARN_HTTPS_PROXY",
|
||||
"NPM_CONFIG_HTTP_PROXY",
|
||||
"NPM_CONFIG_HTTPS_PROXY",
|
||||
"NPM_CONFIG_PROXY",
|
||||
"BUNDLE_HTTP_PROXY",
|
||||
"BUNDLE_HTTPS_PROXY",
|
||||
"PIP_PROXY",
|
||||
"DOCKER_HTTP_PROXY",
|
||||
"DOCKER_HTTPS_PROXY",
|
||||
];
|
||||
|
||||
const HOST_BRIDGE_READY: u8 = 1;
|
||||
const LOOPBACK_INTERFACE_NAME: &[u8] = b"lo";
|
||||
const HANDOFF_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 30);
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub(crate) struct ProxyRouteSpec {
|
||||
routes: Vec<ProxyRouteEntry>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
struct ProxyRouteEntry {
|
||||
env_key: String,
|
||||
control_fd: libc::c_int,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
struct PlannedProxyRoute {
|
||||
env_key: String,
|
||||
endpoint: SocketAddr,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
struct ProxyRoutePlan {
|
||||
routes: Vec<PlannedProxyRoute>,
|
||||
has_proxy_config: bool,
|
||||
}
|
||||
|
||||
pub(crate) fn prepare_host_proxy_route_spec() -> io::Result<(String, Vec<File>)> {
|
||||
let (attribution_token, plan) = extract_attribution_token_and_plan(std::env::vars().collect());
|
||||
// SAFETY: the sandbox helper is single-threaded here, before it forks bridge workers or
|
||||
// executes the user command.
|
||||
unsafe {
|
||||
std::env::remove_var(PROXY_ATTRIBUTION_TOKEN_ENV_KEY);
|
||||
}
|
||||
|
||||
if plan.routes.is_empty() {
|
||||
let message = if plan.has_proxy_config {
|
||||
"managed proxy mode requires parseable loopback proxy endpoints"
|
||||
} else {
|
||||
"managed proxy mode requires proxy environment variables"
|
||||
};
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, message));
|
||||
}
|
||||
|
||||
let mut control_by_endpoint = BTreeMap::new();
|
||||
for route in &plan.routes {
|
||||
if control_by_endpoint.contains_key(&route.endpoint) {
|
||||
continue;
|
||||
}
|
||||
let control = spawn_host_bridge(
|
||||
route.endpoint,
|
||||
attribution_token.as_deref(),
|
||||
&mut control_by_endpoint,
|
||||
)?;
|
||||
control_by_endpoint.insert(route.endpoint, control);
|
||||
}
|
||||
|
||||
let mut routes = Vec::with_capacity(plan.routes.len());
|
||||
for route in plan.routes {
|
||||
let Some(control) = control_by_endpoint.get(&route.endpoint) else {
|
||||
return Err(io::Error::other(format!(
|
||||
"missing bootstrap channel for endpoint {}",
|
||||
route.endpoint
|
||||
)));
|
||||
};
|
||||
routes.push(ProxyRouteEntry {
|
||||
env_key: route.env_key,
|
||||
control_fd: control.as_raw_fd(),
|
||||
});
|
||||
}
|
||||
|
||||
let spec = serde_json::to_string(&ProxyRouteSpec { routes }).map_err(io::Error::other)?;
|
||||
Ok((spec, control_by_endpoint.into_values().collect()))
|
||||
}
|
||||
|
||||
fn extract_attribution_token_and_plan(
|
||||
mut env: HashMap<String, String>,
|
||||
) -> (Option<String>, ProxyRoutePlan) {
|
||||
let attribution_token = env.remove(PROXY_ATTRIBUTION_TOKEN_ENV_KEY);
|
||||
let plan = plan_proxy_routes(&env);
|
||||
(attribution_token, plan)
|
||||
}
|
||||
|
||||
pub(crate) fn activate_proxy_routes_in_netns(serialized_spec: &str) -> io::Result<()> {
|
||||
let spec: ProxyRouteSpec = serde_json::from_str(serialized_spec).map_err(io::Error::other)?;
|
||||
|
||||
if spec.routes.is_empty() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"proxy routing spec contained no routes",
|
||||
));
|
||||
}
|
||||
|
||||
let mut local_port_by_control = BTreeMap::new();
|
||||
for route in &spec.routes {
|
||||
if local_port_by_control.contains_key(&route.control_fd) {
|
||||
continue;
|
||||
}
|
||||
if route.control_fd <= libc::STDERR_FILENO {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"proxy bootstrap channel must not use standard descriptors",
|
||||
));
|
||||
}
|
||||
// SAFETY: F_GETFD takes only a descriptor, with no pointer arguments;
|
||||
// an invalid inherited descriptor returns EBADF.
|
||||
let flags = unsafe { libc::fcntl(route.control_fd, libc::F_GETFD) };
|
||||
if flags < 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
// SAFETY: the outer helper left this descriptor open across exec, which
|
||||
// discarded its Rust owner. F_GETFD above confirmed it is still valid.
|
||||
// The map ensures each descriptor is claimed once, even for proxy aliases.
|
||||
let mut control = unsafe { UnixStream::from_raw_fd(route.control_fd) };
|
||||
// SAFETY: F_SETFD takes integer flags, not a pointer; `control` owns the
|
||||
// live descriptor throughout the call.
|
||||
if unsafe { libc::fcntl(control.as_raw_fd(), libc::F_SETFD, flags | libc::FD_CLOEXEC) } < 0
|
||||
{
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
control.set_read_timeout(Some(HANDOFF_TIMEOUT))?;
|
||||
let listener = bind_local_loopback_listener()?;
|
||||
let local_port = listener.local_addr()?.port();
|
||||
send_listener(&control, &listener)?;
|
||||
let mut ready = [0_u8; 1];
|
||||
control.read_exact(&mut ready)?;
|
||||
if ready != [HOST_BRIDGE_READY] {
|
||||
return Err(io::Error::other("host bridge did not accept its listener"));
|
||||
}
|
||||
// Loop scope closes both descriptors, leaving only the host's listener.
|
||||
// Neither can reach the namespace reaper or the untrusted command.
|
||||
local_port_by_control.insert(route.control_fd, local_port);
|
||||
}
|
||||
|
||||
for route in spec.routes {
|
||||
let Some(local_port) = local_port_by_control.get(&route.control_fd) else {
|
||||
return Err(io::Error::other("missing proxy listener port"));
|
||||
};
|
||||
let original_value = std::env::var(&route.env_key).map_err(|_| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::NotFound,
|
||||
format!("missing proxy env key {}", route.env_key),
|
||||
)
|
||||
})?;
|
||||
let Some(rewritten) = rewrite_proxy_env_value(&original_value, *local_port) else {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!("could not rewrite proxy URL for env key {}", route.env_key),
|
||||
));
|
||||
};
|
||||
// SAFETY: this helper process is single-threaded at this point, and
|
||||
// env mutation happens before execing the user command.
|
||||
unsafe {
|
||||
std::env::set_var(route.env_key, rewritten);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn plan_proxy_routes(env: &HashMap<String, String>) -> ProxyRoutePlan {
|
||||
let mut routes = Vec::new();
|
||||
let mut has_proxy_config = false;
|
||||
|
||||
for (key, value) in env {
|
||||
if !is_proxy_env_key(key) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let trimmed = value.trim();
|
||||
if trimmed.is_empty() {
|
||||
continue;
|
||||
}
|
||||
has_proxy_config = true;
|
||||
|
||||
let Some(endpoint) = parse_loopback_proxy_endpoint(trimmed) else {
|
||||
continue;
|
||||
};
|
||||
routes.push(PlannedProxyRoute {
|
||||
env_key: key.clone(),
|
||||
endpoint,
|
||||
});
|
||||
}
|
||||
|
||||
routes.sort_by(|left, right| left.env_key.cmp(&right.env_key));
|
||||
ProxyRoutePlan {
|
||||
routes,
|
||||
has_proxy_config,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_proxy_env_key(key: &str) -> bool {
|
||||
let upper = key.to_ascii_uppercase();
|
||||
PROXY_ENV_KEYS.contains(&upper.as_str())
|
||||
}
|
||||
|
||||
fn parse_loopback_proxy_endpoint(proxy_url: &str) -> Option<SocketAddr> {
|
||||
let candidate = if proxy_url.contains("://") {
|
||||
proxy_url.to_string()
|
||||
} else {
|
||||
format!("http://{proxy_url}")
|
||||
};
|
||||
|
||||
let parsed = Url::parse(&candidate).ok()?;
|
||||
let host = parsed.host_str()?;
|
||||
if !is_loopback_host(host) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let scheme = parsed.scheme().to_ascii_lowercase();
|
||||
let port = parsed
|
||||
.port()
|
||||
.unwrap_or_else(|| default_proxy_port(scheme.as_str()));
|
||||
if port == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let ip = if host.eq_ignore_ascii_case("localhost") {
|
||||
IpAddr::V4(Ipv4Addr::LOCALHOST)
|
||||
} else {
|
||||
host.parse::<IpAddr>().ok()?
|
||||
};
|
||||
if ip.is_loopback() {
|
||||
Some(SocketAddr::new(ip, port))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn is_loopback_host(host: &str) -> bool {
|
||||
host.eq_ignore_ascii_case("localhost") || host == "127.0.0.1" || host == "::1"
|
||||
}
|
||||
|
||||
fn default_proxy_port(scheme: &str) -> u16 {
|
||||
match scheme {
|
||||
"https" => 443,
|
||||
"socks5" | "socks5h" | "socks4" | "socks4a" => 1080,
|
||||
_ => 80,
|
||||
}
|
||||
}
|
||||
|
||||
fn rewrite_proxy_env_value(proxy_url: &str, local_port: u16) -> Option<String> {
|
||||
let had_scheme = proxy_url.contains("://");
|
||||
let candidate = if had_scheme {
|
||||
proxy_url.to_string()
|
||||
} else {
|
||||
format!("http://{proxy_url}")
|
||||
};
|
||||
|
||||
let mut parsed = Url::parse(&candidate).ok()?;
|
||||
parsed.set_host(Some("127.0.0.1")).ok()?;
|
||||
parsed.set_port(Some(local_port)).ok()?;
|
||||
let mut rewritten = parsed.to_string();
|
||||
if !had_scheme {
|
||||
rewritten = rewritten
|
||||
.strip_prefix("http://")
|
||||
.unwrap_or(rewritten.as_str())
|
||||
.to_string();
|
||||
}
|
||||
if !proxy_url.ends_with('/')
|
||||
&& !proxy_url.contains('?')
|
||||
&& !proxy_url.contains('#')
|
||||
&& rewritten.ends_with('/')
|
||||
{
|
||||
rewritten.pop();
|
||||
}
|
||||
Some(rewritten)
|
||||
}
|
||||
|
||||
fn spawn_host_bridge(
|
||||
endpoint: SocketAddr,
|
||||
attribution_token: Option<&str>,
|
||||
inherited_controls: &mut BTreeMap<SocketAddr, File>,
|
||||
) -> io::Result<File> {
|
||||
let (host_control, control) = UnixStream::pair()?;
|
||||
let host_control = UnixStream::from(move_fd_above_stdio(host_control.into())?);
|
||||
let mut control = UnixStream::from(move_fd_above_stdio(control.into())?);
|
||||
control.set_read_timeout(Some(HANDOFF_TIMEOUT))?;
|
||||
let parent_pid = unsafe { libc::getpid() };
|
||||
let pid = unsafe { libc::fork() };
|
||||
if pid < 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
|
||||
if pid == 0 {
|
||||
drop(control);
|
||||
// A worker must not retain another route's inner bootstrap endpoint.
|
||||
// Drop this child's inherited owners; the parent's copies are unaffected by fork.
|
||||
inherited_controls.clear();
|
||||
let result = run_host_bridge(endpoint, host_control, attribution_token, parent_pid);
|
||||
if result.is_err() {
|
||||
unsafe { libc::_exit(1) };
|
||||
}
|
||||
unsafe { libc::_exit(0) };
|
||||
}
|
||||
|
||||
drop(host_control);
|
||||
let mut ready = [0_u8; 1];
|
||||
control.read_exact(&mut ready)?;
|
||||
if ready != [HOST_BRIDGE_READY] {
|
||||
return Err(io::Error::other(
|
||||
"host bridge did not acknowledge readiness",
|
||||
));
|
||||
}
|
||||
Ok(File::from(OwnedFd::from(control)))
|
||||
}
|
||||
|
||||
fn run_host_bridge(
|
||||
endpoint: SocketAddr,
|
||||
mut control: UnixStream,
|
||||
attribution_token: Option<&str>,
|
||||
parent_pid: libc::pid_t,
|
||||
) -> io::Result<()> {
|
||||
harden_bridge_process(parent_pid)?;
|
||||
control.write_all(&[HOST_BRIDGE_READY])?;
|
||||
// The outer helper must launch bubblewrap before this listener can arrive.
|
||||
// The socket keeps its isolated network namespace even though we accept in
|
||||
// the host process; newly opened upstream sockets use our host namespace.
|
||||
let listener = receive_listener(&control)?;
|
||||
control.write_all(&[HOST_BRIDGE_READY])?;
|
||||
drop(control);
|
||||
|
||||
let attribution_token = attribution_token.map(str::to_owned);
|
||||
loop {
|
||||
let (client_stream, _) = listener.accept()?;
|
||||
let attribution_token = attribution_token.clone();
|
||||
std::thread::spawn(move || {
|
||||
let mut tcp_stream = match TcpStream::connect(endpoint) {
|
||||
Ok(stream) => stream,
|
||||
Err(_) => return,
|
||||
};
|
||||
if let Some(attribution_token) = attribution_token
|
||||
&& write_attribution_frame(&mut tcp_stream, &attribution_token).is_err()
|
||||
{
|
||||
// The shared ingress must reject unauthenticated connections; do not forward
|
||||
// application bytes if this bridge cannot prove the exec attribution first.
|
||||
return;
|
||||
}
|
||||
let _ = proxy_bidirectional(tcp_stream, client_stream);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn bind_local_loopback_listener() -> io::Result<TcpListener> {
|
||||
match TcpListener::bind((Ipv4Addr::LOCALHOST, 0)) {
|
||||
Ok(listener) => Ok(listener),
|
||||
Err(bind_err) => {
|
||||
let should_retry_after_lo_up = matches!(
|
||||
bind_err.raw_os_error(),
|
||||
Some(errno) if errno == libc::EADDRNOTAVAIL || errno == libc::ENETUNREACH
|
||||
);
|
||||
if !should_retry_after_lo_up {
|
||||
return Err(bind_err);
|
||||
}
|
||||
|
||||
ensure_loopback_interface_up()?;
|
||||
TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_loopback_interface_up() -> io::Result<()> {
|
||||
let fd = unsafe { libc::socket(libc::AF_INET, libc::SOCK_DGRAM | libc::SOCK_CLOEXEC, 0) };
|
||||
if fd < 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
|
||||
let mut ifreq = unsafe { std::mem::zeroed::<libc::ifreq>() };
|
||||
for (index, byte) in LOOPBACK_INTERFACE_NAME.iter().copied().enumerate() {
|
||||
ifreq.ifr_name[index] = byte as libc::c_char;
|
||||
}
|
||||
|
||||
let read_flags_result =
|
||||
unsafe { libc::ioctl(fd, libc::SIOCGIFFLAGS as libc::Ioctl, &mut ifreq) };
|
||||
if read_flags_result < 0 {
|
||||
let err = io::Error::last_os_error();
|
||||
let _ = close_fd(fd);
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
let current_flags = unsafe { ifreq.ifr_ifru.ifru_flags };
|
||||
let up_flag = libc::IFF_UP as libc::c_short;
|
||||
if (current_flags & up_flag) != up_flag {
|
||||
ifreq.ifr_ifru.ifru_flags = current_flags | up_flag;
|
||||
let set_flags_result =
|
||||
unsafe { libc::ioctl(fd, libc::SIOCSIFFLAGS as libc::Ioctl, &ifreq) };
|
||||
if set_flags_result < 0 {
|
||||
let err = io::Error::last_os_error();
|
||||
let _ = close_fd(fd);
|
||||
return Err(err);
|
||||
}
|
||||
}
|
||||
|
||||
let mut addr_req = unsafe { std::mem::zeroed::<libc::ifreq>() };
|
||||
for (index, byte) in LOOPBACK_INTERFACE_NAME.iter().copied().enumerate() {
|
||||
addr_req.ifr_name[index] = byte as libc::c_char;
|
||||
}
|
||||
let loopback_addr = libc::sockaddr_in {
|
||||
sin_family: libc::AF_INET as libc::sa_family_t,
|
||||
sin_port: 0,
|
||||
sin_addr: libc::in_addr {
|
||||
s_addr: libc::htonl(libc::INADDR_LOOPBACK),
|
||||
},
|
||||
sin_zero: [0; 8],
|
||||
};
|
||||
unsafe {
|
||||
addr_req.ifr_ifru.ifru_addr =
|
||||
*(&loopback_addr as *const libc::sockaddr_in as *const libc::sockaddr);
|
||||
}
|
||||
let set_addr_result = unsafe { libc::ioctl(fd, libc::SIOCSIFADDR as libc::Ioctl, &addr_req) };
|
||||
if set_addr_result < 0 {
|
||||
let err = io::Error::last_os_error();
|
||||
let allow_existing_or_immutable_addr =
|
||||
matches!(err.raw_os_error(), Some(libc::EEXIST | libc::EPERM));
|
||||
if !allow_existing_or_immutable_addr {
|
||||
let _ = close_fd(fd);
|
||||
return Err(err);
|
||||
}
|
||||
}
|
||||
|
||||
close_fd(fd)
|
||||
}
|
||||
|
||||
fn proxy_bidirectional(mut upstream: TcpStream, mut client: TcpStream) -> io::Result<()> {
|
||||
let mut upstream_reader = upstream.try_clone()?;
|
||||
let mut client_writer = client.try_clone()?;
|
||||
let upstream_to_client = std::thread::spawn(move || {
|
||||
let result = std::io::copy(&mut upstream_reader, &mut client_writer);
|
||||
let _ = client_writer.shutdown(Shutdown::Write);
|
||||
result
|
||||
});
|
||||
let client_to_upstream = std::io::copy(&mut client, &mut upstream);
|
||||
let _ = upstream.shutdown(Shutdown::Write);
|
||||
let upstream_to_client = upstream_to_client
|
||||
.join()
|
||||
.map_err(|_| io::Error::other("bridge thread panicked"))?;
|
||||
upstream_to_client?;
|
||||
client_to_upstream?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "proxy_routing_tests.rs"]
|
||||
mod tests;
|
||||
128
codex-rs/linux-sandbox/src/proxy_routing_tests.rs
Normal file
128
codex-rs/linux-sandbox/src/proxy_routing_tests.rs
Normal file
@@ -0,0 +1,128 @@
|
||||
//! Verify proxy route planning, attribution handling, and URL rewriting.
|
||||
|
||||
use super::PROXY_ATTRIBUTION_TOKEN_ENV_KEY;
|
||||
use super::ProxyRouteEntry;
|
||||
use super::ProxyRouteSpec;
|
||||
use super::default_proxy_port;
|
||||
use super::extract_attribution_token_and_plan;
|
||||
use super::is_proxy_env_key;
|
||||
use super::parse_loopback_proxy_endpoint;
|
||||
use super::plan_proxy_routes;
|
||||
use super::rewrite_proxy_env_value;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::HashMap;
|
||||
use std::net::SocketAddr;
|
||||
|
||||
#[test]
|
||||
fn recognizes_proxy_env_keys_case_insensitively() {
|
||||
assert_eq!(is_proxy_env_key("HTTP_PROXY"), true);
|
||||
assert_eq!(is_proxy_env_key("http_proxy"), true);
|
||||
assert_eq!(is_proxy_env_key("WS_PROXY"), true);
|
||||
assert_eq!(is_proxy_env_key("wss_proxy"), true);
|
||||
assert_eq!(is_proxy_env_key("PATH"), false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_loopback_proxy_endpoint() {
|
||||
let endpoint = parse_loopback_proxy_endpoint("http://127.0.0.1:43128");
|
||||
assert_eq!(
|
||||
endpoint,
|
||||
Some(
|
||||
"127.0.0.1:43128"
|
||||
.parse::<SocketAddr>()
|
||||
.expect("valid socket")
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_non_loopback_proxy_endpoint() {
|
||||
assert_eq!(
|
||||
parse_loopback_proxy_endpoint("http://example.com:3128"),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plan_proxy_routes_only_includes_valid_loopback_endpoints() {
|
||||
let mut env = HashMap::new();
|
||||
env.insert(
|
||||
"HTTP_PROXY".to_string(),
|
||||
"http://127.0.0.1:43128".to_string(),
|
||||
);
|
||||
env.insert(
|
||||
"HTTPS_PROXY".to_string(),
|
||||
"http://example.com:3128".to_string(),
|
||||
);
|
||||
env.insert("PATH".to_string(), "/usr/bin".to_string());
|
||||
|
||||
let plan = plan_proxy_routes(&env);
|
||||
assert_eq!(plan.has_proxy_config, true);
|
||||
assert_eq!(plan.routes.len(), 1);
|
||||
assert_eq!(plan.routes[0].env_key, "HTTP_PROXY");
|
||||
assert_eq!(
|
||||
plan.routes[0].endpoint,
|
||||
"127.0.0.1:43128"
|
||||
.parse::<SocketAddr>()
|
||||
.expect("valid socket")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attribution_token_is_extracted_before_proxy_route_planning() {
|
||||
let mut env = HashMap::new();
|
||||
env.insert(
|
||||
"HTTP_PROXY".to_string(),
|
||||
"http://127.0.0.1:43128".to_string(),
|
||||
);
|
||||
env.insert(
|
||||
PROXY_ATTRIBUTION_TOKEN_ENV_KEY.to_string(),
|
||||
"exec-token".to_string(),
|
||||
);
|
||||
|
||||
let (attribution_token, plan) = extract_attribution_token_and_plan(env);
|
||||
|
||||
assert_eq!(attribution_token.as_deref(), Some("exec-token"));
|
||||
assert_eq!(
|
||||
plan,
|
||||
super::ProxyRoutePlan {
|
||||
routes: vec![super::PlannedProxyRoute {
|
||||
env_key: "HTTP_PROXY".to_string(),
|
||||
endpoint: "127.0.0.1:43128"
|
||||
.parse::<SocketAddr>()
|
||||
.expect("valid socket"),
|
||||
}],
|
||||
has_proxy_config: true,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_proxy_url_to_local_loopback_port() {
|
||||
let rewritten = rewrite_proxy_env_value("socks5h://127.0.0.1:8081", /*local_port*/ 43210)
|
||||
.expect("rewritten value");
|
||||
assert_eq!(rewritten, "socks5h://127.0.0.1:43210");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_proxy_ports_match_expected_schemes() {
|
||||
assert_eq!(default_proxy_port("http"), 80);
|
||||
assert_eq!(default_proxy_port("https"), 443);
|
||||
assert_eq!(default_proxy_port("socks5h"), 1080);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proxy_route_spec_serialization_omits_proxy_urls() {
|
||||
let spec = ProxyRouteSpec {
|
||||
routes: vec![ProxyRouteEntry {
|
||||
env_key: "HTTP_PROXY".to_string(),
|
||||
control_fd: 3,
|
||||
}],
|
||||
};
|
||||
let serialized = serde_json::to_string(&spec).expect("proxy route spec should serialize");
|
||||
|
||||
assert_eq!(
|
||||
serialized,
|
||||
r#"{"routes":[{"env_key":"HTTP_PROXY","control_fd":3}]}"#
|
||||
);
|
||||
}
|
||||
305
codex-rs/linux-sandbox/src/seccomp.rs
Normal file
305
codex-rs/linux-sandbox/src/seccomp.rs
Normal file
@@ -0,0 +1,305 @@
|
||||
//! In-process Linux sandbox primitives: `no_new_privs` and seccomp.
|
||||
//!
|
||||
//! Filesystem restrictions are enforced by bubblewrap in `linux_run_main`.
|
||||
//! The legacy Landlock filesystem implementation is retained here, but the
|
||||
//! helper rejects legacy mode for filesystem-restricted policies.
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
|
||||
use codex_network_proxy::ManagedNetworkSandboxContext;
|
||||
use codex_protocol::error::CodexErr;
|
||||
use codex_protocol::error::Result;
|
||||
use codex_protocol::error::SandboxErr;
|
||||
use codex_protocol::protocol::FileSystemSandboxPolicy;
|
||||
use codex_protocol::protocol::NetworkSandboxPolicy;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
|
||||
use landlock::ABI;
|
||||
#[allow(unused_imports)]
|
||||
use landlock::Access;
|
||||
use landlock::AccessFs;
|
||||
use landlock::CompatLevel;
|
||||
use landlock::Compatible;
|
||||
use landlock::Ruleset;
|
||||
use landlock::RulesetAttr;
|
||||
use landlock::RulesetCreatedAttr;
|
||||
use seccompiler::BpfProgram;
|
||||
use seccompiler::SeccompAction;
|
||||
use seccompiler::SeccompCmpArgLen;
|
||||
use seccompiler::SeccompCmpOp;
|
||||
use seccompiler::SeccompCondition;
|
||||
use seccompiler::SeccompFilter;
|
||||
use seccompiler::SeccompRule;
|
||||
use seccompiler::TargetArch;
|
||||
use seccompiler::apply_filter;
|
||||
|
||||
/// Apply sandbox policies inside this thread so only the child inherits
|
||||
/// them, not the entire CLI process.
|
||||
///
|
||||
/// This function is responsible for:
|
||||
/// - enabling `PR_SET_NO_NEW_PRIVS` when restrictions apply, and
|
||||
/// - installing seccomp restrictions for network isolation and VM sockets.
|
||||
///
|
||||
/// Filesystem restrictions are normally handled by bubblewrap. The legacy
|
||||
/// Landlock implementation is only selected by `apply_landlock_fs`.
|
||||
pub(crate) fn apply_sandbox_policies_to_current_thread(
|
||||
file_system_sandbox_policy: &FileSystemSandboxPolicy,
|
||||
network_sandbox_policy: NetworkSandboxPolicy,
|
||||
cwd: &Path,
|
||||
apply_landlock_fs: bool,
|
||||
managed_network: Option<&ManagedNetworkSandboxContext>,
|
||||
proxy_routing_active: bool,
|
||||
) -> Result<()> {
|
||||
let network_seccomp_mode = network_seccomp_mode(
|
||||
network_sandbox_policy,
|
||||
managed_network.is_some(),
|
||||
proxy_routing_active,
|
||||
)
|
||||
.or_else(|| {
|
||||
// VM sockets can reach host services outside the filesystem sandbox.
|
||||
// In WSL2 they also allow Windows process launch through an alias of
|
||||
// the interop socket, even when /run/WSL is masked. Keep ordinary
|
||||
// network access while denying that host bridge.
|
||||
(!file_system_sandbox_policy.has_full_disk_write_access())
|
||||
.then_some(NetworkSeccompMode::VmSocketRestricted)
|
||||
});
|
||||
|
||||
// `PR_SET_NO_NEW_PRIVS` is required for seccomp, but it also prevents
|
||||
// setuid privilege elevation. Many `bwrap` deployments rely on setuid, so
|
||||
// we avoid this unless we need seccomp or we are explicitly using the
|
||||
// legacy Landlock filesystem pipeline.
|
||||
if network_seccomp_mode.is_some()
|
||||
|| (apply_landlock_fs && !file_system_sandbox_policy.has_full_disk_write_access())
|
||||
{
|
||||
set_no_new_privs()?;
|
||||
}
|
||||
|
||||
if let Some(mode) = network_seccomp_mode {
|
||||
install_network_seccomp_filter_on_current_thread(mode, managed_network)?;
|
||||
}
|
||||
|
||||
if apply_landlock_fs && !file_system_sandbox_policy.has_full_disk_write_access() {
|
||||
if !file_system_sandbox_policy.has_full_disk_read_access() {
|
||||
return Err(CodexErr::UnsupportedOperation(
|
||||
"Restricted read-only access is not supported by the legacy Linux Landlock filesystem backend."
|
||||
.to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let writable_roots = file_system_sandbox_policy
|
||||
.get_writable_roots_with_cwd(cwd)
|
||||
.into_iter()
|
||||
.map(|writable_root| writable_root.root)
|
||||
.collect();
|
||||
install_filesystem_landlock_rules_on_current_thread(writable_roots)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum NetworkSeccompMode {
|
||||
Restricted,
|
||||
ProxyRouted,
|
||||
VmSocketRestricted,
|
||||
}
|
||||
|
||||
fn should_install_network_seccomp(
|
||||
network_sandbox_policy: NetworkSandboxPolicy,
|
||||
allow_network_for_proxy: bool,
|
||||
) -> bool {
|
||||
// Managed-network sessions should remain fail-closed even for policies that
|
||||
// would normally grant full network access (for example, DangerFullAccess).
|
||||
!network_sandbox_policy.is_enabled() || allow_network_for_proxy
|
||||
}
|
||||
|
||||
fn network_seccomp_mode(
|
||||
network_sandbox_policy: NetworkSandboxPolicy,
|
||||
allow_network_for_proxy: bool,
|
||||
proxy_routed_network: bool,
|
||||
) -> Option<NetworkSeccompMode> {
|
||||
if !should_install_network_seccomp(network_sandbox_policy, allow_network_for_proxy) {
|
||||
None
|
||||
} else if proxy_routed_network {
|
||||
Some(NetworkSeccompMode::ProxyRouted)
|
||||
} else {
|
||||
Some(NetworkSeccompMode::Restricted)
|
||||
}
|
||||
}
|
||||
|
||||
/// Enable `PR_SET_NO_NEW_PRIVS` so seccomp can be applied safely.
|
||||
fn set_no_new_privs() -> Result<()> {
|
||||
let result = unsafe { libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) };
|
||||
if result != 0 {
|
||||
return Err(std::io::Error::last_os_error().into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Installs Landlock file-system rules on the current thread allowing read
|
||||
/// access to the entire file-system while restricting write access to
|
||||
/// `/dev/null` and the provided list of `writable_roots`.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns [`CodexErr::Sandbox`] variants when the ruleset fails to apply.
|
||||
///
|
||||
/// Retained for the legacy pipeline. The helper currently rejects legacy mode
|
||||
/// for filesystem-restricted policies, so filesystem sandboxing uses bubblewrap.
|
||||
fn install_filesystem_landlock_rules_on_current_thread(
|
||||
writable_roots: Vec<AbsolutePathBuf>,
|
||||
) -> Result<()> {
|
||||
let abi = ABI::V5;
|
||||
let access_rw = AccessFs::from_all(abi);
|
||||
let access_ro = AccessFs::from_read(abi);
|
||||
|
||||
let mut ruleset = Ruleset::default()
|
||||
.set_compatibility(CompatLevel::BestEffort)
|
||||
.handle_access(access_rw)?
|
||||
.create()?
|
||||
.add_rules(landlock::path_beneath_rules(&["/"], access_ro))?
|
||||
.add_rules(landlock::path_beneath_rules(&["/dev/null"], access_rw))?
|
||||
.set_no_new_privs(true);
|
||||
|
||||
if !writable_roots.is_empty() {
|
||||
ruleset = ruleset.add_rules(landlock::path_beneath_rules(&writable_roots, access_rw))?;
|
||||
}
|
||||
|
||||
let status = ruleset.restrict_self()?;
|
||||
|
||||
if status.ruleset == landlock::RulesetStatus::NotEnforced {
|
||||
return Err(CodexErr::Sandbox(SandboxErr::LandlockRestrict));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Installs a seccomp filter for Linux network sandboxing.
|
||||
///
|
||||
/// The filter is applied to the current thread so only the sandboxed child
|
||||
/// inherits it.
|
||||
fn install_network_seccomp_filter_on_current_thread(
|
||||
mode: NetworkSeccompMode,
|
||||
managed_network: Option<&ManagedNetworkSandboxContext>,
|
||||
) -> std::result::Result<(), SandboxErr> {
|
||||
fn deny_syscall(rules: &mut BTreeMap<i64, Vec<SeccompRule>>, nr: i64) {
|
||||
rules.insert(nr, vec![]); // empty rule vec = unconditional match
|
||||
}
|
||||
|
||||
// Build rule map.
|
||||
let mut rules: BTreeMap<i64, Vec<SeccompRule>> = BTreeMap::new();
|
||||
|
||||
if mode != NetworkSeccompMode::VmSocketRestricted {
|
||||
deny_syscall(&mut rules, libc::SYS_ptrace);
|
||||
deny_syscall(&mut rules, libc::SYS_process_vm_readv);
|
||||
deny_syscall(&mut rules, libc::SYS_process_vm_writev);
|
||||
}
|
||||
// io_uring can create AF_VSOCK sockets without a socket() syscall, so
|
||||
// keep it unavailable in every mode with socket-family restrictions.
|
||||
deny_syscall(&mut rules, libc::SYS_io_uring_setup);
|
||||
deny_syscall(&mut rules, libc::SYS_io_uring_enter);
|
||||
deny_syscall(&mut rules, libc::SYS_io_uring_register);
|
||||
|
||||
match mode {
|
||||
NetworkSeccompMode::Restricted => {
|
||||
deny_syscall(&mut rules, libc::SYS_connect);
|
||||
deny_syscall(&mut rules, libc::SYS_accept);
|
||||
deny_syscall(&mut rules, libc::SYS_accept4);
|
||||
deny_syscall(&mut rules, libc::SYS_bind);
|
||||
deny_syscall(&mut rules, libc::SYS_listen);
|
||||
deny_syscall(&mut rules, libc::SYS_getpeername);
|
||||
deny_syscall(&mut rules, libc::SYS_getsockname);
|
||||
deny_syscall(&mut rules, libc::SYS_shutdown);
|
||||
deny_syscall(&mut rules, libc::SYS_sendto);
|
||||
deny_syscall(&mut rules, libc::SYS_sendmmsg);
|
||||
// NOTE: allowing recvfrom allows some tools like: `cargo clippy`
|
||||
// to run with their socketpair + child processes for sub-proc
|
||||
// management.
|
||||
// deny_syscall(&mut rules, libc::SYS_recvfrom);
|
||||
deny_syscall(&mut rules, libc::SYS_recvmmsg);
|
||||
deny_syscall(&mut rules, libc::SYS_getsockopt);
|
||||
deny_syscall(&mut rules, libc::SYS_setsockopt);
|
||||
|
||||
// For `socket` we allow AF_UNIX (arg0 == AF_UNIX) and deny
|
||||
// everything else.
|
||||
let unix_only_rule = SeccompRule::new(vec![SeccompCondition::new(
|
||||
0, // first argument (domain)
|
||||
SeccompCmpArgLen::Dword,
|
||||
SeccompCmpOp::Ne,
|
||||
libc::AF_UNIX as u64,
|
||||
)?])?;
|
||||
|
||||
rules.insert(libc::SYS_socket, vec![unix_only_rule.clone()]);
|
||||
rules.insert(libc::SYS_socketpair, vec![unix_only_rule]);
|
||||
}
|
||||
NetworkSeccompMode::ProxyRouted => {
|
||||
// In proxy-routed mode we allow IP sockets in the isolated
|
||||
// namespace (used to reach the local TCP bridge). Standalone Unix
|
||||
// sockets require an explicit managed-policy grant; all other
|
||||
// socket families remain denied.
|
||||
let mut denied_socket_conditions = vec![
|
||||
SeccompCondition::new(
|
||||
0,
|
||||
SeccompCmpArgLen::Dword,
|
||||
SeccompCmpOp::Ne,
|
||||
libc::AF_INET as u64,
|
||||
)?,
|
||||
SeccompCondition::new(
|
||||
0,
|
||||
SeccompCmpArgLen::Dword,
|
||||
SeccompCmpOp::Ne,
|
||||
libc::AF_INET6 as u64,
|
||||
)?,
|
||||
];
|
||||
if managed_network.is_some_and(|context| context.dangerously_allow_all_unix_sockets) {
|
||||
denied_socket_conditions.push(SeccompCondition::new(
|
||||
0,
|
||||
SeccompCmpArgLen::Dword,
|
||||
SeccompCmpOp::Ne,
|
||||
libc::AF_UNIX as u64,
|
||||
)?);
|
||||
}
|
||||
let deny_non_ip_socket = SeccompRule::new(denied_socket_conditions)?;
|
||||
let deny_non_unix_socketpair = SeccompRule::new(vec![SeccompCondition::new(
|
||||
0,
|
||||
SeccompCmpArgLen::Dword,
|
||||
SeccompCmpOp::Ne,
|
||||
libc::AF_UNIX as u64,
|
||||
)?])?;
|
||||
rules.insert(libc::SYS_socket, vec![deny_non_ip_socket]);
|
||||
rules.insert(libc::SYS_socketpair, vec![deny_non_unix_socketpair]);
|
||||
}
|
||||
NetworkSeccompMode::VmSocketRestricted => {
|
||||
let deny_vsock = SeccompRule::new(vec![SeccompCondition::new(
|
||||
0,
|
||||
SeccompCmpArgLen::Dword,
|
||||
SeccompCmpOp::Eq,
|
||||
libc::AF_VSOCK as u64,
|
||||
)?])?;
|
||||
rules.insert(libc::SYS_socket, vec![deny_vsock.clone()]);
|
||||
rules.insert(libc::SYS_socketpair, vec![deny_vsock]);
|
||||
}
|
||||
}
|
||||
|
||||
let filter = SeccompFilter::new(
|
||||
rules,
|
||||
SeccompAction::Allow, // default – allow
|
||||
SeccompAction::Errno(libc::EPERM as u32), // when rule matches – return EPERM
|
||||
if cfg!(target_arch = "x86_64") {
|
||||
TargetArch::x86_64
|
||||
} else if cfg!(target_arch = "aarch64") {
|
||||
TargetArch::aarch64
|
||||
} else {
|
||||
unimplemented!("unsupported architecture for seccomp filter");
|
||||
},
|
||||
)?;
|
||||
|
||||
let prog: BpfProgram = filter.try_into()?;
|
||||
|
||||
apply_filter(&prog)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "seccomp_tests.rs"]
|
||||
mod tests;
|
||||
77
codex-rs/linux-sandbox/src/seccomp_tests.rs
Normal file
77
codex-rs/linux-sandbox/src/seccomp_tests.rs
Normal file
@@ -0,0 +1,77 @@
|
||||
//! Verify network policies select the expected seccomp enforcement mode.
|
||||
|
||||
use super::NetworkSeccompMode;
|
||||
use super::network_seccomp_mode;
|
||||
use super::should_install_network_seccomp;
|
||||
use codex_protocol::protocol::NetworkSandboxPolicy;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn managed_network_enforces_seccomp_even_for_full_network_policy() {
|
||||
assert_eq!(
|
||||
should_install_network_seccomp(
|
||||
NetworkSandboxPolicy::Enabled,
|
||||
/*allow_network_for_proxy*/ true,
|
||||
),
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_network_policy_without_managed_network_skips_seccomp() {
|
||||
assert_eq!(
|
||||
should_install_network_seccomp(
|
||||
NetworkSandboxPolicy::Enabled,
|
||||
/*allow_network_for_proxy*/ false,
|
||||
),
|
||||
false
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restricted_network_policy_always_installs_seccomp() {
|
||||
assert!(should_install_network_seccomp(
|
||||
NetworkSandboxPolicy::Restricted,
|
||||
/*allow_network_for_proxy*/ false,
|
||||
));
|
||||
assert!(should_install_network_seccomp(
|
||||
NetworkSandboxPolicy::Restricted,
|
||||
/*allow_network_for_proxy*/ true,
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_proxy_routes_use_proxy_routed_seccomp_mode() {
|
||||
assert_eq!(
|
||||
network_seccomp_mode(
|
||||
NetworkSandboxPolicy::Enabled,
|
||||
/*allow_network_for_proxy*/ true,
|
||||
/*proxy_routed_network*/ true,
|
||||
),
|
||||
Some(NetworkSeccompMode::ProxyRouted)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restricted_network_without_proxy_routing_uses_restricted_mode() {
|
||||
assert_eq!(
|
||||
network_seccomp_mode(
|
||||
NetworkSandboxPolicy::Restricted,
|
||||
/*allow_network_for_proxy*/ false,
|
||||
/*proxy_routed_network*/ false,
|
||||
),
|
||||
Some(NetworkSeccompMode::Restricted)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_network_without_managed_proxy_skips_network_seccomp_mode() {
|
||||
assert_eq!(
|
||||
network_seccomp_mode(
|
||||
NetworkSandboxPolicy::Enabled,
|
||||
/*allow_network_for_proxy*/ false,
|
||||
/*proxy_routed_network*/ false,
|
||||
),
|
||||
None
|
||||
);
|
||||
}
|
||||
66
codex-rs/linux-sandbox/src/wslg.rs
Normal file
66
codex-rs/linux-sandbox/src/wslg.rs
Normal file
@@ -0,0 +1,66 @@
|
||||
//! Identify WSLg's duplicate root without relying on filtered environment variables
|
||||
//! or kernel branding. An unrelated directory at the same path is left untouched.
|
||||
//! Explicit alias paths are rejected before building the restricted filesystem.
|
||||
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
use std::path::Path;
|
||||
|
||||
pub(crate) fn is_duplicate_root(path: &Path) -> io::Result<bool> {
|
||||
match fs::symlink_metadata(path) {
|
||||
Ok(metadata) => {
|
||||
let root = fs::metadata("/")?;
|
||||
Ok(metadata.is_dir() && (metadata.dev(), metadata.ino()) == (root.dev(), root.ino()))
|
||||
}
|
||||
Err(err)
|
||||
if matches!(
|
||||
err.kind(),
|
||||
io::ErrorKind::NotFound | io::ErrorKind::NotADirectory
|
||||
) =>
|
||||
{
|
||||
Ok(false)
|
||||
}
|
||||
Err(_) => {
|
||||
// Mount metadata remains readable when an ancestor is not searchable.
|
||||
// If neither observation is available, fail rather than guess that
|
||||
// an inaccessible duplicate can safely remain in the sandbox.
|
||||
let mountinfo = fs::read_to_string("/proc/self/mountinfo")?;
|
||||
let root = mount_identity(&mountinfo, "/")?
|
||||
.ok_or_else(|| io::Error::other("root mount identity is unavailable"))?;
|
||||
Ok(Some(root) == mount_identity(&mountinfo, &path.to_string_lossy())?)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn ensure_supported_path(path: &Path) -> codex_protocol::error::Result<()> {
|
||||
let alias = crate::bwrap::WSLG_DISTRO_ROOT;
|
||||
if path.starts_with(alias)
|
||||
|| fs::canonicalize(path).is_ok_and(|resolved| resolved.starts_with(alias))
|
||||
{
|
||||
return Err(codex_protocol::error::CodexErr::Fatal(format!(
|
||||
"restricted sandboxes do not support paths under {alias}: {}; use the corresponding path under the primary filesystem root instead",
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn mount_identity<'a>(mountinfo: &'a str, path: &str) -> io::Result<Option<(&'a str, &'a str)>> {
|
||||
let mut identities = mountinfo.lines().filter_map(|line| {
|
||||
let mut fields = line.split_ascii_whitespace();
|
||||
let device = fields.nth(2)?;
|
||||
let root = fields.next()?;
|
||||
let mountpoint = fields.next()?;
|
||||
(mountpoint == path).then_some((device, root))
|
||||
});
|
||||
let identity = identities.next();
|
||||
if identities.any(|other| Some(other) != identity) {
|
||||
return Err(io::Error::other("mount identity is ambiguous"));
|
||||
}
|
||||
Ok(identity)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "wslg_tests.rs"]
|
||||
mod tests;
|
||||
49
codex-rs/linux-sandbox/src/wslg_tests.rs
Normal file
49
codex-rs/linux-sandbox/src/wslg_tests.rs
Normal file
@@ -0,0 +1,49 @@
|
||||
use super::is_duplicate_root;
|
||||
use super::mount_identity;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
#[test]
|
||||
fn ordinary_paths_do_not_identify_a_duplicate_root() {
|
||||
let temp = tempfile::tempdir().expect("temporary directory");
|
||||
let file = temp.path().join("file");
|
||||
fs::write(&file, "fixture").expect("write file");
|
||||
let link = temp.path().join("link");
|
||||
std::os::unix::fs::symlink("/", &link).expect("create symlink");
|
||||
let missing = temp.path().join("missing");
|
||||
let not_a_directory = file.join("child");
|
||||
for path in [temp.path(), &file, &link, &missing, ¬_a_directory] {
|
||||
assert!(!is_duplicate_root(path).expect("inspect path"));
|
||||
}
|
||||
assert!(is_duplicate_root(Path::new("/")).expect("inspect root"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mount_identity_distinguishes_roots_on_the_same_device() {
|
||||
let mounts = "36 25 8:16 / / rw - ext4 /dev/sdb rw\n\
|
||||
39 25 8:16 / /mnt/wslg/distro rw - ext4 /dev/sdb rw\n\
|
||||
40 25 8:16 /other /unrelated rw - ext4 /dev/sdb rw\n\
|
||||
41 25 0:45 / /different-device rw - tmpfs tmpfs rw\n";
|
||||
assert_eq!(
|
||||
mount_identity(mounts, "/").unwrap(),
|
||||
mount_identity(mounts, "/mnt/wslg/distro").unwrap()
|
||||
);
|
||||
assert_ne!(
|
||||
mount_identity(mounts, "/").unwrap(),
|
||||
mount_identity(mounts, "/unrelated").unwrap()
|
||||
);
|
||||
assert_ne!(
|
||||
mount_identity(mounts, "/").unwrap(),
|
||||
mount_identity(mounts, "/different-device").unwrap()
|
||||
);
|
||||
assert_eq!(mount_identity(mounts, "/missing").unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conflicting_stacked_mounts_are_ambiguous() {
|
||||
let mounts = "36 25 8:16 / / rw - ext4 /dev/sdb rw\n\
|
||||
39 25 8:16 / /mnt/wslg/distro rw - ext4 /dev/sdb rw\n\
|
||||
40 39 0:45 / /mnt/wslg/distro rw - tmpfs tmpfs rw\n";
|
||||
assert!(mount_identity(mounts, "/mnt/wslg/distro").is_err());
|
||||
}
|
||||
5
codex-rs/linux-sandbox/tests/all.rs
Normal file
5
codex-rs/linux-sandbox/tests/all.rs
Normal file
@@ -0,0 +1,5 @@
|
||||
#![allow(clippy::expect_used)]
|
||||
|
||||
// Single integration test binary that aggregates all test modules.
|
||||
// The submodules live in `tests/suite/`.
|
||||
mod suite;
|
||||
87
codex-rs/linux-sandbox/tests/suite/bundled_bwrap.rs
Normal file
87
codex-rs/linux-sandbox/tests/suite/bundled_bwrap.rs
Normal file
@@ -0,0 +1,87 @@
|
||||
#![cfg(target_os = "linux")]
|
||||
|
||||
use codex_linux_sandbox::BUNDLED_BWRAP_DIGEST_VERIFICATION_FAILURE_EXIT_CODE;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_utils_cargo_bin::copy_executable;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
|
||||
#[test]
|
||||
fn bazel_build_rejects_tampered_bundled_bwrap() {
|
||||
// Cargo embeds the bundled bwrap digest only in release builds.
|
||||
if option_env!("BAZEL_PACKAGE").is_none() {
|
||||
return;
|
||||
}
|
||||
|
||||
let bwrap_runfile =
|
||||
std::env::var("CARGO_BIN_EXE_bwrap").expect("Bazel should provide the bwrap runfile");
|
||||
let runfiles_dir =
|
||||
std::env::var_os("TEST_SRCDIR").expect("Bazel should provide its runfiles directory");
|
||||
let bwrap_binary = PathBuf::from(runfiles_dir).join(bwrap_runfile);
|
||||
|
||||
let original_bwrap_bytes =
|
||||
std::fs::read(&bwrap_binary).expect("built bwrap should be readable");
|
||||
|
||||
let package = tempfile::tempdir().expect("package directory should be created");
|
||||
let resources = package.path().join("codex-resources");
|
||||
std::fs::create_dir(&resources).expect("package resource directory should be created");
|
||||
|
||||
let sandbox_binary = package.path().join("codex-linux-sandbox");
|
||||
copy_executable(
|
||||
Path::new(env!("CARGO_BIN_EXE_codex-linux-sandbox")),
|
||||
&sandbox_binary,
|
||||
)
|
||||
.expect("sandbox binary should be copied into the package");
|
||||
|
||||
let bundled_bwrap = resources.join("bwrap");
|
||||
copy_executable(&bwrap_binary, &bundled_bwrap)
|
||||
.expect("built bwrap should be copied into the package");
|
||||
|
||||
let permission_profile = serde_json::to_string(&PermissionProfile::read_only())
|
||||
.expect("read-only permission profile should serialize");
|
||||
let run_sandbox = || {
|
||||
Command::new(&sandbox_binary)
|
||||
.arg("--sandbox-policy-cwd")
|
||||
.arg(package.path())
|
||||
.arg("--permission-profile")
|
||||
.arg(&permission_profile)
|
||||
.arg("--no-proc")
|
||||
.arg("--")
|
||||
.arg("/bin/true")
|
||||
.env_clear()
|
||||
.env("PATH", package.path())
|
||||
.output()
|
||||
.expect("sandbox binary should start")
|
||||
};
|
||||
|
||||
let original_output = run_sandbox();
|
||||
assert_ne!(
|
||||
original_output.status.code(),
|
||||
Some(BUNDLED_BWRAP_DIGEST_VERIFICATION_FAILURE_EXIT_CODE),
|
||||
"sandbox should accept the digest of the unmodified bundled bwrap"
|
||||
);
|
||||
|
||||
std::fs::remove_file(&bundled_bwrap).expect("read-only bundled bwrap should be replaceable");
|
||||
let mut tampered_bwrap_bytes = original_bwrap_bytes;
|
||||
tampered_bwrap_bytes.push(0);
|
||||
// Write data to a separate inode, then publish it through the descriptor-safe helper.
|
||||
let tampered_data = package.path().join("tampered-bwrap-data");
|
||||
std::fs::write(&tampered_data, &tampered_bwrap_bytes)
|
||||
.expect("modified bwrap data should be written");
|
||||
copy_executable(&tampered_data, &bundled_bwrap)
|
||||
.expect("modified bwrap should be copied into the package");
|
||||
let bwrap_permissions = std::fs::metadata(&bwrap_binary)
|
||||
.expect("built bwrap metadata should be readable")
|
||||
.permissions();
|
||||
std::fs::set_permissions(&bundled_bwrap, bwrap_permissions)
|
||||
.expect("bundled bwrap should remain executable");
|
||||
|
||||
let tampered_output = run_sandbox();
|
||||
assert_eq!(
|
||||
tampered_output.status.code(),
|
||||
Some(BUNDLED_BWRAP_DIGEST_VERIFICATION_FAILURE_EXIT_CODE),
|
||||
"sandbox should reject the tampered bundled bwrap"
|
||||
);
|
||||
}
|
||||
134
codex-rs/linux-sandbox/tests/suite/bwrap_path.rs
Normal file
134
codex-rs/linux-sandbox/tests/suite/bwrap_path.rs
Normal file
@@ -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:?}"
|
||||
);
|
||||
}
|
||||
359
codex-rs/linux-sandbox/tests/suite/daemon_sockets_tests.rs
Normal file
359
codex-rs/linux-sandbox/tests/suite/daemon_sockets_tests.rs
Normal file
@@ -0,0 +1,359 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::os::fd::AsRawFd;
|
||||
use std::os::unix::net::UnixListener;
|
||||
use std::os::unix::net::UnixStream;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[tokio::test]
|
||||
async fn private_tmp_mount_preserves_daemon_socket_isolation() {
|
||||
if should_skip_bwrap_tests().await {
|
||||
return;
|
||||
}
|
||||
// The parent owns cleanup after the child's disposable mount namespace exits.
|
||||
let private = tempfile::tempdir_in("/tmp").unwrap();
|
||||
let test_executable = std::env::current_exe().unwrap();
|
||||
// Keep both executables available after the original /tmp is hidden.
|
||||
codex_utils_cargo_bin::copy_executable(&test_executable, &private.path().join("test")).unwrap();
|
||||
codex_utils_cargo_bin::copy_executable(
|
||||
&codex_linux_sandbox_exe(),
|
||||
&private.path().join("sandbox"),
|
||||
)
|
||||
.unwrap();
|
||||
let (_, test_module) = module_path!().split_once("::").unwrap();
|
||||
let fixture_test = format!("{test_module}::private_tmp_fixture");
|
||||
// Mount setup needs capabilities, which bubblewrap only accepts as namespace root.
|
||||
let output = tokio::process::Command::new("unshare")
|
||||
.args([
|
||||
"--user",
|
||||
"--map-root-user",
|
||||
"--mount",
|
||||
"--propagation",
|
||||
"private",
|
||||
"--",
|
||||
])
|
||||
.arg(test_executable)
|
||||
.args([
|
||||
"--exact",
|
||||
&fixture_test,
|
||||
"--ignored",
|
||||
"--nocapture",
|
||||
"--test-threads=1",
|
||||
])
|
||||
.env("CODEX_TEST_PRIVATE_TMP", private.path())
|
||||
.kill_on_drop(true)
|
||||
.output()
|
||||
.await
|
||||
.unwrap();
|
||||
if output.status.code() == Some(77)
|
||||
|| String::from_utf8_lossy(&output.stderr).starts_with("unshare:")
|
||||
{
|
||||
eprintln!("skipping private tmp test: user/mount namespaces are unavailable");
|
||||
return;
|
||||
}
|
||||
assert_eq!(output.status.code(), Some(0), "{output:?}");
|
||||
assert!(String::from_utf8_lossy(&output.stdout).contains("private-tmp-validated"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "invoked inside a disposable mount namespace"]
|
||||
fn private_tmp_fixture() {
|
||||
let Some(private) = std::env::var_os("CODEX_TEST_PRIVATE_TMP") else {
|
||||
return;
|
||||
};
|
||||
let mount = std::process::Command::new("mount")
|
||||
.arg("--bind")
|
||||
.arg(private)
|
||||
.arg("/tmp")
|
||||
.output()
|
||||
.unwrap();
|
||||
if !mount.status.success() {
|
||||
std::process::exit(/*code*/ 77);
|
||||
}
|
||||
// Namespace mounts have non-path roots such as `net:[inode]`. An unrelated
|
||||
// one must not stop startup or disable the socket-isolation checks below.
|
||||
let namespace = "/tmp/network-namespace";
|
||||
std::fs::File::create(namespace).unwrap();
|
||||
let mount = std::process::Command::new("mount")
|
||||
.args(["--bind", "/proc/self/ns/net", namespace])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(mount.status.success(), "{mount:?}");
|
||||
let root = codex_uds::prepare_shared_daemon_socket_directory().unwrap();
|
||||
let endpoint = root.join("rpc.sock");
|
||||
let _daemon = UnixListener::bind(&endpoint).unwrap();
|
||||
let _other = UnixListener::bind("/tmp/other.sock").unwrap();
|
||||
UnixStream::connect(&endpoint).expect("host can reach daemon");
|
||||
let profile = PermissionProfile::workspace_write_with(
|
||||
&[AbsolutePathBuf::from_absolute_path("/tmp").unwrap()],
|
||||
NetworkSandboxPolicy::Enabled,
|
||||
/*exclude_tmpdir_env_var*/ true,
|
||||
/*exclude_slash_tmp*/ false,
|
||||
);
|
||||
let mut command = std::process::Command::new("/tmp/sandbox");
|
||||
command
|
||||
.args(["--sandbox-policy-cwd", "/tmp", "--permission-profile"])
|
||||
.arg(serde_json::to_string(&profile).unwrap())
|
||||
.arg("--")
|
||||
.current_dir("/tmp");
|
||||
let (_, test_module) = module_path!().split_once("::").unwrap();
|
||||
let client_test = format!("{test_module}::private_tmp_client");
|
||||
command
|
||||
.args([
|
||||
"/tmp/test",
|
||||
"--exact",
|
||||
&client_test,
|
||||
"--ignored",
|
||||
"--nocapture",
|
||||
"--test-threads=1",
|
||||
])
|
||||
.env("CODEX_TEST_DAEMON_SOCKET", &endpoint)
|
||||
.env("TMPDIR", "/tmp");
|
||||
let output = command.output().unwrap();
|
||||
assert_eq!(output.status.code(), Some(0), "{output:?}");
|
||||
assert!(String::from_utf8_lossy(&output.stdout).contains("private-tmp-isolated"));
|
||||
|
||||
// Devboxes expose their temporary volume through both /tmp and /build/tmp.
|
||||
// An ancestor alias must receive the same socket mask without hiding other files.
|
||||
std::fs::create_dir("/tmp/build").unwrap();
|
||||
let mount = std::process::Command::new("mount")
|
||||
.args(["--bind", "/tmp", "/tmp/build"])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(mount.status.success(), "{mount:?}");
|
||||
let alias_endpoint = PathBuf::from("/tmp/build")
|
||||
.join(root.file_name().unwrap())
|
||||
.join("rpc.sock");
|
||||
UnixStream::connect(&alias_endpoint).expect("host can reach ancestor alias");
|
||||
command
|
||||
.env("CODEX_TEST_DAEMON_ALIAS_SOCKET", &alias_endpoint)
|
||||
.env("CODEX_TEST_OTHER_ALIAS_SOCKET", "/tmp/build/other.sock");
|
||||
let output = command.output().unwrap();
|
||||
assert_eq!(output.status.code(), Some(0), "{output:?}");
|
||||
assert!(String::from_utf8_lossy(&output.stdout).contains("private-tmp-isolated"));
|
||||
|
||||
// Rebinding the synthetic-mount registry must preserve masks for aliases
|
||||
// beneath it, even when the surrounding /tmp is writable.
|
||||
let registry_alias = PathBuf::from(format!(
|
||||
"/tmp/codex-bwrap-synthetic-mount-targets-{}/view",
|
||||
unsafe { libc::geteuid() }
|
||||
));
|
||||
std::fs::create_dir_all(®istry_alias).unwrap();
|
||||
let mount = std::process::Command::new("mount")
|
||||
.args(["--bind", "/tmp"])
|
||||
.arg(®istry_alias)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(mount.status.success(), "{mount:?}");
|
||||
let alias_endpoint = registry_alias
|
||||
.join(root.file_name().unwrap())
|
||||
.join("rpc.sock");
|
||||
UnixStream::connect(&alias_endpoint).expect("host can reach registry alias");
|
||||
command
|
||||
.env("CODEX_TEST_DAEMON_ALIAS_SOCKET", &alias_endpoint)
|
||||
.env(
|
||||
"CODEX_TEST_OTHER_ALIAS_SOCKET",
|
||||
registry_alias.join("other.sock"),
|
||||
);
|
||||
let output = command.output().unwrap();
|
||||
assert_eq!(output.status.code(), Some(0), "{output:?}");
|
||||
assert!(String::from_utf8_lossy(&output.stdout).contains("private-tmp-isolated"));
|
||||
|
||||
// A real alias below the private mount must still prevent startup.
|
||||
std::fs::create_dir("/tmp/alias").unwrap();
|
||||
let mount = std::process::Command::new("mount")
|
||||
.arg("--bind")
|
||||
.arg(&root)
|
||||
.arg("/tmp/alias")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(mount.status.success(), "{mount:?}");
|
||||
UnixStream::connect("/tmp/alias/rpc.sock").expect("host can reach alias");
|
||||
let output = command.output().unwrap();
|
||||
assert!(!output.status.success(), "{output:?}");
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains("unsupported host mount"));
|
||||
assert!(!String::from_utf8_lossy(&output.stdout).contains("private-tmp-client-started"));
|
||||
println!("private-tmp-validated");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "invoked inside the private tmp sandbox"]
|
||||
fn private_tmp_client() {
|
||||
let Some(endpoint) = std::env::var_os("CODEX_TEST_DAEMON_SOCKET") else {
|
||||
return;
|
||||
};
|
||||
println!("private-tmp-client-started");
|
||||
assert!(UnixStream::connect(endpoint).is_err(), "daemon reachable");
|
||||
UnixStream::connect("/tmp/other.sock").expect("unrelated socket reachable");
|
||||
if let Some(alias) = std::env::var_os("CODEX_TEST_DAEMON_ALIAS_SOCKET") {
|
||||
assert!(
|
||||
UnixStream::connect(alias).is_err(),
|
||||
"daemon alias reachable"
|
||||
);
|
||||
UnixStream::connect(std::env::var_os("CODEX_TEST_OTHER_ALIAS_SOCKET").unwrap())
|
||||
.expect("unrelated alias socket reachable");
|
||||
}
|
||||
println!("private-tmp-isolated");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn daemon_socket_bind_mount_alias_rejects_sandbox_startup() {
|
||||
if should_skip_bwrap_tests().await {
|
||||
return;
|
||||
}
|
||||
let root = codex_uds::prepare_shared_daemon_socket_directory().unwrap();
|
||||
let private = tempfile::tempdir_in(&root).unwrap();
|
||||
let alias = tempfile::tempdir().unwrap();
|
||||
let _listener = UnixListener::bind(private.path().join("rpc.sock")).unwrap();
|
||||
let profile = PermissionProfile::from_runtime_permissions(
|
||||
&FileSystemSandboxPolicy::read_only(),
|
||||
NetworkSandboxPolicy::Enabled,
|
||||
);
|
||||
let script = r#"
|
||||
import pathlib, socket, subprocess, sys
|
||||
root, alias, endpoint, helper, profile = sys.argv[1:]
|
||||
mount = subprocess.run(['mount', '--bind', root, alias], capture_output=True)
|
||||
if mount.returncode:
|
||||
sys.exit(77)
|
||||
try:
|
||||
socket.socket(socket.AF_UNIX).connect(str(pathlib.Path(alias) / endpoint))
|
||||
result = subprocess.run([helper, '--sandbox-policy-cwd', '/', '--permission-profile', profile,
|
||||
'--', 'sh', '-c', 'echo command-started'], capture_output=True)
|
||||
assert result.returncode != 0, result
|
||||
assert b'unsupported host mount' in result.stderr, result
|
||||
assert b'command-started' not in result.stdout, result
|
||||
finally:
|
||||
subprocess.run(['umount', alias], check=True)
|
||||
"#;
|
||||
let output = tokio::process::Command::new("unshare")
|
||||
.args([
|
||||
"--user",
|
||||
"--map-current-user",
|
||||
"--keep-caps",
|
||||
"--mount",
|
||||
"--propagation",
|
||||
"private",
|
||||
"--",
|
||||
])
|
||||
.args(["python3", "-c", script])
|
||||
.arg(&root)
|
||||
.arg(alias.path())
|
||||
.arg(private.path().strip_prefix(&root).unwrap().join("rpc.sock"))
|
||||
.arg(codex_linux_sandbox_exe())
|
||||
.arg(serde_json::to_string(&profile).unwrap())
|
||||
.kill_on_drop(true)
|
||||
.output()
|
||||
.await;
|
||||
let Ok(output) = output else {
|
||||
eprintln!("skipping bind-mount test: unshare is unavailable");
|
||||
return;
|
||||
};
|
||||
if output.status.code() == Some(77)
|
||||
|| String::from_utf8_lossy(&output.stderr).starts_with("unshare:")
|
||||
{
|
||||
eprintln!("skipping bind-mount test: user/mount namespaces are unavailable");
|
||||
return;
|
||||
}
|
||||
assert_eq!(output.status.code(), Some(0), "{output:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn daemon_sockets_are_hidden_with_network_and_tmp_write_grants() {
|
||||
if should_skip_bwrap_tests().await {
|
||||
return;
|
||||
}
|
||||
let root = codex_uds::prepare_shared_daemon_socket_directory().unwrap();
|
||||
let private = tempfile::tempdir_in(&root).unwrap();
|
||||
let workspace = tempfile::tempdir().unwrap();
|
||||
let socket = private.path().join("rpc.sock");
|
||||
let alias = workspace.path().join("alias.sock");
|
||||
let unrelated = workspace.path().join("other.sock");
|
||||
let directory_fd = std::fs::File::open(private.path()).unwrap();
|
||||
let _daemon = UnixListener::bind(&socket).unwrap();
|
||||
let _other = UnixListener::bind(&unrelated).unwrap();
|
||||
std::os::unix::fs::symlink(&socket, &alias).unwrap();
|
||||
UnixStream::connect(&alias).expect("host can reach daemon");
|
||||
let script = r#"
|
||||
import os, socket, sys
|
||||
for path in [sys.argv[1], sys.argv[2], '/proc/' + sys.argv[5] + '/root' + sys.argv[1]]:
|
||||
try:
|
||||
socket.socket(socket.AF_UNIX).connect(path)
|
||||
except OSError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError('daemon reachable: ' + path)
|
||||
try:
|
||||
os.link(sys.argv[1], sys.argv[4] + '/hardlink')
|
||||
except OSError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError('daemon hardlink created')
|
||||
socket.socket(socket.AF_UNIX).connect(sys.argv[3])
|
||||
s = socket.socket(socket.AF_UNIX)
|
||||
s.bind(sys.argv[4] + '/local.sock')
|
||||
s.listen(1)
|
||||
c = socket.socket(socket.AF_UNIX)
|
||||
c.connect(sys.argv[4] + '/local.sock')
|
||||
p, _ = s.accept()
|
||||
c.sendall(b'ok')
|
||||
assert p.recv(2) == b'ok'
|
||||
os.unlink(sys.argv[4] + '/local.sock')
|
||||
# Main already hides procfs when isolating WSL interop.
|
||||
if sys.argv[6] == 'host-proc' and not os.path.isdir('/run/WSL'):
|
||||
assert os.path.isfile('/proc/self/status')
|
||||
assert os.path.isdir('/proc/' + sys.argv[5])
|
||||
for name in ['root', 'cwd', 'fd/' + sys.argv[7]]:
|
||||
try:
|
||||
os.readlink('/proc/' + sys.argv[5] + '/' + name)
|
||||
except PermissionError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError('host process link accessible: ' + name)
|
||||
"#;
|
||||
let profile = PermissionProfile::workspace_write_with(
|
||||
&[AbsolutePathBuf::from_absolute_path("/tmp").unwrap()],
|
||||
NetworkSandboxPolicy::Enabled,
|
||||
/*exclude_tmpdir_env_var*/ true,
|
||||
/*exclude_slash_tmp*/ false,
|
||||
);
|
||||
let mut env = create_env_from_core_vars();
|
||||
env.insert(
|
||||
"CODEX_HOME".to_string(),
|
||||
workspace.path().display().to_string(),
|
||||
);
|
||||
env.insert("TMPDIR".to_string(), workspace.path().display().to_string());
|
||||
// Inherited procfs remains useful in containers that prohibit a fresh mount.
|
||||
// Its host-process magic links must still respect the user namespace boundary.
|
||||
for proc_mode in ["fresh-proc", "host-proc"] {
|
||||
let mut command = tokio::process::Command::new(codex_linux_sandbox_exe());
|
||||
command
|
||||
.arg("--sandbox-policy-cwd")
|
||||
.arg(workspace.path())
|
||||
.arg("--permission-profile")
|
||||
.arg(serde_json::to_string(&profile).unwrap())
|
||||
.envs(&env)
|
||||
.current_dir(workspace.path());
|
||||
if proc_mode == "host-proc" {
|
||||
command.arg("--no-proc");
|
||||
}
|
||||
let output = command
|
||||
.args([
|
||||
"--",
|
||||
"python3",
|
||||
"-c",
|
||||
script,
|
||||
socket.to_str().unwrap(),
|
||||
alias.to_str().unwrap(),
|
||||
unrelated.to_str().unwrap(),
|
||||
workspace.path().to_str().unwrap(),
|
||||
&std::process::id().to_string(),
|
||||
proc_mode,
|
||||
&directory_fd.as_raw_fd().to_string(),
|
||||
])
|
||||
.kill_on_drop(true)
|
||||
.output()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(output.status.code(), Some(0), "{output:?}");
|
||||
}
|
||||
}
|
||||
251
codex-rs/linux-sandbox/tests/suite/denied_files_tests.rs
Normal file
251
codex-rs/linux-sandbox/tests/suite/denied_files_tests.rs
Normal file
@@ -0,0 +1,251 @@
|
||||
//! Multiple denied files must not prevent sandbox startup or expose protected contents.
|
||||
|
||||
use super::LONG_TIMEOUT_MS;
|
||||
use super::codex_linux_sandbox_exe;
|
||||
use super::create_env_from_core_vars;
|
||||
use super::run_cmd_result_with_permission_profile_for_cwd;
|
||||
use super::should_skip_bwrap_tests;
|
||||
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_protocol::permissions::NetworkSandboxPolicy;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_cargo_bin::write_executable;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
enum DeniedFileRules {
|
||||
ExactPaths,
|
||||
Globs,
|
||||
GlobsFromRoot,
|
||||
GlobsWithProtectedRg,
|
||||
GlobsWithoutRg,
|
||||
}
|
||||
|
||||
#[test_case::test_case(DeniedFileRules::ExactPaths; "exact_paths")]
|
||||
#[test_case::test_case(DeniedFileRules::Globs; "globs")]
|
||||
#[test_case::test_case(DeniedFileRules::GlobsFromRoot; "globs_from_root")]
|
||||
#[test_case::test_case(DeniedFileRules::GlobsWithProtectedRg; "globs_with_protected_rg")]
|
||||
#[test_case::test_case(DeniedFileRules::GlobsWithoutRg; "globs_without_rg")]
|
||||
#[tokio::test]
|
||||
async fn sandbox_starts_with_multiple_denied_files(rules: DeniedFileRules) {
|
||||
if should_skip_bwrap_tests().await {
|
||||
eprintln!("skipping bwrap test: bwrap sandbox prerequisites are unavailable");
|
||||
return;
|
||||
}
|
||||
|
||||
let use_controlled_rg_path = matches!(
|
||||
rules,
|
||||
DeniedFileRules::GlobsWithProtectedRg | DeniedFileRules::GlobsWithoutRg
|
||||
);
|
||||
let temp = if use_controlled_rg_path {
|
||||
// Bazel can mount the default temp directory noexec.
|
||||
tempfile::tempdir_in(std::env::current_dir().expect("current directory"))
|
||||
.or_else(|_| tempfile::tempdir())
|
||||
} else {
|
||||
tempfile::tempdir()
|
||||
}
|
||||
.expect("tempdir");
|
||||
let workspace = AbsolutePathBuf::try_from(temp.path()).expect("absolute workspace");
|
||||
std::fs::create_dir(workspace.join("nested")).expect("create nested directory");
|
||||
std::fs::write(workspace.join("AGENTS.md"), "project instructions\n")
|
||||
.expect("write allowed instructions");
|
||||
let denied_files = [
|
||||
(workspace.join("one.key"), "dummy first key"),
|
||||
(workspace.join("nested/two.key"), "dummy second key"),
|
||||
(workspace.join(".env.local"), "dummy environment"),
|
||||
(workspace.join("nested/.env"), "dummy nested environment"),
|
||||
(workspace.join("#report-1.csv"), "dummy report"),
|
||||
(workspace.join("!report.csv"), "dummy literal bang report"),
|
||||
(workspace.join("notes.txt "), "dummy spaced filename"),
|
||||
(workspace.join("root-only.cfg"), "dummy root configuration"),
|
||||
];
|
||||
for (path, contents) in &denied_files {
|
||||
std::fs::write(path, contents).expect("write denied dummy file");
|
||||
}
|
||||
for path in ["notes.txt", "nested/allowed.cfg"] {
|
||||
std::fs::write(workspace.join(path), "public").expect("write allowed file");
|
||||
}
|
||||
std::os::unix::fs::symlink("AGENTS.md", workspace.join("relative.key"))
|
||||
.expect("relative file symlink");
|
||||
std::os::unix::fs::symlink(workspace.join("AGENTS.md"), workspace.join("absolute.key"))
|
||||
.expect("absolute file symlink");
|
||||
|
||||
let sandbox_helper = codex_linux_sandbox_exe();
|
||||
let helper_dir = AbsolutePathBuf::try_from(sandbox_helper.parent().expect("helper parent"))
|
||||
.expect("absolute helper directory");
|
||||
let mut entries = vec![
|
||||
FileSystemSandboxEntry::new(
|
||||
FileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::Minimal,
|
||||
},
|
||||
FileSystemAccessMode::Read,
|
||||
),
|
||||
FileSystemSandboxEntry::new(helper_dir.into(), FileSystemAccessMode::Read),
|
||||
FileSystemSandboxEntry::new(workspace.clone().into(), FileSystemAccessMode::Write),
|
||||
];
|
||||
let mut env = create_env_from_core_vars();
|
||||
// User config must not suppress the files used to construct deny masks.
|
||||
let rg_config = workspace.join("ripgrep.conf");
|
||||
std::fs::write(rg_config.as_path(), "--quiet\n").expect("write ripgrep config");
|
||||
env.insert(
|
||||
"RIPGREP_CONFIG_PATH".to_string(),
|
||||
rg_config.to_str().expect("UTF-8 config path").to_string(),
|
||||
);
|
||||
let rg_fixture = if use_controlled_rg_path {
|
||||
let fixture = tempfile::tempdir_in(temp.path().parent().expect("workspace parent"))
|
||||
.expect("rg fixture");
|
||||
write_executable(
|
||||
workspace.join("rg").as_path(),
|
||||
"#!/bin/sh\n: > \"$CODEX_TEST_REJECTED_RG_MARKER\"\nexit 0\n",
|
||||
)
|
||||
.expect("write workspace rg fixture");
|
||||
if matches!(rules, DeniedFileRules::GlobsWithProtectedRg) {
|
||||
write_executable(
|
||||
&fixture.path().join("rg"),
|
||||
r#"#!/bin/sh
|
||||
: > "$CODEX_TEST_PROTECTED_RG_MARKER"
|
||||
printf '%s\000' "$CODEX_TEST_DENIED_PATH_0" "$CODEX_TEST_DENIED_PATH_1" "$CODEX_TEST_DENIED_PATH_2"
|
||||
"#,
|
||||
)
|
||||
.expect("write protected rg fixture");
|
||||
}
|
||||
// Keep bubblewrap available without adding an unrelated rg to the test PATH.
|
||||
if let Some(bwrap) = codex_sandboxing::find_system_bwrap_in_path(
|
||||
&PermissionProfile::read_only().file_system_sandbox_policy(),
|
||||
&std::env::current_dir().expect("current directory"),
|
||||
) {
|
||||
std::os::unix::fs::symlink(bwrap, fixture.path().join("bwrap"))
|
||||
.expect("link system bubblewrap");
|
||||
}
|
||||
env.insert(
|
||||
"PATH".to_string(),
|
||||
std::env::join_paths([workspace.as_path(), fixture.path()])
|
||||
.expect("join PATH")
|
||||
.into_string()
|
||||
.expect("UTF-8 PATH"),
|
||||
);
|
||||
for (name, path) in [
|
||||
(
|
||||
"CODEX_TEST_REJECTED_RG_MARKER",
|
||||
fixture.path().join("rejected-rg-ran"),
|
||||
),
|
||||
(
|
||||
"CODEX_TEST_PROTECTED_RG_MARKER",
|
||||
fixture.path().join("protected-rg-ran"),
|
||||
),
|
||||
("CODEX_TEST_DENIED_PATH_0", denied_files[0].0.to_path_buf()),
|
||||
("CODEX_TEST_DENIED_PATH_1", denied_files[1].0.to_path_buf()),
|
||||
("CODEX_TEST_DENIED_PATH_2", denied_files[2].0.to_path_buf()),
|
||||
] {
|
||||
env.insert(
|
||||
name.to_string(),
|
||||
path.to_str().expect("UTF-8 fixture path").to_string(),
|
||||
);
|
||||
}
|
||||
Some(fixture)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
match rules {
|
||||
DeniedFileRules::ExactPaths => {
|
||||
entries.extend(denied_files.iter().map(|(path, _)| {
|
||||
FileSystemSandboxEntry::new(path.clone().into(), FileSystemAccessMode::Deny)
|
||||
}));
|
||||
}
|
||||
DeniedFileRules::Globs
|
||||
| DeniedFileRules::GlobsFromRoot
|
||||
| DeniedFileRules::GlobsWithProtectedRg
|
||||
| DeniedFileRules::GlobsWithoutRg => {
|
||||
for suffix in [
|
||||
"**/*.key",
|
||||
"**/.env.local",
|
||||
"nest*/.env",
|
||||
"#report-*.csv",
|
||||
"!*.csv",
|
||||
"*.txt ",
|
||||
"*.cfg",
|
||||
] {
|
||||
entries.push(FileSystemSandboxEntry::new(
|
||||
FileSystemPath::GlobPattern {
|
||||
pattern: format!("{}/{suffix}", workspace.display()),
|
||||
},
|
||||
FileSystemAccessMode::Deny,
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
let permission_profile = PermissionProfile::from_runtime_permissions(
|
||||
&FileSystemSandboxPolicy::restricted(entries),
|
||||
NetworkSandboxPolicy::Enabled,
|
||||
);
|
||||
let output = run_cmd_result_with_permission_profile_for_cwd(
|
||||
&[
|
||||
"/bin/sh",
|
||||
"-c",
|
||||
r#"set -eu
|
||||
cd "$1"
|
||||
/bin/cat AGENTS.md
|
||||
for blocked in one.key nested/two.key .env.local nested/.env '#report-1.csv' '!report.csv' 'notes.txt ' root-only.cfg; do
|
||||
if (: < "$blocked") 2>/dev/null; then
|
||||
printf 'read unexpectedly allowed: %s\n' "$blocked" >&2
|
||||
exit 10
|
||||
fi
|
||||
if (printf changed > "$blocked") 2>/dev/null; then
|
||||
printf 'write unexpectedly allowed: %s\n' "$blocked" >&2
|
||||
exit 11
|
||||
fi
|
||||
done
|
||||
for allowed in notes.txt nested/allowed.cfg; do
|
||||
test "$(/bin/cat "$allowed")" = public
|
||||
done
|
||||
for alias in relative.key absolute.key; do
|
||||
test "$(/bin/cat "$alias")" = 'project instructions'
|
||||
done
|
||||
printf 'allowed\n' > allowed.txt
|
||||
/bin/cat allowed.txt
|
||||
"#,
|
||||
"sh",
|
||||
workspace.to_str().expect("UTF-8 workspace"),
|
||||
],
|
||||
if matches!(rules, DeniedFileRules::GlobsFromRoot) {
|
||||
AbsolutePathBuf::try_from("/").expect("absolute root")
|
||||
} else {
|
||||
workspace.clone()
|
||||
},
|
||||
permission_profile,
|
||||
env,
|
||||
LONG_TIMEOUT_MS,
|
||||
/*use_legacy_landlock*/ false,
|
||||
)
|
||||
.await
|
||||
.expect("sandbox should start with multiple denied files");
|
||||
|
||||
assert_eq!(
|
||||
(output.exit_code, output.stdout.text, output.stderr.text),
|
||||
(
|
||||
0,
|
||||
"project instructions\nallowed\n".to_string(),
|
||||
String::new()
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(workspace.join("allowed.txt")).expect("read allowed file"),
|
||||
"allowed\n"
|
||||
);
|
||||
for (path, contents) in &denied_files {
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(path).expect("read host dummy file"),
|
||||
*contents
|
||||
);
|
||||
}
|
||||
if let Some(fixture) = rg_fixture {
|
||||
assert!(
|
||||
!fixture.path().join("rejected-rg-ran").exists(),
|
||||
"writable rg ran before confinement"
|
||||
);
|
||||
assert!(!fixture.path().join("protected-rg-ran").exists());
|
||||
}
|
||||
}
|
||||
1192
codex-rs/linux-sandbox/tests/suite/managed_proxy.rs
Normal file
1192
codex-rs/linux-sandbox/tests/suite/managed_proxy.rs
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,191 @@
|
||||
//! Explicit Unix-socket grants preserve managed-proxy network isolation.
|
||||
|
||||
use super::*;
|
||||
use codex_network_proxy::ConfigReloader;
|
||||
use codex_network_proxy::ConfigReloaderFuture;
|
||||
use codex_network_proxy::ConfigState;
|
||||
use codex_network_proxy::NetworkProxy;
|
||||
use codex_network_proxy::NetworkProxyConfig;
|
||||
use codex_network_proxy::NetworkProxyConstraints;
|
||||
use codex_network_proxy::NetworkProxyState;
|
||||
use codex_network_proxy::build_config_state;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::os::unix::net::UnixListener;
|
||||
use std::os::unix::net::UnixStream;
|
||||
use std::sync::Arc;
|
||||
|
||||
struct TestConfigReloader(ConfigState);
|
||||
|
||||
impl ConfigReloader for TestConfigReloader {
|
||||
fn source_label(&self) -> String {
|
||||
"managed proxy Unix socket test".to_string()
|
||||
}
|
||||
|
||||
fn maybe_reload(&self) -> ConfigReloaderFuture<'_, Option<ConfigState>> {
|
||||
Box::pin(async { Ok(None) })
|
||||
}
|
||||
|
||||
fn reload_now(&self) -> ConfigReloaderFuture<'_, ConfigState> {
|
||||
Box::pin(async { Ok(self.0.clone()) })
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn managed_proxy_allow_all_unix_sockets_preserves_network_isolation() {
|
||||
if let Some(reason) = managed_proxy_skip_reason().await {
|
||||
eprintln!("skipping managed proxy Unix socket test: {reason}");
|
||||
return;
|
||||
}
|
||||
if !Command::new("python3")
|
||||
.arg("--version")
|
||||
.output()
|
||||
.await
|
||||
.is_ok_and(|output| output.status.success())
|
||||
{
|
||||
eprintln!("skipping managed proxy Unix socket test: python3 is unavailable");
|
||||
return;
|
||||
}
|
||||
|
||||
let temp = tempfile::tempdir().expect("socket directory");
|
||||
let socket_path = temp.path().join("daemon.sock");
|
||||
let listener = UnixListener::bind(&socket_path).expect("host Unix listener");
|
||||
let mut control = UnixStream::connect(&socket_path).expect("host Unix control connection");
|
||||
let (mut control_peer, _) = listener.accept().expect("accept host Unix control");
|
||||
control.write_all(b"ok").expect("write host control");
|
||||
let mut control_payload = [0; 2];
|
||||
control_peer
|
||||
.read_exact(&mut control_payload)
|
||||
.expect("read host control");
|
||||
assert_eq!(control_payload, *b"ok");
|
||||
|
||||
// Use another loopback address so the namespace's proxy listener cannot
|
||||
// collide with this host-only endpoint even if it selects the same port.
|
||||
let tcp_listener =
|
||||
TcpListener::bind((Ipv4Addr::new(127, 0, 0, 2), 0)).expect("host TCP listener");
|
||||
let tcp_addr = tcp_listener.local_addr().expect("host TCP address");
|
||||
let _tcp_control = TcpStream::connect(tcp_addr).expect("host TCP control connection");
|
||||
let _tcp_peer = tcp_listener.accept().expect("accept host TCP control");
|
||||
|
||||
listener
|
||||
.set_nonblocking(true)
|
||||
.expect("nonblocking listener");
|
||||
let server = std::thread::spawn(move || {
|
||||
let deadline = Instant::now() + OPERATION_TIMEOUT * 2;
|
||||
loop {
|
||||
match listener.accept() {
|
||||
Ok((mut stream, _)) => {
|
||||
stream
|
||||
.set_read_timeout(Some(OPERATION_TIMEOUT))
|
||||
.expect("set Unix read timeout");
|
||||
let mut request = [0; 4];
|
||||
stream.read_exact(&mut request).expect("read Unix request");
|
||||
assert_eq!(request, *b"ping");
|
||||
stream.write_all(b"pong").expect("write Unix response");
|
||||
break;
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
|
||||
assert!(Instant::now() < deadline, "Unix request timed out");
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
Err(error) => panic!("accept Unix request: {error}"),
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let probe = r#"
|
||||
import errno, socket, sys
|
||||
path, port, mode = sys.argv[1:]
|
||||
try:
|
||||
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
except OSError as error:
|
||||
assert mode == 'deny' and error.errno == errno.EPERM, error
|
||||
else:
|
||||
assert mode == 'allow', 'Unix socket unexpectedly allowed'
|
||||
with client:
|
||||
client.settimeout(2)
|
||||
client.connect(path)
|
||||
client.sendall(b'ping')
|
||||
assert client.recv(4, socket.MSG_WAITALL) == b'pong'
|
||||
for address in [('127.0.0.2', int(port)), ('192.0.2.1', 80)]:
|
||||
try:
|
||||
connection = socket.create_connection(address, timeout=0.5)
|
||||
except OSError:
|
||||
pass
|
||||
else:
|
||||
connection.close()
|
||||
raise AssertionError(('direct network unexpectedly allowed', address))
|
||||
for family in (socket.AF_NETLINK, getattr(socket, 'AF_VSOCK', 40)):
|
||||
try:
|
||||
unexpected = socket.socket(family, socket.SOCK_STREAM)
|
||||
except OSError as error:
|
||||
assert error.errno == errno.EPERM, (family, error)
|
||||
else:
|
||||
unexpected.close()
|
||||
raise AssertionError(('socket family unexpectedly allowed', family))
|
||||
"#;
|
||||
let cwd = std::env::current_dir().expect("current directory");
|
||||
for (label, dangerously_allow_all_unix_sockets, allow_path) in [
|
||||
("default denial", false, false),
|
||||
("path grant stays restricted", false, true),
|
||||
("explicit allow-all", true, false),
|
||||
] {
|
||||
let mut env = create_env_from_core_vars();
|
||||
strip_proxy_env(&mut env);
|
||||
let mut config = NetworkProxyConfig {
|
||||
enabled: true,
|
||||
proxy_url: "http://127.0.0.1:9".to_string(),
|
||||
dangerously_allow_all_unix_sockets: Some(dangerously_allow_all_unix_sockets),
|
||||
..Default::default()
|
||||
};
|
||||
if allow_path {
|
||||
config.set_allow_unix_sockets(vec![socket_path.to_string_lossy().into_owned()]);
|
||||
}
|
||||
let state = build_config_state(
|
||||
config,
|
||||
NetworkProxyConstraints::default(),
|
||||
codex_network_proxy::Platform::native(),
|
||||
)
|
||||
.expect("valid managed network configuration");
|
||||
let network = NetworkProxy::builder()
|
||||
.state(Arc::new(NetworkProxyState::with_reloader(
|
||||
state.clone(),
|
||||
Arc::new(TestConfigReloader(state)),
|
||||
)))
|
||||
.managed_by_codex(/*managed_by_codex*/ false)
|
||||
.build()
|
||||
.await
|
||||
.expect("build managed network proxy");
|
||||
let prepared = network
|
||||
.prepare_for_optional_environment(env, /*environment_id*/ None)
|
||||
.expect("prepare managed network policy");
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_codex-linux-sandbox"));
|
||||
command
|
||||
.arg("--sandbox-policy-cwd")
|
||||
.arg(&cwd)
|
||||
.arg("--permission-profile")
|
||||
.arg(serde_json::to_string(&PermissionProfile::Disabled).unwrap())
|
||||
.arg("--managed-network")
|
||||
.arg(serde_json::to_string(&prepared.sandbox_context).unwrap())
|
||||
.args(["--", "python3", "-c", probe])
|
||||
.arg(&socket_path)
|
||||
.arg(tcp_addr.port().to_string())
|
||||
.arg(if dangerously_allow_all_unix_sockets {
|
||||
"allow"
|
||||
} else {
|
||||
"deny"
|
||||
})
|
||||
.env_clear()
|
||||
.envs(prepared.env)
|
||||
.kill_on_drop(true);
|
||||
let output = tokio::time::timeout(OPERATION_TIMEOUT, command.output())
|
||||
.await
|
||||
.expect("Unix socket probe timed out")
|
||||
.expect("Unix socket probe should execute");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{label}; stderr={}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
server.join().expect("Unix server should finish");
|
||||
}
|
||||
5
codex-rs/linux-sandbox/tests/suite/mod.rs
Normal file
5
codex-rs/linux-sandbox/tests/suite/mod.rs
Normal file
@@ -0,0 +1,5 @@
|
||||
// Aggregates all former standalone integration tests as modules.
|
||||
mod bundled_bwrap;
|
||||
mod bwrap_path;
|
||||
mod managed_proxy;
|
||||
mod sandbox;
|
||||
204
codex-rs/linux-sandbox/tests/suite/nested_metadata_tests.rs
Normal file
204
codex-rs/linux-sandbox/tests/suite/nested_metadata_tests.rs
Normal file
@@ -0,0 +1,204 @@
|
||||
//! Mounts for writable roots must preserve read-only metadata protections.
|
||||
|
||||
use super::LONG_TIMEOUT_MS;
|
||||
use super::create_env_from_core_vars;
|
||||
use super::run_cmd_result_with_cwd_and_writable_roots;
|
||||
use super::run_cmd_result_with_permission_profile_for_cwd;
|
||||
use super::should_skip_bwrap_tests;
|
||||
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_protocol::permissions::NetworkSandboxPolicy;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
enum RootLayout {
|
||||
Directory,
|
||||
Symlink,
|
||||
}
|
||||
|
||||
#[test_case::test_case(RootLayout::Directory, ""; "home_cwd")]
|
||||
#[test_case::test_case(RootLayout::Directory, ".codex/visualizations/thread"; "visualization_cwd")]
|
||||
#[test_case::test_case(RootLayout::Symlink, ""; "symlink_home_cwd")]
|
||||
#[test_case::test_case(RootLayout::Symlink, ".codex/visualizations/thread"; "symlink_visualization_cwd")]
|
||||
#[tokio::test]
|
||||
async fn sandbox_starts_with_nested_writable_metadata(layout: RootLayout, relative_cwd: &str) {
|
||||
if should_skip_bwrap_tests().await {
|
||||
eprintln!("skipping bwrap test: bwrap sandbox prerequisites are unavailable");
|
||||
return;
|
||||
}
|
||||
|
||||
let temp = tempfile::tempdir().expect("tempdir");
|
||||
let home =
|
||||
AbsolutePathBuf::from_absolute_path(temp.path().join("home")).expect("absolute home");
|
||||
match layout {
|
||||
RootLayout::Directory => std::fs::create_dir(&home).expect("create home"),
|
||||
RootLayout::Symlink => {
|
||||
let target = temp.path().join("real-home");
|
||||
std::fs::create_dir(&target).expect("create real home");
|
||||
std::os::unix::fs::symlink(target, &home).expect("create home alias");
|
||||
}
|
||||
}
|
||||
let codex_home = home.join(".codex");
|
||||
let visualization = codex_home.join("visualizations/thread");
|
||||
std::fs::create_dir_all(&visualization).expect("create visualization directory");
|
||||
let protected_file = codex_home.join("config.toml");
|
||||
std::fs::write(&protected_file, "unchanged").expect("write protected config");
|
||||
|
||||
let mut entries = vec![
|
||||
FileSystemSandboxEntry::new(
|
||||
FileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::Root,
|
||||
},
|
||||
FileSystemAccessMode::Read,
|
||||
),
|
||||
FileSystemSandboxEntry::new(home.clone().into(), FileSystemAccessMode::Write),
|
||||
FileSystemSandboxEntry::new(codex_home.clone().into(), FileSystemAccessMode::Read),
|
||||
FileSystemSandboxEntry::new(visualization.clone().into(), FileSystemAccessMode::Write),
|
||||
];
|
||||
// Remote clients expand generated workspace metadata rules to concrete
|
||||
// paths, including paths that do not yet exist on the executor.
|
||||
for name in [".git", ".agents", ".codex", ".aws"] {
|
||||
entries.push(FileSystemSandboxEntry::skip_missing_path(
|
||||
visualization.join(name).into(),
|
||||
FileSystemAccessMode::Read,
|
||||
));
|
||||
}
|
||||
let permission_profile = PermissionProfile::from_runtime_permissions(
|
||||
&FileSystemSandboxPolicy::restricted(entries),
|
||||
NetworkSandboxPolicy::Enabled,
|
||||
);
|
||||
let script = r#"
|
||||
set -eu
|
||||
workspace="$1"
|
||||
visualization="$2"
|
||||
printf home > "$workspace/allowed.txt"
|
||||
printf visualization > "$visualization/allowed.txt"
|
||||
if (rm "$workspace") 2>/dev/null; then
|
||||
exit 13
|
||||
fi
|
||||
if (printf changed > "$workspace/.codex/config.toml") 2>/dev/null; then
|
||||
exit 10
|
||||
fi
|
||||
if (touch "$workspace/.codex/forbidden.txt") 2>/dev/null; then
|
||||
exit 11
|
||||
fi
|
||||
for name in .git .agents .codex .aws; do
|
||||
test -d "$visualization/$name"
|
||||
if (touch "$visualization/$name/forbidden.txt") 2>/dev/null; then
|
||||
exit 12
|
||||
fi
|
||||
done
|
||||
printf nested-metadata-protected
|
||||
"#;
|
||||
let output = run_cmd_result_with_permission_profile_for_cwd(
|
||||
&[
|
||||
"/bin/sh",
|
||||
"-c",
|
||||
script,
|
||||
"nested-metadata-test",
|
||||
home.to_str().expect("UTF-8 home"),
|
||||
visualization
|
||||
.to_str()
|
||||
.expect("UTF-8 visualization directory"),
|
||||
],
|
||||
home.join(relative_cwd),
|
||||
permission_profile,
|
||||
create_env_from_core_vars(),
|
||||
LONG_TIMEOUT_MS,
|
||||
/*use_legacy_landlock*/ false,
|
||||
)
|
||||
.await
|
||||
.expect("nested writable root should start under bubblewrap");
|
||||
|
||||
assert_eq!(
|
||||
(output.exit_code, output.stdout.text, output.stderr.text),
|
||||
(0, "nested-metadata-protected".to_string(), String::new())
|
||||
);
|
||||
for (path, expected) in [
|
||||
(home.join("allowed.txt"), "home"),
|
||||
(visualization.join("allowed.txt"), "visualization"),
|
||||
(protected_file, "unchanged"),
|
||||
] {
|
||||
assert_eq!(std::fs::read_to_string(path).expect("read file"), expected);
|
||||
}
|
||||
for name in [".git", ".agents", ".codex", ".aws"] {
|
||||
assert!(
|
||||
!visualization.join(name).exists(),
|
||||
"temporary {name} mountpoint should be cleaned up"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test_case::test_case(RootLayout::Directory; "direct")]
|
||||
#[test_case::test_case(RootLayout::Symlink; "alias_outside_writable_roots")]
|
||||
#[tokio::test]
|
||||
async fn workspace_write_protects_resolved_gitdir_in_another_writable_root(layout: RootLayout) {
|
||||
if should_skip_bwrap_tests().await {
|
||||
eprintln!("skipping bwrap test: bwrap sandbox prerequisites are unavailable");
|
||||
return;
|
||||
}
|
||||
|
||||
let temp = tempfile::tempdir().expect("tempdir");
|
||||
// Roots at the same depth keep the workspace mount before the additional writable root.
|
||||
let workspace = temp.path().join("workspace");
|
||||
let writable = temp.path().join("writable");
|
||||
let gitdir = writable.join("gitdir");
|
||||
std::fs::create_dir(&workspace).expect("create workspace");
|
||||
std::fs::create_dir_all(gitdir.join("hooks")).expect("create Git hooks directory");
|
||||
let pointer_target = match layout {
|
||||
RootLayout::Directory => gitdir.clone(),
|
||||
RootLayout::Symlink => {
|
||||
let aliases = temp.path().join("readonly-aliases");
|
||||
std::fs::create_dir(&aliases).expect("create aliases directory");
|
||||
let alias = aliases.join("repo");
|
||||
std::os::unix::fs::symlink(&writable, &alias).expect("create gitdir alias");
|
||||
alias.join("gitdir")
|
||||
}
|
||||
};
|
||||
std::fs::write(
|
||||
workspace.join(".git"),
|
||||
format!("gitdir: {}\n", pointer_target.display()),
|
||||
)
|
||||
.expect("write Git pointer");
|
||||
let hook = gitdir.join("hooks/pre-commit");
|
||||
std::fs::write(&hook, "unchanged").expect("write Git hook");
|
||||
|
||||
let script = r#"
|
||||
set -eu
|
||||
printf allowed > "$1/allowed.txt"
|
||||
if (printf changed > "$1/gitdir/hooks/pre-commit") 2>/dev/null; then
|
||||
exit 10
|
||||
fi
|
||||
"#;
|
||||
let output = run_cmd_result_with_cwd_and_writable_roots(
|
||||
&[
|
||||
"/bin/sh",
|
||||
"-c",
|
||||
script,
|
||||
"resolved-gitdir-test",
|
||||
writable.to_str().expect("UTF-8 writable root"),
|
||||
],
|
||||
&workspace,
|
||||
std::slice::from_ref(&writable),
|
||||
LONG_TIMEOUT_MS,
|
||||
/*use_legacy_landlock*/ false,
|
||||
/*network_access*/ true,
|
||||
)
|
||||
.await
|
||||
.expect("sandboxed command should complete");
|
||||
|
||||
assert_eq!(
|
||||
(output.exit_code, output.stdout.text, output.stderr.text),
|
||||
(0, String::new(), String::new())
|
||||
);
|
||||
for (path, expected) in [
|
||||
(writable.join("allowed.txt"), "allowed"),
|
||||
(hook, "unchanged"),
|
||||
] {
|
||||
assert_eq!(std::fs::read_to_string(path).expect("read file"), expected);
|
||||
}
|
||||
}
|
||||
174
codex-rs/linux-sandbox/tests/suite/root_metadata_tests.rs
Normal file
174
codex-rs/linux-sandbox/tests/suite/root_metadata_tests.rs
Normal file
@@ -0,0 +1,174 @@
|
||||
//! Approved root metadata writes must not remount targets hidden by executor-side denials.
|
||||
|
||||
use super::codex_linux_sandbox_exe;
|
||||
use super::should_skip_bwrap_tests;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::permissions::FileSystemAccessMode;
|
||||
use codex_protocol::permissions::FileSystemSandboxEntry;
|
||||
use codex_protocol::permissions::FileSystemSandboxPolicy;
|
||||
use codex_protocol::permissions::FileSystemSandboxPolicyContext;
|
||||
use codex_protocol::permissions::NetworkSandboxPolicy;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::fs;
|
||||
use std::process::Command;
|
||||
|
||||
#[tokio::test]
|
||||
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(
|
||||
&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;
|
||||
};
|
||||
let fixture = tempfile::tempdir_in("/tmp").unwrap();
|
||||
let work = fixture.path().join("work");
|
||||
let private = fixture.path().join("private");
|
||||
fs::create_dir_all(work.join("public")).unwrap();
|
||||
fs::create_dir_all(private.join("reopened")).unwrap();
|
||||
fs::write(work.join("public/secret"), "outside").unwrap();
|
||||
fs::write(private.join("reopened/secret"), "private").unwrap();
|
||||
fs::write(private.join("sibling"), "sibling").unwrap();
|
||||
codex_utils_cargo_bin::copy_executable(&codex_linux_sandbox_exe(), &work.join("sandbox"))
|
||||
.unwrap();
|
||||
|
||||
let path_entry = |path: &str, access| {
|
||||
FileSystemSandboxEntry::new(
|
||||
AbsolutePathBuf::from_absolute_path(path).unwrap().into(),
|
||||
access,
|
||||
)
|
||||
};
|
||||
let cwd = AbsolutePathBuf::from_absolute_path("/tmp").unwrap().into();
|
||||
let context = FileSystemSandboxPolicyContext {
|
||||
cwd: &cwd,
|
||||
workspace_roots: std::slice::from_ref(&cwd),
|
||||
user_home_dir: None,
|
||||
temporary_directories: Some(&[]),
|
||||
};
|
||||
let approved = |denied| {
|
||||
let mut policy = FileSystemSandboxPolicy::read_only();
|
||||
policy
|
||||
.entries
|
||||
.push(path_entry(denied, FileSystemAccessMode::Deny));
|
||||
policy.for_approved_command(&context)
|
||||
};
|
||||
let run = |policy: &FileSystemSandboxPolicy,
|
||||
private_mount: &str,
|
||||
codex_target: &str,
|
||||
script: &str| {
|
||||
let profile =
|
||||
PermissionProfile::from_runtime_permissions(policy, NetworkSandboxPolicy::Enabled);
|
||||
let mut command = Command::new(&bwrap);
|
||||
command
|
||||
.args("--unshare-user --uid 0 --gid 0 --die-with-parent --tmpfs /".split_whitespace());
|
||||
command.args(
|
||||
"--ro-bind /usr /usr --ro-bind /etc /etc --proc /proc --dev /dev".split_whitespace(),
|
||||
);
|
||||
command.args("--dir /run --dir /.agents --symlink /private-link /.git".split_whitespace());
|
||||
command.args(["--symlink", codex_target, "/.codex"]);
|
||||
command.args(["--symlink", "/private/reopened", "/private-link"]);
|
||||
for path in ["/bin", "/sbin", "/lib", "/lib64"] {
|
||||
if let Ok(metadata) = fs::symlink_metadata(path) {
|
||||
if metadata.file_type().is_symlink() {
|
||||
command
|
||||
.arg("--symlink")
|
||||
.arg(fs::read_link(path).unwrap())
|
||||
.arg(path);
|
||||
} else {
|
||||
command.args(["--ro-bind", path, path]);
|
||||
}
|
||||
}
|
||||
}
|
||||
command.arg("--bind").arg(&work).arg("/tmp");
|
||||
command.arg("--bind").arg(&private).arg(private_mount);
|
||||
if private_mount != "/private" {
|
||||
command.args(["--symlink", private_mount, "/private"]);
|
||||
}
|
||||
command.args(
|
||||
"--chdir /tmp --setenv TMPDIR /tmp --setenv PATH /usr/bin:/bin".split_whitespace(),
|
||||
);
|
||||
command.args(
|
||||
"-- /tmp/sandbox --sandbox-policy-cwd /tmp --permission-profile".split_whitespace(),
|
||||
);
|
||||
command.arg(serde_json::to_string(&profile).unwrap());
|
||||
command.args(["--", "/bin/sh", "-c", script]);
|
||||
command.output().unwrap()
|
||||
};
|
||||
|
||||
let private_denied = approved("/private");
|
||||
let script = r#"
|
||||
set -eu
|
||||
if cat /private/reopened/secret >/dev/null 2>&1 ||
|
||||
cat /.codex/secret >/dev/null 2>&1 || cat /.git/secret >/dev/null 2>&1; then exit 21; fi
|
||||
if (printf bad > /.codex/changed) 2>/dev/null; then exit 22; fi
|
||||
printf good > /.agents/allowed
|
||||
printf good > /tmp/marker
|
||||
printf 'root-metadata-denials-held\n'
|
||||
"#;
|
||||
let output = run(&private_denied, "/private", "/private/reopened", script);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
if stderr.starts_with("bwrap: Creating new namespace failed")
|
||||
|| stderr.contains("No permissions to create a new namespace")
|
||||
|| stderr.contains("setting up uid map")
|
||||
{
|
||||
eprintln!("skipping root metadata test: {stderr}");
|
||||
return;
|
||||
}
|
||||
assert_eq!(output.status.code(), Some(0), "{output:?}");
|
||||
assert_eq!(output.stdout, b"root-metadata-denials-held\n");
|
||||
assert_eq!(fs::read_to_string(work.join("marker")).unwrap(), "good");
|
||||
assert!(!private.join("reopened/changed").exists());
|
||||
|
||||
let script = r#"
|
||||
set -eu
|
||||
printf safe > /.codex/allowed
|
||||
if cat /.git/secret >/dev/null 2>&1; then exit 23; fi
|
||||
"#;
|
||||
let output = run(&private_denied, "/private", "/tmp/public", script);
|
||||
assert_eq!(output.status.code(), Some(0), "{output:?}");
|
||||
assert_eq!(
|
||||
fs::read_to_string(work.join("public/allowed")).unwrap(),
|
||||
"safe"
|
||||
);
|
||||
|
||||
let script = r#"
|
||||
set -eu
|
||||
rm /private
|
||||
ln -s /tmp/public /private
|
||||
cat /.codex/secret
|
||||
"#;
|
||||
let output = run(&private_denied, "/real-private", "/private", script);
|
||||
assert!(!output.status.success(), "{output:?}");
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains(
|
||||
"cannot enforce sandbox deny-read path /private because it crosses writable symlink /private"
|
||||
), "{output:?}");
|
||||
assert!(output.stdout.is_empty(), "{output:?}");
|
||||
|
||||
let mut reopened = private_denied;
|
||||
reopened
|
||||
.entries
|
||||
.push(path_entry("/private/reopened", FileSystemAccessMode::Write));
|
||||
let script = r#"
|
||||
set -eu
|
||||
test "$(cat /.codex/secret)" = private
|
||||
if cat /private/sibling >/dev/null 2>&1; then exit 24; fi
|
||||
"#;
|
||||
let output = run(&reopened, "/private", "/private/reopened", script);
|
||||
assert_eq!(output.status.code(), Some(0), "{output:?}");
|
||||
|
||||
let output = run(
|
||||
&approved("/.codex/secret"),
|
||||
"/private",
|
||||
"/private/reopened",
|
||||
"true",
|
||||
);
|
||||
assert!(!output.status.success(), "{output:?}");
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains(
|
||||
"cannot enforce sandbox deny-read path /.codex/secret because it crosses writable symlink /.codex"
|
||||
), "{output:?}");
|
||||
assert!(output.stdout.is_empty(), "{output:?}");
|
||||
}
|
||||
1574
codex-rs/linux-sandbox/tests/suite/sandbox.rs
Normal file
1574
codex-rs/linux-sandbox/tests/suite/sandbox.rs
Normal file
File diff suppressed because it is too large
Load Diff
80
codex-rs/linux-sandbox/tests/suite/wslg_tests.rs
Normal file
80
codex-rs/linux-sandbox/tests/suite/wslg_tests.rs
Normal file
@@ -0,0 +1,80 @@
|
||||
//! WSLg runtime coverage for the duplicate-view mask and procfs fallback.
|
||||
|
||||
use super::NETWORK_TIMEOUT_MS;
|
||||
use super::codex_linux_sandbox_exe;
|
||||
use super::should_skip_bwrap_tests;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::os::unix::fs::MetadataExt as _;
|
||||
use std::time::Duration;
|
||||
|
||||
#[tokio::test]
|
||||
async fn wslg_duplicate_view_is_masked_with_and_without_fresh_procfs() {
|
||||
let root = std::fs::metadata("/").expect("inspect root");
|
||||
let has_wslg_root = std::fs::symlink_metadata("/mnt/wslg/distro").is_ok_and(|metadata| {
|
||||
metadata.is_dir() && (metadata.dev(), metadata.ino()) == (root.dev(), root.ino())
|
||||
});
|
||||
if !has_wslg_root || should_skip_bwrap_tests().await {
|
||||
eprintln!("skipping WSLg test: WSLg or bwrap prerequisites are unavailable");
|
||||
return;
|
||||
}
|
||||
|
||||
let workspace = tempfile::tempdir().expect("create workspace");
|
||||
let allowed = workspace.path().join("allowed.txt");
|
||||
std::fs::write(&allowed, "allowed\n").expect("write allowed fixture");
|
||||
let profile = serde_json::to_string(&PermissionProfile::read_only())
|
||||
.expect("serialize read-only profile");
|
||||
|
||||
for no_proc in [false, true] {
|
||||
let mut command = tokio::process::Command::new(codex_linux_sandbox_exe());
|
||||
command
|
||||
.arg("--sandbox-policy-cwd")
|
||||
.arg(workspace.path())
|
||||
.args(["--permission-profile", &profile]);
|
||||
if no_proc {
|
||||
command.arg("--no-proc");
|
||||
}
|
||||
// Inspect the protection itself, without accessing data through the alias.
|
||||
let script = if no_proc {
|
||||
"stat -c %a /mnt/wslg/distro && stat -f -c %T /mnt/wslg/distro && cat \"$1\" && test ! -e /proc/1"
|
||||
} else {
|
||||
"stat -c %a /mnt/wslg/distro && stat -f -c %T /mnt/wslg/distro && cat \"$1\""
|
||||
};
|
||||
let output = tokio::time::timeout(
|
||||
Duration::from_millis(NETWORK_TIMEOUT_MS),
|
||||
command
|
||||
.args(["--", "/bin/sh", "-c", script, "sh"])
|
||||
.arg(&allowed)
|
||||
.kill_on_drop(true)
|
||||
.output(),
|
||||
)
|
||||
.await
|
||||
.expect("WSLg sandbox check should finish")
|
||||
.expect("sandbox helper should start");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"WSLg mask check failed (no_proc={no_proc}): {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
assert_eq!(output.stdout, b"0\ntmpfs\nallowed\n");
|
||||
}
|
||||
// Exercise the public helper boundary: production wraps the requested
|
||||
// executable in another helper command before constructing bwrap args.
|
||||
let output = tokio::process::Command::new(codex_linux_sandbox_exe())
|
||||
.arg("--sandbox-policy-cwd")
|
||||
.arg(workspace.path())
|
||||
.args([
|
||||
"--permission-profile",
|
||||
&profile,
|
||||
"--",
|
||||
"/mnt/wslg/distro/bin/true",
|
||||
])
|
||||
.output()
|
||||
.await
|
||||
.expect("sandbox helper should start");
|
||||
assert_eq!(output.status.code(), Some(1));
|
||||
assert_eq!(
|
||||
String::from_utf8(output.stderr).expect("UTF-8 diagnostic"),
|
||||
"error building bubblewrap command: Fatal error: restricted sandboxes do not support paths under /mnt/wslg/distro: /mnt/wslg/distro/bin/true; use the corresponding path under the primary filesystem root instead\n"
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user