self_protect.rs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. //! Broker / runner self-protection: rewrite this process's own DACL
  2. //! so the sandbox child cannot `OpenProcess(our_pid,
  3. //! PROCESS_VM_*|CREATE_THREAD|CREATE_PROCESS)`.
  4. //!
  5. //! The DACL is replaced with an explicit ALLOW list scoped to SIDs
  6. //! the sandbox child does NOT have enabled in its token:
  7. //!
  8. //! - SYSTEM (S-1-5-18) — child doesn't carry it
  9. //! - BUILTIN\Admins — child has it deny-only (LUA token)
  10. //! - OWNER RIGHTS = `READ_CONTROL` — suppresses the owner's
  11. //! implicit `WRITE_DAC`, which would otherwise let the child
  12. //! (same user as the runner = owner) `WRITE_DAC` it
  13. //!
  14. //! `PROTECTED_DACL_SECURITY_INFORMATION` is required: without it
  15. //! the inherited "user has full access to their own process" ACE
  16. //! survives and the rewrite is a no-op for same-user children.
  17. //!
  18. //! Called by both the **broker** (real user, before
  19. //! `CreateProcessWithLogonW`) and the **runner** (`srt-sandbox`,
  20. //! before [`crate::launch::run_lockdown`]) — with DIFFERENT
  21. //! `extra_allow`:
  22. //!
  23. //! - **broker** passes `Some(real-user-SID)`: the broker runs as
  24. //! the real user; adding `<real-user>:FA` lets non-elevated
  25. //! sibling tools (debuggers, task managers) open/query it. The
  26. //! child runs as `srt-sandbox`, so this ACE does not match the
  27. //! child.
  28. //! - **runner** passes `None`: the runner runs as `srt-sandbox`
  29. //! and so does the locked-down child. An `srt-sandbox:FA` ACE
  30. //! here would let the child `OpenProcess(PROCESS_CREATE_PROCESS,
  31. //! runner)` and parent-spawn under the runner's unrestricted
  32. //! token — exactly what self-protection exists to close. The
  33. //! runner DACL is therefore `[SY, BA, OW:RC]` only.
  34. //!
  35. //! The runner reaches itself via the `GetCurrentProcess()`
  36. //! pseudo-handle (which bypasses the DACL).
  37. use anyhow::{Context, Result, anyhow};
  38. use std::ffi::c_void;
  39. use std::mem::size_of;
  40. use windows::Win32::Foundation::HANDLE;
  41. use windows::Win32::Security::Authorization::{
  42. ConvertSecurityDescriptorToStringSecurityDescriptorW, GetSecurityInfo, SDDL_REVISION_1,
  43. SE_KERNEL_OBJECT, SetSecurityInfo,
  44. };
  45. use windows::Win32::Security::{
  46. ACL, ACL_REVISION, AddAccessAllowedAce, DACL_SECURITY_INFORMATION, GetLengthSid, InitializeAcl,
  47. PROTECTED_DACL_SECURITY_INFORMATION,
  48. };
  49. use windows::Win32::System::Threading::{GetCurrentProcess, PROCESS_ALL_ACCESS};
  50. use windows::core::PWSTR;
  51. use crate::sid::LocalPsid;
  52. /// Open `current_exe()` with `share_mode = FILE_SHARE_READ` only (no
  53. /// `FILE_SHARE_WRITE|FILE_SHARE_DELETE`) and return the handle. While
  54. /// held, any attempt to open the file for write/delete — and
  55. /// therefore rename-over / `MoveFileEx` /
  56. /// `SetFileInformationByHandle(FileRenameInfo)` onto it — fails with
  57. /// `ERROR_SHARING_VIOLATION`. Closes the "sandboxed command
  58. /// overwrites the broker → next exec runs attacker binary" hole for
  59. /// standalone `srt-win.exe` consumers under a `.`-granted cwd. Moot
  60. /// when the consumer sets `srtWin.path = process.execPath` (a running
  61. /// binary is already section-mapped), but standalone
  62. /// `vendor/srt-win.exe` needs it.
  63. ///
  64. /// Defense-in-depth only — call sites treat failure as
  65. /// warn-and-continue so a third-party opener holding DELETE access
  66. /// (AV/indexer/updater) can't DoS the exec path.
  67. pub fn share_lock_current_exe() -> Result<std::fs::File> {
  68. use std::os::windows::fs::OpenOptionsExt;
  69. use windows::Win32::Storage::FileSystem::FILE_SHARE_READ;
  70. std::fs::OpenOptions::new()
  71. .read(true)
  72. .share_mode(FILE_SHARE_READ.0)
  73. .open(std::env::current_exe().context("current_exe")?)
  74. .context("open current_exe with FILE_SHARE_READ-only")
  75. }
  76. /// Owner-Rights well-known SID (`S-1-3-4`). An ALLOW ACE on this SID
  77. /// REPLACES the implicit `READ_CONTROL|WRITE_DAC` the object's owner
  78. /// otherwise gets. Mask is `READ_CONTROL` for consistency with
  79. /// [`crate::acl::Allow::OWNER_RIGHTS`]; mask-0 would also work here
  80. /// (this path uses kernel `SetSecurityInfo`, which doesn't drop
  81. /// mask-0 ACEs the way `SetNamedSecurityInfoW` does), but
  82. /// `READ_CONTROL` is the project convention.
  83. const SID_OWNER_RIGHTS: &str = "S-1-3-4";
  84. const READ_CONTROL: u32 = 0x0002_0000;
  85. const SID_SYSTEM: &str = "S-1-5-18";
  86. const SID_BUILTIN_ADMINS: &str = "S-1-5-32-544";
  87. /// Rewrite the current process's DACL to SYSTEM + Admins +
  88. /// `OWNER_RIGHTS:READ_CONTROL`, plus an optional `extra_allow:FA`
  89. /// ACE. The broker passes its real-user SID so non-elevated
  90. /// real-user tools can still query/debug it; the runner passes
  91. /// `None` (see module doc). Idempotent — safe to call once per
  92. /// `srt-win exec` / `runner` invocation.
  93. pub fn install_broker_dacl(extra_allow: Option<&str>) -> Result<()> {
  94. // RAII over `ConvertStringSidToSidW` → freed via `LocalFree` on
  95. // drop.
  96. let system = LocalPsid::from_string(SID_SYSTEM)?;
  97. let admins = LocalPsid::from_string(SID_BUILTIN_ADMINS)?;
  98. let owner_rights = LocalPsid::from_string(SID_OWNER_RIGHTS)?;
  99. let extra = extra_allow.map(LocalPsid::from_string).transpose()?;
  100. // (sid, mask) — SYSTEM/Admins (and the optional extra SID) get
  101. // full access; OWNER_RIGHTS gets READ_CONTROL only.
  102. let mut aces: Vec<(windows::Win32::Security::PSID, u32)> = Vec::with_capacity(4);
  103. aces.push((system.as_psid(), PROCESS_ALL_ACCESS.0));
  104. if let Some(ref e) = extra {
  105. aces.push((e.as_psid(), PROCESS_ALL_ACCESS.0));
  106. }
  107. aces.push((admins.as_psid(), PROCESS_ALL_ACCESS.0));
  108. aces.push((owner_rights.as_psid(), READ_CONTROL));
  109. // ACL size = header + Σ(ACE fixed prefix + SID body). The fixed
  110. // prefix of an ACCESS_ALLOWED_ACE is 8 bytes (Header 4 + Mask 4);
  111. // `SidStart` is the first DWORD of the SID, so total per-ACE =
  112. // 8 + GetLengthSid.
  113. const ACE_FIXED: usize = 8;
  114. let mut total = size_of::<ACL>();
  115. for (s, _) in &aces {
  116. let len = unsafe { GetLengthSid(*s) } as usize;
  117. if len == 0 {
  118. return Err(anyhow!("GetLengthSid returned 0"));
  119. }
  120. total += ACE_FIXED + len;
  121. }
  122. total = (total + 3) & !3; // DWORD-align
  123. let mut buf = vec![0u8; total];
  124. let acl = buf.as_mut_ptr() as *mut ACL;
  125. unsafe {
  126. InitializeAcl(acl, total as u32, ACL_REVISION).context("InitializeAcl")?;
  127. for (s, mask) in &aces {
  128. AddAccessAllowedAce(acl, ACL_REVISION, *mask, *s).context("AddAccessAllowedAce")?;
  129. }
  130. // PROTECTED strips inherited ACEs — without it the user
  131. // SID's default "full access to own process" inherited
  132. // grant fires and the rewrite is a no-op.
  133. let r = SetSecurityInfo(
  134. GetCurrentProcess(),
  135. SE_KERNEL_OBJECT,
  136. DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
  137. None,
  138. None,
  139. Some(acl),
  140. None,
  141. );
  142. if r.is_err() {
  143. return Err(anyhow!("SetSecurityInfo(broker process DACL): {r:?}"));
  144. }
  145. }
  146. // `buf` can drop here — `SetSecurityInfo` copies the ACL into
  147. // the kernel object's SECURITY_DESCRIPTOR.
  148. // Diagnostic: read back and dump the DACL as SDDL so CI can
  149. // confirm exactly what's on the broker process. Gated on
  150. // SANDBOX_RUNTIME_WIN_DEBUG — production callers (one exec per
  151. // user command) don't want a stderr line per command.
  152. if std::env::var_os("SANDBOX_RUNTIME_WIN_DEBUG").is_some() {
  153. match read_self_dacl_sddl() {
  154. Some(sddl) => eprintln!("srt-win: self-protect applied (DACL: {sddl})"),
  155. None => eprintln!("srt-win: self-protect applied"),
  156. }
  157. }
  158. Ok(())
  159. }
  160. /// Best-effort read of the current process's DACL as an SDDL
  161. /// string. Returns `None` on any failure rather than erroring —
  162. /// this is diagnostic only.
  163. fn read_self_dacl_sddl() -> Option<String> {
  164. use crate::util::{from_pwstr, local_free};
  165. use windows::Win32::Security::PSECURITY_DESCRIPTOR;
  166. unsafe {
  167. let mut psd = PSECURITY_DESCRIPTOR::default();
  168. let r = GetSecurityInfo(
  169. HANDLE(GetCurrentProcess().0),
  170. SE_KERNEL_OBJECT,
  171. DACL_SECURITY_INFORMATION,
  172. None,
  173. None,
  174. None,
  175. None,
  176. Some(&mut psd),
  177. );
  178. if r.is_err() || psd.0.is_null() {
  179. return None;
  180. }
  181. let mut s = PWSTR::null();
  182. let ok = ConvertSecurityDescriptorToStringSecurityDescriptorW(
  183. psd,
  184. SDDL_REVISION_1,
  185. DACL_SECURITY_INFORMATION,
  186. &mut s,
  187. None,
  188. );
  189. local_free(psd.0);
  190. if ok.is_err() {
  191. return None;
  192. }
  193. let out = from_pwstr(s);
  194. local_free(s.0 as *mut c_void);
  195. Some(out)
  196. }
  197. }