mirror of
https://github.com/openai/codex.git
synced 2026-11-29 00:00:54 +00:00
Honor declared filesystem permissions in Windows sandboxes (#64416)
## Why MXC volume expansion can generate child grants that override restrictions on directory aliases. The restricted-token backend can also reject valid workspace policies because its compatibility check assumes the working directory is writable. ## What changed - Check directory identity before MXC expands writable volume roots. Suppress generated write grants that conflict with read-only aliases, including through junctions on other volumes, while preserving narrower explicit grants. Reject launch if a writable volume is also denied or its relationship to a restricted directory cannot be determined. - Let the restricted-token backend accept the supplied workspace roots when the working directory has no explicit write grant, while retaining exact root matching for filesystem-root write grants. ## Testing Add regression coverage for restricted volume aliases, junctions across writable roots, explicit drive-root denials, and restricted-token workspace roots with nested or read-only working directories or an empty root list. GitOrigin-RevId: 0cd880b52185d0a38c479df17ae48aa68d45eeb1
This commit is contained in:
@@ -31,6 +31,7 @@ thiserror = { workspace = true }
|
||||
tracelogging = "=1.2.3"
|
||||
windows-sys = { workspace = true, features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Globalization",
|
||||
"Win32_Storage_FileSystem",
|
||||
"Win32_System_Com",
|
||||
"Win32_System_SystemInformation",
|
||||
|
||||
@@ -37,15 +37,25 @@ an otherwise usable Windows policy when a network share does not support
|
||||
explicit path grants without that object-identity lookup. The public SDK does
|
||||
perform metadata checks for missing paths: immediate failures produce warnings,
|
||||
while a check that exceeds five seconds rejects startup, including on a slow or
|
||||
unreachable network share. We intentionally accept two alias limitations:
|
||||
unreachable network share.
|
||||
Hard-link names retain independent path permissions. An allowed name can read
|
||||
or modify the same file as a denied or read-only name.
|
||||
|
||||
- Hard-link names retain independent path permissions. An allowed name can read
|
||||
or modify the same file as a denied or read-only name; we do not tighten all
|
||||
names to an object-wide restriction.
|
||||
- Volume-root expansion uses each root's declared access without reconciling
|
||||
aliases first. For example, a writable `V:\` plus a read-only junction to
|
||||
`V:\` can produce a writable `V:\projects` grant. That generated, more-specific
|
||||
grant permits writes through either name despite the read-only root alias.
|
||||
Before expanding a writable volume root, the adapter checks whether a restricted
|
||||
directory names that root. For example, a read-only junction to writable `V:\`
|
||||
suppresses the generated write grant for `V:\projects`. Explicit grants beneath
|
||||
the root still apply. A child junction on another writable drive gets no generated
|
||||
write grant if it points beneath that restriction. When a deny names the same
|
||||
writable volume through another path, the adapter rejects the request before
|
||||
launch. Otherwise generated read-only grants such as `V:\.aws` could expose
|
||||
files beneath the denied root. These checks use the links present during
|
||||
policy construction.
|
||||
|
||||
If the filesystem cannot supply a directory ID, the adapter compares resolved
|
||||
NT names. Different share names can refer to the same directory. If the adapter
|
||||
cannot distinguish a writable volume from a restricted directory, it reports both
|
||||
paths and stops before launch. Explicit grants outside volume expansion require
|
||||
no directory-identity comparison.
|
||||
|
||||
## Selection and rollout
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Translate canonical permissions into MXC path grants.
|
||||
//! Denies and read-only carveouts remain separate kernel policy lists.
|
||||
//! Missing deny parents are created and marked before deny globs and volume grants are expanded.
|
||||
//! Alias limitations are documented in the crate README.
|
||||
//! Writable volume roots expand only when no restrictive alias names the same directory.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
@@ -21,6 +21,8 @@ use codex_windows_sandbox::resolve_windows_deny_read_paths;
|
||||
use mxc_sdk::mxc_common::cmdline::CommandLineContext;
|
||||
use mxc_sdk::mxc_common::cmdline::CommandLineError;
|
||||
use mxc_sdk::mxc_common::cmdline::cmdline_from_argv_for_context;
|
||||
use mxc_sdk::mxc_common::filesystem_object::ExistingObjectComparison;
|
||||
use mxc_sdk::mxc_common::filesystem_object::compare_existing_filesystem_objects;
|
||||
use mxc_sdk::v1::ContainerRequest;
|
||||
use mxc_sdk::v1::Containment;
|
||||
use mxc_sdk::v1::FilesystemPolicy;
|
||||
@@ -65,6 +67,15 @@ pub enum PolicyError {
|
||||
#[source]
|
||||
source: std::io::Error,
|
||||
},
|
||||
#[error(
|
||||
"cannot determine whether writable MXC volume {volume} aliases restricted directory {restriction}"
|
||||
)]
|
||||
IndeterminateVolumeAlias {
|
||||
volume: PathBuf,
|
||||
restriction: PathBuf,
|
||||
},
|
||||
#[error("writable MXC volume {volume} is also denied through {denial}")]
|
||||
ConflictingVolumeDenial { volume: PathBuf, denial: PathBuf },
|
||||
#[error(transparent)]
|
||||
Path(#[from] std::io::Error),
|
||||
#[error(transparent)]
|
||||
@@ -200,13 +211,13 @@ pub(super) fn build_request(
|
||||
let fs = materialize_volume_roots(policy.clone(), &volumes, &read_volumes)?;
|
||||
let absolute_cwd = AbsolutePathBuf::from_absolute_path(cwd)
|
||||
.map_err(|error| PolicyError::PolicyResolution(error.to_string()))?;
|
||||
let (roots, readable_roots, denied_paths) = if fs == policy {
|
||||
let (roots, denied_paths) = if fs == policy {
|
||||
let resolved =
|
||||
fs.resolve_for_enforcement(cwd, FileSystemPolicyProjection::PreserveMutableRoots)?;
|
||||
#[cfg(windows)]
|
||||
crate::windows::log_launch("phase=resolve_deny_paths");
|
||||
let denies = expand_windows_deny_read_paths(&resolved, &absolute_cwd);
|
||||
(resolved.writable_roots, resolved.readable_roots, denies)
|
||||
(resolved.writable_roots, denies)
|
||||
} else {
|
||||
// A symbolic root deny sets the default on every volume. Expanding it into ACL
|
||||
// targets would mask narrower grants and probe disconnected drives.
|
||||
@@ -215,12 +226,10 @@ pub(super) fn build_request(
|
||||
} else {
|
||||
fs.get_writable_roots_with_cwd_preserving_mutable_paths(cwd)
|
||||
};
|
||||
let readable_roots = fs.get_readable_roots_with_cwd(cwd);
|
||||
#[cfg(windows)]
|
||||
crate::windows::log_launch("phase=resolve_deny_paths");
|
||||
(
|
||||
roots,
|
||||
readable_roots,
|
||||
resolve_windows_deny_read_paths(&policy, &absolute_cwd),
|
||||
)
|
||||
};
|
||||
@@ -236,18 +245,38 @@ pub(super) fn build_request(
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut read = collect_paths(
|
||||
readable_roots
|
||||
.into_iter()
|
||||
.filter(|path| !fs.can_write_local_path_with_cwd(path.as_path(), cwd))
|
||||
.map(|path| path.to_path_buf()),
|
||||
)?;
|
||||
let deny = collect_paths(
|
||||
// All symbolic read roots have been bound above. Keep the declared spelling:
|
||||
// canonicalizing a top-level read-only junction can collapse it into an
|
||||
// explicit writable drive before BaseContainer sees the restriction.
|
||||
let mut read = NativePaths::new();
|
||||
for entry in &fs.entries {
|
||||
if let FileSystemPath::Path { path } = &entry.path
|
||||
&& entry.access == FileSystemAccessMode::Read
|
||||
&& let Ok(local) = path.to_abs_path()
|
||||
&& fs.can_read_local_path_with_cwd(&local, cwd)
|
||||
&& !fs.can_write_local_path_with_cwd(&local, cwd)
|
||||
{
|
||||
read.insert(path.clone(), local.into_path_buf());
|
||||
}
|
||||
}
|
||||
let mut deny = collect_paths(
|
||||
denied_paths
|
||||
.map_err(PolicyError::PolicyResolution)?
|
||||
.into_iter()
|
||||
.map(AbsolutePathBuf::into_path_buf),
|
||||
)?;
|
||||
// The shared resolver omits the cwd drive root for a default root denial.
|
||||
// An absolute drive-root denial also constrains aliases of that drive.
|
||||
for entry in &policy.entries {
|
||||
if let FileSystemPath::Path { path } = &entry.path
|
||||
&& entry.access == FileSystemAccessMode::Deny
|
||||
&& let Ok(local) = path.to_abs_path()
|
||||
&& local.parent().is_none()
|
||||
&& !fs.can_read_local_path_with_cwd(&local, cwd)
|
||||
{
|
||||
deny.insert(path.clone(), local.into_path_buf());
|
||||
}
|
||||
}
|
||||
let carveouts = collect_paths(roots.into_iter().flat_map(|root| {
|
||||
let protected = root
|
||||
.protected_metadata_names
|
||||
@@ -269,8 +298,9 @@ pub(super) fn build_request(
|
||||
if policy.include_platform_defaults() {
|
||||
read.extend(collect_paths(platform_read_roots.iter().cloned())?);
|
||||
}
|
||||
write.retain(|key, _| !carveouts.contains_key(key) && !deny.contains_key(key));
|
||||
read.retain(|key, _| !write.contains_key(key) && !deny.contains_key(key));
|
||||
read.retain(|key, _| {
|
||||
(!write.contains_key(key) || carveouts.contains_key(key)) && !deny.contains_key(key)
|
||||
});
|
||||
let volume_roots = volume_roots
|
||||
.iter()
|
||||
.map(PathUri::from_host_native_path)
|
||||
@@ -282,9 +312,7 @@ pub(super) fn build_request(
|
||||
// BaseContainer owns alias precedence for the emitted paths. Do not call
|
||||
// MXC's object normalizer: its metadata preflight rejects usable SMB grants
|
||||
// and inaccessible deny paths before the native API can evaluate them.
|
||||
// The hard-link and volume-root alias tradeoffs are intentional; see README.
|
||||
// Read-only roots already grant recursive access; only expand writable roots.
|
||||
let mut write = expand_volume_roots(write, &volume_roots)?;
|
||||
let mut write = expand_volume_roots(write, &volume_roots, &read, &deny)?;
|
||||
write.retain(|key, _| !carveouts.contains_key(key) && !deny.contains_key(key));
|
||||
// Resolve equal-path write overrides before reaching MXC so the native
|
||||
// API receives one effective access mode for each path identity.
|
||||
@@ -394,7 +422,11 @@ fn prune_unavailable_volume_roots(paths: &mut NativePaths, volume_roots: &HashSe
|
||||
}
|
||||
match std::fs::read_dir(path) {
|
||||
Ok(_) => true,
|
||||
Err(error) => !inaccessible_volume(&error),
|
||||
// An unlistable root can still expose known children. Keep its
|
||||
// restrictions and compare its aliases before generating grants.
|
||||
Err(error) => {
|
||||
error.kind() == std::io::ErrorKind::PermissionDenied || !inaccessible_volume(&error)
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -445,13 +477,46 @@ pub(super) fn materialize_volume_roots(
|
||||
// root after policy construction is not granted. MXC/PSEC still enforces
|
||||
// restrictions on junction-resolved targets at access time.
|
||||
fn expand_volume_roots(
|
||||
paths: NativePaths,
|
||||
mut paths: NativePaths,
|
||||
volume_roots: &HashSet<PathUri>,
|
||||
readonly: &NativePaths,
|
||||
denied: &NativePaths,
|
||||
) -> Result<NativePaths, PolicyError> {
|
||||
let mut expanded = NativePaths::new();
|
||||
for (key, path) in paths {
|
||||
if volume_roots.contains(&key) || path.parent().is_none() {
|
||||
match std::fs::read_dir(&path).and_then(Iterator::collect::<std::io::Result<Vec<_>>>) {
|
||||
let is_volume =
|
||||
|key: &PathUri, path: &Path| volume_roots.contains(key) || path.parent().is_none();
|
||||
if !paths.iter().any(|(key, path)| is_volume(key, path)) {
|
||||
return Ok(paths);
|
||||
}
|
||||
let denied_dirs: Vec<_> = directory_candidates(denied).collect();
|
||||
let readonly_dirs: Vec<_> = directory_candidates(readonly).collect();
|
||||
let restricted_dirs: Vec<_> = readonly_dirs
|
||||
.iter()
|
||||
.copied()
|
||||
.chain(denied_dirs.iter().copied())
|
||||
.collect();
|
||||
let writable: Vec<_> = paths.values().map(PathBuf::as_path).collect();
|
||||
let mut children = Vec::new();
|
||||
let mut unavailable = Vec::new();
|
||||
for (key, path) in &paths {
|
||||
if is_volume(key, path) {
|
||||
let indeterminate = |restriction: &Path| PolicyError::IndeterminateVolumeAlias {
|
||||
volume: path.clone(),
|
||||
restriction: restriction.to_owned(),
|
||||
};
|
||||
// Even an inferred read-only metadata grant could reopen this volume.
|
||||
if let Some(denial) = matching_directory(path, &denied_dirs).map_err(indeterminate)? {
|
||||
return Err(PolicyError::ConflictingVolumeDenial {
|
||||
volume: path.clone(),
|
||||
denial: denial.to_owned(),
|
||||
});
|
||||
}
|
||||
if matching_directory(path, &readonly_dirs)
|
||||
.map_err(indeterminate)?
|
||||
.is_some()
|
||||
{
|
||||
continue;
|
||||
}
|
||||
match std::fs::read_dir(path).and_then(Iterator::collect::<std::io::Result<Vec<_>>>) {
|
||||
Ok(entries) => {
|
||||
for entry in entries {
|
||||
let child = entry.path();
|
||||
@@ -459,29 +524,99 @@ fn expand_volume_roots(
|
||||
continue;
|
||||
}
|
||||
// Windows supplies the file type with directory entries.
|
||||
// Only resolve links: broken targets prevent PSEC startup.
|
||||
if entry.file_type().is_ok_and(|kind| kind.is_symlink())
|
||||
&& std::fs::metadata(&child).is_err()
|
||||
let Ok(kind) = entry.file_type() else {
|
||||
continue;
|
||||
};
|
||||
if kind.is_symlink()
|
||||
&& !can_generate_link_grant(&child, &restricted_dirs, &writable)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
expanded.insert(PathUri::from_host_native_path(&child)?, child);
|
||||
children.push((PathUri::from_host_native_path(&child)?, child));
|
||||
}
|
||||
}
|
||||
// GetLogicalDrives includes disconnected and empty removable
|
||||
// drives. They must not prevent commands on available volumes.
|
||||
Err(error) if inaccessible_volume(&error) => continue,
|
||||
Err(error) if inaccessible_volume(&error) => unavailable.push(key.clone()),
|
||||
Err(error) => {
|
||||
return Err(PolicyError::EnumerateVolume {
|
||||
path,
|
||||
path: path.clone(),
|
||||
source: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
expanded.insert(key, path);
|
||||
}
|
||||
Ok(expanded)
|
||||
for key in unavailable {
|
||||
paths.remove(&key);
|
||||
}
|
||||
paths.extend(children);
|
||||
Ok(paths)
|
||||
}
|
||||
|
||||
fn directory_candidates(paths: &NativePaths) -> impl Iterator<Item = &Path> {
|
||||
// Ordinary files and missing entries cannot be aliases of a directory. Keep
|
||||
// their native restrictions without asking the filesystem for a file ID.
|
||||
paths
|
||||
.values()
|
||||
.filter(|path| match std::fs::symlink_metadata(path) {
|
||||
Ok(metadata) => !metadata.is_file(),
|
||||
Err(error) => error.kind() != std::io::ErrorKind::NotFound,
|
||||
})
|
||||
.map(PathBuf::as_path)
|
||||
}
|
||||
|
||||
// BaseContainer applies the strictest grant to equivalent directories. A
|
||||
// synthesized child would override that restriction by being more specific.
|
||||
fn matching_directory<'a>(
|
||||
path: &Path,
|
||||
directories: &[&'a Path],
|
||||
) -> Result<Option<&'a Path>, &'a Path> {
|
||||
let mut unknown = None;
|
||||
for &directory in directories {
|
||||
match compare_existing_filesystem_objects(path, directory) {
|
||||
ExistingObjectComparison::Same => return Ok(Some(directory)),
|
||||
ExistingObjectComparison::Different => {}
|
||||
ExistingObjectComparison::Unknown => {
|
||||
#[cfg(windows)]
|
||||
if let Ok(same) = crate::windows::same_final_directory(path, directory) {
|
||||
if same {
|
||||
return Ok(Some(directory));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
unknown.get_or_insert(directory);
|
||||
}
|
||||
}
|
||||
}
|
||||
unknown.map_or(Ok(None), Err)
|
||||
}
|
||||
|
||||
fn can_generate_link_grant(link: &Path, restricted: &[&Path], writable: &[&Path]) -> bool {
|
||||
let Ok(metadata) = std::fs::metadata(link) else {
|
||||
return false;
|
||||
};
|
||||
if restricted.is_empty() {
|
||||
return true;
|
||||
}
|
||||
let Ok(mut target) = std::fs::canonicalize(link) else {
|
||||
return false;
|
||||
};
|
||||
// Hard-linked file names keep independent permissions. Compare directories only.
|
||||
if metadata.is_file() {
|
||||
target.pop();
|
||||
}
|
||||
// A junction on a second writable drive can land beneath a restricted
|
||||
// root. Apply the nearest explicit directory grant to its resolved target.
|
||||
for ancestor in target.ancestors() {
|
||||
if matching_directory(ancestor, restricted) != Ok(None) {
|
||||
return false;
|
||||
}
|
||||
if matches!(matching_directory(ancestor, writable), Ok(Some(_))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn collect_paths(paths: impl IntoIterator<Item = PathBuf>) -> Result<NativePaths, PolicyError> {
|
||||
|
||||
@@ -354,6 +354,8 @@ fn volume_expansion_skips_broken_links_and_preserves_other_grants() -> Result<()
|
||||
std::os::unix::fs::symlink(&readable, &alias)?;
|
||||
let denied = root.join("secret");
|
||||
std::fs::write(&denied, "secret")?;
|
||||
let hardlink = root.join("hardlink");
|
||||
std::fs::hard_link(&denied, &hardlink)?;
|
||||
let fs = FileSystemSandboxPolicy::restricted(vec![
|
||||
entry(&root, FileSystemAccessMode::Write)?,
|
||||
entry(&denied, FileSystemAccessMode::Deny)?,
|
||||
@@ -374,6 +376,7 @@ fn volume_expansion_skips_broken_links_and_preserves_other_grants() -> Result<()
|
||||
vec![
|
||||
root.to_str().unwrap().to_owned(),
|
||||
alias.to_str().unwrap().to_owned(),
|
||||
hardlink.to_str().unwrap().to_owned(),
|
||||
readable.to_str().unwrap().to_owned()
|
||||
],
|
||||
vec![denied.to_str().unwrap().to_owned()],
|
||||
@@ -382,6 +385,108 @@ fn volume_expansion_skips_broken_links_and_preserves_other_grants() -> Result<()
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn volume_expansion_respects_a_restricted_root_alias() -> Result<()> {
|
||||
use FileSystemAccessMode::Deny;
|
||||
use FileSystemAccessMode::Read;
|
||||
use FileSystemAccessMode::Write;
|
||||
|
||||
let temp = tempfile::tempdir()?;
|
||||
let base = canonical_root(&temp)?;
|
||||
let volume = base.join("volume");
|
||||
let alias = base.join("alias");
|
||||
let ordinary = volume.join("ordinary");
|
||||
let writable = volume.join("explicit");
|
||||
let other = base.join("other");
|
||||
let unaffected = other.join("unaffected");
|
||||
let bridge = other.join("bridge");
|
||||
let allowed_link = other.join("allowed-link");
|
||||
let private_file = base.join("private-file");
|
||||
std::fs::write(&private_file, b"private")?;
|
||||
std::fs::create_dir_all(volume.join(".aws"))?;
|
||||
std::fs::write(volume.join(".aws").join("credentials"), b"private")?;
|
||||
for directory in [&ordinary, &writable, &unaffected] {
|
||||
std::fs::create_dir_all(directory)?;
|
||||
}
|
||||
for (link, target) in [
|
||||
(&alias, &volume),
|
||||
(&bridge, &ordinary),
|
||||
(&allowed_link, &unaffected),
|
||||
] {
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::symlink(target, link)?;
|
||||
#[cfg(windows)]
|
||||
assert!(
|
||||
std::process::Command::new("cmd.exe")
|
||||
.args(["/d", "/c", "mklink", "/j"])
|
||||
.arg(link)
|
||||
.arg(target)
|
||||
.status()?
|
||||
.success()
|
||||
);
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
assert!(crate::windows::same_final_directory(&volume, &alias)?);
|
||||
assert!(!crate::windows::same_final_directory(&other, &alias)?);
|
||||
}
|
||||
|
||||
for restriction in [Read, Deny] {
|
||||
let fs = FileSystemSandboxPolicy::restricted(vec![
|
||||
entry(&volume, Write)?,
|
||||
entry(&alias, restriction)?,
|
||||
entry(&writable, Write)?,
|
||||
entry(&other, Write)?,
|
||||
entry(&private_file, Deny)?,
|
||||
]);
|
||||
let profile =
|
||||
PermissionProfile::from_runtime_permissions(&fs, NetworkSandboxPolicy::Restricted);
|
||||
#[cfg(unix)]
|
||||
let volume_metadata = std::fs::metadata(&volume)?;
|
||||
#[cfg(unix)]
|
||||
if restriction == Deny {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&volume, std::fs::Permissions::from_mode(0o111))?;
|
||||
// A privileged test process can enumerate its own mode-0111 directory.
|
||||
if volume_metadata.uid() != 0 {
|
||||
assert_eq!(
|
||||
std::fs::read_dir(&volume).unwrap_err().kind(),
|
||||
std::io::ErrorKind::PermissionDenied
|
||||
);
|
||||
}
|
||||
assert_eq!(std::fs::read(volume.join(".aws/credentials"))?, b"private");
|
||||
}
|
||||
let result = build_request(
|
||||
&command(&profile, &base),
|
||||
&base,
|
||||
Vec::new(),
|
||||
&[volume.clone(), other.clone()],
|
||||
&[],
|
||||
);
|
||||
if restriction == Deny {
|
||||
#[cfg(unix)]
|
||||
std::fs::set_permissions(&volume, volume_metadata.permissions())?;
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(PolicyError::ConflictingVolumeDenial { volume: path, denial })
|
||||
if path == volume && denial == alias
|
||||
));
|
||||
continue;
|
||||
}
|
||||
let request = result?.filesystem.unwrap();
|
||||
let writes = &request.readwrite_paths;
|
||||
assert!(!writes.contains(&ordinary.display().to_string()));
|
||||
assert!(!writes.contains(&bridge.display().to_string()));
|
||||
assert!(writes.contains(&allowed_link.display().to_string()));
|
||||
assert!(writes.contains(&writable.display().to_string()));
|
||||
assert!(writes.contains(&unaffected.display().to_string()));
|
||||
let restrictions = &request.readonly_paths;
|
||||
assert!(restrictions.contains(&alias.display().to_string()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_write_access_expands_volume_children() -> Result<()> {
|
||||
let first = tempfile::tempdir()?;
|
||||
@@ -668,6 +773,22 @@ fn root_deny_keeps_only_narrow_explicit_grants() -> Result<()> {
|
||||
assert_eq!((request.readwrite_paths, request.readonly_paths), expected);
|
||||
assert_eq!(request.denied_paths, Vec::<String>::new());
|
||||
}
|
||||
let drive = root.ancestors().last().unwrap();
|
||||
let fs = FileSystemSandboxPolicy::restricted(vec![
|
||||
entry(drive, FileSystemAccessMode::Deny)?,
|
||||
entry(&child, FileSystemAccessMode::Write)?,
|
||||
]);
|
||||
let profile =
|
||||
PermissionProfile::from_runtime_permissions(&fs, NetworkSandboxPolicy::Restricted);
|
||||
let request = build_request(&command(&profile, root), root, Vec::new(), &[], &[])?;
|
||||
let request = request.filesystem.unwrap();
|
||||
assert_eq!(
|
||||
(request.denied_paths, request.readwrite_paths),
|
||||
(
|
||||
vec![drive.display().to_string()],
|
||||
vec![child.display().to_string()]
|
||||
)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
//! Resolve executor-local state and launch the decoded MXC helper request.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::io;
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::os::windows::fs::OpenOptionsExt;
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Instant;
|
||||
@@ -10,8 +13,13 @@ use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use windows_sys::Win32::Foundation::RPC_E_CHANGED_MODE;
|
||||
use windows_sys::Win32::Globalization::CSTR_EQUAL;
|
||||
use windows_sys::Win32::Globalization::CompareStringOrdinal;
|
||||
use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS;
|
||||
use windows_sys::Win32::Storage::FileSystem::GetDriveTypeW;
|
||||
use windows_sys::Win32::Storage::FileSystem::GetFinalPathNameByHandleW;
|
||||
use windows_sys::Win32::Storage::FileSystem::GetLogicalDrives;
|
||||
use windows_sys::Win32::Storage::FileSystem::VOLUME_NAME_NT;
|
||||
use windows_sys::Win32::System::Com::COINIT_MULTITHREADED;
|
||||
use windows_sys::Win32::System::Com::CoInitializeEx;
|
||||
use windows_sys::Win32::System::Com::CoTaskMemFree;
|
||||
@@ -137,6 +145,71 @@ pub(super) fn implicit_read_roots(
|
||||
.collect()
|
||||
}
|
||||
|
||||
// SMB need not support FileIdInfo. Query the resolved NT names through handles
|
||||
// opened with zero requested access, including on directories denying metadata reads.
|
||||
pub(super) fn same_final_directory(left: &Path, right: &Path) -> io::Result<bool> {
|
||||
let left = final_nt_path(left)?;
|
||||
let right = final_nt_path(right)?;
|
||||
// Both buffers contain exactly the wide name returned by the kernel.
|
||||
let comparison = unsafe {
|
||||
CompareStringOrdinal(
|
||||
left.as_ptr(),
|
||||
left.len() as i32,
|
||||
right.as_ptr(),
|
||||
right.len() as i32,
|
||||
/*bignorecase*/ 1,
|
||||
)
|
||||
};
|
||||
if comparison == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
if comparison == CSTR_EQUAL {
|
||||
return Ok(true);
|
||||
}
|
||||
// A share can export a local volume or the same directory as another
|
||||
// share. Different redirector names do not establish distinct objects.
|
||||
let local_disk = |name: &[u16]| {
|
||||
String::from_utf16_lossy(name)
|
||||
.strip_prefix(r"\Device\HarddiskVolume")
|
||||
.and_then(|suffix| suffix.split('\\').next())
|
||||
.is_some_and(|number| !number.is_empty() && number.bytes().all(|b| b.is_ascii_digit()))
|
||||
};
|
||||
if local_disk(&left) && local_disk(&right) {
|
||||
return Ok(false);
|
||||
}
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"directory identities are unavailable across these NT namespaces",
|
||||
))
|
||||
}
|
||||
|
||||
fn final_nt_path(path: &Path) -> io::Result<Vec<u16>> {
|
||||
let directory = std::fs::OpenOptions::new()
|
||||
.access_mode(0)
|
||||
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
|
||||
.open(path)?;
|
||||
let mut name = vec![0; 260];
|
||||
loop {
|
||||
// The handle stays open and name is writable for the supplied length.
|
||||
let length = unsafe {
|
||||
GetFinalPathNameByHandleW(
|
||||
directory.as_raw_handle(),
|
||||
name.as_mut_ptr(),
|
||||
name.len() as u32,
|
||||
VOLUME_NAME_NT,
|
||||
)
|
||||
} as usize;
|
||||
if length == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
if length < name.len() {
|
||||
name.truncate(length);
|
||||
return Ok(name);
|
||||
}
|
||||
name.resize(length + 1, 0);
|
||||
}
|
||||
}
|
||||
|
||||
fn platform_read_roots() -> Result<Vec<PathBuf>> {
|
||||
use std::os::windows::ffi::OsStringExt;
|
||||
|
||||
|
||||
@@ -1218,6 +1218,56 @@ fn windows_file_system_wrapper_materializes_inner_helper() {
|
||||
assert!(materialized_helper.exists());
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn restricted_token_uses_only_the_supplied_workspace_roots() -> anyhow::Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let base = AbsolutePathBuf::from_absolute_path(dunce::canonicalize(temp.path())?)?;
|
||||
let writable = base.join("writable");
|
||||
let roots: &[PathUri] = &[PathUri::from_abs_path(&writable)];
|
||||
let read_only = base.join("read-only-cwd");
|
||||
let permissions = PermissionProfile::workspace_write_with(
|
||||
&[],
|
||||
NetworkSandboxPolicy::Restricted,
|
||||
/*exclude_tmpdir_env_var*/ true,
|
||||
/*exclude_slash_tmp*/ true,
|
||||
);
|
||||
|
||||
let manager = SandboxManager::new()
|
||||
.with_windows_token_session(crate::WindowsSandboxProxySettingsMode::Preserve);
|
||||
for (cwd, roots) in [
|
||||
(writable.join("subdir"), roots),
|
||||
(read_only.clone(), roots),
|
||||
(read_only, &[]),
|
||||
] {
|
||||
std::fs::create_dir_all(&cwd)?;
|
||||
let cwd_uri = PathUri::from_abs_path(&cwd);
|
||||
let wrapped = manager.transform(SandboxTransformRequest {
|
||||
workspace_roots: Some(roots),
|
||||
selection: SandboxSelection::Explicit(SandboxType::WindowsRestrictedToken),
|
||||
windows_sandbox_level: WindowsSandboxLevel::RestrictedToken,
|
||||
..test_request(&cwd_uri, &permissions)
|
||||
})?;
|
||||
let session = wrapped.windows_session.expect("restricted-token session");
|
||||
let writable_roots = wrapped
|
||||
.request
|
||||
.permission_profile
|
||||
.file_system_sandbox_policy()
|
||||
.get_writable_roots_with_cwd(&cwd)
|
||||
.into_iter()
|
||||
.map(|root| root.root)
|
||||
.collect::<Vec<_>>();
|
||||
let expected_roots = if roots.is_empty() {
|
||||
&[]
|
||||
} else {
|
||||
std::slice::from_ref(&writable)
|
||||
};
|
||||
assert_eq!(writable_roots, expected_roots);
|
||||
assert_eq!(session.workspace_roots, expected_roots);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restricted_token_preserves_read_only_carveouts_at_a_volume_root() -> anyhow::Result<()> {
|
||||
let cwd = AbsolutePathBuf::current_dir()?;
|
||||
|
||||
@@ -91,12 +91,11 @@ impl SandboxBackend for WindowsToken<'_> {
|
||||
///
|
||||
/// The elevated Windows backend consumes extra deny-read paths plus explicit
|
||||
/// read and write roots during setup/refresh. The unelevated restricted-token
|
||||
/// backend only consumes extra deny-write carveouts on top of the legacy
|
||||
/// `WorkspaceWrite` allow set. Read-root overrides are layered on top of the
|
||||
/// baseline helper roots that the elevated setup path needs to launch the
|
||||
/// sandboxed command; split policies that opt into platform defaults carry
|
||||
/// that explicitly with the override.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
/// backend derives its writable roots from the permission profile and only
|
||||
/// consumes extra deny-write carveouts here. Read-root overrides are layered on
|
||||
/// top of the baseline helper roots that elevated setup needs to launch the
|
||||
/// command. Split policies that opt into platform defaults carry that explicitly.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct WindowsSandboxFilesystemOverrides {
|
||||
pub read_roots_override: Option<Vec<PathBuf>>,
|
||||
pub read_roots_include_platform_defaults: bool,
|
||||
@@ -233,7 +232,7 @@ pub fn resolve_windows_restricted_token_filesystem_overrides(
|
||||
let legacy_writable_roots =
|
||||
compatibility_writable_roots_for_permission_profile(permission_profile, sandbox_policy_cwd);
|
||||
let split_writable_roots = resolved.writable_roots;
|
||||
let legacy_root_paths: BTreeSet<PathBuf> = legacy_writable_roots
|
||||
let mut legacy_root_paths: BTreeSet<PathBuf> = legacy_writable_roots
|
||||
.iter()
|
||||
.map(|root| normalize_windows_override_path(root.root.as_path()))
|
||||
.collect::<std::result::Result<_, _>>()?;
|
||||
@@ -242,6 +241,15 @@ pub fn resolve_windows_restricted_token_filesystem_overrides(
|
||||
.map(|root| normalize_windows_override_path(root.root.as_path()))
|
||||
.collect::<std::result::Result<_, _>>()?;
|
||||
|
||||
// WorkspaceWrite always adds cwd. The restricted token gets its write capabilities and
|
||||
// allow ACLs from the actual roots, so cwd can be read-only or below a writable root.
|
||||
// For a write grant at the filesystem root, the projected roots must still match exactly.
|
||||
let cwd = normalize_windows_override_path(sandbox_policy_cwd.as_path())?;
|
||||
if !split_root_paths.contains(&cwd)
|
||||
&& split_root_paths.iter().all(|root| root.parent().is_some())
|
||||
{
|
||||
legacy_root_paths.remove(&cwd);
|
||||
}
|
||||
if legacy_root_paths != split_root_paths {
|
||||
return Err(
|
||||
"windows unelevated restricted-token sandbox cannot enforce split writable root sets directly; refusing to run unsandboxed"
|
||||
|
||||
Reference in New Issue
Block a user