Use direct deny ACLs for Windows metadata sentinels

This commit is contained in:
Eva Wong
2026-05-06 15:33:49 -07:00
parent 8177cafbbb
commit 0cebb6116c
9 changed files with 311 additions and 60 deletions
+17 -1
View File
@@ -455,6 +455,22 @@ pub unsafe fn add_allow_ace(path: &Path, psid: *mut c_void) -> Result<bool> {
/// # Safety
/// Caller must ensure `psid` points to a valid SID and `path` refers to an existing file or directory.
pub unsafe fn add_deny_write_ace(path: &Path, psid: *mut c_void) -> Result<bool> {
add_deny_write_ace_with_inheritance(path, psid, CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE)
}
/// Adds a deny ACE to the target object without making the ACE inheritable by children.
///
/// # Safety
/// Caller must ensure `psid` points to a valid SID and `path` refers to an existing file or directory.
pub unsafe fn add_deny_write_ace_non_inheriting(path: &Path, psid: *mut c_void) -> Result<bool> {
add_deny_write_ace_with_inheritance(path, psid, /*inheritance*/ 0)
}
unsafe fn add_deny_write_ace_with_inheritance(
path: &Path,
psid: *mut c_void,
inheritance: u32,
) -> Result<bool> {
let mut p_sd: *mut c_void = std::ptr::null_mut();
let mut p_dacl: *mut ACL = std::ptr::null_mut();
let code = GetNamedSecurityInfoW(
@@ -489,7 +505,7 @@ pub unsafe fn add_deny_write_ace(path: &Path, psid: *mut c_void) -> Result<bool>
| DELETE
| FILE_DELETE_CHILD;
explicit.grfAccessMode = DENY_ACCESS;
explicit.grfInheritance = CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE;
explicit.grfInheritance = inheritance;
explicit.Trustee = trustee;
let mut p_new_dacl: *mut ACL = std::ptr::null_mut();
let code2 = SetEntriesInAclW(1, &explicit, p_dacl, &mut p_new_dacl);
@@ -84,7 +84,6 @@ mod windows_impl {
log_start(&command, logs_base_dir);
let mut protected_metadata_guard =
prepare_protected_metadata_targets(protected_metadata_targets)?;
protected_metadata_guard.arm_sentinel_cleanup()?;
let sandbox_creds = require_logon_sandbox_creds(
&policy,
sandbox_policy_cwd,
@@ -132,6 +131,7 @@ mod windows_impl {
allow_null_device(psid_to_use);
allow_named_pipe_device(psid_to_use);
}
protected_metadata_guard.arm_sentinel_cleanup()?;
let protected_metadata_runtime = protected_metadata_guard.into_runtime()?;
(|| -> Result<CaptureResult> {
+30 -1
View File
@@ -78,6 +78,8 @@ mod session;
#[cfg(target_os = "windows")]
pub use acl::add_deny_write_ace;
#[cfg(target_os = "windows")]
pub use acl::add_deny_write_ace_non_inheriting;
#[cfg(target_os = "windows")]
pub use acl::allow_named_pipe_device;
@@ -267,6 +269,7 @@ mod windows_impl {
use super::ProtectedMetadataTarget;
use super::acl::add_allow_ace;
use super::acl::add_deny_write_ace;
use super::acl::add_deny_write_ace_non_inheriting;
use super::acl::allow_named_pipe_device;
use super::acl::allow_null_device;
use super::acl::ensure_allow_mask_aces;
@@ -289,6 +292,7 @@ mod windows_impl {
use super::token::convert_string_sid_to_sid;
use super::token::create_workspace_write_token_with_caps_from;
use super::workspace_acl::is_command_cwd_root;
use anyhow::Context;
use anyhow::Result;
use std::collections::HashMap;
use std::ffi::c_void;
@@ -455,6 +459,8 @@ mod windows_impl {
let direct_read_paths = legacy_session_direct_read_paths(&env_map);
let mut protected_metadata_guard =
prepare_protected_metadata_targets(protected_metadata_targets)?;
let sentinel_deny_exclusions: Vec<PathBuf> =
protected_metadata_guard.sentinel_paths().cloned().collect();
for path in protected_metadata_guard.deny_paths() {
deny.insert(path.clone());
}
@@ -463,7 +469,7 @@ mod windows_impl {
deny.insert(path.clone());
}
}
protected_metadata_guard.arm_sentinel_cleanup()?;
remove_matching_paths(&mut deny, &sentinel_deny_exclusions);
let canonical_cwd = canonicalize_path(&current_dir);
let mut guards: Vec<(PathBuf, *mut c_void)> = Vec::new();
let read_execute_mask = FILE_GENERIC_READ | FILE_GENERIC_EXECUTE;
@@ -518,6 +524,14 @@ mod windows_impl {
guards.push((p.clone(), psid_generic));
}
}
for p in &sentinel_deny_exclusions {
add_deny_write_ace_non_inheriting(p, psid_generic).with_context(|| {
format!(
"failed to apply protected metadata sentinel ACL to {}",
p.display()
)
})?;
}
allow_null_device(psid_generic);
allow_named_pipe_device(psid_generic);
if let Some(psid) = psid_workspace {
@@ -525,6 +539,7 @@ mod windows_impl {
allow_named_pipe_device(psid);
}
}
protected_metadata_guard.arm_sentinel_cleanup()?;
let protected_metadata_runtime = protected_metadata_guard.into_runtime()?;
let (stdin_pair, stdout_pair, stderr_pair) = unsafe { setup_stdio_pipes()? };
let ((in_r, in_w), (out_r, out_w), (err_r, err_w)) = (stdin_pair, stdout_pair, stderr_pair);
@@ -668,6 +683,20 @@ mod windows_impl {
})
}
fn remove_matching_paths(paths: &mut std::collections::HashSet<PathBuf>, excluded: &[PathBuf]) {
if excluded.is_empty() {
return;
}
let excluded_paths: Vec<PathBuf> = excluded
.iter()
.map(|path| canonicalize_path(path))
.collect();
paths.retain(|path| {
let path = canonicalize_path(path);
!excluded_paths.iter().any(|excluded| excluded == &path)
});
}
pub fn run_windows_sandbox_legacy_preflight(
sandbox_policy: &SandboxPolicy,
sandbox_policy_cwd: &Path,
@@ -12,9 +12,13 @@ use std::os::windows::fs::FileTypeExt;
use std::os::windows::fs::MetadataExt;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
use std::process::Stdio;
use std::sync::Arc;
use std::sync::Mutex;
use std::thread;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::Foundation::FALSE;
use windows_sys::Win32::Foundation::HANDLE;
@@ -23,20 +27,12 @@ use windows_sys::Win32::Foundation::TRUE;
use windows_sys::Win32::Foundation::WAIT_FAILED;
use windows_sys::Win32::Foundation::WAIT_OBJECT_0;
use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT;
use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS;
use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_DELETE_ON_CLOSE;
use windows_sys::Win32::Storage::FileSystem::FILE_NOTIFY_CHANGE_CREATION;
use windows_sys::Win32::Storage::FileSystem::FILE_NOTIFY_CHANGE_DIR_NAME;
use windows_sys::Win32::Storage::FileSystem::FILE_NOTIFY_CHANGE_FILE_NAME;
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::CreateFileW;
use windows_sys::Win32::Storage::FileSystem::DELETE;
use windows_sys::Win32::Storage::FileSystem::FindCloseChangeNotification;
use windows_sys::Win32::Storage::FileSystem::FindFirstChangeNotificationW;
use windows_sys::Win32::Storage::FileSystem::FindNextChangeNotification;
use windows_sys::Win32::Storage::FileSystem::OPEN_EXISTING;
use windows_sys::Win32::System::Threading::CreateEventW;
use windows_sys::Win32::System::Threading::INFINITE;
use windows_sys::Win32::System::Threading::SetEvent;
@@ -59,10 +55,14 @@ impl ProtectedMetadataGuard {
self.deny_paths.iter()
}
pub(crate) fn sentinel_paths(&self) -> impl Iterator<Item = &PathBuf> {
self.sentinel_paths.iter()
}
pub(crate) fn arm_sentinel_cleanup(&mut self) -> Result<()> {
for path in &self.sentinel_paths {
if !self.sentinel_paths.is_empty() {
self.sentinel_handles
.push(open_delete_on_close_directory(path)?);
.push(start_sentinel_cleanup_watchdog(&self.sentinel_paths)?);
}
Ok(())
}
@@ -76,9 +76,8 @@ impl ProtectedMetadataGuard {
}
pub(crate) fn cleanup_created_paths(&mut self) -> Result<Vec<PathBuf>> {
self.sentinel_handles.clear();
let mut removed = Vec::new();
for path in self.monitored_paths.iter().chain(self.sentinel_paths.iter()) {
for path in &self.monitored_paths {
let Some(existing_path) = existing_metadata_path(path)? else {
continue;
};
@@ -86,6 +85,16 @@ impl ProtectedMetadataGuard {
.with_context(|| format!("failed to remove protected metadata {}", path.display()))?;
removed.push(existing_path);
}
// Sentinels are Codex-owned setup artifacts. Remove them, but do not
// report them as command-created protected metadata violations.
for path in &self.sentinel_paths {
let Some(existing_path) = existing_metadata_path(path)? else {
continue;
};
remove_metadata_path(&existing_path)
.with_context(|| format!("failed to remove protected metadata {}", path.display()))?;
}
self.sentinel_handles.clear();
Ok(removed)
}
}
@@ -124,20 +133,17 @@ impl ProtectedMetadataRuntime {
}
}
/// Layer: Windows sentinel cleanup handle. Holds a delete-on-close directory
/// handle for one Codex-created sentinel so forced parent-process termination
/// does not leave a protected metadata artifact behind.
/// Layer: Windows sentinel cleanup watchdog registration. Records the cleanup
/// script path for one out-of-job watchdog that removes Codex-created sentinels
/// if the parent process exits before normal cleanup.
#[derive(Debug)]
struct SentinelHandle(HANDLE);
struct SentinelHandle {
script_path: PathBuf,
}
impl Drop for SentinelHandle {
fn drop(&mut self) {
if self.0 != 0 && self.0 != INVALID_HANDLE_VALUE {
unsafe {
CloseHandle(self.0);
}
self.0 = 0;
}
let _ = std::fs::remove_file(&self.script_path);
}
}
@@ -411,14 +417,11 @@ pub(crate) fn prepare_protected_metadata_targets(
}
ProtectedMetadataMode::MissingDenySentinel => {
let created = ensure_missing_deny_sentinel(&target.path)?;
let existing_deny_paths = protected_metadata_existing_deny_paths(&target.path);
if existing_deny_paths.is_empty() {
deny_paths.push(target.path.clone());
} else {
deny_paths.extend(existing_deny_paths);
}
if created {
sentinel_paths.push(target.path.clone());
} else {
let existing_deny_paths = protected_metadata_existing_deny_paths(&target.path);
deny_paths.extend(existing_deny_paths);
}
}
}
@@ -566,27 +569,65 @@ pub fn ensure_missing_deny_sentinel(path: &Path) -> Result<bool> {
}
}
fn open_delete_on_close_directory(path: &Path) -> Result<SentinelHandle> {
let path_wide = to_wide(path);
let handle = unsafe {
CreateFileW(
path_wide.as_ptr(),
DELETE,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
std::ptr::null_mut(),
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_DELETE_ON_CLOSE,
0,
fn start_sentinel_cleanup_watchdog(paths: &[PathBuf]) -> Result<SentinelHandle> {
let quoted_paths = paths
.iter()
.map(|path| format!("'{}'", powershell_single_quoted(&path.to_string_lossy())))
.collect::<Vec<_>>()
.join(",");
let script = format!(
"$parent = {}; $paths = @({}); try {{ while ($true) {{ $alive = Get-Process -Id $parent -ErrorAction SilentlyContinue; $remaining = @($paths | Where-Object {{ Test-Path -LiteralPath $_ }}); if (-not $alive -or $remaining.Count -eq 0) {{ break }}; Start-Sleep -Milliseconds 200 }}; foreach ($p in $paths) {{ Remove-Item -LiteralPath $p -Recurse -Force -ErrorAction SilentlyContinue }} }} finally {{ Remove-Item -LiteralPath $PSCommandPath -Force -ErrorAction SilentlyContinue }}",
std::process::id(),
quoted_paths
);
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.context("system clock is before Unix epoch")?
.as_millis();
let script_path = std::env::temp_dir().join(format!(
"codex-sentinel-cleanup-{}-{now}.ps1",
std::process::id()
));
std::fs::write(&script_path, script).with_context(|| {
format!(
"failed to write protected metadata sentinel cleanup script {}",
script_path.display()
)
};
if handle == INVALID_HANDLE_VALUE {
})?;
let cleanup_command = format!(
"powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File \"{}\"",
script_path.to_string_lossy().replace('"', "\\\"")
);
let start_script = format!(
"$r = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{{ CommandLine = '{}' }}; if ($r.ReturnValue -ne 0) {{ exit $r.ReturnValue }}",
powershell_single_quoted(&cleanup_command)
);
let status = Command::new("powershell.exe")
.args([
"-NoProfile",
"-NonInteractive",
"-ExecutionPolicy",
"Bypass",
"-Command",
&start_script,
])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.context("failed to start protected metadata sentinel cleanup watchdog launcher")?;
if !status.success() {
let _ = std::fs::remove_file(&script_path);
return Err(anyhow!(
"failed to arm protected metadata sentinel cleanup for {}: {}",
path.display(),
io::Error::last_os_error()
"protected metadata sentinel cleanup watchdog launcher exited with {status}"
));
}
Ok(SentinelHandle(handle))
Ok(SentinelHandle { script_path })
}
fn powershell_single_quoted(value: &str) -> String {
value.replace('\'', "''")
}
fn is_directory_reparse_point(metadata: &Metadata) -> bool {
@@ -704,12 +745,18 @@ mod tests {
assert!(target.is_dir(), "sentinel directory should be created");
assert!(
guard.deny_paths().any(|path| path_text_key(path) == path_text_key(&target)),
"sentinel should be deny-listed"
guard
.sentinel_paths()
.any(|path| path_text_key(path) == path_text_key(&target)),
"sentinel should be tracked separately from inherited deny paths"
);
assert!(
guard.deny_paths().next().is_none(),
"fresh sentinel should not use inherited deny ACL setup"
);
let removed = guard.cleanup_created_paths().expect("cleanup");
assert_eq!(removed, vec![target.clone()]);
assert!(removed.is_empty(), "sentinel cleanup is not a command violation");
assert!(!target.exists(), "sentinel directory should be removed");
}
@@ -725,6 +772,14 @@ mod tests {
}])
.expect("guard");
assert!(
guard.deny_paths().any(|path| path_text_key(path) == path_text_key(&target)),
"pre-existing metadata should still use deny paths"
);
assert!(
guard.sentinel_paths().next().is_none(),
"pre-existing metadata should not be claimed as a sentinel"
);
let removed = guard.cleanup_created_paths().expect("cleanup");
assert!(removed.is_empty(), "pre-existing metadata is not Codex-owned cleanup");
assert!(target.exists(), "pre-existing metadata should not be removed");
@@ -15,6 +15,7 @@ use codex_windows_sandbox::SetupErrorCode;
use codex_windows_sandbox::SetupErrorReport;
use codex_windows_sandbox::SetupFailure;
use codex_windows_sandbox::add_deny_write_ace;
use codex_windows_sandbox::add_deny_write_ace_non_inheriting;
use codex_windows_sandbox::canonicalize_path;
use codex_windows_sandbox::convert_string_sid_to_sid;
use codex_windows_sandbox::ensure_allow_mask_aces_with_inheritance;
@@ -832,7 +833,53 @@ fn run_setup_full(payload: &Payload, log: &mut File, sbx_dir: &Path) -> Result<(
ProtectedMetadataMode::MissingCreationMonitor => continue,
ProtectedMetadataMode::MissingDenySentinel => {
ensure_missing_deny_sentinel(&target.path)?;
protected_metadata_existing_deny_paths(&target.path)
if !seen_deny_paths.insert(target.path.clone()) {
continue;
}
if std::fs::symlink_metadata(&target.path).is_err() {
log_line(
log,
&format!(
"protected metadata sentinel {} missing during setup; skipping",
target.path.display()
),
)?;
continue;
}
let canonical_path = canonicalize_path(&target.path);
let deny_psid = if canonical_path.starts_with(&canonical_command_cwd) {
workspace_psid
} else {
cap_psid
};
match unsafe { add_deny_write_ace_non_inheriting(&target.path, deny_psid) } {
Ok(true) => {
log_line(
log,
&format!(
"applied deny ACE to protect metadata sentinel {}",
target.path.display()
),
)?;
}
Ok(false) => {}
Err(err) => {
refresh_errors.push(format!(
"metadata sentinel deny ACE failed on {}: {err}",
target.path.display()
));
log_line(
log,
&format!(
"metadata sentinel deny ACE failed on {}: {err}",
target.path.display()
),
)?;
}
}
continue;
}
};
if deny_paths.is_empty() {
@@ -198,9 +198,13 @@ fn run_setup_refresh_inner(
return Ok(());
}
let (read_roots, write_roots) = build_payload_roots(&request, &overrides);
let deny_write_paths = build_payload_deny_write_paths(&request, overrides.deny_write_paths);
let protected_metadata_targets =
build_payload_protected_metadata_targets(overrides.protected_metadata_targets);
let deny_write_paths = build_payload_deny_write_paths(
&request,
overrides.deny_write_paths,
&protected_metadata_targets,
);
let network_identity =
SandboxNetworkIdentity::from_policy(request.policy, request.proxy_enforced);
let offline_proxy_settings = offline_proxy_settings_from_env(request.env_map, network_identity);
@@ -757,9 +761,13 @@ pub fn run_elevated_setup(
)
})?;
let (read_roots, write_roots) = build_payload_roots(&request, &overrides);
let deny_write_paths = build_payload_deny_write_paths(&request, overrides.deny_write_paths);
let protected_metadata_targets =
build_payload_protected_metadata_targets(overrides.protected_metadata_targets);
let deny_write_paths = build_payload_deny_write_paths(
&request,
overrides.deny_write_paths,
&protected_metadata_targets,
);
let network_identity =
SandboxNetworkIdentity::from_policy(request.policy, request.proxy_enforced);
let offline_proxy_settings = offline_proxy_settings_from_env(request.env_map, network_identity);
@@ -835,6 +843,7 @@ fn build_payload_roots(
fn build_payload_deny_write_paths(
request: &SandboxSetupRequest<'_>,
explicit_deny_write_paths: Option<Vec<PathBuf>>,
protected_metadata_targets: &[ProtectedMetadataTarget],
) -> Vec<PathBuf> {
let allow_deny_paths: AllowDenyPaths = compute_allow_paths(
request.policy,
@@ -842,6 +851,13 @@ fn build_payload_deny_write_paths(
request.command_cwd,
request.env_map,
);
// Sentinel targets are protected by the dedicated metadata payload so setup
// applies a direct deny ACE without inheriting that deny into descendants.
let sentinel_path_keys: HashSet<String> = protected_metadata_targets
.iter()
.filter(|target| target.mode == ProtectedMetadataMode::MissingDenySentinel)
.map(|target| canonical_path_key(&target.path))
.collect();
let mut deny_write_paths: Vec<PathBuf> = explicit_deny_write_paths
.unwrap_or_default()
.into_iter()
@@ -854,6 +870,7 @@ fn build_payload_deny_write_paths(
})
.collect();
deny_write_paths.extend(allow_deny_paths.deny);
deny_write_paths.retain(|path| !sentinel_path_keys.contains(&canonical_path_key(path)));
deny_write_paths
}
@@ -1472,7 +1489,7 @@ mod tests {
};
let deny_write_paths =
super::build_payload_deny_write_paths(&request, Some(vec![explicit_deny.clone()]));
super::build_payload_deny_write_paths(&request, Some(vec![explicit_deny.clone()]), &[]);
assert_eq!(
[
@@ -1486,6 +1503,41 @@ mod tests {
);
}
#[test]
fn payload_deny_write_paths_skip_missing_metadata_sentinels() {
let tmp = TempDir::new().expect("tempdir");
let codex_home = tmp.path().join("codex-home");
let command_cwd = tmp.path().join("workspace");
let command_git = command_cwd.join(".git");
let explicit_deny = tmp.path().join("explicit-deny");
fs::create_dir_all(&command_git).expect("create command .git sentinel");
let policy = SandboxPolicy::WorkspaceWrite {
writable_roots: vec![],
network_access: false,
exclude_tmpdir_env_var: true,
exclude_slash_tmp: true,
};
let request = super::SandboxSetupRequest {
policy: &policy,
policy_cwd: &command_cwd,
command_cwd: &command_cwd,
env_map: &HashMap::new(),
codex_home: &codex_home,
proxy_enforced: false,
};
let deny_write_paths = super::build_payload_deny_write_paths(
&request,
Some(vec![explicit_deny.clone()]),
&[super::ProtectedMetadataTarget {
path: command_git.clone(),
mode: super::ProtectedMetadataMode::MissingDenySentinel,
}],
);
assert_eq!(vec![explicit_deny], deny_write_paths);
}
#[test]
fn full_read_roots_preserve_legacy_platform_defaults() {
let tmp = TempDir::new().expect("tempdir");
+34 -3
View File
@@ -31,6 +31,7 @@ use crate::workspace_acl::protect_workspace_agents_dir;
use crate::workspace_acl::protect_workspace_codex_dir;
use anyhow::Result;
use std::collections::HashMap;
use std::collections::HashSet;
use std::ffi::c_void;
use std::path::Path;
use std::path::PathBuf;
@@ -229,10 +230,12 @@ pub(crate) fn apply_legacy_session_acl_rules(
psid_workspace: Option<&LocalSid>,
persist_aces: bool,
additional_deny_paths: &[PathBuf],
excluded_deny_paths: &[PathBuf],
) -> Vec<PathBuf> {
let AllowDenyPaths { allow, mut deny } =
compute_allow_paths(policy, sandbox_policy_cwd, current_dir, env_map);
deny.extend(additional_deny_paths.iter().cloned());
remove_matching_paths(&mut deny, excluded_deny_paths);
let mut guards: Vec<PathBuf> = Vec::new();
let read_roots = legacy_session_executable_read_roots(env_map, command);
let direct_read_paths = legacy_session_direct_read_paths(env_map);
@@ -289,14 +292,39 @@ pub(crate) fn apply_legacy_session_acl_rules(
allow_null_device(psid_workspace.as_ptr());
allow_named_pipe_device(psid_workspace.as_ptr());
if persist_aces && matches!(policy, SandboxPolicy::WorkspaceWrite { .. }) {
let _ = protect_workspace_codex_dir(current_dir, psid_workspace.as_ptr());
let _ = protect_workspace_agents_dir(current_dir, psid_workspace.as_ptr());
if !path_matches_any(&current_dir.join(".codex"), excluded_deny_paths) {
let _ = protect_workspace_codex_dir(current_dir, psid_workspace.as_ptr());
}
if !path_matches_any(&current_dir.join(".agents"), excluded_deny_paths) {
let _ = protect_workspace_agents_dir(current_dir, psid_workspace.as_ptr());
}
}
}
}
guards
}
fn remove_matching_paths(paths: &mut HashSet<PathBuf>, excluded: &[PathBuf]) {
if excluded.is_empty() {
return;
}
let excluded_paths: Vec<PathBuf> = excluded
.iter()
.map(|path| canonicalize_path(path))
.collect();
paths.retain(|path| {
let path = canonicalize_path(path);
!excluded_paths.iter().any(|excluded| excluded == &path)
});
}
fn path_matches_any(path: &Path, paths: &[PathBuf]) -> bool {
let path = canonicalize_path(path);
paths
.iter()
.any(|candidate| canonicalize_path(candidate) == path)
}
pub(crate) fn legacy_session_executable_read_roots(
env_map: &HashMap<String, String>,
command: &[String],
@@ -412,6 +440,7 @@ fn windows_tool_root_for_path_dir(path: &Path) -> Option<PathBuf> {
None
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn prepare_elevated_spawn_context(
policy_json_or_preset: &str,
sandbox_policy_cwd: &Path,
@@ -420,6 +449,7 @@ pub(crate) fn prepare_elevated_spawn_context(
env_map: &mut HashMap<String, String>,
command: &[String],
protected_metadata_targets: &[ProtectedMetadataTarget],
excluded_deny_paths: &[PathBuf],
) -> Result<ElevatedSpawnContext> {
let common = prepare_spawn_context_common(
policy_json_or_preset,
@@ -431,12 +461,13 @@ pub(crate) fn prepare_elevated_spawn_context(
/*add_git_safe_directory*/ true,
)?;
let AllowDenyPaths { allow, deny } = compute_allow_paths(
let AllowDenyPaths { allow, mut deny } = compute_allow_paths(
&common.policy,
sandbox_policy_cwd,
&common.current_dir,
env_map,
);
remove_matching_paths(&mut deny, excluded_deny_paths);
let write_roots: Vec<PathBuf> = allow.into_iter().collect();
let deny_write_paths: Vec<PathBuf> = deny.into_iter().collect();
let write_roots_override = if common.is_workspace_write {
@@ -16,6 +16,7 @@ use codex_utils_pty::ProcessDriver;
use codex_utils_pty::SpawnedProcess;
use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
use tokio::sync::broadcast;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
@@ -36,7 +37,8 @@ pub(crate) async fn spawn_windows_sandbox_session_elevated(
) -> Result<SpawnedProcess> {
let mut protected_metadata_guard =
prepare_protected_metadata_targets(protected_metadata_targets)?;
protected_metadata_guard.arm_sentinel_cleanup()?;
let sentinel_deny_exclusions: Vec<PathBuf> =
protected_metadata_guard.sentinel_paths().cloned().collect();
let elevated = prepare_elevated_spawn_context(
policy_json_or_preset,
@@ -46,8 +48,10 @@ pub(crate) async fn spawn_windows_sandbox_session_elevated(
&mut env_map,
&command,
protected_metadata_targets,
&sentinel_deny_exclusions,
)?;
protected_metadata_guard.arm_sentinel_cleanup()?;
let protected_metadata_runtime = protected_metadata_guard.into_runtime()?;
let spawn_request = SpawnRequest {
command: command.clone(),
@@ -1,5 +1,6 @@
use super::windows_common::finish_driver_spawn;
use super::windows_common::normalize_windows_tty_input;
use crate::acl::add_deny_write_ace_non_inheriting;
use crate::acl::revoke_ace;
use crate::conpty::ConptyInstance;
use crate::conpty::spawn_conpty_process_as_user;
@@ -18,6 +19,7 @@ use crate::spawn_prep::allow_null_device_for_workspace_write;
use crate::spawn_prep::apply_legacy_session_acl_rules;
use crate::spawn_prep::prepare_legacy_session_security;
use crate::spawn_prep::prepare_legacy_spawn_context;
use anyhow::Context;
use anyhow::Result;
use codex_utils_pty::ProcessDriver;
use codex_utils_pty::SpawnedProcess;
@@ -332,7 +334,8 @@ pub(crate) async fn spawn_windows_sandbox_session_legacy(
prepare_protected_metadata_targets(protected_metadata_targets)?;
let additional_deny_write_paths: Vec<PathBuf> =
protected_metadata_guard.deny_paths().cloned().collect();
protected_metadata_guard.arm_sentinel_cleanup()?;
let sentinel_deny_exclusions: Vec<PathBuf> =
protected_metadata_guard.sentinel_paths().cloned().collect();
let guards = apply_legacy_session_acl_rules(
&common.policy,
sandbox_policy_cwd,
@@ -343,7 +346,21 @@ pub(crate) async fn spawn_windows_sandbox_session_legacy(
security.psid_workspace.as_ref(),
persist_aces,
&additional_deny_write_paths,
&sentinel_deny_exclusions,
);
unsafe {
for path in &sentinel_deny_exclusions {
add_deny_write_ace_non_inheriting(path, security.psid_generic.as_ptr()).with_context(
|| {
format!(
"failed to apply protected metadata sentinel ACL to {}",
path.display()
)
},
)?;
}
}
protected_metadata_guard.arm_sentinel_cleanup()?;
let protected_metadata_runtime = protected_metadata_guard.into_runtime()?;
let (writer_tx, writer_rx) = mpsc::channel::<Vec<u8>>(128);