acl.rs 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  1. //! ACL helpers for the sandbox-user FS model — `srt-win acl
  2. //! stamp|grant|restore|revoke|recover`.
  3. //!
  4. //! The model is **additive explicit ACEs for the dedicated
  5. //! `srt-sandbox` user SID**, never a `PROTECTED` rewrite or SD
  6. //! snapshot:
  7. //!
  8. //! - `grant` ⇒ `(A;OICI;READ_EXEC|MODIFY_NO_FDC;;;<sb-SID>)` so the
  9. //! sandbox user (which has no inherent rights on real-user-owned
  10. //! files) can reach the working tree;
  11. //! - `stamp` ⇒ `(D;OICI;mask;;;<sb-SID>)` on the target plus
  12. //! `(D;OICI;FILE_DELETE_CHILD;;;<sb-SID>)` on the parent;
  13. //! - install-time ambient write-denies (`ambient.rs`) reuse the
  14. //! `stamp` deny shape, recorded in `ambient_denies` with no holder
  15. //! so they persist across sessions until `uninstall`.
  16. //!
  17. //! Restore = walk the path's explicit ACEs, drop any whose trustee
  18. //! is `<sb-SID>`, write back preserving the DACL's protection state
  19. //! (`UNPROTECTED` re-derives inherited ACEs; a `SE_DACL_PROTECTED`
  20. //! path keeps its severed inheritance). The single chokepoint is
  21. //! [`apply_sandbox_aces`] ([`SbAceSet`]): converge the path to
  22. //! exactly the wanted ALLOW + DENY for `<sb-SID>`, idempotently.
  23. //!
  24. //! The PROTECTED allow-lists in [`set_path_dacl_from_sddl`]'s
  25. //! callers are the ONE remaining `PROTECTED` consumer — they
  26. //! protect the state stores from the sandbox child, not user
  27. //! files. (Cross-broker serialization uses a file lock inside the
  28. //! protected session dir, not a named mutex — named objects are
  29. //! create-first squattable by a same-session sandbox child.)
  30. //!
  31. //! Globs are **rejected**. Directory targets get `(OI)(CI)` ACEs
  32. //! so the additive grant/deny inherits to the whole subtree.
  33. use anyhow::{Context, Result, anyhow, bail};
  34. use std::ffi::c_void;
  35. use std::mem::size_of;
  36. use windows::Win32::Security::Authorization::{
  37. GetNamedSecurityInfoW, SE_FILE_OBJECT, SetNamedSecurityInfoW,
  38. };
  39. use windows::Win32::Security::{
  40. ACE_FLAGS, ACE_HEADER, ACE_REVISION, ACL, ACL_REVISION, ACL_SIZE_INFORMATION,
  41. AclSizeInformation, AddAccessAllowedAceEx, AddAccessDeniedAceEx, AddAce, CONTAINER_INHERIT_ACE,
  42. DACL_SECURITY_INFORMATION, GetAce, GetAclInformation, GetLengthSid,
  43. GetSecurityDescriptorControl, InitializeAcl, InitializeSecurityDescriptor, OBJECT_INHERIT_ACE,
  44. OWNER_SECURITY_INFORMATION, PROTECTED_DACL_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR, PSID,
  45. SE_DACL_PROTECTED, SECURITY_ATTRIBUTES, SECURITY_DESCRIPTOR, SetSecurityDescriptorControl,
  46. SetSecurityDescriptorDacl, UNPROTECTED_DACL_SECURITY_INFORMATION,
  47. };
  48. use windows::Win32::Storage::FileSystem::{
  49. FILE_ALL_ACCESS, FILE_GENERIC_EXECUTE, FILE_GENERIC_READ,
  50. };
  51. use windows::Win32::System::SystemServices::{
  52. ACCESS_DENIED_ACE_TYPE, SECURITY_DESCRIPTOR_REVISION,
  53. };
  54. use crate::sid::LocalPsid;
  55. use crate::util::{OwnedSd, pcwstr, win32_ok, wstr};
  56. /// Owner-Rights well-known SID. ANY ACE for this SID replaces
  57. /// the kernel's implicit `READ_CONTROL|WRITE_DAC` grant to the
  58. /// owner with exactly the ACE's mask.
  59. pub const SID_OWNER_RIGHTS: &str = "S-1-3-4";
  60. pub const SID_SYSTEM: &str = "S-1-5-18";
  61. pub const SID_BUILTIN_ADMINS: &str = "S-1-5-32-544";
  62. pub const SID_BUILTIN_USERS: &str = "S-1-5-32-545";
  63. // ─── DACL builder primitives ────────────────────────────────────────
  64. // The policy functions below declare ACE lists as `&[Allow]`; this
  65. // section turns them into a self-owning ACL buffer. `Mask`'s field
  66. // is private and `Allow::OWNER_RIGHTS` takes no mask, so neither a
  67. // hex-typo (`0x0130_01bf` for `0x0013_01bf`) nor a mask-`0`
  68. // `OWNER_RIGHTS` ACE (which `SetNamedSecurityInfoW` drops on write
  69. // — a silent sandbox escape) is spellable from policy code.
  70. /// Access mask. Construct via the named consts and
  71. /// [`Mask::with`]/[`Mask::without`]; the inner `u32` is private so
  72. /// hex literals at call sites are not possible.
  73. #[derive(Copy, Clone, PartialEq, Eq, Debug)]
  74. pub struct Mask(u32);
  75. impl Mask {
  76. // Standard rights.
  77. pub const DELETE: Self = Self(0x0001_0000);
  78. pub const READ_CONTROL: Self = Self(0x0002_0000);
  79. pub const WRITE_DAC: Self = Self(0x0004_0000);
  80. pub const SYNCHRONIZE: Self = Self(0x0010_0000);
  81. // Generic — resolved via the object's GENERIC_MAPPING.
  82. pub const GENERIC_ALL: Self = Self(0x1000_0000);
  83. // File/dir-specific.
  84. pub const FILE_DELETE_CHILD: Self = Self(0x0000_0040);
  85. pub const FILE_ALL: Self = Self(FILE_ALL_ACCESS.0);
  86. pub const FILE_WRITE_ATTRIBUTES: Self = Self(0x0000_0100);
  87. pub const FILE_GENERIC_READ: Self = Self(FILE_GENERIC_READ.0);
  88. pub const FILE_GENERIC_WRITE: Self =
  89. Self(windows::Win32::Storage::FileSystem::FILE_GENERIC_WRITE.0);
  90. pub const FILE_GENERIC_EXECUTE: Self = Self(FILE_GENERIC_EXECUTE.0);
  91. /// `FILE_GENERIC_READ | FILE_GENERIC_EXECUTE` — the
  92. /// [`GrantMask::ReadOnly`] mask.
  93. pub const FILE_READ_EXEC: Self = Self::FILE_GENERIC_READ.with(Self::FILE_GENERIC_EXECUTE);
  94. /// `FileSystemRights.Modify` MINUS `FILE_DELETE_CHILD` — the
  95. /// working-tree [`GrantMask::Modify`] mask granted to the
  96. /// sandbox-user SID via `acl grant`. The sandbox user can
  97. /// create/write/read/delete non-protected siblings (`DELETE`
  98. /// is in there) but `FILE_DELETE_CHILD` is withheld so a
  99. /// denied file inside the tree stays protected — the
  100. /// parent-FDC DENY (`SbAce::DenyFdc`) is evaluated first, but
  101. /// withholding it from the grant too is defense-in-depth.
  102. pub const MODIFY_NO_FDC: Self = Self::FILE_GENERIC_READ
  103. .with(Self::FILE_GENERIC_WRITE)
  104. .with(Self::FILE_GENERIC_EXECUTE)
  105. .with(Self::DELETE)
  106. .without(Self::FILE_DELETE_CHILD);
  107. pub const fn bits(self) -> u32 {
  108. self.0
  109. }
  110. pub const fn with(self, m: Self) -> Self {
  111. Self(self.0 | m.0)
  112. }
  113. pub const fn without(self, m: Self) -> Self {
  114. Self(self.0 & !m.0)
  115. }
  116. }
  117. impl std::ops::BitOr for Mask {
  118. type Output = Self;
  119. fn bitor(self, r: Self) -> Self {
  120. self.with(r)
  121. }
  122. }
  123. /// `(OI)(CI)` inheritance for directory-target ACEs.
  124. pub const OICI: ACE_FLAGS = ACE_FLAGS(CONTAINER_INHERIT_ACE.0 | OBJECT_INHERIT_ACE.0);
  125. /// No inheritance — the ACE applies to the object itself only.
  126. pub const NO_INHERIT: ACE_FLAGS = ACE_FLAGS(0);
  127. /// One row in an `&[Allow]` ACE list — `(SID, mask, inherit-flags)`.
  128. /// The SID is a string so the policy function reads as an
  129. /// SDDL-style table; [`build_allow_dacl`] does the
  130. /// `ConvertStringSidToSidW` parsing once.
  131. #[derive(Copy, Clone)]
  132. pub struct Allow<'a>(pub &'a str, pub Mask, pub ACE_FLAGS);
  133. impl Allow<'static> {
  134. /// The only `OWNER_RIGHTS` ACE this crate emits. Mask is fixed
  135. /// at `READ_CONTROL` — suppresses owner-implicit `WRITE_DAC`
  136. /// (so an owner-child cannot rewrite the DACL) while still
  137. /// letting the owner read it. **The mask must be non-zero**:
  138. /// `SetNamedSecurityInfoW` silently drops a mask-0 ALLOW ACE on
  139. /// write, so the conceptually-purer `OWNER_RIGHTS:0` never
  140. /// reaches disk. With this const + `Mask`'s private field, the
  141. /// mask-0 mistake is unspellable from policy code.
  142. pub const OWNER_RIGHTS: Self = Allow(SID_OWNER_RIGHTS, Mask::READ_CONTROL, NO_INHERIT);
  143. }
  144. /// Self-owning ACL: `buf` holds the `ACL` header + ACEs.
  145. /// `AddAccessAllowedAceEx` copies SID bytes inline into each ACE
  146. /// (`SidStart` embeds the SID — see the size calc in
  147. /// [`build_allow_dacl`]), so once built `buf` is self-contained.
  148. pub struct BuiltAcl {
  149. buf: Vec<u8>,
  150. }
  151. impl BuiltAcl {
  152. pub fn as_ptr(&self) -> *const ACL {
  153. self.buf.as_ptr() as *const ACL
  154. }
  155. /// Wrap this ACL in an absolute-format SD with `SE_DACL_PROTECTED`
  156. /// set, plus a `SECURITY_ATTRIBUTES` borrowing it — for
  157. /// `CreateMutexExW` and similar object-creation APIs that take
  158. /// a `*const SECURITY_ATTRIBUTES`. The returned [`OwnedSa`] owns
  159. /// the ACL, the SD, and the SA; pass [`OwnedSa::as_ptr`] and
  160. /// keep the [`OwnedSa`] alive until the call returns.
  161. ///
  162. /// No `O:`/`G:` (owner/group): an explicit owner SID at object
  163. /// creation goes through `SeAssignSecurity`, which rejects any
  164. /// owner that isn't the caller's user / an `SE_GROUP_OWNER`
  165. /// group / a `SeRestorePrivilege`-enabled token
  166. /// (`ERROR_INVALID_OWNER`); leaving them unset defaults
  167. /// owner/group to the caller, which is what we want.
  168. pub fn into_security_attributes(self) -> Result<OwnedSa> {
  169. let mut sd: Box<SECURITY_DESCRIPTOR> = Box::default();
  170. let psd = PSECURITY_DESCRIPTOR(&mut *sd as *mut _ as *mut c_void);
  171. unsafe {
  172. InitializeSecurityDescriptor(psd, SECURITY_DESCRIPTOR_REVISION)
  173. .context("InitializeSecurityDescriptor")?;
  174. SetSecurityDescriptorDacl(psd, true, Some(self.as_ptr()), false)
  175. .context("SetSecurityDescriptorDacl")?;
  176. SetSecurityDescriptorControl(psd, SE_DACL_PROTECTED, SE_DACL_PROTECTED)
  177. .context("SetSecurityDescriptorControl(PROTECTED)")?;
  178. }
  179. let sa = SECURITY_ATTRIBUTES {
  180. nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
  181. lpSecurityDescriptor: psd.0,
  182. bInheritHandle: false.into(),
  183. };
  184. Ok(OwnedSa {
  185. _acl: self,
  186. _sd: sd,
  187. sa,
  188. })
  189. }
  190. }
  191. /// A `SECURITY_ATTRIBUTES` with its backing SD and ACL. Heap-pins
  192. /// the SD via `Box` so `sa.lpSecurityDescriptor` stays valid across
  193. /// moves of the [`OwnedSa`] itself. Do not `Clone`.
  194. pub struct OwnedSa {
  195. _acl: BuiltAcl,
  196. _sd: Box<SECURITY_DESCRIPTOR>,
  197. sa: SECURITY_ATTRIBUTES,
  198. }
  199. impl OwnedSa {
  200. pub fn as_ptr(&self) -> *const SECURITY_ATTRIBUTES {
  201. &self.sa
  202. }
  203. }
  204. /// Build an ALLOW-only DACL from an ACE table. Dedups by SID
  205. /// (case-insensitive; first occurrence wins).
  206. pub fn build_allow_dacl(aces: &[Allow<'_>]) -> Result<BuiltAcl> {
  207. // Parse SIDs first so the ACL sizing loop has the lengths.
  208. // Dedup by SID string (case-insensitive) — first wins.
  209. let mut seen = std::collections::HashSet::new();
  210. let parsed: Vec<(LocalPsid, u32, ACE_FLAGS)> = aces
  211. .iter()
  212. .filter(|Allow(s, _, _)| seen.insert(s.to_ascii_uppercase()))
  213. .map(|Allow(sid_str, m, fl)| {
  214. let sid = LocalPsid::from_string(sid_str)
  215. .with_context(|| format!("parse SID '{sid_str}'"))?;
  216. if unsafe { GetLengthSid(sid.as_psid()) } == 0 {
  217. bail!("GetLengthSid('{sid_str}') == 0");
  218. }
  219. Ok((sid, m.bits(), *fl))
  220. })
  221. .collect::<Result<_>>()?;
  222. let head: Vec<NewAce> = parsed
  223. .iter()
  224. .map(|(s, m, fl)| NewAce::Allow(s.as_psid(), *m, *fl))
  225. .collect();
  226. rebuild_acl(ACL_REVISION, &head, &(Vec::new(), 0, ACL_REVISION), &[])
  227. }
  228. /// Fixed prefix of `ACCESS_ALLOWED_ACE` / `ACCESS_DENIED_ACE`
  229. /// (Header 4 + Mask 4); `SidStart` is the first DWORD of the SID.
  230. const ACE_FIXED: usize = 8;
  231. /// `n` rounded up to a DWORD boundary — `InitializeAcl` requires the
  232. /// ACL buffer length to be DWORD-aligned.
  233. const fn dword_align(n: usize) -> usize {
  234. (n + 3) & !3
  235. }
  236. /// One ACE to add at the head/tail of a [`rebuild_acl`] output.
  237. /// `PSID` borrows the caller's SID buffer; keep it alive across the
  238. /// call.
  239. pub(crate) enum NewAce {
  240. Allow(PSID, u32, ACE_FLAGS),
  241. Deny(PSID, u32, ACE_FLAGS),
  242. }
  243. impl NewAce {
  244. fn sid(&self) -> PSID {
  245. let (Self::Allow(s, ..) | Self::Deny(s, ..)) = self;
  246. *s
  247. }
  248. }
  249. /// Size + `InitializeAcl(rev)` + `head` ACEs + `kept` raw ACEs +
  250. /// `tail` ACEs → [`BuiltAcl`]. The single ACL-construction
  251. /// chokepoint: [`build_allow_dacl`] (head only, `rev =
  252. /// ACL_REVISION`), [`apply_sandbox_aces`] (head + kept, `rev` from
  253. /// the source ACL via [`filter_aces`]), and `winsta::recompose_dacl`
  254. /// (kept + tail) all thread through here.
  255. ///
  256. /// `rev` MUST match the kept ACEs' source revision when `kept` is
  257. /// non-empty (`AddAce` requires `ACL_REVISION_DS` when copying
  258. /// object-type ACEs); pass [`KeptAces`].2.
  259. pub(crate) fn rebuild_acl(
  260. rev: ACE_REVISION,
  261. head: &[NewAce],
  262. kept: &KeptAces,
  263. tail: &[NewAce],
  264. ) -> Result<BuiltAcl> {
  265. let mut total = size_of::<ACL>() + kept.1;
  266. for a in head.iter().chain(tail) {
  267. total += ACE_FIXED + unsafe { GetLengthSid(a.sid()) } as usize;
  268. }
  269. total = dword_align(total);
  270. let mut buf = vec![0u8; total];
  271. let acl = buf.as_mut_ptr() as *mut ACL;
  272. unsafe { InitializeAcl(acl, total as u32, rev) }.context("InitializeAcl")?;
  273. let add = |a: &NewAce| match *a {
  274. NewAce::Allow(s, m, f) => unsafe { AddAccessAllowedAceEx(acl, rev, f, m, s) }
  275. .with_context(|| format!("AddAccessAllowedAceEx({m:#x})")),
  276. NewAce::Deny(s, m, f) => unsafe { AddAccessDeniedAceEx(acl, rev, f, m, s) }
  277. .with_context(|| format!("AddAccessDeniedAceEx({m:#x})")),
  278. };
  279. head.iter().try_for_each(&add)?;
  280. for (ace, sz) in &kept.0 {
  281. unsafe { AddAce(acl, rev, u32::MAX, *ace, *sz as u32) }.context("AddAce(keep)")?;
  282. }
  283. tail.iter().try_for_each(&add)?;
  284. Ok(BuiltAcl { buf })
  285. }
  286. // ─── DACL read + ACE-walk primitives ────────────────────────────────
  287. // Shared low-level wrappers so the recompose callers don't each
  288. // open-code GetNamedSecurityInfoW + GetAce loops.
  289. // `winsta.rs::recompose_dacl` uses `filter_aces` with its own
  290. // predicate (it KEEPS inherited ACEs; the file caller here drops
  291. // them).
  292. /// Read a file's DACL via
  293. /// `GetNamedSecurityInfoW(SE_FILE_OBJECT, DACL_SECURITY_INFORMATION)`.
  294. /// The returned `*mut ACL` points INTO the returned `OwnedSd`'s
  295. /// buffer — keep the `OwnedSd` alive while using the pointer.
  296. pub(crate) fn read_file_dacl(canonical_path: &str) -> Result<(OwnedSd, *mut ACL)> {
  297. let w = wstr(canonical_path);
  298. let mut dacl: *mut ACL = std::ptr::null_mut();
  299. let mut psd = PSECURITY_DESCRIPTOR::default();
  300. let r = unsafe {
  301. GetNamedSecurityInfoW(
  302. pcwstr(&w),
  303. SE_FILE_OBJECT,
  304. DACL_SECURITY_INFORMATION,
  305. None,
  306. None,
  307. Some(&mut dacl),
  308. None,
  309. &mut psd,
  310. )
  311. };
  312. win32_ok(r, &format!("GetNamedSecurityInfoW('{canonical_path}')"))?;
  313. Ok((OwnedSd::from_raw(psd), dacl))
  314. }
  315. /// Whether `sd`'s DACL carries `SE_DACL_PROTECTED` — inheritance from
  316. /// the parent was deliberately severed (`icacls /inheritance:d`,
  317. /// hardened trees). [`apply_sandbox_aces`] preserves this bit on
  318. /// write-back: recomposing such a path with `UNPROTECTED_` would
  319. /// silently re-enable inheritance, durably re-admitting the parent's
  320. /// (often permissive — e.g. a data-drive root's `Authenticated
  321. /// Users:(M)`) inheritable ACEs.
  322. pub(crate) fn sd_dacl_protected(sd: &OwnedSd) -> Result<bool> {
  323. // The binding's `pcontrol` is a bare `*mut u16` (the wire shape
  324. // of `SECURITY_DESCRIPTOR_CONTROL`).
  325. let mut control: u16 = 0;
  326. let mut revision = 0u32;
  327. unsafe { GetSecurityDescriptorControl(sd.ptr, &mut control, &mut revision) }
  328. .context("GetSecurityDescriptorControl")?;
  329. Ok(control & SE_DACL_PROTECTED.0 != 0)
  330. }
  331. /// Whether [`write_file_dacl`] sets `PROTECTED_` (block inheritance
  332. /// from the parent — the state-DB dir's allow-list, and
  333. /// [`apply_sandbox_aces`] on a path whose DACL was already
  334. /// protected) or `UNPROTECTED_DACL_SECURITY_INFORMATION` (re-derive
  335. /// inherited ACEs from the parent — [`apply_sandbox_aces`] on the
  336. /// common unprotected path).
  337. pub(crate) enum Protection {
  338. Protected,
  339. Unprotected,
  340. }
  341. /// Write `acl` as `path`'s DACL via
  342. /// `SetNamedSecurityInfoW(SE_FILE_OBJECT, DACL | <p>)`. Mirror of
  343. /// [`read_file_dacl`].
  344. pub(crate) fn write_file_dacl(path: &str, acl: *const ACL, p: Protection) -> Result<()> {
  345. let prot = match p {
  346. Protection::Protected => PROTECTED_DACL_SECURITY_INFORMATION,
  347. Protection::Unprotected => UNPROTECTED_DACL_SECURITY_INFORMATION,
  348. };
  349. let w = wstr(path);
  350. let r = unsafe {
  351. SetNamedSecurityInfoW(
  352. pcwstr(&w),
  353. SE_FILE_OBJECT,
  354. DACL_SECURITY_INFORMATION | prot,
  355. None,
  356. None,
  357. Some(acl),
  358. None,
  359. )
  360. };
  361. win32_ok(r, &format!("SetNamedSecurityInfoW('{path}')"))
  362. }
  363. /// `(kept ACE ptrs+sizes, Σ kept sizes, source AclRevision)`.
  364. pub(crate) type KeptAces = (Vec<(*const c_void, u16)>, usize, ACE_REVISION);
  365. /// Walk every ACE of `acl` and collect `(ptr, AceSize)` for those
  366. /// `keep` accepts. Returns `(kept, Σ kept sizes, source AclRevision)`.
  367. /// `acl == null` → `(∅, 0, ACL_REVISION)`. The kept pointers point
  368. /// into `acl`'s buffer; caller must keep that buffer alive.
  369. ///
  370. /// `keep` receives the raw `ACE_HEADER` and `body` = the full ACE
  371. /// bytes (`hdr.AceSize` long, starting at the ACE pointer — so
  372. /// `body[ACE_FIXED..]` is the embedded SID).
  373. ///
  374. /// The source's `AclRevision` is returned so a caller building a
  375. /// fresh ACL from kept ACEs can preserve it: `AddAce` requires
  376. /// `ACL_REVISION_DS` (4) when copying object-type ACEs, and
  377. /// `RtlValidAcl` rejects an ACL whose revision doesn't match its
  378. /// ACEs.
  379. pub(crate) fn filter_aces(
  380. acl: *const ACL,
  381. mut keep: impl FnMut(&ACE_HEADER, &[u8]) -> bool,
  382. ) -> Result<KeptAces> {
  383. if acl.is_null() {
  384. return Ok((Vec::new(), 0, ACL_REVISION));
  385. }
  386. let src_rev = ACE_REVISION(unsafe { (*acl).AclRevision } as u32);
  387. let mut info = ACL_SIZE_INFORMATION::default();
  388. unsafe {
  389. GetAclInformation(
  390. acl,
  391. &mut info as *mut _ as *mut c_void,
  392. size_of::<ACL_SIZE_INFORMATION>() as u32,
  393. AclSizeInformation,
  394. )
  395. .context("GetAclInformation")?;
  396. }
  397. let mut kept: Vec<(*const c_void, u16)> = Vec::new();
  398. let mut kept_sz = 0usize;
  399. for i in 0..info.AceCount {
  400. let mut ace: *mut c_void = std::ptr::null_mut();
  401. unsafe { GetAce(acl, i, &mut ace) }.map_err(|e| anyhow!("GetAce({i}): {e}"))?;
  402. if ace.is_null() {
  403. bail!("GetAce({i}) returned null");
  404. }
  405. let hdr = unsafe { &*(ace as *const ACE_HEADER) };
  406. let body = unsafe { std::slice::from_raw_parts(ace as *const u8, hdr.AceSize as usize) };
  407. if keep(hdr, body) {
  408. kept.push((ace as *const c_void, hdr.AceSize));
  409. kept_sz += hdr.AceSize as usize;
  410. }
  411. }
  412. Ok((kept, kept_sz, src_rev))
  413. }
  414. /// True iff `body[ACE_FIXED..]` starts with exactly `sid_bytes` —
  415. /// i.e. the ACE's trustee SID is `sid_bytes`.
  416. pub(crate) fn ace_sid_is(body: &[u8], sid_bytes: &[u8]) -> bool {
  417. body.get(ACE_FIXED..ACE_FIXED + sid_bytes.len()) == Some(sid_bytes)
  418. }
  419. /// Apply the broker-only DACL to a directory with `(OI)(CI)`
  420. /// inheritance, optionally **prefixed** by a `(D;OICI;FA;;;
  421. /// <deny_sid>)` ACE. Used by `state_db.rs` and `install.rs` to
  422. /// protect `%LOCALAPPDATA%\sandbox-runtime\`.
  423. ///
  424. /// `deny_sid` is the [`crate::user::SANDBOX_GROUP`] SID when the
  425. /// sandbox user has been provisioned: the credential file in this
  426. /// directory is encrypted with **machine-scope** DPAPI, which any
  427. /// local account can decrypt — so the sandbox account MUST NOT be
  428. /// able to read it. The real-user `PROTECTED` allow set already
  429. /// excludes the sandbox user, but the explicit DENY makes that
  430. /// intent visible in `Get-Acl` and survives any future widening of
  431. /// the allow set.
  432. ///
  433. /// Built via SDDL because [`build_allow_dacl`] only emits ALLOW
  434. /// ACEs, and adding a generic DENY row to the [`Allow`] table
  435. /// would invite misuse.
  436. pub fn stamp_dir_inheriting(canonical_path: &str, deny_sid: Option<&str>) -> Result<()> {
  437. let deny = deny_sid
  438. .map(|s| format!("(D;OICI;FA;;;{s})"))
  439. .unwrap_or_default();
  440. // Trustee = the **real user** (the broker matches; the
  441. // `srt-sandbox` child does not). SY/BA = FILE_ALL `(OI)(CI)`;
  442. // OWNER_RIGHTS = READ_CONTROL `(OI)(CI)`. SDDL's `FA` =
  443. // `FILE_ALL_ACCESS`; `RC` = `READ_CONTROL`; `S-1-3-4` =
  444. // OWNER_RIGHTS. Canonical ACE order = DENY before ALLOW.
  445. let user_sid = crate::sid::current_user_sid()?;
  446. let sddl = format!(
  447. "D:P{deny}\
  448. (A;OICI;FA;;;{user_sid})\
  449. (A;OICI;FA;;;SY)\
  450. (A;OICI;FA;;;BA)\
  451. (A;OICI;RC;;;S-1-3-4)"
  452. );
  453. set_path_dacl_from_sddl(canonical_path, &sddl, "state-db dir")
  454. }
  455. /// SDDL → SD → DACL pointer → `SetNamedSecurityInfoW(PROTECTED)`.
  456. /// One-shot helper for the few call sites that need a DENY ACE
  457. /// (which the [`BuiltAcl`] machinery deliberately doesn't expose).
  458. /// The `D:P` prefix in `sddl` is informational; `PROTECTED` is set
  459. /// here regardless via `PROTECTED_DACL_SECURITY_INFORMATION`.
  460. pub fn set_path_dacl_from_sddl(path: &str, sddl: &str, label: &str) -> Result<()> {
  461. use windows::Win32::Security::GetSecurityDescriptorDacl;
  462. let sd = crate::util::OwnedSd::from_sddl(sddl)
  463. .with_context(|| format!("{label}: build SD from SDDL"))?;
  464. let mut present = windows::core::BOOL::from(false);
  465. let mut dacl: *mut ACL = std::ptr::null_mut();
  466. let mut defaulted = windows::core::BOOL::from(false);
  467. unsafe {
  468. GetSecurityDescriptorDacl(sd.ptr, &mut present, &mut dacl, &mut defaulted)
  469. .with_context(|| format!("{label}: GetSecurityDescriptorDacl"))?;
  470. }
  471. if !present.as_bool() || dacl.is_null() {
  472. bail!("{label}: SDDL '{sddl}' yielded no DACL");
  473. }
  474. write_file_dacl(path, dacl, Protection::Protected).context(label.to_owned())
  475. }
  476. /// Open `path` for security-descriptor writes with NO-FOLLOW
  477. /// semantics and REJECT reparse points. `%ProgramData%`'s default
  478. /// DACL lets standard users pre-create directories — including as
  479. /// NTFS mount points / junctions targeting an arbitrary directory —
  480. /// so an elevated install that take-owns and re-ACLs by NAME can be
  481. /// redirected into re-ACLing a victim tree. Opening with
  482. /// `FILE_FLAG_OPEN_REPARSE_POINT` pins the object itself (no
  483. /// traversal), the attribute check rejects a planted reparse point,
  484. /// and the returned HANDLE is what the security writes below
  485. /// operate on — validate-then-use on the same object, not a name.
  486. pub fn open_for_security_no_follow(path: &str) -> Result<crate::util::OwnedHandle> {
  487. use windows::Win32::Foundation::INVALID_HANDLE_VALUE;
  488. use windows::Win32::Storage::FileSystem::BY_HANDLE_FILE_INFORMATION;
  489. use windows::Win32::Storage::FileSystem::{
  490. CreateFileW, FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_BACKUP_SEMANTICS,
  491. FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE,
  492. GetFileInformationByHandle, OPEN_EXISTING,
  493. };
  494. let w = wstr(path);
  495. let h = unsafe {
  496. CreateFileW(
  497. pcwstr(&w),
  498. Mask::READ_CONTROL.bits() | Mask::WRITE_DAC.bits() | 0x0008_0000, // + WRITE_OWNER
  499. FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
  500. None,
  501. OPEN_EXISTING,
  502. FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
  503. None,
  504. )
  505. }
  506. .with_context(|| format!("CreateFileW('{path}', no-follow)"))?;
  507. if h == INVALID_HANDLE_VALUE {
  508. bail!("CreateFileW('{path}'): INVALID_HANDLE_VALUE");
  509. }
  510. let owned = crate::util::OwnedHandle(h);
  511. let mut info = BY_HANDLE_FILE_INFORMATION::default();
  512. unsafe { GetFileInformationByHandle(owned.0, &mut info) }
  513. .with_context(|| format!("GetFileInformationByHandle('{path}')"))?;
  514. if info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT.0 != 0 {
  515. bail!(
  516. "'{path}' is a reparse point (junction/symlink) — refusing \
  517. to operate on a redirected store path; remove it and re-run"
  518. );
  519. }
  520. Ok(owned)
  521. }
  522. /// Set OWNER = `BUILTIN\Administrators` on an open handle (see
  523. /// [`open_for_security_no_follow`] for why by-handle). Requires
  524. /// `SeTakeOwnershipPrivilege`/`SeRestorePrivilege` enabled unless
  525. /// the caller already owns the object.
  526. pub fn set_handle_owner_admins(h: &crate::util::OwnedHandle, label: &str) -> Result<()> {
  527. use windows::Win32::Security::Authorization::{SE_FILE_OBJECT, SetSecurityInfo};
  528. let admins = crate::sid::LocalPsid::from_string(SID_BUILTIN_ADMINS)?;
  529. let r = unsafe {
  530. SetSecurityInfo(
  531. h.0,
  532. SE_FILE_OBJECT,
  533. OWNER_SECURITY_INFORMATION,
  534. Some(admins.as_psid()),
  535. None,
  536. None,
  537. None,
  538. )
  539. };
  540. win32_ok(r, &format!("SetSecurityInfo(owner, {label})"))
  541. }
  542. /// Write a PROTECTED DACL parsed from `sddl` onto an open handle
  543. /// (see [`open_for_security_no_follow`] for why by-handle).
  544. pub fn set_handle_dacl_from_sddl(
  545. h: &crate::util::OwnedHandle,
  546. sddl: &str,
  547. label: &str,
  548. ) -> Result<()> {
  549. use windows::Win32::Security::Authorization::{SE_FILE_OBJECT, SetSecurityInfo};
  550. use windows::Win32::Security::GetSecurityDescriptorDacl;
  551. let sd = crate::util::OwnedSd::from_sddl(sddl)
  552. .with_context(|| format!("{label}: build SD from SDDL"))?;
  553. let mut present = windows::core::BOOL::from(false);
  554. let mut dacl: *mut ACL = std::ptr::null_mut();
  555. let mut defaulted = windows::core::BOOL::from(false);
  556. unsafe {
  557. GetSecurityDescriptorDacl(sd.ptr, &mut present, &mut dacl, &mut defaulted)
  558. .with_context(|| format!("{label}: GetSecurityDescriptorDacl"))?;
  559. }
  560. if !present.as_bool() || dacl.is_null() {
  561. bail!("{label}: SDDL '{sddl}' yielded no DACL");
  562. }
  563. let r = unsafe {
  564. SetSecurityInfo(
  565. h.0,
  566. SE_FILE_OBJECT,
  567. DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
  568. None,
  569. None,
  570. Some(dacl),
  571. None,
  572. )
  573. };
  574. win32_ok(r, &format!("SetSecurityInfo(dacl, {label})"))
  575. }
  576. // ─── Additive grants (working-tree access for the sandbox user) ─────
  577. //
  578. // Under the separate-user model the sandbox user has NO inherent
  579. // rights on real-user-owned files. `acl grant` adds an inheritable
  580. // ALLOW ACE for the sandbox user's SID on a path (typically the
  581. // working-tree root) so the child can read/write there; `acl stamp
  582. // --sandbox-user-sid` adds an explicit DENY ACE on a path (and a
  583. // `(OI)(CI)` `FILE_DELETE_CHILD` DENY on its parent) so the child
  584. // can NOT read/write/delete it even when an inherited
  585. // `BUILTIN\Users` ACE would otherwise allow. Both are ADDITIVE
  586. // (the path keeps its own explicit ACEs and inheritance);
  587. // revoke/restore drops the SID's ACEs by walk-and-filter, not a
  588. // full-SD restore.
  589. /// Per-grant access level. `Modify` is [`Mask::MODIFY_NO_FDC`] (the
  590. /// working-tree grant — read/write/create/delete-own but NOT
  591. /// `FILE_DELETE_CHILD`, so a denied file inside the granted tree
  592. /// cannot be deleted via parent-FDC even where the only sb-user
  593. /// access comes from this grant). `ReadOnly` is
  594. /// [`Mask::FILE_READ_EXEC`].
  595. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  596. pub enum GrantMask {
  597. ReadOnly,
  598. Modify,
  599. }
  600. /// Per-deny mask. `ReadDeny` denies everything; `WriteDeny` leaves
  601. /// read+execute. The bits are the *denied* rights.
  602. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  603. pub enum DenyMask {
  604. WriteDeny,
  605. ReadDeny,
  606. }
  607. /// One explicit ACE the sandbox user holds on a path. The
  608. /// separate-user FS model is entirely additive: `acl grant` adds
  609. /// ALLOW ACEs, `acl stamp --sandbox-user-sid` adds DENY ACEs (plus
  610. /// a `(OI)(CI)` `FILE_DELETE_CHILD` DENY on the parent). Restore
  611. /// drops the SID's ACEs via walk-and-filter — no PROTECTED rewrite,
  612. /// no SD snapshot, no calibration.
  613. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  614. pub enum SbAce {
  615. Grant(GrantMask),
  616. Deny(DenyMask),
  617. /// `(D;OICI;FILE_DELETE_CHILD;;;<sb>)` — applied to the parent
  618. /// of every denied target so the sandbox user cannot `del`/`ren`
  619. /// it via parent-FDC even when the parent carries an inherited
  620. /// `BUILTIN\Users:(F)` (which the sandbox user, a Users member,
  621. /// would otherwise pick up).
  622. DenyFdc,
  623. /// `(D;;DELETE;;;<sb>)` — object-only (`NO_INHERIT`) DELETE deny
  624. /// on a placeholder INTERMEDIATE directory. Blocks the sandbox
  625. /// from renaming/rmdir'ing the intermediate (which would bypass
  626. /// the leaf's stamp) without leaking any semantics onto children:
  627. /// a full-mask `(OI)(CI)` deny here would deny reads over the
  628. /// whole subtree if the placeholder later becomes a real user
  629. /// directory.
  630. DenyDelete,
  631. }
  632. impl GrantMask {
  633. fn bits(self) -> u32 {
  634. match self {
  635. GrantMask::ReadOnly => Mask::FILE_READ_EXEC.bits(),
  636. GrantMask::Modify => Mask::MODIFY_NO_FDC.bits(),
  637. }
  638. }
  639. }
  640. impl DenyMask {
  641. fn bits(self) -> u32 {
  642. match self {
  643. DenyMask::ReadDeny => Mask::FILE_ALL.bits(),
  644. // FILE_GENERIC_WRITE includes SYNCHRONIZE + READ_CONTROL
  645. // — denying SYNCHRONIZE blocks ANY synchronous open
  646. // (read included). Strip both so denyWrite leaves
  647. // read open. FILE_WRITE_ATTRIBUTES is already in
  648. // FILE_GENERIC_WRITE; the explicit `.with()` is
  649. // belt-and-braces (it survives a constant change).
  650. DenyMask::WriteDeny => Mask::FILE_GENERIC_WRITE
  651. .with(Mask::DELETE)
  652. .with(Mask::FILE_WRITE_ATTRIBUTES)
  653. .without(Mask::SYNCHRONIZE)
  654. .without(Mask::READ_CONTROL)
  655. .bits(),
  656. }
  657. }
  658. }
  659. impl SbAce {
  660. /// `'grant' | 'deny' | 'deny_fdc'` — the row's `kind` column.
  661. pub fn kind(self) -> &'static str {
  662. match self {
  663. SbAce::Grant(_) => "grant",
  664. SbAce::Deny(_) => "deny",
  665. SbAce::DenyFdc => "deny_fdc",
  666. SbAce::DenyDelete => "deny_delete",
  667. }
  668. }
  669. /// `'read' | 'modify' | 'denyRead' | 'denyWrite' | 'fdc'` — the
  670. /// row's `mask` / holder's `want_mask` column. Round-trips via
  671. /// [`SbAce::parse`].
  672. pub fn as_str(self) -> &'static str {
  673. match self {
  674. SbAce::Grant(GrantMask::ReadOnly) => "read",
  675. SbAce::Grant(GrantMask::Modify) => "modify",
  676. SbAce::Deny(DenyMask::ReadDeny) => "denyRead",
  677. SbAce::Deny(DenyMask::WriteDeny) => "denyWrite",
  678. SbAce::DenyFdc => "fdc",
  679. SbAce::DenyDelete => "delete",
  680. }
  681. }
  682. pub fn parse(kind: &str, mask: &str) -> Result<Self> {
  683. Ok(match (kind, mask) {
  684. ("grant", "read") => SbAce::Grant(GrantMask::ReadOnly),
  685. ("grant", "modify") => SbAce::Grant(GrantMask::Modify),
  686. ("deny", "denyRead") => SbAce::Deny(DenyMask::ReadDeny),
  687. ("deny", "denyWrite") => SbAce::Deny(DenyMask::WriteDeny),
  688. ("deny_fdc", _) => SbAce::DenyFdc,
  689. ("deny_delete", _) => SbAce::DenyDelete,
  690. (k, m) => bail!("unknown SbAce kind={k:?} mask={m:?}"),
  691. })
  692. }
  693. /// Widening within one kind: `Modify ⊃ ReadOnly`, `ReadDeny ⊃
  694. /// WriteDeny`, `DenyFdc` is unit. Cross-kind is meaningless (a
  695. /// path can hold one `Grant` row AND one `Deny` row; never
  696. /// merged).
  697. pub fn max(self, other: Self) -> Self {
  698. use DenyMask::ReadDeny as Dr;
  699. use GrantMask::Modify as Gm;
  700. match (self, other) {
  701. (SbAce::Grant(Gm), _) | (_, SbAce::Grant(Gm)) => SbAce::Grant(Gm),
  702. (SbAce::Grant(_), _) | (_, SbAce::Grant(_)) => self,
  703. (SbAce::Deny(Dr), _) | (_, SbAce::Deny(Dr)) => SbAce::Deny(Dr),
  704. _ => self,
  705. }
  706. }
  707. }
  708. /// What [`apply_sandbox_aces`] should converge a path to: at most one
  709. /// ALLOW ACE, one DENY ACE, and one parent-FDC DENY for the sandbox
  710. /// user. State-DB recomputes this from the live holder rows on every
  711. /// change so cross-holder mask escalation/downgrade and the
  712. /// grant/deny-on-same-path interaction are handled in one place.
  713. #[derive(Debug, Clone, Copy, Default)]
  714. pub struct SbAceSet {
  715. pub grant: Option<GrantMask>,
  716. pub deny: Option<DenyMask>,
  717. pub deny_fdc: bool,
  718. pub deny_delete: bool,
  719. }
  720. impl SbAceSet {
  721. /// The set's entries as [`NewAce`]s for `sid`, in canonical
  722. /// deny → deny-fdc → allow order. `Deny`/`DenyFdc`/`Grant` carry
  723. /// [`OICI`]; `DenyDelete` is object-only ([`NO_INHERIT`]) — see
  724. /// [`SbAce::DenyDelete`].
  725. fn head_aces(&self, sid: PSID) -> Vec<NewAce> {
  726. let mut v = Vec::with_capacity(4);
  727. if let Some(m) = self.deny {
  728. v.push(NewAce::Deny(sid, m.bits(), OICI));
  729. }
  730. if self.deny_delete {
  731. v.push(NewAce::Deny(sid, Mask::DELETE.bits(), NO_INHERIT));
  732. }
  733. if self.deny_fdc {
  734. v.push(NewAce::Deny(sid, Mask::FILE_DELETE_CHILD.bits(), OICI));
  735. }
  736. if let Some(m) = self.grant {
  737. v.push(NewAce::Allow(sid, m.bits(), OICI));
  738. }
  739. v
  740. }
  741. }
  742. /// Converge `canonical_path`'s explicit ACEs for `sandbox_sid` to
  743. /// exactly `set`. Idempotent — every existing explicit ACE for the
  744. /// SID (allow AND deny) is dropped, then `set`'s entries are
  745. /// prepended in canonical (deny-before-allow) order. Inherited ACEs
  746. /// are dropped too; on the (common) unprotected DACL,
  747. /// `SetNamedSecurityInfoW` without `PROTECTED_` re-derives them from
  748. /// the parent. A `SE_DACL_PROTECTED` DACL (inheritance deliberately
  749. /// severed — its ACEs are normally all explicit, so nothing is
  750. /// dropped; a hand-crafted stray `INHERITED_ACE`-flagged entry is
  751. /// dropped and not re-derived, which fails closed) is written back
  752. /// `PROTECTED_`: recomposing it `UNPROTECTED_` would
  753. /// silently re-enable inheritance, and neither revoke nor restore
  754. /// could undo that — the parent's inheritable ACEs (e.g. a data-drive
  755. /// root's `Authenticated Users:(M)`) would durably re-open a path its
  756. /// admin had locked down.
  757. ///
  758. /// `SetEntriesInAclW(REVOKE_ACCESS)` is NOT used: per MSDN it
  759. /// removes `ACCESS_ALLOWED_ACE`/`SYSTEM_AUDIT_ACE` for the trustee,
  760. /// not `ACCESS_DENIED_ACE` — so a prior `Deny`/`DenyFdc` ACE would
  761. /// survive. `SET_ACCESS` discards all but adds a new ALLOW ACE,
  762. /// which is wrong when `set` is empty. So we walk + filter
  763. /// manually.
  764. ///
  765. /// Both grant and deny carry `(OI)(CI)` so directory targets cover
  766. /// the subtree; on a file the inheritance flags are inert.
  767. pub fn apply_sandbox_aces(canonical_path: &str, sandbox_sid: &str, set: SbAceSet) -> Result<()> {
  768. let sid = LocalPsid::from_string(sandbox_sid)
  769. .with_context(|| format!("parse sandbox SID '{sandbox_sid}'"))?;
  770. let sid_bytes = sid.as_bytes();
  771. // 1. Read the current DACL and its protection state. `sd` owns
  772. // the buffer `old`/`keep` point into; it's freed after step
  773. // 4's write.
  774. let (sd, old) =
  775. read_file_dacl(canonical_path).with_context(|| format!("recompose '{canonical_path}'"))?;
  776. let protected =
  777. sd_dacl_protected(&sd).with_context(|| format!("recompose '{canonical_path}'"))?;
  778. // 2. Collect surviving explicit ACEs (drop inherited and any
  779. // explicit ACE whose SID == sandbox_sid — allow AND deny).
  780. let kept = filter_aces(old, |hdr, body| {
  781. hdr.AceFlags & INHERITED_ACE == 0 && !ace_sid_is(body, sid_bytes)
  782. })?;
  783. // 3. Build fresh ACL: set's entries (deny-first canonical order)
  784. // then surviving explicit ACEs.
  785. let new = rebuild_acl(kept.2, &set.head_aces(sid.as_psid()), &kept, &[])?;
  786. // 4. Write back, preserving the DACL's protection state:
  787. // UNPROTECTED so the kernel re-derives inherited ACEs from the
  788. // parent, PROTECTED when inheritance was severed before we
  789. // touched the path (see doc comment).
  790. let prot = if protected {
  791. Protection::Protected
  792. } else {
  793. Protection::Unprotected
  794. };
  795. write_file_dacl(canonical_path, new.as_ptr(), prot)
  796. .with_context(|| format!("recompose '{canonical_path}'"))
  797. }
  798. /// Whether `canonical_path` carries an EXPLICIT `(OI)(CI)` deny ACE
  799. /// for `sandbox_sid` covering at least the [`DenyMask::WriteDeny`]
  800. /// bits. Drift check for `srt-win status`'s ambient write-deny
  801. /// report and the install early-out's completeness check — a
  802. /// recorded install-time stamp whose on-disk ACE is gone (e.g. an
  803. /// `icacls /reset` by an admin) reads as absent, and an unrelated
  804. /// narrow deny on the same path (a `DenyDelete` placeholder, a
  805. /// parent-FDC ACE) must NOT count as the write-deny being intact.
  806. pub fn sandbox_deny_present(canonical_path: &str, sandbox_sid: &str) -> Result<bool> {
  807. let sid = LocalPsid::from_string(sandbox_sid)
  808. .with_context(|| format!("parse sandbox SID '{sandbox_sid}'"))?;
  809. let sid_bytes = sid.as_bytes();
  810. let want_mask = DenyMask::WriteDeny.bits();
  811. let want_flags = OICI.0 as u8;
  812. let (_sd, dacl) = read_file_dacl(canonical_path)?;
  813. let denies = filter_aces(dacl, |hdr, body| {
  814. // ACCESS_DENIED_ACE layout: header (4) then Mask (u32 LE).
  815. let mask = u32::from_le_bytes([body[4], body[5], body[6], body[7]]);
  816. u32::from(hdr.AceType) == ACCESS_DENIED_ACE_TYPE
  817. && hdr.AceFlags & INHERITED_ACE == 0
  818. && hdr.AceFlags & want_flags == want_flags
  819. && mask & want_mask == want_mask
  820. && ace_sid_is(body, sid_bytes)
  821. })?;
  822. Ok(!denies.0.is_empty())
  823. }
  824. const INHERITED_ACE: u8 = 0x10;
  825. #[cfg(test)]
  826. mod tests {
  827. use super::*;
  828. fn ace_count(d: &BuiltAcl) -> u16 {
  829. // ACL.AceCount is bytes 4–5 (LE u16).
  830. u16::from_le_bytes([d.buf[4], d.buf[5]])
  831. }
  832. /// IsolatedDesk's `[broker, sb, SY]:GA` DACL — 3 ACEs,
  833. /// revision 2, GENERIC_ALL on each. Regression for the
  834. /// `KeptAces`/`rebuild_acl` chokepoint: a sizing or revision
  835. /// bug here breaks the sandbox-user desktop attach (R1 hang).
  836. #[test]
  837. fn isolated_desk_dacl_shape() {
  838. let d = build_allow_dacl(&[
  839. Allow("S-1-5-21-1-2-3-1000", Mask::GENERIC_ALL, NO_INHERIT),
  840. Allow("S-1-5-21-1-2-3-1004", Mask::GENERIC_ALL, NO_INHERIT),
  841. Allow(SID_SYSTEM, Mask::GENERIC_ALL, NO_INHERIT),
  842. ])
  843. .unwrap();
  844. assert_eq!(d.buf[0], 2, "AclRevision");
  845. assert_eq!(ace_count(&d), 3);
  846. }
  847. #[test]
  848. fn build_allow_dacl_dedup() {
  849. // Same SID twice (case-insensitive) → 1 ACE; first wins.
  850. let d = build_allow_dacl(&[
  851. Allow(SID_BUILTIN_ADMINS, Mask::FILE_ALL, NO_INHERIT),
  852. Allow("s-1-5-32-544", Mask::FILE_READ_EXEC, NO_INHERIT),
  853. ])
  854. .unwrap();
  855. assert_eq!(ace_count(&d), 1);
  856. }
  857. /// Grant → revoke on a `SE_DACL_PROTECTED` directory must leave
  858. /// the protection bit (and the explicit ACE set) intact.
  859. /// Regression: [`apply_sandbox_aces`] used to write back
  860. /// `UNPROTECTED_` unconditionally, which re-enabled inheritance
  861. /// on a deliberately severed path — durably re-admitting the
  862. /// parent's inheritable ACEs (e.g. a data-drive root's
  863. /// `Authenticated Users:(M)`), and revoke could not undo it.
  864. #[test]
  865. fn recompose_preserves_dacl_protection() {
  866. // Guests — a resolvable well-known SID that is never the
  867. // test runner's own identity, standing in for the sandbox
  868. // user (no account provisioning needed to write ACEs).
  869. const FAKE_SB_SID: &str = "S-1-5-32-546";
  870. let dir = std::env::temp_dir().join(format!("srtwin-prot-{}", std::process::id()));
  871. std::fs::create_dir_all(&dir).unwrap();
  872. let path = dir.to_str().unwrap();
  873. // Sever inheritance: protected DACL with an explicit
  874. // owner-side allow (mirrors `icacls /inheritance:d` plus a
  875. // lockdown to a fixed ACE set).
  876. let user_sid = crate::sid::current_user_sid().unwrap();
  877. let lockdown = build_allow_dacl(&[
  878. Allow(&user_sid, Mask::FILE_ALL, OICI),
  879. Allow(SID_SYSTEM, Mask::FILE_ALL, OICI),
  880. ])
  881. .unwrap();
  882. write_file_dacl(path, lockdown.as_ptr(), Protection::Protected).unwrap();
  883. let (sd, _) = read_file_dacl(path).unwrap();
  884. assert!(sd_dacl_protected(&sd).unwrap(), "setup: DACL protected");
  885. // Grant + revoke through the production chokepoint.
  886. let grant = SbAceSet {
  887. grant: Some(GrantMask::Modify),
  888. ..Default::default()
  889. };
  890. apply_sandbox_aces(path, FAKE_SB_SID, grant).unwrap();
  891. let (sd, dacl) = read_file_dacl(path).unwrap();
  892. assert!(sd_dacl_protected(&sd).unwrap(), "protection survives grant");
  893. let (aces, ..) = filter_aces(dacl, |hdr, _| hdr.AceFlags & INHERITED_ACE != 0).unwrap();
  894. assert!(aces.is_empty(), "no inherited ACEs re-derived after grant");
  895. apply_sandbox_aces(path, FAKE_SB_SID, SbAceSet::default()).unwrap();
  896. let (sd, dacl) = read_file_dacl(path).unwrap();
  897. assert!(
  898. sd_dacl_protected(&sd).unwrap(),
  899. "protection survives revoke"
  900. );
  901. let (aces, ..) = filter_aces(dacl, |hdr, _| hdr.AceFlags & INHERITED_ACE != 0).unwrap();
  902. assert!(aces.is_empty(), "no inherited ACEs re-derived after revoke");
  903. // The common case keeps its contract: an unprotected dir
  904. // stays unprotected across the same round-trip, and its
  905. // inherited ACEs (the parent's OICI lockdown entries
  906. // propagate to it) really are re-derived by the
  907. // `UNPROTECTED_` write-back — not merely "protection bit
  908. // still clear".
  909. let plain = dir.join("plain");
  910. std::fs::create_dir_all(&plain).unwrap();
  911. let plain_path = plain.to_str().unwrap();
  912. apply_sandbox_aces(plain_path, FAKE_SB_SID, grant).unwrap();
  913. apply_sandbox_aces(plain_path, FAKE_SB_SID, SbAceSet::default()).unwrap();
  914. let (sd, dacl) = read_file_dacl(plain_path).unwrap();
  915. assert!(
  916. !sd_dacl_protected(&sd).unwrap(),
  917. "unprotected dir stays unprotected"
  918. );
  919. let (aces, ..) = filter_aces(dacl, |hdr, _| hdr.AceFlags & INHERITED_ACE != 0).unwrap();
  920. assert!(
  921. !aces.is_empty(),
  922. "inherited ACEs re-derived on the unprotected dir"
  923. );
  924. std::fs::remove_dir_all(&dir).ok();
  925. }
  926. #[test]
  927. fn mask_consts_regression() {
  928. let m = Mask::MODIFY_NO_FDC;
  929. assert_eq!(m.bits(), 0x0013_01bf);
  930. assert_ne!(m.bits() & Mask::DELETE.bits(), 0, "must carry DELETE");
  931. assert_eq!(m.bits() & Mask::FILE_DELETE_CHILD.bits(), 0);
  932. assert_eq!(m.bits() & 0xffe0_0000, 0, "stray high bits");
  933. let ow = Allow::OWNER_RIGHTS.1;
  934. assert_eq!(ow.bits(), Mask::READ_CONTROL.bits());
  935. assert_ne!(ow.bits(), 0);
  936. assert_eq!(ow.bits() & Mask::WRITE_DAC.bits(), 0);
  937. }
  938. }