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:
Eric Traut authored and copyberry committed 2026-09-16 16:56:41 +00:00
1 parent 0666c12e78
commit 49305d74b4
25 files changed
+828 -191

No files matched your search

+1
View File
@@ -57,6 +57,7 @@ url = { workspace = true }
uuid = { workspace = true, features = ["serde", "v7"] }
[target.'cfg(unix)'.dependencies]
libc = { workspace = true }
signal-hook = { workspace = true }
[dev-dependencies]
-1
View File
@@ -37,7 +37,6 @@ pub use transport::app_server_control_socket_path;
pub use transport::app_server_startup_lock_path;
pub use transport::auth;
pub use transport::daemon_recovery_file_path;
pub use transport::prepare_control_socket_path;
pub use transport::start_control_socket_acceptor;
pub use transport::start_remote_control;
pub use transport::start_stdio_connection;
@@ -46,7 +46,6 @@ pub use stdio::start_stdio_connection;
pub use unix_socket::AppServerStartupLock;
pub use unix_socket::DaemonShutdownAccess;
pub use unix_socket::acquire_app_server_startup_lock;
pub use unix_socket::prepare_control_socket_path;
pub use unix_socket::start_control_socket_acceptor;
pub use websocket::start_websocket_acceptor;
@@ -39,6 +39,45 @@ pub async fn start_control_socket_acceptor(
shutdown_token: CancellationToken,
daemon_shutdown_access: DaemonShutdownAccess,
) -> IoResult<JoinHandle<()>> {
#[cfg(unix)]
let (socket_path, rendezvous_path, _startup_lock) = {
use std::os::unix::fs::MetadataExt;
if let Some(parent) = socket_path.as_path().parent() {
// The advertised path is only an alias; preserve existing parents.
match tokio::fs::DirBuilder::new()
.mode(0o700)
.create(parent)
.await
{
Ok(()) => {}
Err(error) if error.kind() == ErrorKind::AlreadyExists => {}
Err(error) => return Err(error),
}
let metadata = std::fs::metadata(parent)?;
if !metadata.is_dir()
|| (metadata.uid() != 0 && metadata.uid() != unsafe { libc::geteuid() })
|| (metadata.mode() & 0o022 != 0 && metadata.mode() & 0o1000 == 0)
{
return Err(std::io::Error::new(
ErrorKind::PermissionDenied,
"socket parent must be owned by the user or root and prevent other users from replacing socket entries",
));
}
}
codex_uds::prepare_shared_daemon_socket_directory()?;
let physical_path = protected_socket_path(socket_path.as_path())?;
let lock = acquire_app_server_startup_lock(AbsolutePathBuf::from_absolute_path_checked(
physical_path.with_extension("lock"),
)?)
.await?;
prepare_control_socket_path(socket_path.as_path()).await?;
(
AbsolutePathBuf::from_absolute_path_checked(physical_path)?,
socket_path,
lock,
)
};
#[cfg(windows)]
let (socket_path, directory_guard) = {
if let Some(parent) = socket_path.as_path().parent() {
@@ -51,10 +90,17 @@ pub async fn start_control_socket_acceptor(
let listener = UnixListener::bind(socket_path.as_path()).await?;
let socket_guard = ControlSocketFileGuard {
socket_path,
#[cfg(unix)]
rendezvous_path,
#[cfg(windows)]
_directory_guard: directory_guard,
};
set_control_socket_permissions(socket_guard.socket_path.as_path()).await?;
#[cfg(unix)]
std::os::unix::fs::symlink(
socket_guard.socket_path.as_path(),
socket_guard.rendezvous_path.as_path(),
)?;
info!(
socket_path = %socket_guard.socket_path.display(),
"app-server control socket listening"
@@ -155,11 +201,8 @@ async fn run_daemon_shutdown(
.await;
}
pub async fn prepare_control_socket_path(socket_path: &Path) -> IoResult<()> {
if let Some(parent) = socket_path.parent() {
codex_uds::prepare_private_socket_directory(parent).await?;
}
// Unix callers hold the physical socket's startup lock through bind and publication.
async fn prepare_control_socket_path(socket_path: &Path) -> IoResult<()> {
#[cfg(windows)]
let (socket_path, _directory_guard) = codex_uds::validate_private_socket_path(socket_path)?;
#[cfg(windows)]
@@ -177,7 +220,7 @@ pub async fn prepare_control_socket_path(socket_path: &Path) -> IoResult<()> {
),
));
}
Err(err) if err.kind() == ErrorKind::NotFound => return Ok(()),
Err(err) if err.kind() == ErrorKind::NotFound => {}
Err(err) if err.kind() == ErrorKind::ConnectionRefused => {}
Err(err) => {
if !socket_path.exists() {
@@ -187,6 +230,15 @@ pub async fn prepare_control_socket_path(socket_path: &Path) -> IoResult<()> {
}
}
// A crashed daemon can leave a dangling rendezvous symlink. Only recognize
// our own deterministic alias; never remove an arbitrary symlink target.
#[cfg(unix)]
if std::fs::read_link(socket_path).ok().as_deref()
== Some(protected_socket_path(socket_path)?.as_path())
{
return tokio::fs::remove_file(socket_path).await;
}
if !socket_path.try_exists()? {
return Ok(());
}
@@ -203,6 +255,23 @@ pub async fn prepare_control_socket_path(socket_path: &Path) -> IoResult<()> {
tokio::fs::remove_file(socket_path).await
}
#[cfg(unix)]
fn protected_socket_path(rendezvous_path: &Path) -> IoResult<std::path::PathBuf> {
use sha2::Digest;
use sha2::Sha256;
use std::os::unix::ffi::OsStrExt;
let parent = rendezvous_path.parent().ok_or_else(|| {
std::io::Error::new(ErrorKind::InvalidInput, "socket path must have a parent")
})?;
let name = rendezvous_path.file_name().ok_or_else(|| {
std::io::Error::new(ErrorKind::InvalidInput, "socket path must have a filename")
})?;
let path = std::fs::canonicalize(parent)?.join(name);
let hash = Sha256::digest(path.as_os_str().as_bytes());
Ok(codex_uds::shared_daemon_socket_directory()?.join(format!("{hash:x}")))
}
pub struct AppServerStartupLock {
_file: std::fs::File,
}
@@ -245,6 +314,8 @@ async fn set_control_socket_permissions(_socket_path: &Path) -> IoResult<()> {
struct ControlSocketFileGuard {
socket_path: AbsolutePathBuf,
#[cfg(unix)]
rendezvous_path: AbsolutePathBuf,
// Keep the directory pinned until after the socket file is removed in Drop.
#[cfg(windows)]
_directory_guard: std::os::windows::io::OwnedHandle,
@@ -252,6 +323,14 @@ struct ControlSocketFileGuard {
impl Drop for ControlSocketFileGuard {
fn drop(&mut self) {
#[cfg(unix)]
if std::fs::read_link(self.rendezvous_path.as_path())
.ok()
.as_deref()
== Some(self.socket_path.as_path())
{
let _ = std::fs::remove_file(self.rendezvous_path.as_path());
}
if let Err(err) = std::fs::remove_file(self.socket_path.as_path())
&& err.kind() != ErrorKind::NotFound
{
@@ -246,6 +246,35 @@ async fn app_server_startup_lock_serializes_waiters() {
.expect("second startup lock should succeed");
}
#[cfg(unix)]
#[tokio::test]
async fn control_socket_rejects_writable_parent_without_changing_permissions() {
use std::os::unix::fs::PermissionsExt;
let directory = tempfile::tempdir().unwrap();
std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o777)).unwrap();
let path = AbsolutePathBuf::from_absolute_path(directory.path().join("rpc.sock")).unwrap();
let (tx, _rx) = mpsc::channel(CHANNEL_CAPACITY);
let error = start_control_socket_acceptor(
path.clone(),
tx,
CancellationToken::new(),
DaemonShutdownAccess::Disabled,
)
.await
.unwrap_err();
assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
assert_eq!(
std::fs::metadata(directory.path())
.unwrap()
.permissions()
.mode()
& 0o777,
0o777
);
assert!(std::fs::symlink_metadata(path).is_err());
}
#[cfg(unix)]
#[tokio::test]
async fn control_socket_file_is_private_after_bind() {
@@ -253,6 +282,9 @@ async fn control_socket_file_is_private_after_bind() {
let temp_dir = tempfile::TempDir::new().expect("temp dir");
let socket_path = test_socket_path(temp_dir.path());
let parent = socket_path.as_path().parent().unwrap();
std::fs::create_dir_all(parent).unwrap();
std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o755)).unwrap();
let (transport_event_tx, _transport_event_rx) =
mpsc::channel::<TransportEvent>(CHANNEL_CAPACITY);
let shutdown_token = CancellationToken::new();
@@ -269,9 +301,60 @@ async fn control_socket_file_is_private_after_bind() {
.await
.expect("socket metadata should exist");
assert_eq!(metadata.permissions().mode() & 0o777, 0o600);
assert_eq!(
std::fs::metadata(parent).unwrap().permissions().mode() & 0o777,
0o755
);
let physical_path = std::fs::read_link(socket_path.as_path()).expect("rendezvous symlink");
assert_eq!(
physical_path.parent(),
Some(
codex_uds::shared_daemon_socket_directory()
.unwrap()
.as_path()
)
);
shutdown_token.cancel();
accept_handle.await.expect("acceptor should join");
assert!(!physical_path.exists());
assert!(std::fs::symlink_metadata(socket_path.as_path()).is_err());
// Simulate a dangling rendezvous left by an interrupted cleanup.
std::os::unix::fs::symlink(&physical_path, socket_path.as_path()).unwrap();
let (sender, _receiver) = mpsc::channel::<TransportEvent>(CHANNEL_CAPACITY);
let shutdown = CancellationToken::new();
let (first, second) = tokio::join!(
start_control_socket_acceptor(
socket_path.clone(),
sender.clone(),
shutdown.clone(),
DaemonShutdownAccess::Disabled,
),
start_control_socket_acceptor(
socket_path.clone(),
sender,
shutdown.clone(),
DaemonShutdownAccess::Disabled,
),
);
let (acceptor, error) = match (first, second) {
(Ok(acceptor), Err(error)) | (Err(error), Ok(acceptor)) => (acceptor, error),
_ => panic!("exactly one concurrent restart should replace the stale symlink"),
};
assert_eq!(error.kind(), std::io::ErrorKind::AddrInUse);
let _client = connect_to_socket(socket_path.as_path()).await.unwrap();
// Cleanup must not remove a replacement at the advertised path.
std::fs::remove_file(socket_path.as_path()).unwrap();
std::fs::write(socket_path.as_path(), b"replacement").unwrap();
shutdown.cancel();
acceptor.await.unwrap();
assert_eq!(
std::fs::read(socket_path.as_path()).unwrap(),
b"replacement"
);
assert!(!physical_path.exists());
}
#[cfg(windows)]