Honor explicit Unix socket grants in the Linux managed sandbox (#45534)

## Why

Linux proxy-routed sandboxing denied standalone Unix sockets even when the effective network policy enabled `dangerously_allow_all_unix_sockets`.

## What changed

- Carry Unix socket permissions in `ManagedNetworkSandboxContext` and pass the prepared context through Linux sandbox launches with `--managed-network`.
- Allow `AF_UNIX` socket creation in proxy-routed mode when `dangerously_allow_all_unix_sockets` is enabled, while preserving network namespace isolation and restrictions on other socket families.
- Keep standalone Unix sockets denied by default and for path-only grants. Default missing fields in older serialized contexts to restrictive values.

## Testing

Add coverage for policy preparation and transport, legacy deserialization, and malformed policy rejection. Add a Linux integration test covering default denial, path-only denial, and explicit allow-all access, while checking that direct TCP access and `AF_NETLINK`/`AF_VSOCK` sockets remain blocked.

GitOrigin-RevId: 2695b945ad3e59fcb3faf7662d852a26650af16c
This commit is contained in:
viyatb-oai authored and copyberry committed 2026-09-14 22:40:20 +00:00
1 parent d39cfa8a2d
commit 99914f4950
18 files changed
+599 -68

No files matched your search

+14 -6
View File
@@ -1,3 +1,4 @@
use codex_network_proxy::ManagedNetworkSandboxContext;
use codex_protocol::models::PermissionProfile;
use std::path::Path;
@@ -15,18 +16,20 @@ pub fn allow_network_for_proxy(enforce_managed_network: bool) -> bool {
/// Converts the permission profile into the CLI invocation for
/// `codex-linux-sandbox`.
///
/// A managed context selects proxy isolation; a default context keeps its
/// restrictive policy when an older caller supplies no additional details.
///
/// The helper performs the actual sandboxing (bubblewrap by default + seccomp)
/// after parsing these arguments. The profile JSON flag is emitted before
/// helper feature flags so the argv order matches the helper's CLI shape. See
/// `docs/linux_sandbox.md` for the Linux semantics.
#[allow(clippy::too_many_arguments)]
pub fn create_linux_sandbox_command_args_for_permission_profile(
command: Vec<String>,
command_cwd: &Path,
permission_profile: &PermissionProfile,
sandbox_policy_cwd: &Path,
use_legacy_landlock: bool,
allow_network_for_proxy: bool,
managed_network: Option<&ManagedNetworkSandboxContext>,
) -> Vec<String> {
let permission_profile_json = serde_json::to_string(permission_profile)
.unwrap_or_else(|err| panic!("failed to serialize permission profile: {err}"));
@@ -48,11 +51,15 @@ pub fn create_linux_sandbox_command_args_for_permission_profile(
permission_profile_json,
];
// Proxy-only networking requires bubblewrap's isolated network namespace.
if use_legacy_landlock && !allow_network_for_proxy {
if use_legacy_landlock && managed_network.is_none() {
linux_cmd.push("--use-legacy-landlock".to_string());
}
if allow_network_for_proxy {
linux_cmd.push("--allow-network-for-proxy".to_string());
if let Some(managed_network) = managed_network {
linux_cmd.push("--managed-network".to_string());
linux_cmd.push(
serde_json::to_string(managed_network)
.unwrap_or_else(|err| panic!("failed to serialize managed network context: {err}")),
);
}
linux_cmd.push("--".to_string());
linux_cmd.extend(command);
@@ -89,7 +96,8 @@ fn create_linux_sandbox_command_args(
linux_cmd.push("--use-legacy-landlock".to_string());
}
if allow_network_for_proxy {
linux_cmd.push("--allow-network-for-proxy".to_string());
linux_cmd.push("--managed-network".to_string());
linux_cmd.push("{}".to_string());
}
// Separator so that command arguments starting with `-` are not parsed as
+4 -7
View File
@@ -33,7 +33,7 @@ fn legacy_landlock_flag_is_included_when_requested() {
}
#[test]
fn proxy_flag_takes_precedence_over_legacy_landlock() {
fn managed_context_takes_precedence_over_legacy_landlock() {
let command = vec!["/bin/true".to_string()];
let command_cwd = Path::new("/tmp/link");
let cwd = Path::new("/tmp");
@@ -45,12 +45,9 @@ fn proxy_flag_takes_precedence_over_legacy_landlock() {
&permission_profile,
cwd,
/*use_legacy_landlock*/ true,
/*allow_network_for_proxy*/ true,
);
assert_eq!(
args.contains(&"--allow-network-for-proxy".to_string()),
true
Some(&ManagedNetworkSandboxContext::default()),
);
assert_eq!(args.contains(&"--managed-network".to_string()), true);
assert_eq!(args.contains(&"--use-legacy-landlock".to_string()), false);
}
@@ -67,7 +64,7 @@ fn permission_profile_flag_is_included() {
&permission_profile,
cwd,
/*use_legacy_landlock*/ true,
/*allow_network_for_proxy*/ false,
/*managed_network*/ None,
);
assert_eq!(
+19 -4
View File
@@ -3,7 +3,6 @@ use crate::bwrap::WSL1_BWRAP_WARNING;
#[cfg(target_os = "linux")]
use crate::bwrap::is_wsl1;
use crate::landlock::CODEX_LINUX_SANDBOX_ARG0;
use crate::landlock::allow_network_for_proxy;
use crate::landlock::create_linux_sandbox_command_args_for_permission_profile;
use crate::policy_transforms::effective_permission_profile;
use crate::policy_transforms::should_require_platform_sandbox;
@@ -496,14 +495,30 @@ impl SandboxManager {
let pending = pending_sandboxed_request?;
let exe =
sandbox_exe.ok_or(SandboxTransformError::MissingLinuxSandboxExecutable)?;
let allow_proxy_network = allow_network_for_proxy(enforce_managed_network);
if enforce_managed_network
&& command.managed_network.is_none()
&& let Some(network) = network
{
let prepared = network
.prepare_for_optional_environment(
std::mem::take(&mut command.env),
environment_id,
)
.map_err(|err| {
SandboxTransformError::EnvironmentNetworkProxy(err.to_string())
})?;
command.env = prepared.env;
command.managed_network = Some(prepared.sandbox_context);
}
let managed_network =
enforce_managed_network.then(|| command.managed_network.unwrap_or_default());
#[cfg(target_os = "linux")]
ensure_linux_bubblewrap_is_supported(
&pending
.effective_permission_profile
.file_system_sandbox_policy(),
use_legacy_landlock,
allow_proxy_network,
managed_network.is_some(),
is_wsl1(),
)?;
let mut args = create_linux_sandbox_command_args_for_permission_profile(
@@ -512,7 +527,7 @@ impl SandboxManager {
&pending.effective_permission_profile,
pending.native_sandbox_policy_cwd.as_path(),
use_legacy_landlock,
allow_proxy_network,
managed_network.as_ref(),
);
let mut full_command = Vec::with_capacity(1 + args.len());
full_command.push(os_string_to_command_component(exe.as_os_str().to_owned()));
+125
View File
@@ -530,6 +530,131 @@ fn transform_linux_seccomp_uses_helper_alias_when_launcher_is_not_helper_path()
assert_eq!(exec_request.arg0, Some("codex-linux-sandbox".to_string()));
}
#[cfg(unix)]
#[tokio::test]
async fn linux_unix_socket_grant_uses_effective_managed_policy() -> anyhow::Result<()> {
use codex_network_proxy::ConfigReloader;
use codex_network_proxy::ConfigReloaderFuture;
use codex_network_proxy::ConfigState;
use codex_network_proxy::ManagedNetworkSandboxContext;
use codex_network_proxy::NetworkProxy;
use codex_network_proxy::NetworkProxyConfig;
use codex_network_proxy::NetworkProxyConstraints;
use codex_network_proxy::NetworkProxyState;
use codex_network_proxy::build_config_state;
use std::sync::Arc;
struct TestConfigReloader;
impl ConfigReloader for TestConfigReloader {
fn source_label(&self) -> String {
"sandbox manager test config".to_string()
}
fn maybe_reload(&self) -> ConfigReloaderFuture<'_, Option<ConfigState>> {
Box::pin(async { Ok(None) })
}
fn reload_now(&self) -> ConfigReloaderFuture<'_, ConfigState> {
Box::pin(async { Err(anyhow::anyhow!("test config cannot reload")) })
}
}
let state = build_config_state(
NetworkProxyConfig {
enabled: true,
dangerously_allow_all_unix_sockets: true,
..Default::default()
},
NetworkProxyConstraints::default(),
)?;
let network = NetworkProxy::builder()
.state(Arc::new(NetworkProxyState::with_reloader(
state,
Arc::new(TestConfigReloader),
)))
.managed_by_codex(/*managed_by_codex*/ false)
.build()
.await?;
let prepared =
network.prepare_for_optional_environment(HashMap::new(), /*environment_id*/ None)?;
let allow_all = prepared.sandbox_context;
let path_only = ManagedNetworkSandboxContext {
allow_unix_sockets: vec!["/tmp/daemon.sock".to_string()],
..Default::default()
};
let denied = ManagedNetworkSandboxContext::default();
let cwd = AbsolutePathBuf::current_dir()?;
let cwd_uri = PathUri::from_abs_path(&cwd);
let manager = SandboxManager::new();
for (label, context, live_proxy, enforce_managed_network, expected) in [
(
"missing policy stays managed with restrictive defaults",
None,
false,
true,
Some(denied.clone()),
),
(
"path grant stays restricted",
Some(path_only.clone()),
false,
true,
Some(path_only),
),
(
"prepared allow-all",
Some(allow_all.clone()),
false,
true,
Some(allow_all.clone()),
),
(
"prepared denial overrides live allow-all",
Some(denied.clone()),
true,
true,
Some(denied),
),
(
"live proxy fallback",
None,
true,
true,
Some(allow_all.clone()),
),
("no managed network", Some(allow_all), true, false, None),
] {
let request = manager.transform(SandboxTransformRequest {
command: SandboxCommand {
program: "true".into(),
args: Vec::new(),
cwd: cwd_uri.clone(),
env: HashMap::new(),
managed_network: context,
additional_permissions: None,
},
permissions: &PermissionProfile::Disabled,
sandbox: SandboxType::LinuxSeccomp,
enforce_managed_network,
environment_id: None,
network: live_proxy.then_some(&network),
sandbox_policy_cwd: &cwd_uri,
sandbox_exe: Some(std::path::Path::new("/tmp/codex-linux-sandbox")),
use_legacy_landlock: false,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
windows_sandbox_private_desktop: false,
})?;
let transported_context = request
.command
.windows(2)
.find(|args| args[0] == "--managed-network")
.map(|args| serde_json::from_str::<ManagedNetworkSandboxContext>(&args[1]))
.transpose()?;
assert_eq!(transported_context, expected, "{label}");
}
Ok(())
}
#[cfg(target_os = "windows")]
#[test]
fn transform_for_direct_spawn_windows_preserves_only_wrapper_setup_environment() {
@@ -777,6 +777,7 @@ fn prepared_managed_network_context_allows_only_its_proxy_ports() {
let managed_network = ManagedNetworkSandboxContext {
loopback_ports: vec![43123, 48081],
allow_local_binding: false,
..Default::default()
};
let args = create_seatbelt_command_args(CreateSeatbeltCommandArgsParams {
command: vec!["/bin/true".to_string()],