Skip to content

Commit 843c9d4

Browse files
committed
fix(windows-sandbox): batch protected-path deny ACL updates
1 parent a34f824 commit 843c9d4

3 files changed

Lines changed: 206 additions & 33 deletions

File tree

‎codex-rs/windows-sandbox-rs/src/acl.rs‎

Lines changed: 43 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ use windows_sys::Win32::Security::GetAclInformation;
4242
use windows_sys::Win32::Security::IsValidAcl;
4343
use windows_sys::Win32::Security::MapGenericMask;
4444
use windows_sys::Win32::Security::OWNER_SECURITY_INFORMATION;
45+
use windows_sys::Win32::Security::PSID;
4546
use windows_sys::Win32::Storage::FileSystem::CreateFileW;
4647
use windows_sys::Win32::Storage::FileSystem::DELETE;
4748
use windows_sys::Win32::Storage::FileSystem::FILE_ALL_ACCESS;
@@ -825,7 +826,17 @@ pub unsafe fn add_allow_ace(path: &Path, psid: *mut c_void) -> Result<bool> {
825826
/// # Safety
826827
/// Caller must ensure `psid` points to a valid SID and `path` refers to an existing file or directory.
827828
pub unsafe fn add_deny_write_ace(path: &Path, psid: *mut c_void) -> Result<bool> {
828-
add_deny_ace(path, psid, DenyAceKind::Write)
829+
add_deny_write_aces(path, &[psid])
830+
}
831+
832+
/// Adds missing inheritable write-deny ACEs with a single DACL update.
833+
/// Returns false without propagating inheritance when all denies are already present.
834+
///
835+
/// # Safety
836+
/// Caller must ensure every SID pointer is valid for the duration of this call and
837+
/// `path` refers to an existing file or directory (unless `psids` is empty).
838+
pub unsafe fn add_deny_write_aces(path: &Path, psids: &[PSID]) -> Result<bool> {
839+
add_deny_aces(path, psids, DenyAceKind::Write)
829840
}
830841

831842
#[derive(Clone, Copy)]
@@ -864,7 +875,7 @@ impl DenyAceKind {
864875
unsafe fn deny_ace_already_present(
865876
handle: &std::fs::File,
866877
path: &Path,
867-
psid: *mut c_void,
878+
psids: &[PSID],
868879
kind: DenyAceKind,
869880
) -> Result<bool> {
870881
let (mut p_dacl, mut p_sd) = (std::ptr::null_mut(), std::ptr::null_mut());
@@ -878,15 +889,22 @@ unsafe fn deny_ace_already_present(
878889
std::ptr::null_mut(),
879890
&mut p_sd,
880891
);
881-
let result =
882-
acl_api_result(path, "GetSecurityInfo", code).map(|()| kind.already_present(p_dacl, psid));
892+
let result = acl_api_result(path, "GetSecurityInfo", code)
893+
.map(|()| psids.iter().all(|&psid| kind.already_present(p_dacl, psid)));
883894
if !p_sd.is_null() {
884895
LocalFree(p_sd as HLOCAL);
885896
}
886897
result
887898
}
888899

889900
unsafe fn add_deny_ace(path: &Path, psid: *mut c_void, kind: DenyAceKind) -> Result<bool> {
901+
add_deny_aces(path, &[psid], kind)
902+
}
903+
904+
unsafe fn add_deny_aces(path: &Path, psids: &[PSID], kind: DenyAceKind) -> Result<bool> {
905+
if psids.is_empty() {
906+
return Ok(false);
907+
}
890908
let handle = match OpenOptions::new()
891909
.access_mode(READ_CONTROL | WRITE_DAC)
892910
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
@@ -902,7 +920,7 @@ unsafe fn add_deny_ace(path: &Path, psid: *mut c_void, kind: DenyAceKind) -> Res
902920
if matches!(kind, DenyAceKind::Read) {
903921
ensure_handle_is_not_filesystem_root(&read_handle, path)?;
904922
}
905-
if deny_ace_already_present(&read_handle, path, psid, kind)? {
923+
if deny_ace_already_present(&read_handle, path, psids, kind)? {
906924
return Ok(false);
907925
}
908926
return Err(write_error).context("open deny ACL target for update");
@@ -932,9 +950,15 @@ unsafe fn add_deny_ace(path: &Path, psid: *mut c_void, kind: DenyAceKind) -> Res
932950
path.display()
933951
));
934952
}
935-
let result = if kind.already_present(p_dacl, psid) {
936-
Ok(false)
937-
} else {
953+
let mut entries: Vec<EXPLICIT_ACCESS_W> = Vec::new();
954+
for &psid in psids {
955+
if kind.already_present(p_dacl, psid)
956+
|| entries
957+
.iter()
958+
.any(|entry| EqualSid(entry.Trustee.ptstrName.cast(), psid) != 0)
959+
{
960+
continue;
961+
}
938962
let trustee = TRUSTEE_W {
939963
pMultipleTrustee: std::ptr::null_mut(),
940964
MultipleTrusteeOperation: 0,
@@ -947,8 +971,18 @@ unsafe fn add_deny_ace(path: &Path, psid: *mut c_void, kind: DenyAceKind) -> Res
947971
explicit.grfAccessMode = DENY_ACCESS;
948972
explicit.grfInheritance = CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE;
949973
explicit.Trustee = trustee;
974+
entries.push(explicit);
975+
}
976+
let result = if entries.is_empty() {
977+
Ok(false)
978+
} else {
950979
let mut p_new_dacl: *mut ACL = std::ptr::null_mut();
951-
let code2 = SetEntriesInAclW(1, &explicit, p_dacl, &mut p_new_dacl);
980+
let code2 = SetEntriesInAclW(
981+
entries.len() as u32,
982+
entries.as_ptr(),
983+
p_dacl,
984+
&mut p_new_dacl,
985+
);
952986
let result = if let Err(err) = acl_api_result(path, "SetEntriesInAclW", code2) {
953987
Err(err)
954988
} else {

‎codex-rs/windows-sandbox-rs/src/acl_tests.rs‎

Lines changed: 136 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -66,9 +66,10 @@ fn existing_deny_ace_is_visible_without_write_dac() {
6666
let path = target.path();
6767
let psid = sid.as_ptr();
6868
assert!(unsafe { super::add_deny_read_ace(path, psid) }.expect("add deny ACE"));
69-
let already_present =
70-
unsafe { deny_ace_already_present(target.as_file(), path, psid, super::DenyAceKind::Read) }
71-
.expect("read existing deny ACE");
69+
let already_present = unsafe {
70+
deny_ace_already_present(target.as_file(), path, &[psid], super::DenyAceKind::Read)
71+
}
72+
.expect("read existing deny ACE");
7273
assert!(already_present);
7374
}
7475

@@ -461,3 +462,135 @@ fn specific_denies_preserve_access_and_do_not_split_or_grow() {
461462
);
462463
}
463464
}
465+
466+
fn ace_snapshot(path: &Path) -> Vec<Vec<u8>> {
467+
unsafe {
468+
let (acl, descriptor) = fetch_dacl_handle(path).unwrap();
469+
let mut entries = Vec::new();
470+
for index in 0..u32::from((*acl).AceCount) {
471+
let mut ace = std::ptr::null_mut();
472+
assert_ne!(super::GetAce(acl, index, &mut ace), 0);
473+
let header = &*ace.cast::<super::ACE_HEADER>();
474+
entries.push(
475+
std::slice::from_raw_parts(ace.cast::<u8>(), usize::from(header.AceSize)).to_vec(),
476+
);
477+
}
478+
LocalFree(descriptor as HLOCAL);
479+
entries
480+
}
481+
}
482+
483+
#[test]
484+
fn batch_write_denies_preserve_existing_aces_and_are_idempotent() {
485+
let parent = tempfile::tempdir().unwrap();
486+
let root = parent.path().join("protected");
487+
let existing = LocalSid::from_string("S-1-5-21-915763429-1123581321-271828182-4250").unwrap();
488+
let first = LocalSid::from_string("S-1-5-21-915763429-1123581321-271828182-4251").unwrap();
489+
let second = LocalSid::from_string("S-1-5-21-915763429-1123581321-271828182-4252").unwrap();
490+
let duplicate = LocalSid::from_string("S-1-5-21-915763429-1123581321-271828182-4251").unwrap();
491+
let marker = LocalSid::from_string("S-1-5-21-915763429-1123581321-271828182-4253").unwrap();
492+
unsafe {
493+
super::ensure_allow_mask_aces(parent.path(), &[marker.as_ptr()], super::FILE_GENERIC_READ)
494+
.unwrap();
495+
}
496+
std::fs::create_dir(&root).unwrap();
497+
std::fs::create_dir(root.join("existing")).unwrap();
498+
std::fs::write(root.join("existing/file"), b"test").unwrap();
499+
let sids = [
500+
existing.as_ptr(),
501+
first.as_ptr(),
502+
second.as_ptr(),
503+
duplicate.as_ptr(),
504+
];
505+
unsafe {
506+
super::ensure_allow_mask_aces(&root, &sids[..3], super::FILE_ALL_ACCESS).unwrap();
507+
assert!(super::add_deny_write_ace(&root, existing.as_ptr()).unwrap());
508+
assert!(super::add_deny_read_ace(&root, marker.as_ptr()).unwrap());
509+
}
510+
assert!(restricted_access_allowed(
511+
&root,
512+
first.as_ptr(),
513+
super::FILE_WRITE_DATA
514+
));
515+
assert!(restricted_access_allowed(
516+
&root,
517+
second.as_ptr(),
518+
super::FILE_WRITE_DATA
519+
));
520+
let before = ace_snapshot(&root);
521+
let control = acl_snapshot(&root).0;
522+
assert!(unsafe { super::add_deny_write_aces(&root, &sids) }.unwrap());
523+
let after = ace_snapshot(&root);
524+
assert_eq!(
525+
acl_snapshot(&root).0,
526+
control,
527+
"preserve inheritance control"
528+
);
529+
assert_eq!(after.len(), before.len() + 2, "only the two missing SIDs");
530+
for ace in &before {
531+
assert_eq!(
532+
after.iter().filter(|entry| *entry == ace).count(),
533+
before.iter().filter(|entry| *entry == ace).count(),
534+
"preserve every existing explicit and inherited ACE"
535+
);
536+
}
537+
std::fs::create_dir(root.join("later")).unwrap();
538+
std::fs::write(root.join("later/file"), b"test").unwrap();
539+
let paths = ["", "existing", "existing/file", "later", "later/file"];
540+
for relative in paths {
541+
let path = root.join(relative);
542+
let flags = if relative.is_empty() {
543+
3
544+
} else if path.is_dir() {
545+
0x13
546+
} else {
547+
0x10
548+
};
549+
for &sid in &sids[..3] {
550+
assert_single_deny(&path, sid, super::DenyAceKind::Write.mask(), flags);
551+
assert!(!restricted_access_allowed(
552+
&path,
553+
sid,
554+
super::FILE_WRITE_DATA
555+
));
556+
}
557+
}
558+
// The READ_CONTROL-only fallback must recognize the entire batch, not just one SID.
559+
let read_handle = OpenOptions::new()
560+
.access_mode(READ_CONTROL)
561+
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
562+
.open(&root)
563+
.unwrap();
564+
assert!(unsafe {
565+
deny_ace_already_present(&read_handle, &root, &sids, super::DenyAceKind::Write).unwrap()
566+
});
567+
assert!(!unsafe {
568+
deny_ace_already_present(
569+
&read_handle,
570+
&root,
571+
&[existing.as_ptr(), marker.as_ptr()],
572+
super::DenyAceKind::Write,
573+
)
574+
.unwrap()
575+
});
576+
let stable: Vec<_> = paths.iter().map(|p| acl_snapshot(&root.join(p))).collect();
577+
for _ in 0..3 {
578+
assert!(!unsafe { super::add_deny_write_aces(&root, &sids) }.unwrap());
579+
assert!(!unsafe { super::add_deny_write_ace(&root, first.as_ptr()) }.unwrap());
580+
}
581+
assert_eq!(
582+
paths
583+
.iter()
584+
.map(|p| acl_snapshot(&root.join(p)))
585+
.collect::<Vec<_>>(),
586+
stable
587+
);
588+
}
589+
590+
#[test]
591+
fn empty_write_deny_batch_does_not_open_the_path() {
592+
let parent = tempfile::tempdir().unwrap();
593+
let missing = parent.path().join("absent");
594+
assert!(!unsafe { super::add_deny_write_aces(&missing, &[]) }.unwrap());
595+
assert!(!missing.exists());
596+
}

‎codex-rs/windows-sandbox-rs/src/setup_provisioning.rs‎

Lines changed: 27 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ use crate::SetupErrorCode;
1313
use crate::SetupErrorReport;
1414
use crate::SetupFailure;
1515
use crate::SetupRuntime;
16+
use crate::acl::add_deny_write_aces;
1617
use crate::acquire_sandbox_setup_lock;
17-
use crate::add_deny_write_ace;
1818
use crate::convert_string_sid_to_sid;
1919
use crate::ensure_allow_mask_aces_with_inheritance;
2020
use crate::ensure_allow_write_aces;
@@ -1160,30 +1160,36 @@ fn run_setup_full(payload: &Payload, log: &mut dyn Write, sbx_dir: &Path) -> Res
11601160
&payload.write_roots,
11611161
path,
11621162
)?;
1163+
let mut deny_psids = Vec::with_capacity(deny_sid_strs.len());
11631164
for deny_sid_str in deny_sid_strs {
1164-
let deny_psid = unsafe {
1165-
convert_string_sid_to_sid(&deny_sid_str)
1166-
.ok_or_else(|| anyhow::anyhow!("convert deny capability SID failed"))?
1165+
let Some(deny_psid) = (unsafe { convert_string_sid_to_sid(&deny_sid_str) }) else {
1166+
for psid in deny_psids {
1167+
unsafe { LocalFree(psid as HLOCAL) };
1168+
}
1169+
return Err(anyhow::anyhow!("convert deny capability SID failed"));
11671170
};
1171+
deny_psids.push(deny_psid);
1172+
}
11681173

1169-
match unsafe { add_deny_write_ace(path, deny_psid) } {
1170-
Ok(true) => {
1171-
log_line(
1172-
log,
1173-
&format!("applied deny ACE to protect {}", path.display()),
1174-
)?;
1175-
}
1176-
Ok(false) => {}
1177-
Err(err) => {
1178-
refresh_errors.push(format!("deny ACE failed on {}: {err}", path.display()));
1179-
log_line(
1180-
log,
1181-
&format!("deny ACE failed on {}: {err}", path.display()),
1182-
)?;
1183-
}
1174+
let result = unsafe { add_deny_write_aces(path, &deny_psids) };
1175+
// Free every converted SID before logging or propagating an ACL error.
1176+
for psid in deny_psids {
1177+
unsafe { LocalFree(psid as HLOCAL) };
1178+
}
1179+
match result {
1180+
Ok(true) => {
1181+
log_line(
1182+
log,
1183+
&format!("applied deny ACE to protect {}", path.display()),
1184+
)?;
11841185
}
1185-
unsafe {
1186-
LocalFree(deny_psid as HLOCAL);
1186+
Ok(false) => {}
1187+
Err(err) => {
1188+
refresh_errors.push(format!("deny ACE failed on {}: {err}", path.display()));
1189+
log_line(
1190+
log,
1191+
&format!("deny ACE failed on {}: {err}", path.display()),
1192+
)?;
11871193
}
11881194
}
11891195
}

0 commit comments

Comments
 (0)