state_db.rs 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423
  1. //! Cross-broker state DB for `srt-win acl` — refcount additive
  2. //! sandbox-user ACEs (grant ALLOW / stamp DENY) so the LAST broker
  3. //! to release a path can drop the ACE.
  4. //!
  5. //! TWO stores, split by scope and by writer:
  6. //!
  7. //! - SESSION store (`%LOCALAPPDATA%\sandbox-runtime\state.db`,
  8. //! per-user): brokers / ace_holders / working_aces. These rows
  9. //! DRIVE ACL mutations on the owning user's files, so they are
  10. //! only trustworthy while only that user (and admins) can write
  11. //! them — the directory is stamped real-user-only on every open.
  12. //! - MACHINE state (`HKLM\SOFTWARE\sandbox-runtime` — see
  13. //! `crate::reg` — plus the `ca\` key material under
  14. //! `%ProgramData%\sandbox-runtime`): install-owned, admin-written,
  15. //! read unprivileged. Not this module's concern beyond
  16. //! [`machine_store_dir`] and the recompose ambient fold-in.
  17. //!
  18. //! ## Disk-is-truth invariant
  19. //!
  20. //! A row is a refcount edge + `file_id` identity check. It NEVER
  21. //! asserts on-disk state. Every add/drop/crash-recover routes
  22. //! through [`recompose_at`], which reads the live `working_aces`
  23. //! rows for the path and converges the on-disk ACEs for the
  24. //! sandbox SID to exactly that set (walk-and-filter, no PROTECTED
  25. //! rewrite, no SD snapshot). A poisoned row therefore degrades to
  26. //! "sandbox user has an extra ACE the user can manually remove",
  27. //! never to attacker-chosen permissions on the user's own files.
  28. //!
  29. //! ## Locking and crash safety
  30. //!
  31. //! Every `acl stamp|grant|restore|revoke|recover` runs under an
  32. //! exclusive file lock on `.acl-init.lock` in the per-user session
  33. //! dir (see `InitMutex::acquire` for why a file lock and not a
  34. //! named mutex). The lock — NOT a DB transaction — serializes
  35. //! whole operations across the user's brokers; the kernel drops it
  36. //! when a holder dies, and crash-recovery runs unconditionally at
  37. //! every acquire.
  38. //!
  39. //! There is deliberately NO single enclosing transaction. Each
  40. //! path's (FS mutation + row change) commits independently so a
  41. //! failure on path Y can't revert path X. The one ordering rule is
  42. //! record-first: upsert, THEN `SetNamedSecurityInfoW`. A crash
  43. //! between leaves a row whose ACE hasn't been written; the next
  44. //! call re-derives and reapplies.
  45. use anyhow::{Context, Result, anyhow, bail};
  46. use rusqlite::{Connection, OptionalExtension, params};
  47. use std::path::PathBuf;
  48. use std::time::{SystemTime, UNIX_EPOCH};
  49. use windows::Win32::Foundation::{FILETIME, HANDLE, WAIT_OBJECT_0};
  50. use windows::Win32::System::Threading::{
  51. GetCurrentProcess, GetProcessTimes, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
  52. WaitForSingleObject,
  53. };
  54. use crate::acl::{self, SbAce};
  55. use crate::path_id::{self, FileId};
  56. /// Holder PID — the LONG-LIVED process that owns a set of stamps
  57. /// (the Node host in production), NOT the ephemeral `srt-win acl`
  58. /// CLI process. Newtype to avoid confusing it with arbitrary PIDs
  59. /// at call sites; the SQLite `brokers.pid` column stores the bare
  60. /// `u32`.
  61. #[derive(Copy, Clone, Debug, PartialEq, Eq)]
  62. pub struct HolderPid(pub u32);
  63. impl std::str::FromStr for HolderPid {
  64. type Err = std::num::ParseIntError;
  65. fn from_str(s: &str) -> Result<Self, Self::Err> {
  66. s.parse::<u32>().map(HolderPid)
  67. }
  68. }
  69. /// Per-user session DB (brokers / ace_holders / working_aces).
  70. const SESSION_SCHEMA_VERSION: i64 = 8;
  71. const SESSION_SCHEMA_SQL: &str = r#"
  72. CREATE TABLE IF NOT EXISTS brokers (
  73. pid INTEGER PRIMARY KEY,
  74. process_create_time INTEGER NOT NULL,
  75. started_at INTEGER NOT NULL
  76. );
  77. -- Additive explicit ACEs for the sandbox user. kind ∈
  78. -- {'grant','deny','deny_fdc'}: `acl grant` writes ALLOW rows,
  79. -- `acl stamp` writes DENY rows on the target plus a `deny_fdc`
  80. -- row on the parent. Stores no original_sd — restore is a
  81. -- walk-and-filter that drops the SID's ACEs, not a full-SD
  82. -- restore. One row per (path, kind); a path may carry one grant
  83. -- AND one deny (the recompose chokepoint applies both).
  84. -- Refcounted via ace_holders.
  85. CREATE TABLE IF NOT EXISTS working_aces (
  86. canonical_path TEXT NOT NULL,
  87. kind TEXT NOT NULL,
  88. file_id BLOB NOT NULL,
  89. -- The effective mask currently on disk: the MAX across live
  90. -- holders' want_mask (recomputed on every holder add/drop).
  91. mask TEXT NOT NULL,
  92. PRIMARY KEY (canonical_path, kind)
  93. );
  94. CREATE TABLE IF NOT EXISTS ace_holders (
  95. canonical_path TEXT NOT NULL,
  96. kind TEXT NOT NULL,
  97. pid INTEGER NOT NULL REFERENCES brokers(pid) ON DELETE CASCADE,
  98. -- THIS holder's requested mask. The on-disk ACE is the MAX
  99. -- across live holders; release recomputes it so a holder that
  100. -- escalated the mask doesn't leave it escalated past its exit.
  101. want_mask TEXT NOT NULL,
  102. PRIMARY KEY (canonical_path, kind, pid)
  103. );
  104. CREATE INDEX IF NOT EXISTS ace_holders_by_pid ON ace_holders (pid);
  105. -- Filesystem objects `acl stamp` created (empty file at a
  106. -- non-existent deny target + any missing intermediate dirs) so a
  107. -- Deny ACE could be stamped on the exact path. Placeholders are
  108. -- PERMANENT once created (leave-in-place — never deleted by
  109. -- restore/recover, so a user who wrote into one cannot lose data).
  110. -- The record exists so a LATER holder denying the same or a
  111. -- descendant path can discover and hold the full ancestor chain
  112. -- (`Locked::placeholder_ancestors_of`) — otherwise releasing the
  113. -- creating holder would strip intermediates the later holder
  114. -- depends on.
  115. CREATE TABLE IF NOT EXISTS placeholders (
  116. canonical_path TEXT PRIMARY KEY
  117. );
  118. "#;
  119. /// Outcome of a crash-recovery pass.
  120. #[derive(Debug, Default)]
  121. pub struct RecoveryReport {
  122. pub dead_brokers: u32,
  123. /// Orphaned `working_aces` rows whose ACE was revoked.
  124. pub aces_revoked: u32,
  125. }
  126. /// RAII guard for the init lock — an exclusive `LockFileEx` range
  127. /// lock on `.acl-init.lock` inside the per-user session dir.
  128. ///
  129. /// A FILE lock, not a named mutex, on purpose: the sandbox child
  130. /// shares the broker's Terminal-Services session, and Windows named
  131. /// objects are first-come — a child could CREATE the well-known
  132. /// name before the broker and sit on it (create-first squatting
  133. /// bypasses any DACL we would put on our own object; confirmed
  134. /// empirically — a sandboxed `New-Object Threading.Mutex` held the
  135. /// old `Local\` name and stalled the owner's acl ops for the full
  136. /// timeout). The lock file lives in the session dir, whose DACL
  137. /// excludes the sandbox child, so there is nothing for it to squat;
  138. /// and the kernel releases file locks when the holder dies, which
  139. /// also retires the abandoned-mutex special case (crash recovery
  140. /// runs at every acquire regardless).
  141. struct InitMutex {
  142. file: std::fs::File,
  143. }
  144. impl Drop for InitMutex {
  145. fn drop(&mut self) {
  146. use std::os::windows::io::AsRawHandle;
  147. use windows::Win32::Storage::FileSystem::UnlockFile;
  148. unsafe {
  149. let _ = UnlockFile(HANDLE(self.file.as_raw_handle()), 0, 0, 1, 0);
  150. }
  151. }
  152. }
  153. impl InitMutex {
  154. fn acquire() -> Result<Self> {
  155. use std::os::windows::io::AsRawHandle;
  156. use windows::Win32::Storage::FileSystem::{
  157. LOCK_FILE_FLAGS, LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY, LockFileEx,
  158. };
  159. use windows::Win32::System::IO::OVERLAPPED;
  160. let dir = session_store_dir()?;
  161. std::fs::create_dir_all(&dir)
  162. .with_context(|| format!("create_dir_all {}", dir.display()))?;
  163. let path = dir.join(".acl-init.lock");
  164. let file = std::fs::OpenOptions::new()
  165. .read(true)
  166. .write(true)
  167. .create(true)
  168. // Never truncate: the file's only role is carrying the
  169. // kernel byte-range lock; its content is irrelevant.
  170. .truncate(false)
  171. .open(&path)
  172. .with_context(|| format!("open init-lock file {}", path.display()))?;
  173. // Bounded, not infinite: crash-recovery under this lock is
  174. // sub-second and real contention is a handful of concurrent
  175. // acl ops for ONE user, so a minute means a wedged holder —
  176. // fail the op loudly rather than hang.
  177. const ACQUIRE_TIMEOUT_MS: u64 = 60_000;
  178. const POLL_MS: u64 = 100;
  179. let deadline =
  180. std::time::Instant::now() + std::time::Duration::from_millis(ACQUIRE_TIMEOUT_MS);
  181. loop {
  182. let mut ov = OVERLAPPED::default();
  183. let r = unsafe {
  184. LockFileEx(
  185. HANDLE(file.as_raw_handle()),
  186. LOCK_FILE_FLAGS(LOCKFILE_EXCLUSIVE_LOCK.0 | LOCKFILE_FAIL_IMMEDIATELY.0),
  187. None,
  188. 1,
  189. 0,
  190. &mut ov,
  191. )
  192. };
  193. if r.is_ok() {
  194. return Ok(Self { file });
  195. }
  196. if std::time::Instant::now() >= deadline {
  197. bail!(
  198. "init lock {} not acquired within {ACQUIRE_TIMEOUT_MS}ms — \
  199. another srt-win/broker is holding it (wedged?)",
  200. path.display(),
  201. );
  202. }
  203. std::thread::sleep(std::time::Duration::from_millis(POLL_MS));
  204. }
  205. }
  206. }
  207. /// The one seam through which install-time flows (ambient deny
  208. /// stamping/clearing) serialize against this user's brokers —
  209. /// acquire the session init lock without opening the session DB.
  210. pub fn acquire_session_lock() -> Result<impl Drop> {
  211. InitMutex::acquire()
  212. }
  213. /// Open (creating if needed) the per-user SESSION DB. Stamps the
  214. /// parent directory real-user-only on EVERY open — the session
  215. /// store is the pre-split `%LOCALAPPDATA%` model: rows here are
  216. /// TRUSTED because only the owning user (and admins) can write
  217. /// them, which is exactly why session bookkeeping must not live in
  218. /// the Users-writable machine store.
  219. pub fn open_db() -> Result<Connection> {
  220. let dir = session_store_dir()?;
  221. std::fs::create_dir_all(&dir).with_context(|| format!("create_dir_all {}", dir.display()))?;
  222. // Stamp the directory `(OI)(CI)` real-user-only so the sandbox
  223. // child cannot tamper with state.db / -wal / -shm. Done on
  224. // EVERY open, not just first creation: defense-in-depth — the
  225. // child runs as a different user, but a working-tree grant
  226. // could otherwise expose this directory if it lives under a
  227. // granted root. `SetNamedSecurityInfoW` is
  228. // idempotent, so re-stamping an already-correct dir is a no-op.
  229. // Best-effort: if it fails we proceed (the `%LOCALAPPDATA%`
  230. // default DACL already excludes the separate `srt-sandbox`
  231. // user; the explicit stamp + sandbox-users DENY below is
  232. // belt-and-braces against a working-tree ALLOW grant covering
  233. // this directory) and warn so the test harness can assert. We
  234. // own this directory, so a user-applied custom DACL on it is
  235. // NOT preserved — it is rewritten on every open by design.
  236. let dir_str = dir.to_str().ok_or_else(|| {
  237. anyhow!(
  238. "state-DB directory path '{}' is not representable as \
  239. UTF-8 (contains unpaired surrogates); not supported",
  240. dir.display()
  241. )
  242. })?;
  243. // Include the sandbox-users DENY when the install has
  244. // provisioned that group. The credential file in this
  245. // directory is machine-scope DPAPI — readable-by-sandbox =
  246. // decryptable-by-sandbox — so the DENY is load-bearing once
  247. // the separate-user runner exists. The lookup distinguishes
  248. // "group genuinely absent" (install never run / older install
  249. // → DENY skipped, broker-only allow set still excludes the
  250. // sandbox user) from a transient SAM/LSA failure — the latter
  251. // is surfaced rather than silently dropping a security ACE.
  252. let deny_sid = match crate::sid::lookup_account_sid(crate::user::SANDBOX_GROUP) {
  253. Ok(s) => Some(s),
  254. Err(e) => {
  255. match crate::sid::sid_account_exists("S-1-5-32-545") {
  256. // BUILTIN\Users always maps; if it does, SAM is up
  257. // and the sandbox group is genuinely absent.
  258. Ok(crate::sid::SidExistence::Mapped) => None,
  259. _ => {
  260. eprintln!(
  261. "srt-win: WARNING: cannot resolve \
  262. '{}' to add the state-dir DENY ACE \
  263. ({e:#}); the broker-only allow set \
  264. still excludes the sandbox user, but \
  265. the explicit DENY is omitted for this \
  266. stamp",
  267. crate::user::SANDBOX_GROUP,
  268. );
  269. None
  270. }
  271. }
  272. }
  273. };
  274. if let Err(e) = acl::stamp_dir_inheriting(dir_str, deny_sid.as_deref()) {
  275. eprintln!(
  276. "srt-win: WARNING: failed to stamp state-DB dir {} \
  277. broker-only: {e:#}",
  278. dir.display()
  279. );
  280. }
  281. open_db_at(
  282. &dir.join("state.db"),
  283. SESSION_SCHEMA_SQL,
  284. SESSION_SCHEMA_VERSION,
  285. )
  286. }
  287. /// Filter on `release_aces` for the deny-ACE lifecycle.
  288. pub const KIND_DENY: &[&str] = &["deny", "deny_fdc", "deny_delete"];
  289. /// Filter on `release_aces` for the grant lifecycle.
  290. pub const KIND_GRANT: &[&str] = &["grant"];
  291. /// `prepare → query_map → collect` with one error context. Shared
  292. /// by every "list of T from one query" site so error plumbing is
  293. /// edited once.
  294. fn query_vec<T, P: rusqlite::Params>(
  295. conn: &Connection,
  296. sql: &str,
  297. p: P,
  298. row: impl FnMut(&rusqlite::Row<'_>) -> rusqlite::Result<T>,
  299. ) -> Result<Vec<T>> {
  300. let mut s = conn
  301. .prepare(sql)
  302. .with_context(|| format!("prepare: {sql}"))?;
  303. let it = s
  304. .query_map(p, row)
  305. .with_context(|| format!("query: {sql}"))?;
  306. let mut v = Vec::new();
  307. for r in it {
  308. v.push(r.with_context(|| format!("row: {sql}"))?);
  309. }
  310. Ok(v)
  311. }
  312. /// Read-only open of the per-user SESSION DB. Returns `None` if it
  313. /// doesn't exist yet. No mutex, no `create_dir_all`, no dir-stamp,
  314. /// no schema apply.
  315. pub fn open_db_ro() -> Result<Option<Connection>> {
  316. open_ro_at(&session_store_dir()?.join("state.db"))
  317. }
  318. fn open_ro_at(path: &std::path::Path) -> Result<Option<Connection>> {
  319. let schema_version = SESSION_SCHEMA_VERSION;
  320. let path = path.to_path_buf();
  321. // Degrade, don't fail: a garbage/unreadable session DB must read
  322. // as "nothing recorded" — an Err here would propagate through
  323. // crash_recovery into every acl op for this user. The RW open
  324. // path renames a corrupt file away and recreates it.
  325. match path.try_exists() {
  326. Ok(false) => return Ok(None),
  327. Ok(true) => {}
  328. Err(e) => bail!(
  329. "cannot determine state-DB presence at {}: {e}",
  330. path.display()
  331. ),
  332. }
  333. let conn = Connection::open_with_flags(&path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)
  334. .with_context(|| format!("sqlite open RO {}", path.display()))?;
  335. conn.pragma_update(None, "busy_timeout", 5000)?;
  336. // Schema-mismatch chokepoint: a v≠SCHEMA_VERSION DB is from an
  337. // older install whose `sandbox_user` row is stranded. Reading
  338. // it would surface a stale credential. Return None so
  339. // `srt-win user status` reports `provisioned=false` and the TS
  340. // dependency-check tells the user to re-run `srt-win install`
  341. // (which routes through `open_db_at()` → renames the stale DB
  342. // to `.bak` and creates fresh) at the start of the session,
  343. // not mid-exec. Also covers a DB
  344. // with no schema at all (`open_db_at` crashed between
  345. // `Connection::open` and `execute_batch(SCHEMA_SQL)`): ver==0
  346. // and there's no `sandbox_user` row, so "not provisioned yet"
  347. // is the right answer.
  348. let ver: i64 = match conn.query_row("PRAGMA user_version", [], |r| r.get(0)) {
  349. Ok(v) => v,
  350. Err(e) => {
  351. eprintln!(
  352. "srt-win: state DB at {} is unreadable ({e}); treating \
  353. as not provisioned. Re-run `srt-win install` to \
  354. recreate it.",
  355. path.display(),
  356. );
  357. return Ok(None);
  358. }
  359. };
  360. if ver != schema_version {
  361. if ver != 0 {
  362. eprintln!(
  363. "srt-win: state DB at {} is at schema v{ver} \
  364. (expected v{schema_version}); treating as not \
  365. provisioned. Re-run `srt-win install` to migrate.",
  366. path.display(),
  367. );
  368. }
  369. return Ok(None);
  370. }
  371. Ok(Some(conn))
  372. }
  373. /// Open at an arbitrary path with the given schema + version.
  374. /// Tests use `:memory:`.
  375. pub(crate) fn open_db_at(
  376. path: &std::path::Path,
  377. schema_sql: &str,
  378. schema_version: i64,
  379. ) -> Result<Connection> {
  380. // Schema mismatch → rename + recreate. No ALTER/DROP migration:
  381. // the old DB is preserved (debugging/recovery) at
  382. // state.db.v<old>.<ts>.bak alongside `path`, and a fresh DB is
  383. // created at the expected schema. The next recovery converges
  384. // from the fresh (empty) rows. A PRE-SPLIT per-user DB carried
  385. // the DPAPI cred blob in its `sandbox_user` row (machine-scope:
  386. // readable = decryptable), so the blob is scrubbed from the
  387. // .bak below before anything else can read it. The .bak keeps
  388. // its directory's DACL (real-user-only stamp); no per-file
  389. // stamp.
  390. if path.exists() {
  391. let probe = Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY);
  392. if let Ok(c) = probe {
  393. // A garbage (non-SQLite) file fails the pragma — mark it
  394. // ver -1 so it takes the rename-away path below instead
  395. // of reaching the schema apply (which would hard-error
  396. // forever on a file any local user can plant).
  397. let ver: i64 = c
  398. .query_row("PRAGMA user_version", [], |r| r.get(0))
  399. .unwrap_or(-1);
  400. drop(c);
  401. if ver != 0 && ver != schema_version {
  402. let dir = path
  403. .parent()
  404. .ok_or_else(|| anyhow!("state DB path '{}' has no parent", path.display()))?;
  405. let stem = path
  406. .file_name()
  407. .and_then(|s| s.to_str())
  408. .unwrap_or("state.db");
  409. let ts = unix_now();
  410. let bak = dir.join(format!("{stem}.v{ver}.{ts}.bak"));
  411. std::fs::rename(path, &bak).map_err(|e| {
  412. // SQLite's win32 VFS opens with no
  413. // FILE_SHARE_DELETE; another live broker holds
  414. // the file → rename fails 32 here where DROP
  415. // TABLE under WAL would have succeeded.
  416. if e.raw_os_error() == Some(32) {
  417. anyhow!(
  418. "rename incompatible state DB {} → {}: {e} \
  419. — the DB is open in another process \
  420. (likely a running srt-win/broker); close \
  421. it and retry",
  422. path.display(),
  423. bak.display()
  424. )
  425. } else {
  426. anyhow::Error::new(e).context(format!(
  427. "rename incompatible state DB {} → {}",
  428. path.display(),
  429. bak.display()
  430. ))
  431. }
  432. })?;
  433. // WAL sidecars too (best-effort — they hold no cred,
  434. // only journal pages of it).
  435. for ext in ["-wal", "-shm"] {
  436. let p = dir.join(format!("{stem}{ext}"));
  437. let to = dir.join(format!("{stem}.v{ver}.{ts}.bak{ext}"));
  438. let _ = std::fs::rename(&p, &to);
  439. }
  440. // Best-effort cred scrub (pre-split schemas only —
  441. // absent table/column is fine).
  442. if let Ok(bc) = Connection::open(&bak) {
  443. let _ = bc.execute("UPDATE sandbox_user SET cred = x''", []);
  444. }
  445. eprintln!(
  446. "srt-win: state DB at schema v{ver} found, expected \
  447. v{schema_version}; renamed to {} and created fresh. \
  448. Re-run `srt-win install` (and `srt-win user \
  449. trust-ca <pem>` if you use TLS termination) to \
  450. re-provision. `srt-win acl recover` will sweep \
  451. any sandbox-user DENY ACEs from a prior install; \
  452. PROTECTED-stamp DACLs from the removed same-user \
  453. mode require manual `icacls <path> /reset`.",
  454. bak.display(),
  455. );
  456. }
  457. }
  458. }
  459. let conn = Connection::open(path).with_context(|| format!("sqlite open {}", path.display()))?;
  460. // WAL = concurrent readers + single writer + crash safety.
  461. // `synchronous=NORMAL` is the recommended companion for WAL and
  462. // is durable across power loss. busy_timeout is belt-and-braces
  463. // — the named mutex already serializes whole operations across
  464. // brokers, but a brief contention inside one process (tests)
  465. // shouldn't error.
  466. conn.pragma_update(None, "journal_mode", "WAL")?;
  467. conn.pragma_update(None, "synchronous", "NORMAL")?;
  468. conn.pragma_update(None, "foreign_keys", "ON")?;
  469. conn.pragma_update(None, "busy_timeout", 5000)?;
  470. conn.execute_batch(schema_sql).context("apply schema")?;
  471. conn.pragma_update(None, "user_version", schema_version)?;
  472. Ok(conn)
  473. }
  474. /// The machine-wide store dir: `%ProgramData%\sandbox-runtime` —
  475. /// since the move of credential/marker/identity/CA-record/ambient
  476. /// state to `HKLM\SOFTWARE\sandbox-runtime` ([`crate::reg`]), this
  477. /// hosts only the managed CA key material (`ca\`), which must stay
  478. /// on the filesystem because the broker's unelevated
  479. /// generate-if-absent self-heal rewrites it. Created (and ACL'd) by
  480. /// the elevated install (`install::provision_machine_store`); a
  481. /// pre-created directory is healed there by taking ownership and
  482. /// rewriting the DACL.
  483. pub fn machine_store_dir() -> Result<PathBuf> {
  484. state_dir_from_base(std::env::var_os("ProgramData"), "ProgramData")
  485. }
  486. /// The per-user SESSION dir: `%LOCALAPPDATA%\sandbox-runtime` —
  487. /// ACL-bookkeeping state (`state.db`: brokers/holders/working
  488. /// ACEs). Per-user by design: these rows DRIVE ACL mutations on the
  489. /// owning user's files, so they must only be writable by that user
  490. /// (and admins) — in a shared store any local user could seed rows
  491. /// for another user's broker to apply. Stamped real-user-only on
  492. /// every [`open_db`].
  493. pub fn session_store_dir() -> Result<PathBuf> {
  494. state_dir_from_base(std::env::var_os("LOCALAPPDATA"), "LOCALAPPDATA")
  495. }
  496. /// Errors if `var` (`%ProgramData%`) is unset,
  497. /// empty, or yields a non-absolute path — a relative state dir
  498. /// would put the ACL-protected DB in the CWD and break cross-broker
  499. /// refcounting/recovery.
  500. fn state_dir_from_base(base: Option<std::ffi::OsString>, var: &str) -> Result<PathBuf> {
  501. let base = base
  502. .filter(|s| !s.is_empty())
  503. .map(PathBuf::from)
  504. .ok_or_else(|| anyhow!("{var} not set or empty"))?;
  505. let dir = base.join("sandbox-runtime");
  506. if !dir.is_absolute() {
  507. bail!(
  508. "state-DB directory '{}' is not absolute \
  509. ({var}='{}'); refusing relative state path",
  510. dir.display(),
  511. base.display()
  512. );
  513. }
  514. Ok(dir)
  515. }
  516. /// Run `f` under the init mutex with the DB open. Crash recovery is
  517. /// run first. `f` receives a `Locked` view whose mutating methods
  518. /// each autocommit (single-statement) or use their own short
  519. /// transaction — there is NO single enclosing transaction.
  520. ///
  521. /// See module doc for the no-enclosing-tx and ordering rationale.
  522. pub fn with_init_lock<R>(
  523. holder_pid: HolderPid,
  524. force_recover: bool,
  525. f: impl FnOnce(&mut Locked) -> Result<R>,
  526. ) -> Result<(R, RecoveryReport)> {
  527. let (_mutex, conn, report) = locked_recovered(force_recover)?;
  528. let mut locked = Locked { conn, holder_pid };
  529. let out = f(&mut locked)?;
  530. Ok((out, report))
  531. }
  532. /// The shared critical-section preamble of [`with_init_lock`] and
  533. /// [`with_install_lock`]: acquire the init mutex, open the DB, run
  534. /// crash recovery. Keep the mutex guard alive for the whole
  535. /// critical section.
  536. fn locked_recovered(force_recover: bool) -> Result<(InitMutex, Connection, RecoveryReport)> {
  537. let mutex = InitMutex::acquire()?;
  538. let conn = open_db()?;
  539. let report = crash_recovery(&conn, force_recover)?;
  540. Ok((mutex, conn, report))
  541. }
  542. /// View inside `with_init_lock`. Owns the `Connection`; each method
  543. /// commits independently (rusqlite autocommits a lone `execute`).
  544. ///
  545. /// `holder_pid` is the LONG-LIVED owner of the stamps — typically
  546. /// the Node host (sandbox-runtime) process, NOT this ephemeral
  547. /// `srt-win acl` process. The CLI exits immediately; keying holders
  548. /// on its PID would let the next acl op's crash-recovery reap it and
  549. /// tear the stamp down. Keying on the caller-supplied holder PID
  550. /// means a stamp persists until that process exits (or explicitly
  551. /// restores), and refcount / crash-recovery track the real session.
  552. pub struct Locked {
  553. conn: Connection,
  554. holder_pid: HolderPid,
  555. }
  556. impl Locked {
  557. /// Record `self.holder_pid` in `brokers`. The row's
  558. /// `process_create_time` is the HOLDER's, so crash-recovery
  559. /// checks whether the holder — not this short-lived CLI — is
  560. /// still alive.
  561. ///
  562. /// UPSERT, not `INSERT OR REPLACE`: with `foreign_keys=ON` and
  563. /// `ace_holders.pid REFERENCES brokers ON DELETE CASCADE`,
  564. /// REPLACE is a DELETE (cascading away every `ace_holders` row
  565. /// for this pid) plus a fresh INSERT — so a holder's *second*
  566. /// `acl stamp`/`grant` would silently drop its first batch's
  567. /// holds, and the next crash-recovery would strip those ACEs
  568. /// while the holder's child is still running. `ON CONFLICT DO
  569. /// UPDATE` updates in place and leaves child rows intact.
  570. pub fn register_broker(&self) -> Result<()> {
  571. let ct = pid_create_time(self.holder_pid.0)
  572. .with_context(|| format!("read create-time of holder pid {}", self.holder_pid.0))?;
  573. let now = unix_now();
  574. self.conn
  575. .execute(
  576. "INSERT INTO brokers (pid, process_create_time, started_at) \
  577. VALUES (?1, ?2, ?3) \
  578. ON CONFLICT(pid) DO UPDATE SET \
  579. process_create_time = excluded.process_create_time, \
  580. started_at = excluded.started_at",
  581. params![self.holder_pid.0 as i64, ct, now],
  582. )
  583. .context("INSERT brokers")?;
  584. Ok(())
  585. }
  586. /// Remove the holder's `brokers` row. CASCADE drops its
  587. /// `holders` rows.
  588. pub fn unregister_broker(&self) -> Result<()> {
  589. self.conn
  590. .execute(
  591. "DELETE FROM brokers WHERE pid = ?1",
  592. params![self.holder_pid.0 as i64],
  593. )
  594. .context("DELETE brokers")?;
  595. Ok(())
  596. }
  597. /// Register the holder, run `f`, and on per-path failure roll
  598. /// back any ACEs `f` freshly added (then drop the broker row if
  599. /// it now holds nothing). All-or-nothing for `apply_aces`.
  600. fn with_broker_registration(
  601. &self,
  602. sandbox_sid: &str,
  603. f: impl FnOnce(&Self) -> Result<(Vec<AceWitness>, usize)>,
  604. ) -> Result<(Vec<AceWitness>, usize)> {
  605. self.register_broker()?;
  606. let (witnesses, failed) = f(self)?;
  607. if failed > 0 {
  608. for w in witnesses.iter().filter(|w| w.holder_added) {
  609. if let Err(e) = self.release_one_ace(&w.canon, w.ace.kind(), sandbox_sid) {
  610. eprintln!(
  611. "srt-win: WARNING: rollback {} '{}': {e:#}; \
  612. ACE left in place",
  613. w.ace.kind(),
  614. w.canon
  615. );
  616. }
  617. }
  618. if self
  619. .my_ace_holds(None)
  620. .map(|h| h.is_empty())
  621. .unwrap_or(false)
  622. {
  623. let _ = self.unregister_broker();
  624. }
  625. }
  626. Ok((witnesses, failed))
  627. }
  628. /// Apply additive sandbox-user ACEs on each `(canon, ace)` and
  629. /// record `self.holder_pid` as a holder. Refcounted: a path
  630. /// already held by another holder gets its on-disk ACE
  631. /// re-converged (idempotent) and a holder row added; release
  632. /// recomputes the effective mask from the remaining holders.
  633. ///
  634. /// `Deny` targets implicitly add a `(parent, DenyFdc)` entry so
  635. /// the sandbox user cannot `del`/`ren` the file via parent-FDC
  636. /// even when the parent carries an inherited
  637. /// `BUILTIN\Users:(F)`. Multiple denied siblings under one
  638. /// parent share the parent's `deny_fdc` row (PK
  639. /// `(path, kind, pid)` dedupes within one holder; refcount
  640. /// handles cross-holder).
  641. ///
  642. /// All-or-nothing per batch (via [`Self::with_broker_registration`]).
  643. pub fn apply_aces(
  644. &self,
  645. sandbox_sid: &str,
  646. targets: &[(String, SbAce)],
  647. ) -> Result<(Vec<AceWitness>, usize)> {
  648. self.with_broker_registration(sandbox_sid, |db| {
  649. let mut witnesses = Vec::with_capacity(targets.len());
  650. let mut failed = 0usize;
  651. let mut one = |canon: &str, ace: SbAce| -> bool {
  652. match db.ensure_ace(canon, ace, sandbox_sid) {
  653. Ok(w) => {
  654. witnesses.push(w);
  655. true
  656. }
  657. Err(e) => {
  658. eprintln!("srt-win: {} '{canon}': {e:#}", ace.kind());
  659. failed += 1;
  660. false
  661. }
  662. }
  663. };
  664. for (canon, ace) in targets {
  665. // Skip the parent-FDC ACE when the file's own
  666. // Deny failed (e.g. hardlink refuse) — the batch
  667. // is going to roll back anyway (`failed > 0`),
  668. // and stamping the parent first just to release
  669. // it in the same pass wastes a SetSecurityInfo
  670. // round-trip and clutters the failure output.
  671. if one(canon, *ace)
  672. && matches!(ace, SbAce::Deny(_) | SbAce::DenyDelete)
  673. && let Some(p) = path_id::canonical_parent_of(canon)
  674. {
  675. one(&p, SbAce::DenyFdc);
  676. }
  677. }
  678. Ok((witnesses, failed))
  679. })
  680. }
  681. /// Disk-first single-ACE converge. Record-first upsert (holder
  682. /// row plus `working_aces` row) then [`recompose_at`] so a
  683. /// crash between leaves a row whose ACE hasn't been written —
  684. /// the next call re-derives and reapplies.
  685. fn ensure_ace(&self, canon: &str, want: SbAce, sandbox_sid: &str) -> Result<AceWitness> {
  686. let (cur_id, links, is_dir) = path_id::capture_id_and_links(canon)
  687. .with_context(|| format!("capture file_id+links '{canon}'"))?;
  688. // Hardlink guard: NTFS hardlinks share one SD across
  689. // distinct canonical paths, but `ace_holders` is
  690. // PATH-keyed. A Deny on one alias is invisible to a holder
  691. // of another — `release_one_ace` on the alias sees
  692. // remaining=0 and recomposes the SHARED DACL without the
  693. // deny while the other holder's child is still running.
  694. // Refuse Deny on multi-link files; Grant is fail-open so
  695. // an early release is safe, and `DenyFdc` only targets
  696. // directories.
  697. if matches!(want, SbAce::Deny(_)) && !is_dir && links > 1 {
  698. bail!(
  699. "deny refused: '{canon}' has {links} hardlink(s); \
  700. ace_holders rows are path-keyed, so releasing an \
  701. alias would prematurely strip the shared deny ACE"
  702. );
  703. }
  704. let prior: Option<Vec<u8>> = self
  705. .conn
  706. .prepare_cached(
  707. "SELECT file_id FROM working_aces \
  708. WHERE canonical_path = ?1 AND kind = ?2",
  709. )?
  710. .query_row(params![canon, want.kind()], |r| r.get(0))
  711. .optional()
  712. .context("SELECT working_aces")?;
  713. if let Some(fid) = &prior
  714. && FileId::from_bytes(fid)? != cur_id
  715. {
  716. bail!(
  717. "'{canon}': file_id changed since prior {} — path \
  718. was substituted (refusing)",
  719. want.kind()
  720. );
  721. }
  722. // Holder row first (`want_mask` is THIS holder's request,
  723. // independent of what other holders want — `effective_ace`
  724. // computes the MAX). UPSERT so a re-apply at a different
  725. // mask updates this holder's want. `holder_added` must
  726. // reflect whether THIS call inserted a NEW (canon, kind,
  727. // pid) row — NOT whether `working_aces` was empty
  728. // (`prior.is_none()`): the latter would give a second
  729. // holder of an already-held path `holder_added=false`,
  730. // and partial-failure rollback (`with_broker_registration`)
  731. // would leak its row. SQLite's UPSERT `changes()` returns
  732. // 1 for both branches, so probe first.
  733. let already_held: bool = self
  734. .conn
  735. .prepare_cached(
  736. "SELECT 1 FROM ace_holders WHERE \
  737. canonical_path = ?1 AND kind = ?2 AND pid = ?3 \
  738. LIMIT 1",
  739. )?
  740. .exists(params![canon, want.kind(), self.holder_pid.0 as i64])
  741. .context("SELECT ace_holders (held?)")?;
  742. self.conn
  743. .prepare_cached(
  744. "INSERT INTO ace_holders \
  745. (canonical_path, kind, pid, want_mask) \
  746. VALUES (?1, ?2, ?3, ?4) \
  747. ON CONFLICT(canonical_path, kind, pid) \
  748. DO UPDATE SET want_mask = excluded.want_mask",
  749. )?
  750. .execute(params![
  751. canon,
  752. want.kind(),
  753. self.holder_pid.0 as i64,
  754. want.as_str()
  755. ])
  756. .context("UPSERT ace_holders")?;
  757. let holder_added = !already_held;
  758. let eff = self.effective_ace(canon, want.kind())?.unwrap_or(want);
  759. self.conn
  760. .prepare_cached(
  761. "INSERT INTO working_aces \
  762. (canonical_path, kind, file_id, mask) \
  763. VALUES (?1, ?2, ?3, ?4) \
  764. ON CONFLICT(canonical_path, kind) DO UPDATE SET \
  765. file_id = excluded.file_id, \
  766. mask = excluded.mask",
  767. )?
  768. .execute(params![
  769. canon,
  770. want.kind(),
  771. cur_id.as_bytes().as_slice(),
  772. eff.as_str()
  773. ])
  774. .context("UPSERT working_aces")?;
  775. recompose_at(&self.conn, canon, sandbox_sid)?;
  776. Ok(AceWitness {
  777. canon: canon.to_string(),
  778. ace: eff,
  779. already: prior.is_some(),
  780. holder_added,
  781. _sealed: (),
  782. })
  783. }
  784. /// `MAX(want_mask)` across live holders of `(canon, kind)`.
  785. fn effective_ace(&self, canon: &str, kind: &str) -> Result<Option<SbAce>> {
  786. let masks: Vec<String> = query_vec(
  787. &self.conn,
  788. "SELECT want_mask FROM ace_holders \
  789. WHERE canonical_path = ?1 AND kind = ?2",
  790. params![canon, kind],
  791. |r| r.get(0),
  792. )?;
  793. masks
  794. .iter()
  795. .map(|m| SbAce::parse(kind, m))
  796. .reduce(|a, b| Ok(a?.max(b?)))
  797. .transpose()
  798. }
  799. /// Release one `(canon, kind)` hold; recompute the effective ACE
  800. /// from the remaining holders (downgrade if this holder was the
  801. /// one that escalated it; revoke when zero remain).
  802. /// Identity-validated: if the path now resolves to a different
  803. /// `file_id`, the row is dropped and the ACE on the foreign
  804. /// object is NOT touched — except for `Grant`, where we
  805. /// best-effort `locate_by_file_id` and revoke at the moved path
  806. /// so the sandbox user does not keep stale access.
  807. fn release_one_ace(&self, canon: &str, kind: &str, sandbox_sid: &str) -> Result<AceRelease> {
  808. self.conn
  809. .prepare_cached(
  810. "DELETE FROM ace_holders WHERE canonical_path = ?1 \
  811. AND kind = ?2 AND pid = ?3",
  812. )?
  813. .execute(params![canon, kind, self.holder_pid.0 as i64])
  814. .context("DELETE ace_holders (self)")?;
  815. let row: Option<(Vec<u8>, String)> = self
  816. .conn
  817. .prepare_cached(
  818. "SELECT file_id, mask FROM working_aces \
  819. WHERE canonical_path = ?1 AND kind = ?2",
  820. )?
  821. .query_row(params![canon, kind], |r| Ok((r.get(0)?, r.get(1)?)))
  822. .optional()?;
  823. let Some((fid, stored)) = row else {
  824. return Ok(AceRelease::NoRow);
  825. };
  826. let new_eff = self.effective_ace(canon, kind)?;
  827. // Row update first (record-first), then converge disk.
  828. match new_eff {
  829. Some(e) => self
  830. .conn
  831. .execute(
  832. "UPDATE working_aces SET mask = ?3 \
  833. WHERE canonical_path = ?1 AND kind = ?2",
  834. params![canon, kind, e.as_str()],
  835. )
  836. .context("UPDATE working_aces (downgrade)")?,
  837. None => self
  838. .conn
  839. .execute(
  840. "DELETE FROM working_aces \
  841. WHERE canonical_path = ?1 AND kind = ?2",
  842. params![canon, kind],
  843. )
  844. .context("DELETE working_aces")?,
  845. };
  846. let want_id = FileId::from_bytes(&fid)?;
  847. match identity_gate(canon, want_id) {
  848. IdGate::Match => {
  849. recompose_at(&self.conn, canon, sandbox_sid)?;
  850. Ok(match new_eff {
  851. Some(e) if e.as_str() == stored => AceRelease::StillHeld,
  852. Some(_) => AceRelease::Downgraded,
  853. None => AceRelease::Revoked,
  854. })
  855. }
  856. IdGate::Mismatch if kind == "grant" => {
  857. // The granted object moved. The ALLOW ACE travels
  858. // with the inode → the sandbox user still has
  859. // access at the new path. Chase by file_id and
  860. // revoke there (then re-converge if the new path
  861. // happens to be tracked too). DENY/FDC are left in
  862. // place on the moved inode (fail-closed).
  863. Ok(match path_id::locate_by_file_id(&want_id) {
  864. Some(at) => {
  865. eprintln!(
  866. "srt-win: grant '{canon}': file_id moved \
  867. to '{at}'; revoking there"
  868. );
  869. recompose_at(&self.conn, &at, sandbox_sid)?;
  870. AceRelease::Relocated { moved_to: at }
  871. }
  872. None => {
  873. eprintln!(
  874. "srt-win: grant '{canon}': file_id not \
  875. found on volume; dropping row"
  876. );
  877. AceRelease::Missing
  878. }
  879. })
  880. }
  881. IdGate::Mismatch => {
  882. eprintln!(
  883. "srt-win: {kind} '{canon}': file_id mismatch — \
  884. path substituted; not touching ACE on the \
  885. foreign object (fail-closed)"
  886. );
  887. Ok(AceRelease::Mismatch)
  888. }
  889. IdGate::Unreadable => {
  890. eprintln!(
  891. "srt-win: {kind} '{canon}': open failed; \
  892. dropping row"
  893. );
  894. Ok(AceRelease::Missing)
  895. }
  896. }
  897. }
  898. /// `(canon, kind)` rows held by this holder, optionally filtered
  899. /// to one set of kinds.
  900. fn my_ace_holds(&self, kinds: Option<&[&str]>) -> Result<Vec<(String, String)>> {
  901. let all: Vec<(String, String)> = query_vec(
  902. &self.conn,
  903. "SELECT canonical_path, kind FROM ace_holders \
  904. WHERE pid = ?1",
  905. params![self.holder_pid.0 as i64],
  906. |r| Ok((r.get(0)?, r.get(1)?)),
  907. )?;
  908. Ok(all
  909. .into_iter()
  910. .filter(|(_, k)| kinds.is_none_or(|ks| ks.contains(&k.as_str())))
  911. .collect())
  912. }
  913. /// Release every ACE hold of `self.holder_pid` for the given
  914. /// `kinds` ([`KIND_GRANT`] for `acl revoke`; [`KIND_DENY`] for
  915. /// `acl restore --sandbox-user-sid`) and unregister if no holds
  916. /// of any kind remain. Per-path catch-and-continue.
  917. pub fn release_aces(
  918. &self,
  919. sandbox_sid: &str,
  920. kinds: &[&str],
  921. ) -> Result<(Vec<(String, AceRelease)>, usize)> {
  922. let holds = self.my_ace_holds(Some(kinds))?;
  923. let mut out = Vec::with_capacity(holds.len());
  924. let mut failed = 0usize;
  925. for (canon, kind) in &holds {
  926. match self.release_one_ace(canon, kind, sandbox_sid) {
  927. Ok(r) => out.push((canon.clone(), r)),
  928. Err(e) => {
  929. eprintln!(
  930. "srt-win: WARNING: release {kind} '{canon}': \
  931. {e:#}; ACE left in place"
  932. );
  933. failed += 1;
  934. }
  935. }
  936. }
  937. if self
  938. .my_ace_holds(None)
  939. .map(|h| h.is_empty())
  940. .unwrap_or(false)
  941. {
  942. self.unregister_broker()?;
  943. }
  944. Ok((out, failed))
  945. }
  946. /// Record a placeholder component `acl stamp` is about to
  947. /// create (see the `placeholders` table comment). Idempotent
  948. /// (`INSERT OR IGNORE`); called intent-first — before the
  949. /// on-disk create — so a crash between record and create leaves
  950. /// a harmless orphan row rather than an unrecorded on-disk
  951. /// component a later holder cannot discover.
  952. pub fn record_placeholder(&self, canon: &str) -> Result<()> {
  953. self.conn
  954. .prepare_cached(
  955. "INSERT OR IGNORE INTO placeholders (canonical_path) \
  956. VALUES (?1)",
  957. )?
  958. .execute(params![canon])
  959. .with_context(|| format!("INSERT placeholders '{canon}'"))?;
  960. Ok(())
  961. }
  962. /// Every recorded placeholder that is a STRICT ancestor of
  963. /// `canon` (i.e. `canon` starts with `placeholder || '\'`) —
  964. /// the discovery half of the full-chain hold (see the
  965. /// `placeholders` table comment). The table is tiny, so filter
  966. /// in Rust rather than a `LIKE` pattern that would have to
  967. /// escape `?`/`_` in canonical paths.
  968. pub fn placeholder_ancestors_of(&self, canon: &str) -> Result<Vec<String>> {
  969. let all: Vec<String> = query_vec(
  970. &self.conn,
  971. "SELECT canonical_path FROM placeholders",
  972. [],
  973. |r| r.get(0),
  974. )?;
  975. let cb = canon.as_bytes();
  976. Ok(all
  977. .into_iter()
  978. .filter(|p| cb.get(p.len()) == Some(&b'\\') && canon.starts_with(p.as_str()))
  979. .collect())
  980. }
  981. }
  982. /// Read all `working_aces` rows for `canon` and converge the on-disk
  983. /// ACEs for `sandbox_sid` to exactly that set. The single chokepoint
  984. /// for sandbox-user ACE state — every add/drop/crash-recover routes
  985. /// here so a path with both a grant AND a deny (or a parent that is
  986. /// both granted and `deny_fdc`'d) is handled consistently.
  987. fn recompose_at(conn: &Connection, canon: &str, sandbox_sid: &str) -> Result<()> {
  988. let rows: Vec<(String, String)> = query_vec(
  989. conn,
  990. "SELECT kind, mask FROM working_aces \
  991. WHERE canonical_path = ?1",
  992. params![canon],
  993. |r| Ok((r.get(0)?, r.get(1)?)),
  994. )?;
  995. let mut set = acl::SbAceSet::default();
  996. for (k, m) in &rows {
  997. match SbAce::parse(k, m)? {
  998. SbAce::Grant(g) => set.grant = Some(g),
  999. SbAce::Deny(d) => set.deny = Some(d),
  1000. SbAce::DenyFdc => set.deny_fdc = true,
  1001. SbAce::DenyDelete => set.deny_delete = true,
  1002. }
  1003. }
  1004. // Install-time ambient write-deny (HKLM AmbientDenies) folds
  1005. // into every converge on the path, so session release/recovery
  1006. // cannot strip it. WriteDeny is the floor: a session's wider
  1007. // ReadDeny wins while its row is held, and the floor returns on
  1008. // release. The registry value is admin-written (HKLM\SOFTWARE
  1009. // default DACL), so the list is trustworthy as read.
  1010. if crate::install::ambient_deny_recorded(canon) {
  1011. set.deny.get_or_insert(acl::DenyMask::WriteDeny);
  1012. }
  1013. acl::apply_sandbox_aces(canon, sandbox_sid, set)
  1014. .with_context(|| format!("recompose '{canon}' ({set:?})"))
  1015. }
  1016. /// Sealed proof that [`Locked::apply_aces`] converged `canon` to
  1017. /// carry `ace` for the sandbox user.
  1018. #[must_use]
  1019. #[allow(clippy::manual_non_exhaustive)]
  1020. #[derive(Debug)]
  1021. pub struct AceWitness {
  1022. pub canon: String,
  1023. pub ace: SbAce,
  1024. /// A row already existed (another holder, or a re-apply).
  1025. pub already: bool,
  1026. pub holder_added: bool,
  1027. _sealed: (),
  1028. }
  1029. /// Per-path outcome of [`Locked::release_aces`].
  1030. #[derive(Debug, Clone, PartialEq, Eq)]
  1031. pub enum AceRelease {
  1032. /// ACE removed (last holder); row deleted.
  1033. Revoked,
  1034. /// Other holders remain at the SAME effective mask; ACE
  1035. /// untouched.
  1036. StillHeld,
  1037. /// Other holders remain at a NARROWER mask; ACE re-applied at
  1038. /// the new MAX(want_mask).
  1039. Downgraded,
  1040. /// `file_id` mismatch; for `grant` the ACE was revoked at the
  1041. /// relocated path. Row deleted.
  1042. Relocated { moved_to: String },
  1043. /// `file_id` mismatch — row deleted, ACE on the foreign object
  1044. /// not touched.
  1045. Mismatch,
  1046. /// Path no longer opens — row deleted.
  1047. Missing,
  1048. /// Holder row removed but no `working_aces` row found.
  1049. NoRow,
  1050. }
  1051. impl AceRelease {
  1052. pub fn as_str(&self) -> &'static str {
  1053. match self {
  1054. AceRelease::Revoked => "revoked",
  1055. AceRelease::StillHeld => "stillHeld",
  1056. AceRelease::Downgraded => "downgraded",
  1057. AceRelease::Relocated { .. } => "relocated",
  1058. AceRelease::Mismatch => "mismatch",
  1059. AceRelease::Missing => "missing",
  1060. AceRelease::NoRow => "noRow",
  1061. }
  1062. }
  1063. }
  1064. /// Prune dead brokers and revoke any sandbox-user ACEs they orphaned.
  1065. ///
  1066. /// Per-path commit: the dead-broker prune is one short tx (pure DB,
  1067. /// CASCADE); then each orphan's (recompose FS mutation + row
  1068. /// delete) is committed independently, so a failure on path Y
  1069. /// leaves path X's recompose+delete durable. `force` is reserved
  1070. /// for a future "force-recompose ignoring file-id mismatch" mode.
  1071. fn crash_recovery(conn: &Connection, force: bool) -> Result<RecoveryReport> {
  1072. let mut report = RecoveryReport::default();
  1073. // 1. Find dead brokers.
  1074. let dead: Vec<i64> = query_vec(
  1075. conn,
  1076. "SELECT pid, process_create_time FROM brokers",
  1077. [],
  1078. |r| Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?)),
  1079. )?
  1080. .into_iter()
  1081. .filter(|&(pid, ct)| !is_process_alive(pid as u32, ct))
  1082. .map(|(pid, _)| pid)
  1083. .collect();
  1084. // 2. Delete dead brokers in one short tx; CASCADE drops their
  1085. // holder rows. (No-op if none — but still cheap.)
  1086. if !dead.is_empty() {
  1087. report.dead_brokers = dead.len() as u32;
  1088. let tx = conn
  1089. .unchecked_transaction()
  1090. .context("begin prune-dead tx")?;
  1091. for pid_i in &dead {
  1092. tx.execute("DELETE FROM brokers WHERE pid = ?1", params![pid_i])
  1093. .context("DELETE dead broker")?;
  1094. }
  1095. tx.commit().context("commit prune-dead")?;
  1096. }
  1097. // Even with no dead brokers there can be orphaned ACE rows
  1098. // (a broker that unregistered but crashed before releasing), so
  1099. // always run step 3.
  1100. // 3. Orphaned sandbox-user ACEs: any working_aces row with
  1101. // zero ace_holders is one whose holder died (CASCADE
  1102. // dropped the holder row above). Re-converge the path —
  1103. // `recompose_at` reads the (possibly remaining) rows and
  1104. // applies exactly that, so a path with one orphaned kind
  1105. // and one still-held kind keeps the held one. Sandbox SID
  1106. // comes from `read_setup_info` — when no sandbox user is
  1107. // provisioned, there are no `working_aces` rows to orphan.
  1108. // Identity comes from the VALIDATED machine-store read (name↔SID
  1109. // + sandbox-group membership against SAM), never from raw rows:
  1110. // the machine DB is Users-writable, and this SID is about to be
  1111. // written into DACLs. No valid identity → skip disk work
  1112. // entirely (the session rows stay put for a later recovery).
  1113. if let Some(sb) = crate::install::read_setup()?.map(|s| s.sandbox_user_sid) {
  1114. let orphan_aces: Vec<(String, String, Vec<u8>)> = query_vec(
  1115. conn,
  1116. "SELECT g.canonical_path, g.kind, g.file_id \
  1117. FROM working_aces g \
  1118. LEFT JOIN ace_holders h \
  1119. ON h.canonical_path = g.canonical_path \
  1120. AND h.kind = g.kind \
  1121. WHERE h.canonical_path IS NULL",
  1122. [],
  1123. |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
  1124. )?;
  1125. for (canon, kind, fid) in orphan_aces {
  1126. conn.execute(
  1127. "DELETE FROM working_aces \
  1128. WHERE canonical_path = ?1 AND kind = ?2",
  1129. params![&canon, &kind],
  1130. )
  1131. .context("DELETE working_aces (orphan)")?;
  1132. let want = FileId::from_bytes(&fid)?;
  1133. match identity_gate(&canon, want) {
  1134. IdGate::Match => {
  1135. if let Err(e) = recompose_at(conn, &canon, &sb) {
  1136. eprintln!(
  1137. "srt-win: orphaned {kind} '{canon}': \
  1138. recompose failed ({e:#})"
  1139. );
  1140. continue;
  1141. }
  1142. }
  1143. IdGate::Mismatch if kind == "grant" => {
  1144. if let Some(at) = path_id::locate_by_file_id(&want) {
  1145. let _ = recompose_at(conn, &at, &sb);
  1146. }
  1147. }
  1148. _ => {} // gone/substituted — nothing on disk to do
  1149. }
  1150. report.aces_revoked += 1;
  1151. }
  1152. }
  1153. let _ = force; // reserved for a future "force-recompose" mode
  1154. Ok(report)
  1155. }
  1156. enum IdGate {
  1157. Match,
  1158. Mismatch,
  1159. Unreadable,
  1160. }
  1161. /// `(path, file_id)` identity check. `path` gone
  1162. /// (ERROR_FILE/PATH_NOT_FOUND) or different inode → `Mismatch`;
  1163. /// any other open error → `Unreadable` (retryable, not a
  1164. /// mismatch).
  1165. fn identity_gate(path: &str, expect: FileId) -> IdGate {
  1166. match path_id::capture_file_id(path) {
  1167. Ok(cur) if cur == expect => IdGate::Match,
  1168. Ok(_) => IdGate::Mismatch,
  1169. Err(e) => {
  1170. if path_id::is_not_found(&e) {
  1171. IdGate::Mismatch
  1172. } else {
  1173. eprintln!(
  1174. "srt-win: '{path}': cannot read file_id ({e:#}); \
  1175. leaving row (use `acl recover --force`)"
  1176. );
  1177. IdGate::Unreadable
  1178. }
  1179. }
  1180. }
  1181. }
  1182. /// True if `pid` refers to a live process whose CreationTime
  1183. /// matches `expected_create_filetime`. PID-recycle guard.
  1184. fn is_process_alive(pid: u32, expected_create_filetime: i64) -> bool {
  1185. if pid == std::process::id() {
  1186. // Don't reap ourselves even if the stored CreationTime is
  1187. // somehow stale.
  1188. return true;
  1189. }
  1190. // SYNCHRONIZE so the WaitForSingleObject(0) signaled-check works.
  1191. let h = match unsafe {
  1192. OpenProcess(
  1193. PROCESS_QUERY_LIMITED_INFORMATION
  1194. | windows::Win32::System::Threading::PROCESS_SYNCHRONIZE,
  1195. false,
  1196. pid,
  1197. )
  1198. } {
  1199. Ok(h) if !h.is_invalid() => h,
  1200. // A spurious `Ok` with an invalid handle is "uncertain" —
  1201. // treat as ALIVE, matching the conservative stance below
  1202. // (better to leave a stale row than reap a live broker and
  1203. // restore a file it still holds).
  1204. Ok(_) => return true,
  1205. // Treat as DEAD only on ERROR_INVALID_PARAMETER (87) — the
  1206. // "no such PID" signal. Every other error (ACCESS_DENIED,
  1207. // transient low-memory, etc.) is uncertain → ALIVE, so we
  1208. // never reap (and restore a file still used by) a holder
  1209. // that's actually running.
  1210. Err(e) => {
  1211. return (e.code().0 as u32 & 0xFFFF) != 87;
  1212. }
  1213. };
  1214. let h = crate::util::OwnedHandle(h);
  1215. match process_create_time(h.raw()) {
  1216. Ok(ct) => {
  1217. ct == expected_create_filetime
  1218. // An exited process whose handle is still held
  1219. // elsewhere remains openable with the same
  1220. // CreationTime — without this check it reads as
  1221. // alive forever and is never reaped. Only
  1222. // WAIT_OBJECT_0 (= signaled = exited) is "dead";
  1223. // WAIT_TIMEOUT and WAIT_FAILED are both "alive"
  1224. // (uncertain → ALIVE, matching the conservative
  1225. // stance everywhere else in this function).
  1226. && unsafe { WaitForSingleObject(h.raw(), 0) }
  1227. != WAIT_OBJECT_0
  1228. }
  1229. // Transient GetProcessTimes failure → uncertain → ALIVE,
  1230. // matching the conservative stance everywhere else (better
  1231. // a stale row than a live holder reaped and its files
  1232. // restored under it).
  1233. Err(_) => true,
  1234. }
  1235. }
  1236. /// Creation FILETIME (as i64) of an arbitrary PID. Opens the
  1237. /// process for limited query; special-cases self to avoid needing
  1238. /// OpenProcess rights on our own token.
  1239. fn pid_create_time(pid: u32) -> Result<i64> {
  1240. if pid == std::process::id() {
  1241. return process_create_time(unsafe { GetCurrentProcess() });
  1242. }
  1243. let h = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) }
  1244. .with_context(|| format!("OpenProcess({pid}) for create-time"))?;
  1245. if h.is_invalid() {
  1246. bail!("OpenProcess({pid}) returned invalid handle");
  1247. }
  1248. let h = crate::util::OwnedHandle(h);
  1249. process_create_time(h.raw())
  1250. }
  1251. /// FILETIME (100-ns since 1601-01-01) → i64 for storage.
  1252. fn process_create_time(h: HANDLE) -> Result<i64> {
  1253. let mut create = FILETIME::default();
  1254. let mut exit = FILETIME::default();
  1255. let mut kernel = FILETIME::default();
  1256. let mut user = FILETIME::default();
  1257. unsafe {
  1258. GetProcessTimes(h, &mut create, &mut exit, &mut kernel, &mut user)
  1259. .context("GetProcessTimes")?;
  1260. }
  1261. Ok(((create.dwHighDateTime as i64) << 32) | (create.dwLowDateTime as i64))
  1262. }
  1263. fn unix_now() -> i64 {
  1264. SystemTime::now()
  1265. .duration_since(UNIX_EPOCH)
  1266. .map(|d| d.as_secs() as i64)
  1267. .unwrap_or(0)
  1268. }
  1269. #[cfg(test)]
  1270. mod tests {
  1271. use super::*;
  1272. #[test]
  1273. fn state_dir_rejects_empty_or_relative() {
  1274. use std::ffi::OsString;
  1275. // Unset or empty → error (var_os returns Some("") for a
  1276. // present-but-empty var, which the old code accepted).
  1277. assert!(state_dir_from_base(None, "ProgramData").is_err());
  1278. assert!(state_dir_from_base(Some(OsString::from("")), "ProgramData").is_err());
  1279. // Relative → error (would put the broker-only-stamped DB
  1280. // in CWD).
  1281. assert!(state_dir_from_base(Some(OsString::from("rel")), "ProgramData").is_err());
  1282. // Absolute → ok.
  1283. let ok = state_dir_from_base(
  1284. Some(OsString::from(r"C:\Users\u\AppData\Local")),
  1285. "ProgramData",
  1286. );
  1287. assert_eq!(
  1288. ok.unwrap(),
  1289. PathBuf::from(r"C:\Users\u\AppData\Local\sandbox-runtime")
  1290. );
  1291. }
  1292. /// Open an in-memory DB and run `f` against a `Locked` view
  1293. /// (autocommit, like production). Skips the named mutex + dir
  1294. /// stamp (those are integration-tested via the G-rows in
  1295. /// smoke-exec.ps1).
  1296. fn with_mem_db<R>(f: impl FnOnce(&mut Locked) -> R) -> R {
  1297. let conn = open_db_at(
  1298. std::path::Path::new(":memory:"),
  1299. SESSION_SCHEMA_SQL,
  1300. SESSION_SCHEMA_VERSION,
  1301. )
  1302. .unwrap();
  1303. let mut db = Locked {
  1304. conn,
  1305. holder_pid: HolderPid(std::process::id()),
  1306. };
  1307. f(&mut db)
  1308. }
  1309. /// Regression: `register_broker` uses ON CONFLICT DO UPDATE,
  1310. /// not INSERT OR REPLACE — the latter would CASCADE-delete
  1311. /// this holder's existing `ace_holders` rows on a second
  1312. /// stamp/grant.
  1313. #[test]
  1314. fn second_register_broker_keeps_existing_holds() {
  1315. with_mem_db(|db| {
  1316. db.register_broker().unwrap();
  1317. // Two holds via direct INSERT (ensure_ace needs a real
  1318. // file; the CASCADE behavior under test is pure SQL).
  1319. for p in [r"\\?\C:\a", r"\\?\C:\b"] {
  1320. db.conn
  1321. .execute(
  1322. "INSERT INTO ace_holders \
  1323. (canonical_path, kind, pid, want_mask) \
  1324. VALUES (?1, 'deny', ?2, 'denyRead')",
  1325. params![p, db.holder_pid.0 as i64],
  1326. )
  1327. .unwrap();
  1328. }
  1329. assert_eq!(db.my_ace_holds(None).unwrap().len(), 2);
  1330. // Second batch by the same holder.
  1331. db.register_broker().unwrap();
  1332. // Holds intact (would be 0 with INSERT OR REPLACE).
  1333. assert_eq!(db.my_ace_holds(None).unwrap().len(), 2);
  1334. });
  1335. }
  1336. #[test]
  1337. fn schema_applies_in_memory() {
  1338. // Session schema: bookkeeping tables only — the setup
  1339. // record lives in the MACHINE schema since the store split.
  1340. with_mem_db(|db| {
  1341. let n: i64 = db
  1342. .conn
  1343. .query_row(
  1344. "SELECT count(*) FROM sqlite_master WHERE type='table' \
  1345. AND name IN ('brokers','working_aces','ace_holders', \
  1346. 'placeholders','sandbox_user')",
  1347. [],
  1348. |r| r.get(0),
  1349. )
  1350. .unwrap();
  1351. assert_eq!(
  1352. n, 4,
  1353. "session schema: 4 bookkeeping tables, no sandbox_user"
  1354. );
  1355. });
  1356. }
  1357. #[test]
  1358. fn aliveness_self_is_alive() {
  1359. let ct = process_create_time(unsafe { GetCurrentProcess() }).unwrap();
  1360. assert!(is_process_alive(std::process::id(), ct));
  1361. // Same PID, wrong create time would normally be "recycled →
  1362. // dead", but we special-case ourselves.
  1363. assert!(is_process_alive(std::process::id(), ct + 1));
  1364. }
  1365. #[test]
  1366. fn aliveness_bogus_pid_is_dead() {
  1367. // PID 0x7FFF_FFFE is well above any plausible live PID.
  1368. assert!(!is_process_alive(0x7FFF_FFFE, 0));
  1369. }
  1370. }