diff --git a/codex-rs/linux-sandbox/README.md b/codex-rs/linux-sandbox/README.md index 0d9204f0e7..bf8932bd30 100644 --- a/codex-rs/linux-sandbox/README.md +++ b/codex-rs/linux-sandbox/README.md @@ -78,6 +78,12 @@ commands that would enter the bubblewrap path. otherwise unrestricted networking still block `AF_VSOCK` sockets. All filter modes block `io_uring` to prevent bypassing socket-family restrictions. - When bubblewrap is active, the filesystem is read-only by default via `--ro-bind / /`. +- Filesystem-restricted commands see an empty, read-only `/etc/ssh/ssh_config.d` + by default. Host root-owned files can appear to belong to `nobody` in the user + namespace, causing OpenSSH to reject them. SSH skips settings in the masked + directory, including any `KnownHostsCommand` defined there. Settings in the main + `/etc/ssh/ssh_config` and the user's SSH config still apply. Explicit grants + to the drop-ins and overlapping write grants keep their configured access. - When bubblewrap is active, writable roots are layered with `--bind `. - When bubblewrap is active, protected subpaths under writable roots (for example `.git`, diff --git a/codex-rs/linux-sandbox/src/bwrap.rs b/codex-rs/linux-sandbox/src/bwrap.rs index f822a6daec..d0cfab5929 100644 --- a/codex-rs/linux-sandbox/src/bwrap.rs +++ b/codex-rs/linux-sandbox/src/bwrap.rs @@ -484,6 +484,14 @@ fn create_filesystem_args( unreadable_roots.sort(); unreadable_roots.dedup(); + let ssh_drop_ins = Path::new("/etc/ssh/ssh_config.d"); + let inherits_ssh_drop_ins = resolved.has_full_disk_read_access + || resolved.include_platform_defaults + || resolved + .readable_roots + .iter() + .any(|root| ssh_drop_ins.starts_with(root.as_path())); + let mut args = if resolved.has_full_disk_read_access { // Read-only root, then mount a minimal device tree. // In bubblewrap (`bubblewrap.c`, `SETUP_MOUNT_DEV`), `--dev /dev` @@ -756,6 +764,35 @@ fn create_filesystem_args( append_unreadable_root_args(&mut bwrap_args, &unreadable_root, &allowed_write_paths)?; } + // OpenSSH rejects host root-owned includes when root is unmapped. An empty + // directory makes its Include glob match nothing. Preserve explicit paths, + // and avoid targeting a symlink that could redirect the mask elsewhere. + if inherits_ssh_drop_ins + && !unreadable_roots + .iter() + .any(|path| ssh_drop_ins.starts_with(path)) + && !allowed_write_paths + .iter() + .any(|path| ssh_drop_ins.starts_with(path) || path.starts_with(ssh_drop_ins)) + && ssh_drop_ins.ancestors().all(|path| { + fs::symlink_metadata(path).is_ok_and(|m| { + m.is_dir() && (path == ssh_drop_ins || (m.uid() == 0 && m.mode() & 0o022 == 0)) + }) + }) + && !file_system_sandbox_policy + .entries + .iter() + .filter(|entry| entry.access == FileSystemAccessMode::Read) + .any(|entry| { + FileSystemSandboxPolicy::restricted(vec![entry.clone()]) + .get_readable_roots_with_cwd(cwd) + .iter() + .any(|path| path.as_path().starts_with(ssh_drop_ins)) + }) + { + append_empty_directory_args(&mut bwrap_args, ssh_drop_ins); + } + if options.mask_wslg_distro && !unreadable_roots.iter().any(|denied| { let distro = Path::new(WSLG_DISTRO_ROOT); diff --git a/codex-rs/linux-sandbox/tests/fixtures/ssh_handshake.sh b/codex-rs/linux-sandbox/tests/fixtures/ssh_handshake.sh new file mode 100644 index 0000000000..f6d9a654bd --- /dev/null +++ b/codex-rs/linux-sandbox/tests/fixtures/ssh_handshake.sh @@ -0,0 +1,74 @@ +#!/bin/sh +# Called in private mount, PID and network namespaces. The server and client use disposable keys. +set -eu +export PATH=/usr/bin:/usr/sbin:/bin:/sbin +export LC_ALL=C +skip() { echo "$*" >&2; exit 77; } +for tool in ssh sshd ssh-keygen bwrap setpriv ip; do + command -v "$tool" >/dev/null || skip "$tool is unavailable" +done +cd / +as_client() { setpriv --reuid 1000 --regid 1000 --clear-groups "$@"; } +as_client bwrap --unshare-user --unshare-pid --ro-bind / / --proc /proc -- /bin/true || + skip "the ordinary user cannot start a stock bubblewrap sandbox" +mount -t tmpfs -o mode=0755 tmpfs /etc/ssh || skip "cannot mount private SSH configuration" +mount -t tmpfs -o mode=0755 tmpfs /run || skip "cannot stage the private sshd runtime" +ip link set lo up || skip "cannot enable isolated loopback" +umask 022 +mkdir -p /run/sshd /etc/ssh/home /etc/ssh/ssh_config.d +install -m 755 "$1" /etc/ssh/codex-linux-sandbox +# Supply an unlocked account independently of the host's users and PAM configuration. +{ echo 'codexssh:x:1000:1000::/etc/ssh/home:/bin/sh'; cat /etc/passwd; } > /etc/ssh/passwd +mount --bind /etc/ssh/passwd /etc/passwd +chown 1000:1000 /etc/ssh/home +cd /etc/ssh +ssh-keygen -q -t ed25519 -N '' -f host_key +ssh-keygen -q -t ed25519 -N '' -f client_key +chown 1000:1000 client_key +cat > sshd_config <<'EOF' +ListenAddress 127.0.0.1 +Port 2222 +HostKey /etc/ssh/host_key +PidFile /run/sshd.pid +AuthorizedKeysFile /etc/ssh/client_key.pub +AuthenticationMethods publickey +UsePAM no +UseDNS no +EOF +"$(command -v sshd)" -t -f /etc/ssh/sshd_config +"$(command -v sshd)" -D -e -f /etc/ssh/sshd_config >/run/sshd.log 2>&1 & +sshd_pid=$! +trap 'kill "$sshd_pid" 2>/dev/null || :' EXIT + +echo 'ServerAliveInterval 73' > ssh_config.d/site.conf +cat > ssh_config <<'EOF' +Include /etc/ssh/ssh_config.d/*.conf +Host fixture.invalid + HostName 127.0.0.1 + Port 2222 + User codexssh + IdentityFile /etc/ssh/client_key + IdentitiesOnly yes + BatchMode yes + ConnectionAttempts 5 + HostKeyAlias fixture.invalid + StrictHostKeyChecking yes + UserKnownHostsFile /etc/ssh/pinned_host + GlobalKnownHostsFile none +EOF +pin() { { printf 'fixture.invalid '; cat "$1"; } > pinned_host; } +profile=$2 +sandbox() { as_client /etc/ssh/codex-linux-sandbox --sandbox-policy-cwd / --permission-profile "$profile" -- "$@"; } +as_client ssh -G -T fixture.invalid > /run/native +grep -qx 'serveraliveinterval 73' /run/native +pin host_key.pub +sandbox ssh -T fixture.invalid 'id -u' > /run/remote +grep -qx 1000 /run/remote +sandbox sh -c 'test ! -e /etc/ssh/ssh_config.d/site.conf' + +pin client_key.pub +rc=0 +sandbox ssh -T fixture.invalid 'echo unexpected' > /run/wrong-key 2>/run/error || rc=$? +test "$rc" = 255 +test ! -s /run/wrong-key +grep -F 'REMOTE HOST IDENTIFICATION HAS CHANGED' /run/error diff --git a/codex-rs/linux-sandbox/tests/suite/sandbox.rs b/codex-rs/linux-sandbox/tests/suite/sandbox.rs index e0167df88c..64109c0c46 100644 --- a/codex-rs/linux-sandbox/tests/suite/sandbox.rs +++ b/codex-rs/linux-sandbox/tests/suite/sandbox.rs @@ -39,6 +39,9 @@ mod root_metadata_tests; #[path = "denied_files_tests.rs"] mod denied_files_tests; +#[path = "ssh_config_tests.rs"] +mod ssh_config_tests; + // At least on GitHub CI, the arm64 tests appear to need longer timeouts. #[cfg(not(target_arch = "aarch64"))] diff --git a/codex-rs/linux-sandbox/tests/suite/ssh_config_tests.rs b/codex-rs/linux-sandbox/tests/suite/ssh_config_tests.rs new file mode 100644 index 0000000000..1ed6086514 --- /dev/null +++ b/codex-rs/linux-sandbox/tests/suite/ssh_config_tests.rs @@ -0,0 +1,46 @@ +//! Masking system drop-ins must preserve host-key checks in the main SSH configuration. + +use super::codex_linux_sandbox_exe; +use codex_protocol::models::PermissionProfile; +use codex_protocol::permissions::FileSystemSandboxPolicy; +use codex_protocol::permissions::NetworkSandboxPolicy; +use std::process::Command; + +#[test] +fn ssh_masks_system_dropins_and_rejects_a_changed_host_key() { + // The fixture stages root-owned files, then runs the client as UID 1000. + if unsafe { libc::geteuid() } != 0 { + eprintln!("skipping SSH handshake: root is required to create the two-owner fixture"); + return; + } + let profile = PermissionProfile::from_runtime_permissions( + &FileSystemSandboxPolicy::read_only(), + NetworkSandboxPolicy::Enabled, + ); + let fixture = codex_utils_cargo_bin::find_resource!("tests/fixtures/ssh_handshake.sh").unwrap(); + let output = Command::new("unshare") + .args(["--mount-proc", "--net", "--pid", "--fork"]) + .args(["--propagation", "private", "--", "/bin/sh"]) + .arg(fixture) + .arg(codex_linux_sandbox_exe()) + .arg(serde_json::to_string(&profile).unwrap()) + .output(); + let output = match output { + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + eprintln!("skipping SSH handshake: unshare is unavailable"); + return; + } + result => result.unwrap(), + }; + if output.status.code() == Some(77) + || (output.stderr.starts_with(b"unshare:") + && String::from_utf8_lossy(&output.stderr).contains("Operation not permitted")) + { + eprintln!( + "skipping SSH handshake: {}", + String::from_utf8_lossy(&output.stderr) + ); + return; + } + assert!(output.status.success(), "{output:?}"); +}