install.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. //! Install-time state: the sandbox-user **credential** (DPAPI
  2. //! ciphertext), the **setup marker**, and the optional **MITM CA**
  3. //! (DER), in the machine store (`state_db::machine_store_dir()`).
  4. //!
  5. //! Written by the elevated `srt-win install` step (after
  6. //! [`crate::user::provision`]) and read by the non-elevated broker
  7. //! at `srt-win exec` / `srt-win user status` time.
  8. //!
  9. //! The store is `HKLM\SOFTWARE\sandbox-runtime` ([`crate::reg`]):
  10. //! identity + marker under the default admin-write/users-read DACL,
  11. //! the DPAPI credential blob in the `Cred` subkey (Users read-only,
  12. //! sandbox DENY), the CA record in the `Ca` subkey (user-recordable
  13. //! for unelevated trust-ca, sandbox DENY). Only the managed CA key
  14. //! material stays on the filesystem
  15. //! ([`provision_machine_store`]).
  16. use anyhow::{Context, Result, anyhow};
  17. use crate::state_db;
  18. use crate::{dpapi, logon, runner, user};
  19. /// Bumped on schema-incompatible changes to the `sandbox_user`
  20. /// row, or when `install` gains a step existing installs must pick
  21. /// up (v2: ambient write-deny stamps — `ambient.rs`). The broker
  22. /// compares this to the on-disk marker and refuses with a "re-run
  23. /// `srt-win install`" message on mismatch; `install` treats a stale
  24. /// marker as a partial install and completes the missing steps.
  25. pub const SETUP_VERSION: u32 = 2;
  26. #[derive(Debug, Clone)]
  27. pub struct SetupInfo {
  28. pub sandbox_user: String,
  29. pub sandbox_user_sid: String,
  30. pub sandbox_group_sid: String,
  31. pub marker_version: u32,
  32. pub created_at_unix: u64,
  33. }
  34. /// Guard the one piece of install state that must stay on the
  35. /// FILESYSTEM: `%ProgramData%\sandbox-runtime\ca\` — the managed
  36. /// CA key material, which the broker's unelevated generate-if-absent
  37. /// self-heal must be able to rewrite (so it cannot live under an
  38. /// admin-only registry key). Everything else moved to
  39. /// `HKLM\SOFTWARE\sandbox-runtime` ([`crate::reg`]), whose default
  40. /// security model needs none of this.
  41. ///
  42. /// `%ProgramData%`'s default DACL lets standard users pre-create
  43. /// directories — including as junctions targeting a victim tree —
  44. /// so the elevated install takes ownership and rewrites the DACL
  45. /// by HANDLE with no-follow semantics (a planted reparse point is
  46. /// removed, never followed). The DACL is deliberately multi-user:
  47. /// SYSTEM/Administrators full; BUILTIN\Users modify (the ca\
  48. /// self-heal); sandbox group explicit DENY (the CA key must not be
  49. /// readable from inside the sandbox).
  50. ///
  51. /// Accepted trade-off (decided): any REAL local user can read or
  52. /// replace the CA key material. The sandbox account is
  53. /// network-confined by SID-keyed WFP filters regardless of who
  54. /// spawns it, and concurrently-interactive multi-user machines are
  55. /// rare.
  56. pub fn provision_machine_store(sandbox_group_sid: &str) -> Result<std::path::PathBuf> {
  57. let dir = state_db::machine_store_dir()?;
  58. std::fs::create_dir_all(&dir)
  59. .with_context(|| format!("create machine state dir {}", dir.display()))?;
  60. let dir_str = dir
  61. .to_str()
  62. .ok_or_else(|| anyhow::anyhow!("machine state dir is not UTF-8"))?;
  63. if !crate::util::enable_privilege("SeTakeOwnershipPrivilege")? {
  64. anyhow::bail!("SeTakeOwnershipPrivilege not held — machine store requires elevation");
  65. }
  66. crate::util::enable_privilege("SeRestorePrivilege")?;
  67. let h = match crate::acl::open_for_security_no_follow(dir_str) {
  68. Ok(h) => h,
  69. Err(e) if format!("{e:#}").contains("reparse point") => {
  70. std::fs::remove_dir(&dir)
  71. .with_context(|| format!("remove planted reparse point {}", dir.display()))?;
  72. std::fs::create_dir_all(&dir)
  73. .with_context(|| format!("recreate machine state dir {}", dir.display()))?;
  74. crate::acl::open_for_security_no_follow(dir_str)?
  75. }
  76. Err(e) => return Err(e),
  77. };
  78. crate::acl::set_handle_owner_admins(&h, "machine state dir")
  79. .context("take ownership of machine state dir")?;
  80. // 0x1301bf = FILE_GENERIC_READ|WRITE|EXECUTE + DELETE ("modify"
  81. // minus FILE_DELETE_CHILD).
  82. let sddl = format!(
  83. "D:P(D;OICI;FA;;;{sandbox_group_sid})\
  84. (A;OICI;FA;;;SY)\
  85. (A;OICI;FA;;;BA)\
  86. (A;OICI;0x1301bf;;;BU)"
  87. );
  88. crate::acl::set_handle_dacl_from_sddl(&h, &sddl, "machine state dir")?;
  89. drop(h);
  90. // Pre-registry alpha builds kept install.db/cred.dat here —
  91. // best-effort cleanup so stale copies don't linger.
  92. for f in [
  93. "cred.dat",
  94. "install.db",
  95. "install.db-wal",
  96. "install.db-shm",
  97. "state.db",
  98. "state.db-wal",
  99. "state.db-shm",
  100. ] {
  101. let _ = std::fs::remove_file(dir.join(f));
  102. }
  103. Ok(dir)
  104. }
  105. /// Record the install: identity + marker into
  106. /// `HKLM\SOFTWARE\sandbox-runtime` and the DPAPI credential blob
  107. /// into its `Cred` subkey (created with an explicit
  108. /// SYSTEM/Admins-full, Users-read, sandbox-DENY DACL — atomic with
  109. /// creation, and nothing unprivileged can pre-create a key under
  110. /// HKLM\SOFTWARE). `MarkerVersion` is written LAST: registry writes
  111. /// are not transactional across values, so the marker is the commit
  112. /// point a crashed install never reaches.
  113. pub fn write_setup(u: &user::ProvisionedUser) -> Result<()> {
  114. let blob = dpapi::protect_machine(u.password.as_bytes())?;
  115. let (base, _) = crate::reg::Key::create(crate::reg::BASE, None)?;
  116. // A --force re-install under a DIFFERENT sandbox-user name must
  117. // drop the recorded CA: the cert was written into the OLD
  118. // account's CurrentUser\Root hive, so keeping the record for
  119. // the new account would make the trust reconcile skip a re-trust
  120. // that has never happened (schannel then fails at runtime
  121. // instead of being healed at setup).
  122. let name_changed = base
  123. .get_sz("SandboxUser")?
  124. .is_some_and(|old| old != u.username);
  125. let cred_sddl = format!(
  126. "O:BAD:P(D;;KA;;;{})(A;;KA;;;SY)(A;;KA;;;BA)(A;;KR;;;BU)",
  127. u.group_sid
  128. );
  129. let cred = crate::reg::ensure_key_with_dacl(crate::reg::CRED_SUBKEY, &cred_sddl)?;
  130. cred.set_binary("Blob", &blob)?;
  131. // Ca subkey: Users KEY_READ|KEY_SET_VALUE (0x2001b) so the
  132. // unelevated trust-ca can record the DER; sandbox group DENY so
  133. // the CHILD cannot touch the record.
  134. let ca_sddl = format!(
  135. "O:BAD:P(D;;KA;;;{})(A;;KA;;;SY)(A;;KA;;;BA)(A;;0x2001b;;;BU)",
  136. u.group_sid
  137. );
  138. let ca = crate::reg::ensure_key_with_dacl(crate::reg::CA_SUBKEY, &ca_sddl)?;
  139. if name_changed {
  140. crate::reg::delete_value(&ca, "Der")?;
  141. }
  142. base.set_sz("SandboxUser", &u.username)?;
  143. base.set_sz("SandboxUserSid", &u.sid)?;
  144. base.set_sz("SandboxGroupSid", &u.group_sid)?;
  145. base.set_qword(
  146. "CreatedAt",
  147. std::time::SystemTime::now()
  148. .duration_since(std::time::UNIX_EPOCH)
  149. .map(|d| d.as_secs())
  150. .unwrap_or(0),
  151. )?;
  152. base.set_dword("MarkerVersion", SETUP_VERSION)?;
  153. Ok(())
  154. }
  155. /// Outcome of [`set_ambient_denies`].
  156. #[derive(Debug, Default)]
  157. pub struct AmbientReport {
  158. /// Paths whose deny ACE is on disk (freshly stamped or
  159. /// re-converged on re-install).
  160. pub applied: Vec<String>,
  161. /// Paths whose stamp failed (odd system DACL even with
  162. /// `SeRestorePrivilege`). `status` shows `present: false`, and
  163. /// a later install retries.
  164. pub failed: Vec<String>,
  165. }
  166. /// The recorded ambient-deny target list (HKLM `AmbientDenies`
  167. /// MULTI_SZ). Empty when no install has run. Admin-written, so
  168. /// trustworthy as read.
  169. pub fn ambient_recorded_paths() -> Result<Vec<String>> {
  170. let Some(base) = crate::reg::Key::open(crate::reg::BASE, false)? else {
  171. return Ok(Vec::new());
  172. };
  173. Ok(base.get_multi_sz("AmbientDenies")?.unwrap_or_default())
  174. }
  175. /// Whether `canon` is a recorded ambient deny target — the
  176. /// recompose fold-in predicate. Errors read as "not recorded"
  177. /// (fail-open for the DENY floor is bounded: the next install
  178. /// re-records and re-applies).
  179. pub fn ambient_deny_recorded(canon: &str) -> bool {
  180. ambient_recorded_paths()
  181. .map(|v| v.iter().any(|p| p == canon))
  182. .unwrap_or(false)
  183. }
  184. /// Whether the install-time ambient write-deny step is complete:
  185. /// every CURRENT target is both recorded and carrying its on-disk
  186. /// deny ACE. An install that died mid-list falls through the
  187. /// install early-out and finishes the remainder; "re-run `srt-win
  188. /// install`" is the repair for on-disk drift. Targets that no
  189. /// longer canonicalize are ignored; any error reads as incomplete
  190. /// (the idempotent install steps just run).
  191. pub fn ambient_complete(sandbox_sid: &str, raw_targets: &[String]) -> bool {
  192. let recorded = match ambient_recorded_paths() {
  193. Ok(v) => v,
  194. Err(_) => return false,
  195. };
  196. raw_targets.iter().all(|raw| {
  197. let Ok((canon, _)) = crate::path_id::canonicalize_path(raw) else {
  198. return true;
  199. };
  200. recorded.contains(&canon)
  201. && crate::acl::sandbox_deny_present(&canon, sandbox_sid).unwrap_or(false)
  202. })
  203. }
  204. /// Stamp the ambient write-denies: apply `(D;OICI;WriteDeny)` for
  205. /// the sandbox SID DIRECTLY on each static env-derived target (per
  206. /// path best-effort), then record the applied set in the registry.
  207. /// Under the session init lock so a live broker's recompose in this
  208. /// TS session cannot interleave a converge that misses the fresh
  209. /// deny; SeRestorePrivilege enabled for TrustedInstaller-owned
  210. /// targets.
  211. pub fn set_ambient_denies(sandbox_sid: &str, raw_paths: &[String]) -> Result<AmbientReport> {
  212. let _lock = state_db::acquire_session_lock()?;
  213. if let Err(e) = crate::util::enable_privilege("SeRestorePrivilege") {
  214. eprintln!("srt-win: ambient deny: enable SeRestorePrivilege: {e:#}");
  215. }
  216. let mut report = AmbientReport::default();
  217. let deny_only = crate::acl::SbAceSet {
  218. deny: Some(crate::acl::DenyMask::WriteDeny),
  219. ..Default::default()
  220. };
  221. let mut recorded = ambient_recorded_paths()?;
  222. for raw in raw_paths {
  223. let canon = match crate::path_id::canonicalize_path(raw) {
  224. Ok((c, _)) => c,
  225. Err(e) => {
  226. eprintln!("srt-win: warning: ambient deny target '{raw}': {e:#}");
  227. report.failed.push(raw.clone());
  228. continue;
  229. }
  230. };
  231. match crate::acl::apply_sandbox_aces(&canon, sandbox_sid, deny_only) {
  232. Ok(()) => {
  233. if !recorded.contains(&canon) {
  234. recorded.push(canon.clone());
  235. }
  236. report.applied.push(canon);
  237. }
  238. Err(e) => {
  239. eprintln!("srt-win: warning: ambient deny stamp '{canon}': {e:#}");
  240. report.failed.push(canon);
  241. }
  242. }
  243. }
  244. let (base, _) = crate::reg::Key::create(crate::reg::BASE, None)?;
  245. base.set_multi_sz("AmbientDenies", &recorded)?;
  246. Ok(report)
  247. }
  248. /// Remove the ambient write-denies (uninstall): per RECORDED path
  249. /// (admin-written list — trustworthy), strip the sandbox SID's ACEs
  250. /// directly; a failed removal keeps its entry so `status` surfaces
  251. /// it and a later uninstall/install retries. Returns how many paths
  252. /// actually carried a deny that was removed. Same lock + privilege
  253. /// preamble as [`set_ambient_denies`].
  254. pub fn clear_ambient_denies(sandbox_sid: &str) -> Result<usize> {
  255. let _lock = state_db::acquire_session_lock()?;
  256. if let Err(e) = crate::util::enable_privilege("SeRestorePrivilege") {
  257. eprintln!("srt-win: ambient deny: enable SeRestorePrivilege: {e:#}");
  258. }
  259. let recorded = ambient_recorded_paths()?;
  260. let mut removed = 0usize;
  261. let mut kept: Vec<String> = Vec::new();
  262. for canon in recorded {
  263. let had = crate::acl::sandbox_deny_present(&canon, sandbox_sid).unwrap_or(false);
  264. match crate::acl::apply_sandbox_aces(&canon, sandbox_sid, crate::acl::SbAceSet::default()) {
  265. Ok(()) => {
  266. if had {
  267. removed += 1;
  268. }
  269. }
  270. Err(e) => {
  271. eprintln!("srt-win: warning: ambient deny removal '{canon}': {e:#}");
  272. kept.push(canon);
  273. }
  274. }
  275. }
  276. if let Some(base) = crate::reg::Key::open(crate::reg::BASE, true)? {
  277. base.set_multi_sz("AmbientDenies", &kept)?;
  278. }
  279. if !kept.is_empty() {
  280. eprintln!(
  281. "srt-win: warning: {} ambient deny path(s) could not be \
  282. cleared and stay recorded (retry via uninstall/install)",
  283. kept.len(),
  284. );
  285. }
  286. Ok(removed)
  287. }
  288. /// Read the install record from `HKLM\SOFTWARE\sandbox-runtime`.
  289. /// `Ok(None)` when no install has run (key or marker absent). The
  290. /// values are trustworthy as read: only administrators can write
  291. /// them (HKLM\SOFTWARE default DACL), which is what deleted the
  292. /// SAM cross-validation an earlier %ProgramData% file store needed.
  293. pub fn read_setup() -> Result<Option<SetupInfo>> {
  294. let Some(base) = crate::reg::Key::open(crate::reg::BASE, false)? else {
  295. return Ok(None);
  296. };
  297. let (Some(marker_version), Some(sandbox_user), Some(sandbox_user_sid), Some(sandbox_group_sid)) = (
  298. base.get_dword("MarkerVersion")?,
  299. base.get_sz("SandboxUser")?,
  300. base.get_sz("SandboxUserSid")?,
  301. base.get_sz("SandboxGroupSid")?,
  302. ) else {
  303. // Partial write (install crashed before the marker commit
  304. // point) or manual tamper by an admin — either way the
  305. // repair is re-running the elevated install.
  306. return Ok(None);
  307. };
  308. Ok(Some(SetupInfo {
  309. sandbox_user,
  310. sandbox_user_sid,
  311. sandbox_group_sid,
  312. marker_version,
  313. created_at_unix: base.get_qword("CreatedAt")?.unwrap_or(0),
  314. }))
  315. }
  316. /// Read the recorded MITM CA (DER), if `srt-win user trust-ca`
  317. /// ever ran. `Ok(None)` when no install has run or no CA
  318. /// is recorded.
  319. pub fn read_ca_cert() -> Result<Option<crate::cert_store::CertDer>> {
  320. let Some(ca) = crate::reg::Key::open(crate::reg::CA_SUBKEY, false)? else {
  321. return Ok(None);
  322. };
  323. match ca.get_binary("Der")? {
  324. // Round-trip through the parser so a corrupted stored value
  325. // reads as an error, not a poisoned CertDer.
  326. Some(der) => Ok(Some(crate::cert_store::CertDer::from_pem_or_der(&der)?)),
  327. None => Ok(None),
  328. }
  329. }
  330. /// Decrypted sandbox-user credential, as the broker needs it for
  331. /// the two-hop launch. Zeroed on drop so the cleartext doesn't
  332. /// linger past the `CreateProcessWithLogonW` call.
  333. pub struct SandboxCred {
  334. pub user: String,
  335. pub pw: String,
  336. }
  337. impl Drop for SandboxCred {
  338. fn drop(&mut self) {
  339. // SAFETY: writing zeros into the String's bytes keeps it
  340. // valid UTF-8.
  341. unsafe { self.pw.as_mut_vec() }.fill(0);
  342. }
  343. }
  344. /// Decrypt and return the sandbox user's credential. Fails if the
  345. /// caller cannot read the `Cred` key — by design, the sandbox user
  346. /// is DENY'd on it (and on the store directory) and so cannot call
  347. /// this to learn its own password.
  348. pub fn read_cred() -> Result<SandboxCred> {
  349. let info = read_setup()?.ok_or_else(|| {
  350. anyhow!(
  351. "no sandbox-user setup record in the state store — run \
  352. `srt-win install`"
  353. )
  354. })?;
  355. if info.marker_version != SETUP_VERSION {
  356. return Err(anyhow!(
  357. "setup marker version mismatch (have {}, expected {}); \
  358. re-run `srt-win install`",
  359. info.marker_version,
  360. SETUP_VERSION,
  361. ));
  362. }
  363. let blob = read_cred_blob()?;
  364. let pw = String::from_utf8(dpapi::unprotect(&blob)?).context("password is not UTF-8")?;
  365. Ok(SandboxCred {
  366. user: info.sandbox_user,
  367. pw,
  368. })
  369. }
  370. /// The DPAPI blob from `HKLM\...\Cred\Blob`. A missing key/value
  371. /// means the install is incomplete; the repair is the elevated
  372. /// re-run either way.
  373. pub(crate) fn read_cred_blob() -> Result<Vec<u8>> {
  374. let key = crate::reg::Key::open(crate::reg::CRED_SUBKEY, false)?.ok_or_else(|| {
  375. anyhow!(
  376. "no credential key (HKLM\\{}) — run `srt-win install` \
  377. (elevated) to (re)provision it",
  378. crate::reg::CRED_SUBKEY,
  379. )
  380. })?;
  381. key.get_binary("Blob")?.ok_or_else(|| {
  382. anyhow!(
  383. "credential key present but Blob value missing — re-run \
  384. `srt-win install` (elevated)"
  385. )
  386. })
  387. }
  388. /// Whether the credential blob exists AND decrypts — the
  389. /// `cred_present` half of `srt-win user status`, and the credential
  390. /// term of the install early-out. Readable by every real user,
  391. /// which is the point of the shared credential: a SYSTEM/fleet
  392. /// install must read as present from an ordinary user's session.
  393. /// The DPAPI round-trip keeps self-heal working if the machine
  394. /// DPAPI master key is ever lost (plain re-install rewrites the
  395. /// blob instead of early-outing on a present-but-undecryptable one).
  396. pub fn cred_present() -> bool {
  397. read_cred_blob()
  398. .and_then(|b| dpapi::unprotect(&b))
  399. .map(|pw| !pw.is_empty())
  400. .unwrap_or(false)
  401. }
  402. /// Write `der` into the **sandbox user's** `CurrentUser\Root` via a
  403. /// one-shot `CreateProcessWithLogonW(srt-sandbox, "srt-win runner")`
  404. /// carrying [`runner::RunnerCmd::InstallCa`], and — only on success
  405. /// — record it in the `sandbox_user.ca_cert` column. The state-DB
  406. /// record is what the host's `tlsTerminate` gate keys on, so it must
  407. /// only exist when the registry write actually landed. Called only
  408. /// from `srt-win user trust-ca` (with [`read_cred`]); `srt-win
  409. /// install` never touches the CA. Persistent until `srt-win
  410. /// uninstall` deletes the profile.
  411. pub fn trust_ca(der: &crate::cert_store::CertDer, cred: &SandboxCred, sb_sid: &str) -> Result<()> {
  412. let code = logon::spawn_runner(
  413. &cred.user,
  414. &cred.pw,
  415. sb_sid,
  416. None,
  417. &runner::RunnerCmd::InstallCa { der: der.clone() },
  418. false,
  419. )
  420. .context("spawn runner for CA install")?;
  421. if code != 0 {
  422. return Err(anyhow!(
  423. "CA install runner exited {code} — the registry write \
  424. into the sandbox user's hive failed; CA NOT recorded"
  425. ));
  426. }
  427. // Set-value open, not KEY_WRITE: trust-ca runs UNELEVATED, and
  428. // the Ca DACL grants Users exactly KEY_READ|KEY_SET_VALUE.
  429. let ca = crate::reg::Key::open_for_set_value(crate::reg::CA_SUBKEY)?
  430. .ok_or_else(|| anyhow!("CA key absent — run `srt-win install` first"))?;
  431. ca.set_binary("Der", der.as_bytes())
  432. }
  433. /// Remove the install record: identity, marker, credential, and CA
  434. /// record go with the account. Idempotent. When ambient-deny
  435. /// removal left failed entries recorded ([`clear_ambient_denies`]'s
  436. /// retry contract — `status` surfaces them and a later
  437. /// uninstall/install retries), the base key and `AmbientDenies`
  438. /// value survive; otherwise the whole tree is deleted.
  439. pub fn clear_setup() -> Result<()> {
  440. let kept = ambient_recorded_paths()?;
  441. if kept.is_empty() {
  442. return crate::reg::delete_tree();
  443. }
  444. crate::reg::delete_subtree(crate::reg::CRED_SUBKEY)?;
  445. crate::reg::delete_subtree(crate::reg::CA_SUBKEY)?;
  446. if let Some(base) = crate::reg::Key::open(crate::reg::BASE, true)? {
  447. for v in [
  448. "SandboxUser",
  449. "SandboxUserSid",
  450. "SandboxGroupSid",
  451. "MarkerVersion",
  452. "CreatedAt",
  453. ] {
  454. crate::reg::delete_value(&base, v)?;
  455. }
  456. }
  457. Ok(())
  458. }