reg.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. //! Machine-wide install state in `HKLM\SOFTWARE\sandbox-runtime`.
  2. //!
  3. //! The registry is the natural home for small machine-wide
  4. //! key/value state written by an elevated installer and read
  5. //! unprivileged, and its DEFAULT security model is exactly the one
  6. //! the install state needs — properties a `%ProgramData%` file
  7. //! store had to hand-build (and defend in review, repeatedly):
  8. //!
  9. //! - Standard users cannot create keys under `HKLM\SOFTWARE`, so
  10. //! there is nothing to squat: no take-ownership, no no-follow
  11. //! open, no reparse rejection for the store itself.
  12. //! - Admin-write / Users-read is the inherited default, so the
  13. //! identity, marker, and ambient-deny values are trustworthy on
  14. //! read — no SAM cross-validation, no corrupt-file degrade
  15. //! paths, no schema-version machinery.
  16. //!
  17. //! Layout (all opens `KEY_WOW64_64KEY` so a 32-bit build would not
  18. //! land in WOW6432Node):
  19. //!
  20. //! - `HKLM\SOFTWARE\sandbox-runtime`: `MarkerVersion` (DWORD,
  21. //! written LAST — registry writes are not transactional across
  22. //! values, so the marker is the commit point), `SandboxUser`,
  23. //! `SandboxUserSid`, `SandboxGroupSid` (SZ), `CreatedAt`
  24. //! (QWORD), `AmbientDenies` (MULTI_SZ).
  25. //! - `…\Cred`: one `Blob` (BINARY, machine-scope DPAPI). Created
  26. //! with an explicit SA — DACL atomic with creation — SYSTEM/
  27. //! Administrators full, Users READ (machine DPAPI means readable
  28. //! ⇒ decryptable: the shared-credential trade-off), sandbox
  29. //! group DENY (the child must never learn its own password: with
  30. //! it, it could CreateProcessWithLogonW itself a fresh logon
  31. //! session outside the job/desktop confinement).
  32. //! - `…\Ca`: one `Der` (BINARY). Users KEY_READ|KEY_SET_VALUE so
  33. //! the unelevated `trust-ca` can record the CA; sandbox group
  34. //! DENY so the CHILD cannot touch the record (the accepted
  35. //! replace-the-CA trade-off is scoped to REAL local users).
  36. use anyhow::{Context, Result, anyhow};
  37. use windows::Win32::Foundation::ERROR_FILE_NOT_FOUND;
  38. use windows::Win32::Security::Authorization::{SE_REGISTRY_KEY, SetNamedSecurityInfoW};
  39. use windows::Win32::Security::{
  40. DACL_SECURITY_INFORMATION, GetSecurityDescriptorDacl, PROTECTED_DACL_SECURITY_INFORMATION,
  41. };
  42. use windows::Win32::System::Registry::{
  43. HKEY, HKEY_LOCAL_MACHINE, KEY_READ, KEY_WOW64_64KEY, KEY_WRITE, REG_BINARY, REG_DWORD,
  44. REG_MULTI_SZ, REG_OPENED_EXISTING_KEY, REG_OPTION_NON_VOLATILE, REG_QWORD, REG_SZ, RegCloseKey,
  45. RegCreateKeyExW, RegDeleteTreeW, RegOpenKeyExW, RegQueryValueExW, RegSetValueExW,
  46. };
  47. use crate::util::{OwnedSd, pcwstr, wstr};
  48. pub const BASE: &str = r"SOFTWARE\sandbox-runtime";
  49. pub const CRED_SUBKEY: &str = r"SOFTWARE\sandbox-runtime\Cred";
  50. pub const CA_SUBKEY: &str = r"SOFTWARE\sandbox-runtime\Ca";
  51. /// RAII HKEY.
  52. pub struct Key(HKEY);
  53. impl Drop for Key {
  54. fn drop(&mut self) {
  55. unsafe {
  56. let _ = RegCloseKey(self.0);
  57. }
  58. }
  59. }
  60. impl Key {
  61. /// Open an existing key. `Ok(None)` when absent.
  62. pub fn open(path: &str, write: bool) -> Result<Option<Key>> {
  63. let mut h = HKEY::default();
  64. let w = wstr(path);
  65. let access =
  66. KEY_READ | KEY_WOW64_64KEY | if write { KEY_WRITE } else { Default::default() };
  67. let r = unsafe { RegOpenKeyExW(HKEY_LOCAL_MACHINE, pcwstr(&w), None, access, &mut h) };
  68. if r == ERROR_FILE_NOT_FOUND {
  69. return Ok(None);
  70. }
  71. if r.is_err() {
  72. return Err(anyhow!("RegOpenKeyExW(HKLM\\{path}): {r:?}"));
  73. }
  74. Ok(Some(Key(h)))
  75. }
  76. /// Open an existing key for VALUE WRITES ONLY: `KEY_READ |
  77. /// KEY_SET_VALUE`, never `KEY_WRITE` — `KEY_WRITE` (0x20006)
  78. /// includes `KEY_CREATE_SUB_KEY` (0x4), which the `Ca` subkey's
  79. /// `BUILTIN\Users` allow mask (0x2001b) deliberately does not
  80. /// grant, so an unelevated `trust-ca` open requesting KEY_WRITE
  81. /// would be ACCESS_DENIED despite having exactly the rights it
  82. /// needs. `Ok(None)` when absent.
  83. pub fn open_for_set_value(path: &str) -> Result<Option<Key>> {
  84. use windows::Win32::System::Registry::KEY_SET_VALUE;
  85. let mut h = HKEY::default();
  86. let w = wstr(path);
  87. let access = KEY_READ | KEY_SET_VALUE | KEY_WOW64_64KEY;
  88. let r = unsafe { RegOpenKeyExW(HKEY_LOCAL_MACHINE, pcwstr(&w), None, access, &mut h) };
  89. if r == ERROR_FILE_NOT_FOUND {
  90. return Ok(None);
  91. }
  92. if r.is_err() {
  93. return Err(anyhow!("RegOpenKeyExW(HKLM\\{path}, set-value): {r:?}"));
  94. }
  95. Ok(Some(Key(h)))
  96. }
  97. /// Create (or open) a key, optionally with an explicit security
  98. /// descriptor (SDDL). Returns `(key, created)`. When the key
  99. /// already existed the SA is IGNORED by the API — callers that
  100. /// need a guaranteed DACL must follow up with
  101. /// [`set_key_dacl_from_sddl`] (only admins can have created it,
  102. /// so this is drift-healing, not squat defense).
  103. pub fn create(path: &str, sddl: Option<&str>) -> Result<(Key, bool)> {
  104. let mut h = HKEY::default();
  105. let mut disp = Default::default();
  106. let w = wstr(path);
  107. let sd;
  108. let mut sa = None;
  109. if let Some(sddl) = sddl {
  110. sd = OwnedSd::from_sddl(sddl).with_context(|| format!("SD for HKLM\\{path}"))?;
  111. sa = Some(windows::Win32::Security::SECURITY_ATTRIBUTES {
  112. nLength: std::mem::size_of::<windows::Win32::Security::SECURITY_ATTRIBUTES>()
  113. as u32,
  114. lpSecurityDescriptor: sd.ptr.0,
  115. bInheritHandle: false.into(),
  116. });
  117. }
  118. let r = unsafe {
  119. RegCreateKeyExW(
  120. HKEY_LOCAL_MACHINE,
  121. pcwstr(&w),
  122. None,
  123. None,
  124. REG_OPTION_NON_VOLATILE,
  125. KEY_READ | KEY_WRITE | KEY_WOW64_64KEY,
  126. sa.as_ref().map(|s| s as *const _),
  127. &mut h,
  128. Some(&mut disp),
  129. )
  130. };
  131. if r.is_err() {
  132. return Err(anyhow!("RegCreateKeyExW(HKLM\\{path}): {r:?}"));
  133. }
  134. Ok((Key(h), disp != REG_OPENED_EXISTING_KEY))
  135. }
  136. fn set_raw(
  137. &self,
  138. name: &str,
  139. ty: windows::Win32::System::Registry::REG_VALUE_TYPE,
  140. data: &[u8],
  141. ) -> Result<()> {
  142. let w = wstr(name);
  143. let r = unsafe { RegSetValueExW(self.0, pcwstr(&w), None, ty, Some(data)) };
  144. if r.is_err() {
  145. return Err(anyhow!("RegSetValueExW({name}): {r:?}"));
  146. }
  147. Ok(())
  148. }
  149. pub fn set_sz(&self, name: &str, val: &str) -> Result<()> {
  150. let mut v: Vec<u16> = val.encode_utf16().collect();
  151. v.push(0);
  152. self.set_raw(name, REG_SZ, unsafe {
  153. std::slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * 2)
  154. })
  155. }
  156. pub fn set_dword(&self, name: &str, val: u32) -> Result<()> {
  157. self.set_raw(name, REG_DWORD, &val.to_le_bytes())
  158. }
  159. pub fn set_qword(&self, name: &str, val: u64) -> Result<()> {
  160. self.set_raw(name, REG_QWORD, &val.to_le_bytes())
  161. }
  162. pub fn set_binary(&self, name: &str, val: &[u8]) -> Result<()> {
  163. self.set_raw(name, REG_BINARY, val)
  164. }
  165. pub fn set_multi_sz(&self, name: &str, vals: &[String]) -> Result<()> {
  166. let mut v: Vec<u16> = Vec::new();
  167. for s in vals {
  168. v.extend(s.encode_utf16());
  169. v.push(0);
  170. }
  171. v.push(0); // double-NUL terminator (also for the empty list)
  172. self.set_raw(name, REG_MULTI_SZ, unsafe {
  173. std::slice::from_raw_parts(v.as_ptr() as *const u8, v.len() * 2)
  174. })
  175. }
  176. fn get_raw(&self, name: &str) -> Result<Option<Vec<u8>>> {
  177. let w = wstr(name);
  178. let mut len: u32 = 0;
  179. let r = unsafe { RegQueryValueExW(self.0, pcwstr(&w), None, None, None, Some(&mut len)) };
  180. if r == ERROR_FILE_NOT_FOUND {
  181. return Ok(None);
  182. }
  183. if r.is_err() {
  184. return Err(anyhow!("RegQueryValueExW({name}) sizing: {r:?}"));
  185. }
  186. let mut buf = vec![0u8; len as usize];
  187. let mut len2 = len;
  188. let r = unsafe {
  189. RegQueryValueExW(
  190. self.0,
  191. pcwstr(&w),
  192. None,
  193. None,
  194. Some(buf.as_mut_ptr()),
  195. Some(&mut len2),
  196. )
  197. };
  198. if r.is_err() {
  199. return Err(anyhow!("RegQueryValueExW({name}): {r:?}"));
  200. }
  201. buf.truncate(len2 as usize);
  202. Ok(Some(buf))
  203. }
  204. pub fn get_sz(&self, name: &str) -> Result<Option<String>> {
  205. let Some(b) = self.get_raw(name)? else {
  206. return Ok(None);
  207. };
  208. let u16s: Vec<u16> = b
  209. .as_chunks::<2>()
  210. .0
  211. .iter()
  212. .map(|&c| u16::from_le_bytes(c))
  213. .take_while(|&c| c != 0)
  214. .collect();
  215. Ok(Some(String::from_utf16_lossy(&u16s)))
  216. }
  217. pub fn get_dword(&self, name: &str) -> Result<Option<u32>> {
  218. Ok(self
  219. .get_raw(name)?
  220. .filter(|b| b.len() >= 4)
  221. .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])))
  222. }
  223. pub fn get_qword(&self, name: &str) -> Result<Option<u64>> {
  224. Ok(self
  225. .get_raw(name)?
  226. .filter(|b| b.len() >= 8)
  227. .map(|b| u64::from_le_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]])))
  228. }
  229. pub fn get_binary(&self, name: &str) -> Result<Option<Vec<u8>>> {
  230. self.get_raw(name)
  231. }
  232. pub fn get_multi_sz(&self, name: &str) -> Result<Option<Vec<String>>> {
  233. let Some(b) = self.get_raw(name)? else {
  234. return Ok(None);
  235. };
  236. let u16s: Vec<u16> = b
  237. .as_chunks::<2>()
  238. .0
  239. .iter()
  240. .map(|&c| u16::from_le_bytes(c))
  241. .collect();
  242. let mut out = Vec::new();
  243. for part in u16s.split(|&c| c == 0) {
  244. if !part.is_empty() {
  245. out.push(String::from_utf16_lossy(part));
  246. }
  247. }
  248. Ok(Some(out))
  249. }
  250. }
  251. /// Rewrite a key's DACL from SDDL (PROTECTED). Drift-healing for
  252. /// open-existing paths — see [`Key::create`].
  253. pub fn set_key_dacl_from_sddl(path: &str, sddl: &str) -> Result<()> {
  254. let sd = OwnedSd::from_sddl(sddl).with_context(|| format!("SD for HKLM\\{path}"))?;
  255. let mut present = windows::core::BOOL::from(false);
  256. let mut dacl = std::ptr::null_mut();
  257. let mut defaulted = windows::core::BOOL::from(false);
  258. unsafe {
  259. GetSecurityDescriptorDacl(sd.ptr, &mut present, &mut dacl, &mut defaulted)
  260. .with_context(|| format!("GetSecurityDescriptorDacl for HKLM\\{path}"))?;
  261. }
  262. if !present.as_bool() || dacl.is_null() {
  263. anyhow::bail!("SDDL '{sddl}' yielded no DACL");
  264. }
  265. let full = format!(r"MACHINE\{path}");
  266. let w = wstr(&full);
  267. let r = unsafe {
  268. SetNamedSecurityInfoW(
  269. pcwstr(&w),
  270. SE_REGISTRY_KEY,
  271. DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
  272. None,
  273. None,
  274. Some(dacl),
  275. None,
  276. )
  277. };
  278. crate::util::win32_ok(r, &format!("SetNamedSecurityInfoW(HKLM\\{path})"))
  279. }
  280. /// Delete the whole `HKLM\SOFTWARE\sandbox-runtime` tree
  281. /// (uninstall). No-op when absent.
  282. pub fn delete_tree() -> Result<()> {
  283. let w = wstr(BASE);
  284. let r = unsafe { RegDeleteTreeW(HKEY_LOCAL_MACHINE, pcwstr(&w)) };
  285. if r == ERROR_FILE_NOT_FOUND || r.is_ok() {
  286. return Ok(());
  287. }
  288. Err(anyhow!("RegDeleteTreeW(HKLM\\{BASE}): {r:?}"))
  289. }
  290. /// Create the key with `sddl` atomically, or — when it already
  291. /// exists (RegCreateKeyExW IGNORES the SA then; the rotation path)
  292. /// — rewrite its DACL to `sddl`. One primitive so no call site can
  293. /// take the create half without the heal half. Only admins can have
  294. /// created a key under HKLM\SOFTWARE, so the heal is drift repair,
  295. /// not squat defense.
  296. pub fn ensure_key_with_dacl(path: &str, sddl: &str) -> Result<Key> {
  297. let (key, created) = Key::create(path, Some(sddl))?;
  298. if !created {
  299. set_key_dacl_from_sddl(path, sddl)?;
  300. }
  301. Ok(key)
  302. }
  303. /// Delete one subkey tree under HKLM. No-op when absent.
  304. pub fn delete_subtree(path: &str) -> Result<()> {
  305. let w = wstr(path);
  306. let r = unsafe { RegDeleteTreeW(HKEY_LOCAL_MACHINE, pcwstr(&w)) };
  307. if r == ERROR_FILE_NOT_FOUND || r.is_ok() {
  308. return Ok(());
  309. }
  310. Err(anyhow!("RegDeleteTreeW(HKLM\\{path}): {r:?}"))
  311. }
  312. /// Delete one value from an open key. No-op when absent.
  313. pub fn delete_value(key: &Key, name: &str) -> Result<()> {
  314. use windows::Win32::System::Registry::RegDeleteValueW;
  315. let w = wstr(name);
  316. let r = unsafe { RegDeleteValueW(key.0, pcwstr(&w)) };
  317. if r == ERROR_FILE_NOT_FOUND || r.is_ok() {
  318. return Ok(());
  319. }
  320. Err(anyhow!("RegDeleteValueW({name}): {r:?}"))
  321. }