Route Windows sandbox proxy traffic by restricting SID (#34613)

## Why

Elevated Windows sandboxes need stable managed-proxy ports while preserving the network policy and environment attribution of each sandboxed process.

## What changed

- Keep shared HTTP and SOCKS5 loopback ingress listeners alive across managed-proxy instances.
- Add a per-route restricting SID to elevated sandbox tokens and dispatch incoming connections to the matching proxy policy after attributing the client process.
- Reject connections without exactly one registered route, remove routes when their proxy handle is dropped, and keep unsandboxed Windows launches off the managed ingress.
- Provision the elevated sandbox with the configured proxy ports and local-binding setting, honoring the selected profile and CLI overrides.

## Testing

- Add Windows unit tests for TCP ownership attribution, route selection, restricting-token propagation, and setup settings.
- Add an end-to-end Windows test covering stable ports, isolated environment policies, HTTP and SOCKS5 routing, and route teardown.

GitOrigin-RevId: 783fac6e0f904dc9bb1955b75d4a5895e8bb9690
This commit is contained in:
iceweasel-oai
2026-07-21 21:06:04 +00:00
committed by copyberry
parent dfd2d8133c
commit 999a715089
40 changed files with 2792 additions and 191 deletions
@@ -14,6 +14,8 @@ use codex_network_proxy::NetworkProxyHandle;
use codex_network_proxy::NetworkProxyState;
use codex_network_proxy::build_config_state;
use codex_network_proxy::host_and_port_from_network_addr;
#[cfg(any(target_os = "windows", test))]
use codex_network_proxy::managed_proxy_ports;
use codex_network_proxy::normalize_host;
use codex_network_proxy::validate_policy_against_constraints;
use codex_protocol::models::PermissionProfile;
@@ -85,6 +87,16 @@ impl NetworkProxySpec {
self.config.enable_socks5
}
#[cfg(any(target_os = "windows", test))]
pub(crate) fn configured_proxy_ports(&self) -> std::io::Result<Vec<u16>> {
managed_proxy_ports(&self.config).map_err(std::io::Error::other)
}
#[cfg(any(target_os = "windows", test))]
pub(crate) fn allow_local_binding(&self) -> bool {
self.config.allow_local_binding
}
pub(crate) fn from_config_and_constraints(
config: NetworkProxyConfig,
requirements: Option<NetworkConstraints>,
+13
View File
@@ -632,6 +632,18 @@ async fn exec_windows_sandbox(
network_proxy_environment_error(network_environment_id.as_deref(), err)
})?;
}
let network_proxy_restricting_sid = network
.as_ref()
.map(|network| {
network
.network_proxy_restricting_sid(network_environment_id.as_deref())
.ok_or_else(|| {
CodexErr::Io(io::Error::other(
"managed Windows proxy route is missing its restricting SID",
))
})
})
.transpose()?;
// Windows sandbox capture still receives timeout and cancellation separately.
let (cancellation, timeout_ms) = if capture_policy.uses_expiration() {
@@ -686,6 +698,7 @@ async fn exec_windows_sandbox(
cancellation,
use_private_desktop: windows_sandbox_private_desktop,
proxy_enforced,
network_proxy_restricting_sid,
read_roots_override: elevated_read_roots_override.as_deref(),
read_roots_include_platform_defaults:
elevated_read_roots_include_platform_defaults,
+8 -1
View File
@@ -903,7 +903,14 @@ async fn managed_network_proxy_decider_survives_full_access_start() -> anyhow::R
use tokio::io::AsyncReadExt as _;
use tokio::io::AsyncWriteExt as _;
let mut stream = tokio::net::TcpStream::connect(started_proxy.proxy().http_addr()).await?;
let prepared = started_proxy
.proxy()
.prepare_for_remote_environment(std::collections::HashMap::new(), "test-bridge")?;
let proxy_addr = prepared.env["HTTP_PROXY"]
.strip_prefix("http://")
.expect("HTTP proxy URL")
.parse::<std::net::SocketAddr>()?;
let mut stream = tokio::net::TcpStream::connect(proxy_addr).await?;
stream
.write_all(
b"GET http://example.com/ HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n",
+2 -23
View File
@@ -19,7 +19,8 @@ use codex_network_proxy::PROXY_ACTIVE_ENV_KEY;
use codex_network_proxy::PROXY_ENV_KEYS;
#[cfg(target_os = "macos")]
use codex_network_proxy::PROXY_GIT_SSH_COMMAND_ENV_KEY;
use codex_network_proxy::is_managed_mitm_ca_trust_bundle_path;
pub(crate) use codex_network_proxy::is_managed_proxy_env_var;
pub(crate) use codex_network_proxy::strip_managed_proxy_env;
use codex_protocol::config_types::WindowsSandboxLevel;
use codex_protocol::models::AdditionalPermissionProfile;
use codex_sandboxing::SandboxCommand;
@@ -69,28 +70,6 @@ pub(crate) fn exec_env_for_sandbox_permissions(
env
}
pub(crate) fn is_managed_proxy_env_var(key: &str, value: &str) -> bool {
if PROXY_ENV_KEYS.contains(&key) {
return true;
}
if CUSTOM_CA_ENV_KEYS.contains(&key) {
return is_managed_mitm_ca_trust_bundle_path(value);
}
#[cfg(target_os = "macos")]
{
key == PROXY_GIT_SSH_COMMAND_ENV_KEY
&& value.starts_with(CODEX_PROXY_GIT_SSH_COMMAND_MARKER)
}
#[cfg(not(target_os = "macos"))]
{
false
}
}
pub(crate) fn strip_managed_proxy_env(env: &mut HashMap<String, String>) {
env.retain(|key, value| !is_managed_proxy_env_var(key, value));
}
/// Prepends `path_entry` to `PATH`, removing duplicate and empty existing
/// entries.
///
@@ -1031,6 +1031,35 @@ impl UnifiedExecProcessManager {
if request.command.is_empty() {
return Err(UnifiedExecError::MissingCommandLine);
}
let network_proxy_restricting_sid = {
#[cfg(target_os = "windows")]
{
if request.sandbox == codex_sandboxing::SandboxType::WindowsRestrictedToken {
request
.network
.as_ref()
.map(|network| {
network
.network_proxy_restricting_sid(
request.network_environment_id.as_deref(),
)
.ok_or_else(|| {
UnifiedExecError::create_process(
"managed Windows proxy route is missing its restricting SID"
.to_string(),
)
})
})
.transpose()?
} else {
None
}
}
#[cfg(not(target_os = "windows"))]
{
None::<String>
}
};
let windows_sandbox = if request.sandbox
== codex_sandboxing::SandboxType::WindowsRestrictedToken
{
@@ -1039,6 +1068,7 @@ impl UnifiedExecProcessManager {
workspace_roots: &request.windows_sandbox_workspace_roots,
windows_sandbox_level: request.windows_sandbox_level,
proxy_enforced: request.network.is_some(),
network_proxy_restricting_sid: network_proxy_restricting_sid.as_deref(),
proxy_settings_mode: codex_sandboxing::WindowsSandboxProxySettingsMode::Reconcile,
filesystem_overrides: request.windows_sandbox_filesystem_overrides.as_ref(),
use_private_desktop: request.windows_sandbox_private_desktop,
+28 -3
View File
@@ -123,9 +123,30 @@ pub fn run_elevated_setup(
)
}
#[cfg(any(target_os = "windows", test))]
fn provisioning_settings(
network: Option<&crate::config::NetworkProxySpec>,
) -> std::io::Result<codex_windows_sandbox::WindowsSandboxProvisioningSettings> {
let Some(network) = network.filter(|network| network.enabled()) else {
return Ok(codex_windows_sandbox::WindowsSandboxProvisioningSettings::default());
};
Ok(codex_windows_sandbox::WindowsSandboxProvisioningSettings {
proxy_ports: network.configured_proxy_ports()?,
allow_local_binding: network.allow_local_binding(),
})
}
#[cfg(target_os = "windows")]
pub fn run_elevated_provisioning_setup(codex_home: &Path, real_user: &str) -> anyhow::Result<()> {
codex_windows_sandbox::run_elevated_provisioning_setup(codex_home, real_user)
pub fn run_elevated_provisioning_setup(
codex_home: &Path,
real_user: &str,
network: Option<&crate::config::NetworkProxySpec>,
) -> anyhow::Result<()> {
codex_windows_sandbox::run_elevated_provisioning_setup(
codex_home,
real_user,
provisioning_settings(network)?,
)
}
#[cfg(not(target_os = "windows"))]
@@ -140,7 +161,11 @@ pub fn run_elevated_setup(
}
#[cfg(not(target_os = "windows"))]
pub fn run_elevated_provisioning_setup(_codex_home: &Path, _real_user: &str) -> anyhow::Result<()> {
pub fn run_elevated_provisioning_setup(
_codex_home: &Path,
_real_user: &str,
_network: Option<&crate::config::NetworkProxySpec>,
) -> anyhow::Result<()> {
anyhow::bail!("elevated Windows sandbox setup is only supported on Windows")
}
@@ -2,6 +2,8 @@ use super::*;
use codex_config::types::WindowsToml;
use codex_features::Features;
use codex_features::FeaturesToml;
use codex_network_proxy::NetworkProxyConfig;
use codex_protocol::models::PermissionProfile;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
@@ -115,3 +117,44 @@ fn resolve_windows_sandbox_private_desktop_respects_explicit_cfg_value() {
assert!(!resolve_windows_sandbox_private_desktop(&cfg));
}
#[test]
fn provisioning_settings_omit_the_disabled_socks_proxy() {
let config = NetworkProxyConfig {
enabled: true,
proxy_url: "http://127.0.0.1:43128".to_string(),
enable_socks5: false,
socks_url: "socks5h://127.0.0.1:48081".to_string(),
allow_local_binding: true,
..Default::default()
};
let spec = crate::config::NetworkProxySpec::from_config_and_constraints(
config,
/*requirements*/ None,
&PermissionProfile::workspace_write(),
)
.expect("managed proxy config should resolve");
assert_eq!(
provisioning_settings(Some(&spec)).expect("provisioning settings should resolve"),
codex_windows_sandbox::WindowsSandboxProvisioningSettings {
proxy_ports: vec![43128],
allow_local_binding: true,
}
);
}
#[test]
fn provisioning_settings_are_empty_when_managed_network_is_disabled() {
let spec = crate::config::NetworkProxySpec::from_config_and_constraints(
NetworkProxyConfig::default(),
/*requirements*/ None,
&PermissionProfile::workspace_write(),
)
.expect("managed proxy config should resolve");
assert_eq!(
provisioning_settings(Some(&spec)).expect("provisioning settings should resolve"),
codex_windows_sandbox::WindowsSandboxProvisioningSettings::default()
);
}