mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:31:09 +00:00
Harden unsandboxed patch filesystem access (#39659)
## Why An `apply_patch` path can be replaced with a symlink after verification, allowing an unsandboxed patch operation to reach a different file than the one that was approved. ## What changed - Add `follow_symlinks` options to executor filesystem reads, writes, metadata lookups, directory creation, and removal, including the corresponding `followSymlinks` protocol fields. - Implement no-follow filesystem operations on Unix and Windows that reject links in any path component and restrict file access to regular files. - Run `apply_patch` with symlink traversal disabled when an otherwise-required sandbox is bypassed, while retaining the existing follow-symlink default for standalone callers. ## Testing - Cover leaf and ancestor symlinks across patch add, update, delete, and move operations, including a path swap after verification. - Exercise local and remote no-follow filesystem behavior, concurrent directory creation, special-file rejection, and Windows reparse points. GitOrigin-RevId: 43fd479084891493ce13564fbd894b98f329c6dd
This commit is contained in:
1 parent
4e1a772a7d
commit
e3e5ad2847
88 files changed
+2782
-302
No files matched your search
@@ -0,0 +1,60 @@
|
||||
use crate::FileMetadata;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
#[cfg(windows)]
|
||||
use std::time::SystemTime;
|
||||
#[cfg(windows)]
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
#[cfg(unix)]
|
||||
mod unix;
|
||||
#[cfg(windows)]
|
||||
mod windows;
|
||||
|
||||
#[cfg(unix)]
|
||||
use unix as imp;
|
||||
#[cfg(windows)]
|
||||
use windows as imp;
|
||||
|
||||
pub(crate) async fn open_file(path: &Path) -> io::Result<tokio::fs::File> {
|
||||
imp::open_file(path.to_path_buf()).await
|
||||
}
|
||||
|
||||
pub(crate) async fn write_file(path: &Path, contents: Vec<u8>) -> io::Result<()> {
|
||||
imp::write_file(path.to_path_buf(), contents).await
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
pub(crate) async fn metadata(path: &Path) -> io::Result<FileMetadata> {
|
||||
imp::metadata(path.to_path_buf()).await
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub(crate) async fn metadata(path: &Path) -> io::Result<FileMetadata> {
|
||||
imp::metadata(path.to_path_buf())
|
||||
.await
|
||||
.map(|metadata| FileMetadata {
|
||||
is_directory: metadata.is_dir(),
|
||||
is_file: metadata.is_file(),
|
||||
is_symlink: false,
|
||||
size: metadata.len(),
|
||||
created_at_ms: metadata.created().ok().map_or(0, system_time_to_unix_ms),
|
||||
modified_at_ms: metadata.modified().ok().map_or(0, system_time_to_unix_ms),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn system_time_to_unix_ms(time: SystemTime) -> i64 {
|
||||
time.duration_since(UNIX_EPOCH)
|
||||
.ok()
|
||||
.and_then(|duration| i64::try_from(duration.as_millis()).ok())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
pub(crate) async fn create_directory(path: &Path, recursive: bool) -> io::Result<()> {
|
||||
imp::create_directory(path.to_path_buf(), recursive).await
|
||||
}
|
||||
|
||||
pub(crate) async fn remove(path: &Path, recursive: bool, force: bool) -> io::Result<()> {
|
||||
imp::remove(path.to_path_buf(), recursive, force).await
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
use crate::FileMetadata;
|
||||
use rustix::fs::AtFlags;
|
||||
use rustix::fs::Mode;
|
||||
use rustix::fs::OFlags;
|
||||
use rustix::fs::Stat;
|
||||
use rustix::fs::fstat;
|
||||
use rustix::fs::mkdirat;
|
||||
use rustix::fs::open;
|
||||
use rustix::fs::openat;
|
||||
use rustix::fs::statat;
|
||||
use rustix::fs::unlinkat;
|
||||
use std::ffi::OsString;
|
||||
use std::io;
|
||||
use std::io::Write;
|
||||
use std::os::fd::OwnedFd;
|
||||
use std::path::Component;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
||||
fn directory_access_flags() -> OFlags {
|
||||
OFlags::PATH
|
||||
}
|
||||
|
||||
#[cfg(target_vendor = "apple")]
|
||||
fn directory_access_flags() -> OFlags {
|
||||
OFlags::from_bits_retain(libc::O_SEARCH as u32)
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "linux", target_os = "android", target_vendor = "apple")))]
|
||||
fn directory_access_flags() -> OFlags {
|
||||
OFlags::RDONLY
|
||||
}
|
||||
|
||||
fn components(path: &Path) -> io::Result<Vec<OsString>> {
|
||||
if !path.is_absolute() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"no-follow filesystem operations require an absolute path",
|
||||
));
|
||||
}
|
||||
path.components()
|
||||
.filter_map(|component| match component {
|
||||
Component::RootDir => None,
|
||||
Component::Normal(component) => Some(Ok(component.to_os_string())),
|
||||
Component::CurDir | Component::ParentDir | Component::Prefix(_) => {
|
||||
Some(Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"no-follow filesystem operations require a normalized path",
|
||||
)))
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn root() -> io::Result<OwnedFd> {
|
||||
open(
|
||||
"/",
|
||||
directory_access_flags() | OFlags::DIRECTORY | OFlags::CLOEXEC,
|
||||
Mode::empty(),
|
||||
)
|
||||
.map_err(io::Error::from)
|
||||
}
|
||||
|
||||
fn open_directory(parent: &OwnedFd, name: &OsString) -> io::Result<OwnedFd> {
|
||||
openat(
|
||||
parent,
|
||||
name,
|
||||
directory_access_flags() | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
|
||||
Mode::empty(),
|
||||
)
|
||||
.map_err(io::Error::from)
|
||||
}
|
||||
|
||||
fn parent(path: &Path) -> io::Result<(OwnedFd, OsString)> {
|
||||
let mut components = components(path)?;
|
||||
let leaf = components
|
||||
.pop()
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path must name an entry"))?;
|
||||
let mut directory = root()?;
|
||||
for component in components {
|
||||
directory = open_directory(&directory, &component)?;
|
||||
}
|
||||
Ok((directory, leaf))
|
||||
}
|
||||
|
||||
fn open_entry_sync(path: &Path) -> io::Result<std::fs::File> {
|
||||
let (parent, leaf) = parent(path)?;
|
||||
let file = openat(
|
||||
&parent,
|
||||
leaf,
|
||||
OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC,
|
||||
Mode::empty(),
|
||||
)
|
||||
.map_err(io::Error::from)?;
|
||||
Ok(std::fs::File::from(file))
|
||||
}
|
||||
|
||||
fn open_file_sync(path: &Path) -> io::Result<std::fs::File> {
|
||||
let file = open_entry_sync(path)?;
|
||||
if !file.metadata()?.is_file() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"path is not a regular file",
|
||||
));
|
||||
}
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
pub(super) async fn open_file(path: PathBuf) -> io::Result<tokio::fs::File> {
|
||||
tokio::task::spawn_blocking(move || open_file_sync(&path).map(tokio::fs::File::from_std))
|
||||
.await
|
||||
.map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
|
||||
}
|
||||
|
||||
pub(super) async fn write_file(path: PathBuf, contents: Vec<u8>) -> io::Result<()> {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let (parent, leaf) = parent(&path)?;
|
||||
// Prevent FIFOs and devices from blocking during open before the
|
||||
// descriptor can be validated as a regular file below.
|
||||
let file = openat(
|
||||
&parent,
|
||||
leaf,
|
||||
OFlags::WRONLY | OFlags::CREATE | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC,
|
||||
Mode::from_raw_mode(0o666),
|
||||
)
|
||||
.map_err(io::Error::from)?;
|
||||
let mut file = std::fs::File::from(file);
|
||||
if !file.metadata()?.is_file() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"path is not a regular file",
|
||||
));
|
||||
}
|
||||
file.set_len(0)?;
|
||||
file.write_all(&contents)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
|
||||
}
|
||||
|
||||
fn metadata_sync(path: &Path) -> io::Result<FileMetadata> {
|
||||
let components = components(path)?;
|
||||
let metadata = if components.is_empty() {
|
||||
fstat(root()?).map_err(io::Error::from)?
|
||||
} else {
|
||||
let (parent, leaf) = parent(path)?;
|
||||
statat(&parent, leaf, AtFlags::SYMLINK_NOFOLLOW).map_err(io::Error::from)?
|
||||
};
|
||||
file_metadata(metadata)
|
||||
}
|
||||
|
||||
fn file_metadata(metadata: Stat) -> io::Result<FileMetadata> {
|
||||
let kind = metadata.st_mode & libc::S_IFMT;
|
||||
if kind == libc::S_IFLNK {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"path contains a symbolic link",
|
||||
));
|
||||
}
|
||||
Ok(FileMetadata {
|
||||
is_directory: kind == libc::S_IFDIR,
|
||||
is_file: kind == libc::S_IFREG,
|
||||
is_symlink: false,
|
||||
size: u64::try_from(metadata.st_size).unwrap_or(0),
|
||||
created_at_ms: created_at_ms(&metadata),
|
||||
modified_at_ms: unix_time_ms(metadata.st_mtime, metadata.st_mtime_nsec),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(target_vendor = "apple")]
|
||||
fn created_at_ms(metadata: &Stat) -> i64 {
|
||||
unix_time_ms(metadata.st_birthtime, metadata.st_birthtime_nsec)
|
||||
}
|
||||
|
||||
#[cfg(not(target_vendor = "apple"))]
|
||||
fn created_at_ms(_metadata: &Stat) -> i64 {
|
||||
0
|
||||
}
|
||||
|
||||
fn unix_time_ms(seconds: i64, nanoseconds: impl TryInto<i64>) -> i64 {
|
||||
let nanoseconds = nanoseconds.try_into().unwrap_or_default();
|
||||
seconds
|
||||
.saturating_mul(1_000)
|
||||
.saturating_add(nanoseconds / 1_000_000)
|
||||
}
|
||||
|
||||
pub(super) async fn metadata(path: PathBuf) -> io::Result<FileMetadata> {
|
||||
tokio::task::spawn_blocking(move || metadata_sync(&path))
|
||||
.await
|
||||
.map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
|
||||
}
|
||||
|
||||
pub(super) async fn create_directory(path: PathBuf, recursive: bool) -> io::Result<()> {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let components = components(&path)?;
|
||||
if components.is_empty() && !recursive {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::AlreadyExists,
|
||||
"directory already exists",
|
||||
));
|
||||
}
|
||||
let mut directory = root()?;
|
||||
for (index, component) in components.iter().enumerate() {
|
||||
let is_leaf = index + 1 == components.len();
|
||||
if !recursive && is_leaf {
|
||||
mkdirat(&directory, component, Mode::from_raw_mode(0o777))
|
||||
.map_err(io::Error::from)?;
|
||||
return Ok(());
|
||||
}
|
||||
match open_directory(&directory, component) {
|
||||
Ok(next) => directory = next,
|
||||
Err(error) if recursive && error.kind() == io::ErrorKind::NotFound => {
|
||||
match mkdirat(&directory, component, Mode::from_raw_mode(0o777)) {
|
||||
Ok(()) | Err(rustix::io::Errno::EXIST) => {}
|
||||
Err(error) => return Err(io::Error::from(error)),
|
||||
}
|
||||
directory = open_directory(&directory, component)?;
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
.map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
|
||||
}
|
||||
|
||||
pub(super) async fn remove(path: PathBuf, recursive: bool, force: bool) -> io::Result<()> {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
if recursive {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"recursive no-follow removal is unsupported",
|
||||
));
|
||||
}
|
||||
let (parent, leaf) = match parent(&path) {
|
||||
Ok(value) => value,
|
||||
Err(error) if force && error.kind() == io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let metadata = match statat(&parent, &leaf, AtFlags::SYMLINK_NOFOLLOW) {
|
||||
Ok(metadata) => metadata,
|
||||
Err(error) if force && error == rustix::io::Errno::NOENT => return Ok(()),
|
||||
Err(error) => return Err(io::Error::from(error)),
|
||||
};
|
||||
let kind = metadata.st_mode & libc::S_IFMT;
|
||||
if kind == libc::S_IFLNK {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"path contains a symbolic link",
|
||||
));
|
||||
}
|
||||
let flags = if kind == libc::S_IFDIR {
|
||||
AtFlags::REMOVEDIR
|
||||
} else {
|
||||
AtFlags::empty()
|
||||
};
|
||||
unlinkat(&parent, leaf, flags).map_err(io::Error::from)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
use crate::regular_file;
|
||||
use std::ffi::OsStr;
|
||||
use std::ffi::c_void;
|
||||
use std::io;
|
||||
use std::io::Write;
|
||||
use std::mem::size_of;
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::os::windows::io::FromRawHandle;
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
use std::os::windows::io::RawHandle;
|
||||
use std::path::Component;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::path::Prefix;
|
||||
use std::ptr;
|
||||
use windows_sys::Win32::Foundation::HANDLE;
|
||||
use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
|
||||
use windows_sys::Win32::Foundation::NTSTATUS;
|
||||
use windows_sys::Win32::Foundation::RtlNtStatusToDosError;
|
||||
use windows_sys::Win32::Foundation::UNICODE_STRING;
|
||||
use windows_sys::Win32::Security::SECURITY_QUALITY_OF_SERVICE;
|
||||
use windows_sys::Win32::Security::SecurityIdentification;
|
||||
use windows_sys::Win32::Storage::FileSystem::DELETE;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_NORMAL;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_READ;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_READ_ATTRIBUTES;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_DELETE;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_WRITE_DATA;
|
||||
use windows_sys::Win32::System::IO::IO_STATUS_BLOCK;
|
||||
use windows_sys::Win32::System::IO::IO_STATUS_BLOCK_0;
|
||||
use windows_sys::Win32::System::Kernel::OBJ_CASE_INSENSITIVE;
|
||||
use windows_sys::Win32::System::Kernel::OBJ_DONT_REPARSE;
|
||||
|
||||
const FILE_DIRECTORY_FILE: u32 = 0x0000_0001;
|
||||
const FILE_SYNCHRONOUS_IO_NONALERT: u32 = 0x0000_0020;
|
||||
const FILE_NON_DIRECTORY_FILE: u32 = 0x0000_0040;
|
||||
const FILE_DELETE_ON_CLOSE: u32 = 0x0000_1000;
|
||||
const FILE_OPEN: u32 = 1;
|
||||
const FILE_CREATE: u32 = 2;
|
||||
const FILE_OPEN_IF: u32 = 3;
|
||||
const SYNCHRONIZE_ACCESS: u32 = 0x0010_0000;
|
||||
const STATUS_REPARSE_POINT_ENCOUNTERED: NTSTATUS = 0xC000_050B_u32 as i32;
|
||||
const SECURITY_STATIC_TRACKING: u8 = 0;
|
||||
const BOOLEAN_TRUE: u8 = 1;
|
||||
|
||||
#[repr(C)]
|
||||
struct ObjectAttributes {
|
||||
length: u32,
|
||||
root_directory: HANDLE,
|
||||
object_name: *const UNICODE_STRING,
|
||||
attributes: u32,
|
||||
security_descriptor: *const c_void,
|
||||
security_quality_of_service: *const c_void,
|
||||
}
|
||||
|
||||
#[link(name = "ntdll")]
|
||||
unsafe extern "system" {
|
||||
fn NtCreateFile(
|
||||
file_handle: *mut HANDLE,
|
||||
desired_access: u32,
|
||||
object_attributes: *const ObjectAttributes,
|
||||
io_status_block: *mut IO_STATUS_BLOCK,
|
||||
allocation_size: *const i64,
|
||||
file_attributes: u32,
|
||||
share_access: u32,
|
||||
create_disposition: u32,
|
||||
create_options: u32,
|
||||
ea_buffer: *const c_void,
|
||||
ea_length: u32,
|
||||
) -> NTSTATUS;
|
||||
}
|
||||
|
||||
fn nt_path(path: &Path) -> io::Result<Vec<u16>> {
|
||||
if !path.is_absolute() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"no-follow filesystem operations require an absolute path",
|
||||
));
|
||||
}
|
||||
|
||||
let (prefix, source_offset) = match path.components().next() {
|
||||
Some(Component::Prefix(prefix)) => match prefix.kind() {
|
||||
Prefix::Disk(_) => ("\\??\\", 0),
|
||||
Prefix::VerbatimDisk(_) => ("\\??\\", 4),
|
||||
Prefix::UNC(_, _) => ("\\??\\UNC\\", 2),
|
||||
Prefix::VerbatimUNC(_, _) => ("\\??\\UNC\\", 8),
|
||||
_ => {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"no-follow filesystem operations require a local disk or UNC path",
|
||||
));
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"no-follow filesystem operations require an absolute Windows path",
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let mut result: Vec<u16> = OsStr::new(prefix).encode_wide().collect();
|
||||
result.extend(
|
||||
path.as_os_str()
|
||||
.encode_wide()
|
||||
.skip(source_offset)
|
||||
.map(|unit| {
|
||||
if unit == b'/' as u16 {
|
||||
b'\\' as u16
|
||||
} else {
|
||||
unit
|
||||
}
|
||||
}),
|
||||
);
|
||||
result.push(0);
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn open_handle(
|
||||
path: &Path,
|
||||
desired_access: u32,
|
||||
create_disposition: u32,
|
||||
create_options: u32,
|
||||
) -> io::Result<OwnedHandle> {
|
||||
let mut path = nt_path(path)?;
|
||||
let name_length = u16::try_from((path.len() - 1) * size_of::<u16>())
|
||||
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "filesystem path is too long"))?;
|
||||
let maximum_length = u16::try_from(path.len() * size_of::<u16>())
|
||||
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "filesystem path is too long"))?;
|
||||
let object_name = UNICODE_STRING {
|
||||
Length: name_length,
|
||||
MaximumLength: maximum_length,
|
||||
Buffer: path.as_mut_ptr(),
|
||||
};
|
||||
let security_quality_of_service = SECURITY_QUALITY_OF_SERVICE {
|
||||
Length: size_of::<SECURITY_QUALITY_OF_SERVICE>() as u32,
|
||||
ImpersonationLevel: SecurityIdentification,
|
||||
ContextTrackingMode: SECURITY_STATIC_TRACKING,
|
||||
EffectiveOnly: BOOLEAN_TRUE,
|
||||
};
|
||||
let object_attributes = ObjectAttributes {
|
||||
length: size_of::<ObjectAttributes>() as u32,
|
||||
root_directory: 0,
|
||||
object_name: &object_name,
|
||||
attributes: OBJ_CASE_INSENSITIVE as u32 | OBJ_DONT_REPARSE as u32,
|
||||
security_descriptor: ptr::null(),
|
||||
security_quality_of_service: (&raw const security_quality_of_service).cast(),
|
||||
};
|
||||
let mut io_status_block = IO_STATUS_BLOCK {
|
||||
Anonymous: IO_STATUS_BLOCK_0 { Status: 0 },
|
||||
Information: 0,
|
||||
};
|
||||
let mut handle = 0;
|
||||
let status = unsafe {
|
||||
NtCreateFile(
|
||||
&mut handle,
|
||||
desired_access | SYNCHRONIZE_ACCESS,
|
||||
&object_attributes,
|
||||
&mut io_status_block,
|
||||
ptr::null(),
|
||||
FILE_ATTRIBUTE_NORMAL,
|
||||
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
|
||||
create_disposition,
|
||||
create_options | FILE_SYNCHRONOUS_IO_NONALERT,
|
||||
ptr::null(),
|
||||
/*ea_length*/ 0,
|
||||
)
|
||||
};
|
||||
if status < 0 {
|
||||
if status == STATUS_REPARSE_POINT_ENCOUNTERED {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"path contains a reparse point",
|
||||
));
|
||||
}
|
||||
let code = unsafe { RtlNtStatusToDosError(status) };
|
||||
return Err(io::Error::from_raw_os_error(code as i32));
|
||||
}
|
||||
if handle == 0 || handle == INVALID_HANDLE_VALUE {
|
||||
return Err(io::Error::other(
|
||||
"NtCreateFile returned an invalid filesystem handle",
|
||||
));
|
||||
}
|
||||
|
||||
Ok(unsafe { OwnedHandle::from_raw_handle(handle as RawHandle) })
|
||||
}
|
||||
|
||||
fn open_entry(path: &Path) -> io::Result<std::fs::File> {
|
||||
let handle = open_handle(
|
||||
path,
|
||||
FILE_READ_ATTRIBUTES,
|
||||
FILE_OPEN,
|
||||
/*create_options*/ 0,
|
||||
)?;
|
||||
Ok(std::fs::File::from(handle))
|
||||
}
|
||||
|
||||
fn open_file_sync(path: &Path) -> io::Result<std::fs::File> {
|
||||
let handle = open_handle(path, FILE_GENERIC_READ, FILE_OPEN, FILE_NON_DIRECTORY_FILE)?;
|
||||
let file = std::fs::File::from(handle);
|
||||
validate_regular_file(&file, path)?;
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
fn validate_regular_file(file: &std::fs::File, path: &Path) -> io::Result<()> {
|
||||
if !regular_file::is_disk_file(file) || !file.metadata()?.is_file() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!("path `{}` is not a file", path.display()),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn open_file(path: PathBuf) -> io::Result<tokio::fs::File> {
|
||||
tokio::task::spawn_blocking(move || open_file_sync(&path).map(tokio::fs::File::from_std))
|
||||
.await
|
||||
.map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
|
||||
}
|
||||
|
||||
pub(super) async fn write_file(path: PathBuf, contents: Vec<u8>) -> io::Result<()> {
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let handle = open_handle(
|
||||
&path,
|
||||
FILE_READ_ATTRIBUTES | FILE_WRITE_DATA,
|
||||
FILE_OPEN_IF,
|
||||
FILE_NON_DIRECTORY_FILE,
|
||||
)?;
|
||||
let mut file = std::fs::File::from(handle);
|
||||
validate_regular_file(&file, &path)?;
|
||||
file.set_len(0)?;
|
||||
file.write_all(&contents)
|
||||
})
|
||||
.await
|
||||
.map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
|
||||
}
|
||||
|
||||
pub(super) async fn metadata(path: PathBuf) -> io::Result<std::fs::Metadata> {
|
||||
tokio::task::spawn_blocking(move || open_entry(&path)?.metadata())
|
||||
.await
|
||||
.map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
|
||||
}
|
||||
|
||||
fn create_directory_sync(path: &Path, recursive: bool) -> io::Result<()> {
|
||||
if !recursive {
|
||||
open_handle(path, FILE_READ_ATTRIBUTES, FILE_CREATE, FILE_DIRECTORY_FILE)?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut current = PathBuf::new();
|
||||
for component in path.components() {
|
||||
current.push(component.as_os_str());
|
||||
if matches!(component, Component::Normal(_)) {
|
||||
open_or_create_directory(¤t)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn open_or_create_directory(path: &Path) -> io::Result<()> {
|
||||
match open_handle(path, FILE_READ_ATTRIBUTES, FILE_OPEN, FILE_DIRECTORY_FILE) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {
|
||||
match open_handle(path, FILE_READ_ATTRIBUTES, FILE_CREATE, FILE_DIRECTORY_FILE) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
|
||||
open_handle(path, FILE_READ_ATTRIBUTES, FILE_OPEN, FILE_DIRECTORY_FILE)?;
|
||||
Ok(())
|
||||
}
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
Err(error) => Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn create_directory(path: PathBuf, recursive: bool) -> io::Result<()> {
|
||||
tokio::task::spawn_blocking(move || create_directory_sync(&path, recursive))
|
||||
.await
|
||||
.map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
|
||||
}
|
||||
|
||||
fn remove_sync(path: &Path, recursive: bool, force: bool) -> io::Result<()> {
|
||||
if recursive {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"recursive no-follow removal is unsupported",
|
||||
));
|
||||
}
|
||||
|
||||
let metadata = match open_entry(path).and_then(|file| file.metadata()) {
|
||||
Ok(metadata) => metadata,
|
||||
Err(error) if force && error.kind() == io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let create_options = if metadata.is_dir() {
|
||||
FILE_DIRECTORY_FILE
|
||||
} else {
|
||||
FILE_NON_DIRECTORY_FILE
|
||||
};
|
||||
open_handle(
|
||||
path,
|
||||
DELETE,
|
||||
FILE_OPEN,
|
||||
create_options | FILE_DELETE_ON_CLOSE,
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn remove(path: PathBuf, recursive: bool, force: bool) -> io::Result<()> {
|
||||
tokio::task::spawn_blocking(move || remove_sync(&path, recursive, force))
|
||||
.await
|
||||
.map_err(|error| io::Error::other(format!("filesystem task failed: {error}")))?
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "windows_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,43 @@
|
||||
use super::*;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_WRITE;
|
||||
use windows_sys::Win32::Storage::FileSystem::PIPE_ACCESS_DUPLEX;
|
||||
use windows_sys::Win32::System::Pipes::CreateNamedPipeW;
|
||||
use windows_sys::Win32::System::Pipes::PIPE_READMODE_BYTE;
|
||||
use windows_sys::Win32::System::Pipes::PIPE_TYPE_BYTE;
|
||||
use windows_sys::Win32::System::Pipes::PIPE_WAIT;
|
||||
|
||||
#[test]
|
||||
fn native_open_rejects_named_pipes_before_connecting() {
|
||||
let pipe_name = format!("codex-no-follow-{}", uuid::Uuid::new_v4());
|
||||
let server_path = PathBuf::from(format!(r"\\.\pipe\{pipe_name}"));
|
||||
let client_path = PathBuf::from(format!(r"\\localhost\pipe\{pipe_name}"));
|
||||
let wide_path = server_path
|
||||
.as_os_str()
|
||||
.encode_wide()
|
||||
.chain(std::iter::once(0))
|
||||
.collect::<Vec<_>>();
|
||||
let pipe = unsafe {
|
||||
CreateNamedPipeW(
|
||||
wide_path.as_ptr(),
|
||||
PIPE_ACCESS_DUPLEX,
|
||||
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
|
||||
/*nmaxinstances*/ 1,
|
||||
/*noutbuffersize*/ 1,
|
||||
/*ninbuffersize*/ 1,
|
||||
/*ndefaulttimeout*/ 1_000,
|
||||
ptr::null(),
|
||||
)
|
||||
};
|
||||
assert_ne!(pipe, INVALID_HANDLE_VALUE);
|
||||
let _pipe = unsafe { OwnedHandle::from_raw_handle(pipe as RawHandle) };
|
||||
|
||||
let error = open_handle(
|
||||
&client_path,
|
||||
FILE_GENERIC_READ | FILE_GENERIC_WRITE,
|
||||
FILE_OPEN,
|
||||
FILE_NON_DIRECTORY_FILE,
|
||||
)
|
||||
.expect_err("strict native open should reject named pipes");
|
||||
assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
|
||||
assert_eq!(error.to_string(), "path contains a reparse point");
|
||||
}
|
||||
Reference in new issue
Block a user