Base: codex-main originale (prima del fork aKode)

This commit is contained in:
Andrea
2026-11-09 10:37:42 +01:00
commit 7874033c81
10166 changed files with 2728937 additions and 0 deletions

View 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
}

View 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(),
&current_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;

View 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");
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View 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"]));
}

View 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;

View 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"),
])
);
}
}

View 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;

View 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
}

View 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;

View 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);
}

View 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;

View 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
);
}

View 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");
}

File diff suppressed because it is too large Load Diff

View 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(&registrations);
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(&registrations);
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(&registrations);
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,
);
}

View 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()
}

View 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;

View 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(())
}

View 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;

View 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}]}"#
);
}

View 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;

View 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
);
}

View 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;

View 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, &not_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());
}