From 808ea21a5de3e82fae6eece809d6a9148c7ad15e Mon Sep 17 00:00:00 2001 From: viyatb-oai Date: Tue, 2 Jun 2026 15:45:51 -0700 Subject: [PATCH] fix: reject symlinked output-last-message paths Co-authored-by: Codex noreply@openai.com --- codex-rs/Cargo.lock | 2 + codex-rs/exec/Cargo.toml | 1 + codex-rs/exec/src/event_processor.rs | 19 +++- codex-rs/exec/src/event_processor_tests.rs | 60 +++++++++++++ codex-rs/utils/path-utils/Cargo.toml | 3 + codex-rs/utils/path-utils/src/lib.rs | 90 +++++++++++++++++++ .../utils/path-utils/src/path_utils_tests.rs | 36 ++++++++ 7 files changed, 210 insertions(+), 1 deletion(-) create mode 100644 codex-rs/exec/src/event_processor_tests.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index e9c171d778..f1a95ad46f 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -2751,6 +2751,7 @@ dependencies = [ "codex-utils-cargo-bin", "codex-utils-cli", "codex-utils-oss", + "codex-utils-path", "codex-utils-sandbox-summary", "core_test_support", "libc", @@ -4088,6 +4089,7 @@ version = "0.0.0" dependencies = [ "codex-utils-absolute-path", "dunce", + "libc", "pretty_assertions", "tempfile", ] diff --git a/codex-rs/exec/Cargo.toml b/codex-rs/exec/Cargo.toml index cdfc569b68..48a825292c 100644 --- a/codex-rs/exec/Cargo.toml +++ b/codex-rs/exec/Cargo.toml @@ -39,6 +39,7 @@ codex-protocol = { workspace = true } codex-utils-absolute-path = { workspace = true } codex-utils-cli = { workspace = true } codex-utils-oss = { workspace = true } +codex-utils-path = { workspace = true } codex-utils-sandbox-summary = { workspace = true } owo-colors = { workspace = true } serde = { workspace = true, features = ["derive"] } diff --git a/codex-rs/exec/src/event_processor.rs b/codex-rs/exec/src/event_processor.rs index 4d1da09001..f1bde65c8b 100644 --- a/codex-rs/exec/src/event_processor.rs +++ b/codex-rs/exec/src/event_processor.rs @@ -1,3 +1,5 @@ +#[cfg(unix)] +use std::io::Write; use std::path::Path; use codex_app_server_protocol::ServerNotification; @@ -41,8 +43,23 @@ pub(crate) fn handle_last_message(last_agent_message: Option<&str>, output_file: fn write_last_message_file(contents: &str, last_message_path: Option<&Path>) { if let Some(path) = last_message_path - && let Err(e) = std::fs::write(path, contents) + && let Err(e) = write_last_message_to_path(path, contents) { eprintln!("Failed to write last message file {path:?}: {e}"); } } + +#[cfg(unix)] +fn write_last_message_to_path(path: &Path, contents: &str) -> std::io::Result<()> { + let mut file = codex_utils_path::open_file_for_write_no_follow(path)?; + file.write_all(contents.as_bytes()) +} + +#[cfg(not(unix))] +fn write_last_message_to_path(path: &Path, contents: &str) -> std::io::Result<()> { + std::fs::write(path, contents) +} + +#[cfg(test)] +#[path = "event_processor_tests.rs"] +mod tests; diff --git a/codex-rs/exec/src/event_processor_tests.rs b/codex-rs/exec/src/event_processor_tests.rs new file mode 100644 index 0000000000..6353b3bb66 --- /dev/null +++ b/codex-rs/exec/src/event_processor_tests.rs @@ -0,0 +1,60 @@ +use super::write_last_message_to_path; +use pretty_assertions::assert_eq; +use tempfile::tempdir; + +#[test] +fn writes_last_message_to_regular_file() { + let temp_dir = tempdir().expect("tempdir"); + let output_path = temp_dir + .path() + .canonicalize() + .expect("canonical tempdir") + .join("output.md"); + + write_last_message_to_path(&output_path, "hello").expect("write output"); + + assert_eq!( + std::fs::read_to_string(&output_path).expect("read output"), + "hello" + ); +} + +#[cfg(unix)] +#[test] +fn rejects_symlinked_last_message_path() { + let temp_dir = tempdir().expect("tempdir"); + let temp_dir = temp_dir.path().canonicalize().expect("canonical tempdir"); + let target_path = temp_dir.join("target.md"); + let output_path = temp_dir.join("output.md"); + std::fs::write(&target_path, "original").expect("write target"); + std::os::unix::fs::symlink(&target_path, &output_path).expect("create symlink"); + + let err = write_last_message_to_path(&output_path, "hello").expect_err("symlink should fail"); + + assert_eq!(err.raw_os_error(), Some(libc::ELOOP)); + assert_eq!( + std::fs::read_to_string(&target_path).expect("read target"), + "original" + ); +} + +#[cfg(unix)] +#[test] +fn rejects_symlinked_last_message_parent_directory() { + let temp_dir = tempdir().expect("tempdir"); + let temp_dir = temp_dir.path().canonicalize().expect("canonical tempdir"); + let target_dir = temp_dir.join("target"); + let symlinked_dir = temp_dir.join("link"); + std::fs::create_dir(&target_dir).expect("create target directory"); + let target_path = target_dir.join("output.md"); + std::fs::write(&target_path, "original").expect("write target"); + std::os::unix::fs::symlink(&target_dir, &symlinked_dir).expect("create symlink"); + + write_last_message_to_path(&symlinked_dir.join("output.md"), "hello") + .expect_err("symlinked parent should fail"); + + assert_eq!( + std::fs::read_to_string(&target_path).expect("read target"), + "original" + ); +} diff --git a/codex-rs/utils/path-utils/Cargo.toml b/codex-rs/utils/path-utils/Cargo.toml index d1503fd060..287247f877 100644 --- a/codex-rs/utils/path-utils/Cargo.toml +++ b/codex-rs/utils/path-utils/Cargo.toml @@ -12,6 +12,9 @@ codex-utils-absolute-path = { workspace = true } dunce = { workspace = true } tempfile = { workspace = true } +[target.'cfg(unix)'.dependencies] +libc = { workspace = true } + [dev-dependencies] pretty_assertions = { workspace = true } tempfile = { workspace = true } diff --git a/codex-rs/utils/path-utils/src/lib.rs b/codex-rs/utils/path-utils/src/lib.rs index 71b0a6473d..5b346084bb 100644 --- a/codex-rs/utils/path-utils/src/lib.rs +++ b/codex-rs/utils/path-utils/src/lib.rs @@ -5,7 +5,19 @@ pub use env::is_wsl; use codex_utils_absolute_path::AbsolutePathBuf; use std::collections::HashSet; +#[cfg(unix)] +use std::ffi::CString; +#[cfg(unix)] +use std::fs::File; use std::io; +#[cfg(unix)] +use std::os::fd::AsRawFd; +#[cfg(unix)] +use std::os::fd::FromRawFd; +#[cfg(unix)] +use std::os::unix::ffi::OsStrExt; +#[cfg(unix)] +use std::path::Component; use std::path::Path; use std::path::PathBuf; use tempfile::NamedTempFile; @@ -132,6 +144,84 @@ pub fn write_atomically(write_path: &Path, contents: &str) -> io::Result<()> { Ok(()) } +/// Opens a file for writing without following symlinks in any path component. +#[cfg(unix)] +pub fn open_file_for_write_no_follow(path: &Path) -> io::Result { + open_file_no_follow( + path, + libc::O_WRONLY | libc::O_CREAT | libc::O_TRUNC, + /*mode*/ 0o666, + ) +} + +#[cfg(unix)] +fn open_file_no_follow(path: &Path, flags: libc::c_int, mode: libc::mode_t) -> io::Result { + let components = path + .components() + .filter_map(|component| match component { + Component::RootDir | Component::CurDir => None, + Component::ParentDir => Some(Ok(std::ffi::OsStr::new(".."))), + Component::Normal(component) => Some(Ok(component)), + Component::Prefix(_) => Some(Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("unsupported path prefix in {}", path.display()), + ))), + }) + .collect::>>()?; + let Some((file_name, parent_components)) = components.split_last() else { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("path {} does not name a file", path.display()), + )); + }; + + let mut current_dir = if path.is_absolute() { + File::open("/")? + } else { + File::open(".")? + }; + for component in parent_components { + current_dir = openat( + ¤t_dir, + component, + libc::O_RDONLY | libc::O_CLOEXEC | libc::O_DIRECTORY | libc::O_NOFOLLOW, + /*mode*/ 0, + )?; + } + openat( + ¤t_dir, + file_name, + flags | libc::O_CLOEXEC | libc::O_NOFOLLOW, + mode, + ) +} + +#[cfg(unix)] +fn openat( + directory: &File, + path: &std::ffi::OsStr, + flags: libc::c_int, + mode: libc::mode_t, +) -> io::Result { + let path = CString::new(path.as_bytes()) + .map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?; + // SAFETY: `path` is NUL-terminated, `directory` owns a valid fd, and the + // returned fd is transferred into a `File` exactly once. + let fd = unsafe { + libc::openat( + directory.as_raw_fd(), + path.as_ptr(), + flags, + libc::c_uint::from(mode), + ) + }; + if fd == -1 { + return Err(io::Error::last_os_error()); + } + // SAFETY: `openat` returned a new owned file descriptor. + Ok(unsafe { File::from_raw_fd(fd) }) +} + fn normalize_for_wsl(path: PathBuf) -> PathBuf { normalize_for_wsl_with_flag(path, env::is_wsl()) } diff --git a/codex-rs/utils/path-utils/src/path_utils_tests.rs b/codex-rs/utils/path-utils/src/path_utils_tests.rs index 94c914fec2..a768f8fac2 100644 --- a/codex-rs/utils/path-utils/src/path_utils_tests.rs +++ b/codex-rs/utils/path-utils/src/path_utils_tests.rs @@ -1,7 +1,9 @@ #[cfg(unix)] mod symlinks { + use super::super::open_file_for_write_no_follow; use super::super::resolve_symlink_write_paths; use pretty_assertions::assert_eq; + use std::io::Write; use std::os::unix::fs::symlink; #[test] @@ -19,6 +21,40 @@ mod symlinks { assert_eq!(resolved.write_path, a); Ok(()) } + + #[test] + fn no_follow_write_rejects_symlinked_parent_directory() -> std::io::Result<()> { + let dir = tempfile::tempdir()?; + let dir = dir.path().canonicalize()?; + let target_dir = dir.join("target"); + let symlinked_dir = dir.join("link"); + std::fs::create_dir(&target_dir)?; + std::fs::write(target_dir.join("payload"), "original")?; + symlink(&target_dir, &symlinked_dir)?; + + let err = open_file_for_write_no_follow(&symlinked_dir.join("payload")) + .expect_err("symlinked parent should fail"); + + assert!(err.raw_os_error().is_some()); + assert_eq!( + std::fs::read_to_string(target_dir.join("payload"))?, + "original" + ); + Ok(()) + } + + #[test] + fn no_follow_write_writes_regular_file() -> std::io::Result<()> { + let dir = tempfile::tempdir()?; + let path = dir.path().canonicalize()?.join("payload"); + + let mut writer = open_file_for_write_no_follow(&path)?; + writer.write_all(b"hello")?; + drop(writer); + + assert_eq!(std::fs::read_to_string(&path)?, "hello"); + Ok(()) + } } #[cfg(target_os = "linux")]