Skip to content

Commit a34f824

Browse files
committed
fix(windows-sandbox): avoid redundant generic deny ACEs
1 parent b65ab46 commit a34f824

2 files changed

Lines changed: 270 additions & 2 deletions

File tree

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

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -836,15 +836,17 @@ enum DenyAceKind {
836836

837837
impl DenyAceKind {
838838
fn mask(self) -> u32 {
839+
// File-specific rights already include the generic mapping. Keeping
840+
// generic bits makes Windows split inheritable denies into effective
841+
// and inherit-only ACEs, needlessly consuming the bounded ACL space.
839842
match self {
840-
Self::Read => FILE_GENERIC_READ | GENERIC_READ_MASK,
843+
Self::Read => FILE_GENERIC_READ,
841844
Self::Write => {
842845
FILE_GENERIC_WRITE
843846
| FILE_WRITE_DATA
844847
| FILE_APPEND_DATA
845848
| FILE_WRITE_EA
846849
| FILE_WRITE_ATTRIBUTES
847-
| GENERIC_WRITE_MASK
848850
| DELETE
849851
| FILE_DELETE_CHILD
850852
}

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

Lines changed: 266 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,3 +195,269 @@ fn noninheriting_read_attributes_preserve_unprotected_child_dacl() {
195195
});
196196
assert_eq!(acl_snapshot(&child), before);
197197
}
198+
199+
// Use a synthetic restricting SID, never the real user's SID, so deny tests
200+
// cannot lock the test process out of its temporary files.
201+
fn restricted_access_allowed(path: &Path, psid: *mut c_void, desired: u32) -> bool {
202+
use std::os::windows::io::AsRawHandle;
203+
use std::os::windows::io::FromRawHandle;
204+
use std::os::windows::io::OwnedHandle;
205+
use windows_sys::Win32::Security::AccessCheck;
206+
use windows_sys::Win32::Security::CreateRestrictedToken;
207+
use windows_sys::Win32::Security::DISABLE_MAX_PRIVILEGE;
208+
use windows_sys::Win32::Security::DuplicateToken;
209+
use windows_sys::Win32::Security::GENERIC_MAPPING;
210+
use windows_sys::Win32::Security::MapGenericMask;
211+
use windows_sys::Win32::Security::SID_AND_ATTRIBUTES;
212+
use windows_sys::Win32::Security::SecurityImpersonation;
213+
214+
unsafe {
215+
let base = OwnedHandle::from_raw_handle(
216+
crate::token::get_current_token_for_restriction().expect("current token") as _,
217+
);
218+
let restricting = SID_AND_ATTRIBUTES {
219+
Sid: psid,
220+
Attributes: 0,
221+
};
222+
let mut restricted = std::ptr::null_mut();
223+
assert_ne!(
224+
CreateRestrictedToken(
225+
base.as_raw_handle() as _,
226+
DISABLE_MAX_PRIVILEGE,
227+
0,
228+
std::ptr::null(),
229+
0,
230+
std::ptr::null(),
231+
1,
232+
&restricting,
233+
&mut restricted,
234+
),
235+
0,
236+
"create restricting token: {}",
237+
std::io::Error::last_os_error()
238+
);
239+
let restricted = OwnedHandle::from_raw_handle(restricted as _);
240+
let mut impersonation = std::ptr::null_mut();
241+
assert_ne!(
242+
DuplicateToken(
243+
restricted.as_raw_handle() as _,
244+
SecurityImpersonation,
245+
&mut impersonation
246+
),
247+
0
248+
);
249+
let impersonation = OwnedHandle::from_raw_handle(impersonation as _);
250+
let mapping = GENERIC_MAPPING {
251+
GenericRead: super::FILE_GENERIC_READ,
252+
GenericWrite: super::FILE_GENERIC_WRITE,
253+
GenericExecute: super::FILE_GENERIC_EXECUTE,
254+
GenericAll: super::FILE_ALL_ACCESS,
255+
};
256+
let mut desired = desired;
257+
MapGenericMask(&mut desired, &mapping);
258+
let mut descriptor = std::ptr::null_mut();
259+
assert_eq!(
260+
windows_sys::Win32::Security::Authorization::GetNamedSecurityInfoW(
261+
to_wide(path).as_ptr(),
262+
1,
263+
DACL_SECURITY_INFORMATION
264+
| windows_sys::Win32::Security::OWNER_SECURITY_INFORMATION
265+
| windows_sys::Win32::Security::GROUP_SECURITY_INFORMATION,
266+
std::ptr::null_mut(),
267+
std::ptr::null_mut(),
268+
std::ptr::null_mut(),
269+
std::ptr::null_mut(),
270+
&mut descriptor,
271+
),
272+
0,
273+
"AccessCheck requires the owner and group as well as the DACL"
274+
);
275+
let mut privileges = [0u64; 128];
276+
let mut privilege_bytes = std::mem::size_of_val(&privileges) as u32;
277+
let mut granted = 0;
278+
let mut allowed = 0;
279+
let checked = AccessCheck(
280+
descriptor,
281+
impersonation.as_raw_handle() as _,
282+
desired,
283+
&mapping,
284+
privileges.as_mut_ptr().cast(),
285+
&mut privilege_bytes,
286+
&mut granted,
287+
&mut allowed,
288+
);
289+
LocalFree(descriptor as HLOCAL);
290+
assert_ne!(
291+
checked,
292+
0,
293+
"AccessCheck: {}",
294+
std::io::Error::last_os_error()
295+
);
296+
allowed != 0
297+
}
298+
}
299+
300+
fn install_legacy_deny(path: &Path, psid: *mut c_void, mask: u32) {
301+
use windows_sys::Win32::Security::Authorization::EXPLICIT_ACCESS_W;
302+
use windows_sys::Win32::Security::Authorization::SetEntriesInAclW;
303+
use windows_sys::Win32::Security::Authorization::SetNamedSecurityInfoW;
304+
use windows_sys::Win32::Security::Authorization::TRUSTEE_W;
305+
unsafe {
306+
let (dacl, descriptor) = fetch_dacl_handle(path).unwrap();
307+
let entry = EXPLICIT_ACCESS_W {
308+
grfAccessPermissions: mask,
309+
grfAccessMode: super::DENY_ACCESS,
310+
grfInheritance: super::CONTAINER_INHERIT_ACE | super::OBJECT_INHERIT_ACE,
311+
Trustee: TRUSTEE_W {
312+
pMultipleTrustee: std::ptr::null_mut(),
313+
MultipleTrusteeOperation: 0,
314+
TrusteeForm: super::TRUSTEE_IS_SID,
315+
TrusteeType: super::TRUSTEE_IS_UNKNOWN,
316+
ptstrName: psid.cast(),
317+
},
318+
};
319+
let mut updated = std::ptr::null_mut();
320+
assert_eq!(SetEntriesInAclW(1, &entry, dacl, &mut updated), 0);
321+
let result = SetNamedSecurityInfoW(
322+
to_wide(path).as_ptr() as *mut u16,
323+
1,
324+
DACL_SECURITY_INFORMATION,
325+
std::ptr::null_mut(),
326+
std::ptr::null_mut(),
327+
updated,
328+
std::ptr::null_mut(),
329+
);
330+
LocalFree(updated as HLOCAL);
331+
LocalFree(descriptor as HLOCAL);
332+
assert_eq!(result, 0);
333+
}
334+
}
335+
336+
fn assert_single_deny(path: &Path, psid: *mut c_void, mask: u32, flags: u8) {
337+
use windows_sys::Win32::Security::ACCESS_DENIED_ACE;
338+
use windows_sys::Win32::Security::EqualSid;
339+
use windows_sys::Win32::Security::GetAce;
340+
unsafe {
341+
let (acl, descriptor) = fetch_dacl_handle(path).unwrap();
342+
let mut denies = Vec::new();
343+
for index in 0..u32::from((*acl).AceCount) {
344+
let mut ace = std::ptr::null_mut();
345+
assert_ne!(GetAce(acl, index, &mut ace), 0);
346+
let ace = &*ace.cast::<ACCESS_DENIED_ACE>();
347+
if ace.Header.AceType == super::ACCESS_DENIED_ACE_TYPE
348+
&& EqualSid(std::ptr::addr_of!(ace.SidStart) as *mut c_void, psid) != 0
349+
{
350+
denies.push((ace.Mask, ace.Header.AceFlags));
351+
}
352+
}
353+
LocalFree(descriptor as HLOCAL);
354+
assert_eq!(denies, vec![(mask, flags)], "{}", path.display());
355+
}
356+
}
357+
358+
#[test]
359+
fn specific_denies_preserve_access_and_do_not_split_or_grow() {
360+
for (kind, generic) in [
361+
(super::DenyAceKind::Read, super::GENERIC_READ_MASK),
362+
(super::DenyAceKind::Write, super::GENERIC_WRITE_MASK),
363+
] {
364+
let legacy = tempfile::tempdir().unwrap();
365+
let compact = tempfile::tempdir().unwrap();
366+
let sid = LocalSid::from_string("S-1-5-21-915763429-1123581321-271828182-4245").unwrap();
367+
let mask = kind.mask();
368+
// A real allow establishes that AccessCheck fails because of the deny,
369+
// rather than because the synthetic restricting SID lacks a grant.
370+
for root in [legacy.path(), compact.path()] {
371+
unsafe {
372+
super::ensure_allow_mask_aces(root, &[sid.as_ptr()], super::FILE_ALL_ACCESS)
373+
.unwrap();
374+
}
375+
assert!(restricted_access_allowed(root, sid.as_ptr(), generic));
376+
std::fs::create_dir(root.join("existing")).unwrap();
377+
std::fs::write(root.join("existing/file"), b"test").unwrap();
378+
}
379+
install_legacy_deny(legacy.path(), sid.as_ptr(), mask | generic);
380+
assert!(unsafe { super::add_deny_ace(compact.path(), sid.as_ptr(), kind) }.unwrap());
381+
for root in [legacy.path(), compact.path()] {
382+
std::fs::create_dir(root.join("later")).unwrap();
383+
std::fs::create_dir(root.join("later/nested")).unwrap();
384+
std::fs::write(root.join("later/nested/file"), b"test").unwrap();
385+
}
386+
let paths = [
387+
"",
388+
"existing",
389+
"existing/file",
390+
"later",
391+
"later/nested",
392+
"later/nested/file",
393+
];
394+
for relative in paths {
395+
let old = legacy.path().join(relative);
396+
let new = compact.path().join(relative);
397+
let flags = if relative.is_empty() {
398+
3
399+
} else if new.is_dir() {
400+
0x13
401+
} else {
402+
0x10
403+
};
404+
assert_single_deny(&new, sid.as_ptr(), mask, flags);
405+
assert!(!restricted_access_allowed(&new, sid.as_ptr(), generic));
406+
// Check every specific right, including unrelated rights, against
407+
// the legacy behavior on self, existing children and later descendants.
408+
for bit in 0..32 {
409+
let access = 1u32 << bit;
410+
if access & super::FILE_ALL_ACCESS != 0 {
411+
assert_eq!(
412+
restricted_access_allowed(&new, sid.as_ptr(), access),
413+
restricted_access_allowed(&old, sid.as_ptr(), access),
414+
"{relative}: access {access:#x}"
415+
);
416+
}
417+
}
418+
}
419+
let before: Vec<_> = paths
420+
.iter()
421+
.map(|p| acl_snapshot(&compact.path().join(p)))
422+
.collect();
423+
// A second SID forces another native DACL update, which must not split
424+
// the first SID's ACE during automatic inheritance.
425+
let other = LocalSid::from_string("S-1-5-21-915763429-1123581321-271828182-4246").unwrap();
426+
assert!(unsafe { super::add_deny_ace(compact.path(), other.as_ptr(), kind) }.unwrap());
427+
for relative in paths {
428+
let path = compact.path().join(relative);
429+
let flags = if relative.is_empty() {
430+
3
431+
} else if path.is_dir() {
432+
0x13
433+
} else {
434+
0x10
435+
};
436+
assert_single_deny(&path, sid.as_ptr(), mask, flags);
437+
assert_single_deny(&path, other.as_ptr(), mask, flags);
438+
}
439+
let stable: Vec<_> = paths
440+
.iter()
441+
.map(|p| acl_snapshot(&compact.path().join(p)))
442+
.collect();
443+
for _ in 0..8 {
444+
for root in paths.map(|p| compact.path().join(p)) {
445+
assert!(!unsafe { super::add_deny_ace(&root, sid.as_ptr(), kind) }.unwrap());
446+
assert!(!unsafe { super::add_deny_ace(&root, other.as_ptr(), kind) }.unwrap());
447+
}
448+
}
449+
assert_eq!(
450+
paths
451+
.iter()
452+
.map(|p| acl_snapshot(&compact.path().join(p)))
453+
.collect::<Vec<_>>(),
454+
stable
455+
);
456+
assert!(
457+
stable
458+
.iter()
459+
.zip(before)
460+
.all(|(after, before)| after.1.len() == before.1.len() + 36)
461+
);
462+
}
463+
}

0 commit comments

Comments
 (0)