mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:31:09 +00:00
Isolate app-server Unix sockets from filesystem-restricted commands (#45984)
## Why Network access and Unix-socket allowlists must not let commands with filesystem restrictions reach the privileged app-server RPC transport. ## What changed - Bind Unix control sockets in a fixed, user-owned directory with mode `0700`, independent of environment settings, and expose the advertised paths as symlinks. Preserve existing parent permissions, reject unsafe parents, and serialize socket setup and publication. - Mask the socket directory in Linux bubblewrap sandboxes after each bind that exposes it. Reject host mount aliases and nested mounts that compromise isolation. - Deny access to the directory and outbound connections to its sockets in macOS Seatbelt policies, including when network access or Unix-socket allowlists grant broader access. - Require bubblewrap for filesystem-restricted Linux execution. Users with `features.use_legacy_landlock` enabled must disable it for these policies. ## Testing Add regression coverage for direct and symlink socket access, hardlink attempts, Linux host-process links and bind-mount aliases, and continued use of unrelated and sandbox-local sockets. Add transport coverage for parent permissions, concurrent restart after a stale symlink, and cleanup that preserves a replacement at the advertised path. GitOrigin-RevId: 53372c27eea278d964f2cf68aed24323ef3b7082
This commit is contained in:
1 parent
0666c12e78
commit
49305d74b4
25 files changed
+828
-191
No files matched your search
@@ -0,0 +1,167 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::os::fd::AsRawFd;
|
||||
use std::os::unix::net::UnixListener;
|
||||
use std::os::unix::net::UnixStream;
|
||||
|
||||
#[tokio::test]
|
||||
async fn daemon_socket_bind_mount_alias_rejects_sandbox_startup() {
|
||||
if should_skip_bwrap_tests().await {
|
||||
return;
|
||||
}
|
||||
let root = codex_uds::prepare_shared_daemon_socket_directory().unwrap();
|
||||
let private = tempfile::tempdir_in(&root).unwrap();
|
||||
let alias = tempfile::tempdir().unwrap();
|
||||
let _listener = UnixListener::bind(private.path().join("rpc.sock")).unwrap();
|
||||
let profile = PermissionProfile::from_runtime_permissions(
|
||||
&FileSystemSandboxPolicy::read_only(),
|
||||
NetworkSandboxPolicy::Enabled,
|
||||
);
|
||||
let script = r#"
|
||||
import pathlib, socket, subprocess, sys
|
||||
root, alias, endpoint, helper, profile = sys.argv[1:]
|
||||
mount = subprocess.run(['mount', '--bind', root, alias], capture_output=True)
|
||||
if mount.returncode:
|
||||
sys.exit(77)
|
||||
try:
|
||||
socket.socket(socket.AF_UNIX).connect(str(pathlib.Path(alias) / endpoint))
|
||||
result = subprocess.run([helper, '--sandbox-policy-cwd', '/', '--permission-profile', profile,
|
||||
'--', 'sh', '-c', 'echo command-started'], capture_output=True)
|
||||
assert result.returncode != 0, result
|
||||
assert b'unsupported host mount' in result.stderr, result
|
||||
assert b'command-started' not in result.stdout, result
|
||||
finally:
|
||||
subprocess.run(['umount', alias], check=True)
|
||||
"#;
|
||||
let output = tokio::process::Command::new("unshare")
|
||||
.args([
|
||||
"--user",
|
||||
"--map-current-user",
|
||||
"--keep-caps",
|
||||
"--mount",
|
||||
"--propagation",
|
||||
"private",
|
||||
"--",
|
||||
])
|
||||
.args(["python3", "-c", script])
|
||||
.arg(&root)
|
||||
.arg(alias.path())
|
||||
.arg(private.path().strip_prefix(&root).unwrap().join("rpc.sock"))
|
||||
.arg(codex_linux_sandbox_exe())
|
||||
.arg(serde_json::to_string(&profile).unwrap())
|
||||
.kill_on_drop(true)
|
||||
.output()
|
||||
.await;
|
||||
let Ok(output) = output else {
|
||||
eprintln!("skipping bind-mount test: unshare is unavailable");
|
||||
return;
|
||||
};
|
||||
if output.status.code() == Some(77)
|
||||
|| String::from_utf8_lossy(&output.stderr).starts_with("unshare:")
|
||||
{
|
||||
eprintln!("skipping bind-mount test: user/mount namespaces are unavailable");
|
||||
return;
|
||||
}
|
||||
assert_eq!(output.status.code(), Some(0), "{output:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn daemon_sockets_are_hidden_with_network_and_tmp_write_grants() {
|
||||
if should_skip_bwrap_tests().await {
|
||||
return;
|
||||
}
|
||||
let root = codex_uds::prepare_shared_daemon_socket_directory().unwrap();
|
||||
let private = tempfile::tempdir_in(&root).unwrap();
|
||||
let workspace = tempfile::tempdir().unwrap();
|
||||
let socket = private.path().join("rpc.sock");
|
||||
let alias = workspace.path().join("alias.sock");
|
||||
let unrelated = workspace.path().join("other.sock");
|
||||
let directory_fd = std::fs::File::open(private.path()).unwrap();
|
||||
let _daemon = UnixListener::bind(&socket).unwrap();
|
||||
let _other = UnixListener::bind(&unrelated).unwrap();
|
||||
std::os::unix::fs::symlink(&socket, &alias).unwrap();
|
||||
UnixStream::connect(&alias).expect("host can reach daemon");
|
||||
let script = r#"
|
||||
import os, socket, sys
|
||||
for path in [sys.argv[1], sys.argv[2], '/proc/' + sys.argv[5] + '/root' + sys.argv[1]]:
|
||||
try:
|
||||
socket.socket(socket.AF_UNIX).connect(path)
|
||||
except OSError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError('daemon reachable: ' + path)
|
||||
try:
|
||||
os.link(sys.argv[1], sys.argv[4] + '/hardlink')
|
||||
except OSError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError('daemon hardlink created')
|
||||
socket.socket(socket.AF_UNIX).connect(sys.argv[3])
|
||||
s = socket.socket(socket.AF_UNIX)
|
||||
s.bind(sys.argv[4] + '/local.sock')
|
||||
s.listen(1)
|
||||
c = socket.socket(socket.AF_UNIX)
|
||||
c.connect(sys.argv[4] + '/local.sock')
|
||||
p, _ = s.accept()
|
||||
c.sendall(b'ok')
|
||||
assert p.recv(2) == b'ok'
|
||||
os.unlink(sys.argv[4] + '/local.sock')
|
||||
# Main already hides procfs when isolating WSL interop.
|
||||
if sys.argv[6] == 'host-proc' and not os.path.isdir('/run/WSL'):
|
||||
assert os.path.isfile('/proc/self/status')
|
||||
assert os.path.isdir('/proc/' + sys.argv[5])
|
||||
for name in ['root', 'cwd', 'fd/' + sys.argv[7]]:
|
||||
try:
|
||||
os.readlink('/proc/' + sys.argv[5] + '/' + name)
|
||||
except PermissionError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError('host process link accessible: ' + name)
|
||||
"#;
|
||||
let profile = PermissionProfile::workspace_write_with(
|
||||
&[AbsolutePathBuf::from_absolute_path("/tmp").unwrap()],
|
||||
NetworkSandboxPolicy::Enabled,
|
||||
/*exclude_tmpdir_env_var*/ true,
|
||||
/*exclude_slash_tmp*/ false,
|
||||
);
|
||||
let mut env = create_env_from_core_vars();
|
||||
env.insert(
|
||||
"CODEX_HOME".to_string(),
|
||||
workspace.path().display().to_string(),
|
||||
);
|
||||
env.insert("TMPDIR".to_string(), workspace.path().display().to_string());
|
||||
// Inherited procfs remains useful in containers that prohibit a fresh mount.
|
||||
// Its host-process magic links must still respect the user namespace boundary.
|
||||
for proc_mode in ["fresh-proc", "host-proc"] {
|
||||
let mut command = tokio::process::Command::new(codex_linux_sandbox_exe());
|
||||
command
|
||||
.arg("--sandbox-policy-cwd")
|
||||
.arg(workspace.path())
|
||||
.arg("--permission-profile")
|
||||
.arg(serde_json::to_string(&profile).unwrap())
|
||||
.envs(&env)
|
||||
.current_dir(workspace.path());
|
||||
if proc_mode == "host-proc" {
|
||||
command.arg("--no-proc");
|
||||
}
|
||||
let output = command
|
||||
.args([
|
||||
"--",
|
||||
"python3",
|
||||
"-c",
|
||||
script,
|
||||
socket.to_str().unwrap(),
|
||||
alias.to_str().unwrap(),
|
||||
unrelated.to_str().unwrap(),
|
||||
workspace.path().to_str().unwrap(),
|
||||
&std::process::id().to_string(),
|
||||
proc_mode,
|
||||
&directory_fd.as_raw_fd().to_string(),
|
||||
])
|
||||
.kill_on_drop(true)
|
||||
.output()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(output.status.code(), Some(0), "{output:?}");
|
||||
}
|
||||
}
|
||||
@@ -561,59 +561,6 @@ async fn wsl_interop_cannot_reenter_distro_as_root_with_network_access() {
|
||||
assert_ne!(output.stdout.text.trim(), "0");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn legacy_landlock_rejects_wsl_interop_with_network_access() {
|
||||
let Some(powershell) = wsl_windows_executable(r"WindowsPowerShell\v1.0\powershell.exe").await
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if wsl_baseline_output(
|
||||
&powershell,
|
||||
&["-NoProfile", "-NonInteractive", "-Command", "exit 0"],
|
||||
)
|
||||
.await
|
||||
.is_none()
|
||||
{
|
||||
eprintln!("skipping legacy WSL interop test: Windows interop is unavailable on the host");
|
||||
return;
|
||||
}
|
||||
|
||||
let safe_profile = PermissionProfile::from_runtime_permissions(
|
||||
&FileSystemSandboxPolicy::read_only(),
|
||||
NetworkSandboxPolicy::Restricted,
|
||||
);
|
||||
let linux_output = run_cmd_result_with_permission_profile(
|
||||
&["/bin/true"],
|
||||
safe_profile,
|
||||
NETWORK_TIMEOUT_MS,
|
||||
/*use_legacy_landlock*/ true,
|
||||
)
|
||||
.await
|
||||
.expect("legacy Landlock should run a Linux command");
|
||||
assert_eq!(linux_output.exit_code, 0);
|
||||
|
||||
let unsafe_profile = PermissionProfile::from_runtime_permissions(
|
||||
&FileSystemSandboxPolicy::read_only(),
|
||||
NetworkSandboxPolicy::Enabled,
|
||||
);
|
||||
let output = expect_denied(
|
||||
run_cmd_result_with_permission_profile(
|
||||
&["/bin/true"],
|
||||
unsafe_profile,
|
||||
NETWORK_TIMEOUT_MS,
|
||||
/*use_legacy_landlock*/ true,
|
||||
)
|
||||
.await,
|
||||
"legacy Landlock must reject restricted filesystem access with full network access on WSL",
|
||||
);
|
||||
assert!(
|
||||
output
|
||||
.stderr
|
||||
.text
|
||||
.contains("legacy Landlock cannot isolate WSL Windows interop")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_root_read() {
|
||||
run_cmd(&["ls", "-l", "/bin"], &[], SHORT_TIMEOUT_MS).await;
|
||||
@@ -767,20 +714,19 @@ async fn sandbox_ignores_missing_writable_roots_under_bwrap() {
|
||||
#[tokio::test]
|
||||
async fn test_no_new_privs_is_enabled() {
|
||||
let output = run_cmd_output(
|
||||
&["bash", "-lc", "grep '^NoNewPrivs:' /proc/self/status"],
|
||||
&[
|
||||
"python3",
|
||||
"-c",
|
||||
"import ctypes; print(ctypes.CDLL(None).prctl(39, 0, 0, 0, 0))",
|
||||
],
|
||||
&[],
|
||||
// We have seen timeouts when running this test in CI on GitHub,
|
||||
// so we are using a generous timeout until we can diagnose further.
|
||||
LONG_TIMEOUT_MS,
|
||||
)
|
||||
.await;
|
||||
let line = output
|
||||
.stdout
|
||||
.text
|
||||
.lines()
|
||||
.find(|line| line.starts_with("NoNewPrivs:"))
|
||||
.unwrap_or("");
|
||||
assert_eq!(line.trim(), "NoNewPrivs:\t1");
|
||||
assert_eq!(output.exit_code, 0);
|
||||
assert_eq!(output.stdout.text, "1\n");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -792,19 +738,16 @@ async fn sandboxed_command_has_no_effective_or_permitted_capabilities() {
|
||||
|
||||
let output = run_cmd_output(
|
||||
&[
|
||||
"bash",
|
||||
"-lc",
|
||||
"awk '$1 == \"CapPrm:\" || $1 == \"CapEff:\" { print $1, $2 }' /proc/self/status",
|
||||
"python3",
|
||||
"-c",
|
||||
"import ctypes; h=(ctypes.c_uint*2)(0x20080522,0); d=(ctypes.c_uint*6)(); assert ctypes.CDLL(None).capget(h,d)==0; print(d[0],d[1],d[3],d[4])",
|
||||
],
|
||||
&[],
|
||||
LONG_TIMEOUT_MS,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
output.stdout.text,
|
||||
"CapPrm: 0000000000000000\nCapEff: 0000000000000000\n"
|
||||
);
|
||||
assert_eq!(output.exit_code, 0);
|
||||
assert_eq!(output.stdout.text, "0 0 0 0\n");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -1622,3 +1565,6 @@ async fn sandbox_blocks_dev_tcp_redirection() {
|
||||
// all images ship bash, so we guard against 127 as well.
|
||||
assert_network_blocked(&["bash", "-c", "echo hi > /dev/tcp/127.0.0.1/80"]).await;
|
||||
}
|
||||
|
||||
#[path = "daemon_sockets_tests.rs"]
|
||||
mod daemon_sockets_tests;
|
||||
@@ -246,7 +246,7 @@ async fn assert_seccomp_filtered_namespace_reaper(
|
||||
&[
|
||||
"bash",
|
||||
"-c",
|
||||
"if [ \"$(readlink /proc/1/ns/pid 2>/dev/null)\" != \"$(readlink /proc/self/ns/pid 2>/dev/null)\" ]; then printf 'namespace proc unavailable\\n'; exit 0; fi; printf '%s\\n' \"$PPID\"; awk '$1 == \"Seccomp:\" && FNR == NR { print $2 } $1 == \"Seccomp_filters:\" { print $2 }' /proc/1/status /proc/self/status",
|
||||
"if [ ! -r /proc/self/status ] || [ ! -r /proc/1/status ] || [ \"$(readlink /proc/1/ns/pid 2>/dev/null)\" != \"$(readlink /proc/self/ns/pid 2>/dev/null)\" ]; then printf 'namespace proc unavailable\\n'; exit 0; fi; printf '%s\\n' \"$PPID\"; awk '$1 == \"Seccomp:\" && FNR == NR { print $2 } $1 == \"Seccomp_filters:\" { print $2 }' /proc/1/status /proc/self/status",
|
||||
],
|
||||
permission_profile,
|
||||
allow_network_for_proxy,
|
||||
@@ -286,7 +286,7 @@ async fn namespace_reaper_collects_orphaned_descendants() {
|
||||
&[
|
||||
"bash",
|
||||
"-c",
|
||||
"if [ \"$(readlink /proc/1/ns/pid 2>/dev/null)\" != \"$(readlink /proc/self/ns/pid 2>/dev/null)\" ]; then printf 'namespace proc unavailable\\n'; exit 0; fi; orphan=$(bash -c 'sleep 0.05 </dev/null >/dev/null 2>&1 & printf \"%s\\n\" \"$!\"'); for _ in $(seq 1 100); do if [ ! -e \"/proc/$orphan\" ]; then printf 'orphan reaped\\n'; exit 0; fi; sleep 0.01; done; exit 1",
|
||||
"if [ ! -r /proc/self/status ] || [ ! -r /proc/1/status ] || [ \"$(readlink /proc/1/ns/pid 2>/dev/null)\" != \"$(readlink /proc/self/ns/pid 2>/dev/null)\" ]; then printf 'namespace proc unavailable\\n'; exit 0; fi; orphan=$(bash -c 'sleep 0.05 </dev/null >/dev/null 2>&1 & printf \"%s\\n\" \"$!\"'); for _ in $(seq 1 100); do if [ ! -e \"/proc/$orphan\" ]; then printf 'orphan reaped\\n'; exit 0; fi; sleep 0.01; done; exit 1",
|
||||
],
|
||||
&PermissionProfile::read_only(),
|
||||
/*allow_network_for_proxy*/ false,
|
||||
@@ -717,18 +717,25 @@ fn handoff_client() {
|
||||
return;
|
||||
};
|
||||
assert!(std::env::var_os(PROXY_ATTRIBUTION_TOKEN_ENV_KEY).is_none());
|
||||
let inherited_sockets = std::fs::read_dir("/proc/self/fd")
|
||||
.expect("enumerate inherited descriptors")
|
||||
.filter_map(Result::ok)
|
||||
.filter_map(|entry| {
|
||||
let target = std::fs::read_link(entry.path()).ok()?;
|
||||
target
|
||||
.to_string_lossy()
|
||||
.starts_with("socket:")
|
||||
.then(|| (entry.file_name(), target))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(inherited_sockets, Vec::new(), "privileged socket leaked");
|
||||
match std::fs::read_dir("/proc/self/fd") {
|
||||
Ok(entries) => {
|
||||
let inherited_sockets = entries
|
||||
.filter_map(Result::ok)
|
||||
.filter_map(|entry| {
|
||||
let target = std::fs::read_link(entry.path()).ok()?;
|
||||
target
|
||||
.to_string_lossy()
|
||||
.starts_with("socket:")
|
||||
.then(|| (entry.file_name(), target))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(inherited_sockets, Vec::new(), "privileged socket leaked");
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
eprintln!("skipping descriptor enumeration: sandbox proc is unavailable");
|
||||
}
|
||||
Err(error) => panic!("enumerate inherited descriptors: {error}"),
|
||||
}
|
||||
|
||||
let shared = std::env::var("CODEX_TEST_HANDOFF_SHARED").expect("shared directory");
|
||||
let shared = Path::new(&shared);
|
||||
|
||||
Reference in new issue
Block a user