cli.rs 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809
  1. //! `srt-win` CLI dispatch — exposed as a library entry point so an
  2. //! embedding multicall binary can link the crate and route to it when
  3. //! `argv[1] == `[`SRT_WIN_DISPATCH_ARG1`] instead of shipping a
  4. //! separate `srt-win.exe`. Dispatch keys on `argv[1]`, not `argv[0]`:
  5. //! Windows cannot preserve a spoofed `argv[0]` across
  6. //! `CreateProcessWithLogonW` / `ShellExecuteExW(runas)`, so a
  7. //! Unix-style multicall-on-argv0 would lose the route on every
  8. //! internal re-spawn. The standalone binary (`main.rs`) is a
  9. //! one-line shim over [`run_from_args`].
  10. //!
  11. //! Subcommands:
  12. //! install | uninstall — provision/remove the
  13. //! `srt-sandbox` user account +
  14. //! user-SID-keyed WFP filters
  15. //! (one UAC prompt)
  16. //! status — combined `{user, wfp}` JSON
  17. //! user status | read-cred | trust-ca — inspect the sandbox user
  18. //! wfp status | verify | uninstall — inspect/probe/remove WFP filters
  19. //! acl stamp | grant | restore | revoke | recover
  20. //! — additive sandbox-user ACEs
  21. //! exec -- <target> [args...] — spawn under the two-hop
  22. //! sandbox-user lockdown
  23. //!
  24. //! `status` subcommands write one line of JSON to stdout and exit 0.
  25. //! Mutating subcommands require elevation and write human-readable
  26. //! progress to stderr. `exec` propagates the child's exit code.
  27. //!
  28. //! Several arms call `std::process::exit` directly (exec's child
  29. //! propagation, install's structured exit codes, self-elevate's
  30. //! cancel path). [`run_from_args`] therefore returns the exit code
  31. //! only for the fall-through (`Ok` → 0, `Err` → 1) cases; an
  32. //! embedder must be prepared for the process to exit from inside the
  33. //! dispatch.
  34. // Re-alias so paths from this file's prior life as the [[bin]]
  35. // crate root (`srt_win::…`) keep resolving now that it's a lib
  36. // module.
  37. use crate as srt_win;
  38. use clap::{Parser, Subcommand};
  39. use std::ffi::OsString;
  40. /// `argv[1]` sentinel an embedding multicall binary's dispatcher
  41. /// matches against to route into [`run_from_args`]. The two internal
  42. /// re-spawn sites (`logon::spawn_runner`, [`maybe_self_elevate`])
  43. /// always emit it, so the dispatch survives the
  44. /// `CreateProcessWithLogonW` runner hop and the
  45. /// `ShellExecuteExW(runas)` elevation hop — neither of which can
  46. /// preserve a spoofed `argv[0]` on Windows. [`run_from_args`] strips
  47. /// it before clap, so the standalone binary accepts it harmlessly.
  48. pub const SRT_WIN_DISPATCH_ARG1: &str = "--srt-win";
  49. /// Library entry point for the `srt-win` CLI. Parses `args` (with
  50. /// `args[0]` as the binary name, same convention as
  51. /// `std::env::args_os()`), runs the matching subcommand, and returns
  52. /// the process exit code for the fall-through paths. See the module
  53. /// doc for the arms that `process::exit` directly.
  54. ///
  55. /// `--help` / `--version` / parse errors print to the appropriate
  56. /// stream and `process::exit` (clap's `parse_from` behaviour).
  57. ///
  58. /// **Multicall dispatch.** An embedder's `main()` checks
  59. /// `argv[1] == SRT_WIN_DISPATCH_ARG1` and on match calls
  60. /// `run_from_args(argv)` with the FULL argv (sentinel included);
  61. /// `run_from_args` strips the sentinel before clap. The sentinel
  62. /// survives every internal re-spawn — both `logon::spawn_runner`
  63. /// (the runtime `exec` / `wfp verify` / `user trust-ca` hop) and
  64. /// [`maybe_self_elevate`] (the `install` / `uninstall` /
  65. /// `wfp uninstall` UAC hop) emit it as the first parameter, and the
  66. /// child binary is always `current_exe()` — so the embedder's
  67. /// dispatcher routes back into `srt-win` regardless of what
  68. /// `argv[0]` the OS sets.
  69. pub fn run_from_args<I, T>(args: I) -> i32
  70. where
  71. I: IntoIterator<Item = T>,
  72. T: Into<OsString>,
  73. {
  74. let mut args: Vec<OsString> = args.into_iter().map(Into::into).collect();
  75. if args.get(1).map(OsString::as_os_str) == Some(SRT_WIN_DISPATCH_ARG1.as_ref()) {
  76. args.remove(1);
  77. }
  78. match run(Cli::parse_from(&args), &args) {
  79. Ok(()) => 0,
  80. Err(e) => {
  81. eprintln!("srt-win: error: {e:#}");
  82. 1
  83. }
  84. }
  85. }
  86. #[derive(Parser)]
  87. #[command(name = "srt-win", version, about)]
  88. struct Cli {
  89. #[command(subcommand)]
  90. cmd: Cmd,
  91. }
  92. #[derive(Subcommand)]
  93. enum Cmd {
  94. /// Provision the dedicated `srt-sandbox` user account + the
  95. /// user-SID-keyed WFP filter set in one elevated step.
  96. ///
  97. /// Self-elevates via UAC if not already running as admin (one
  98. /// prompt; the elevated child does the work and the parent
  99. /// relays its exit code). Idempotent — re-running rotates the
  100. /// sandbox user's password and refreshes the WFP filters.
  101. ///
  102. /// Exit codes:
  103. /// 0 — installed (or already installed with the same
  104. /// port-range; no changes)
  105. /// 10 — UAC prompt cancelled by the user
  106. /// 12 — WFP filter install failed
  107. /// 13 — already installed under this sublayer with a
  108. /// DIFFERENT port-range or sandbox-user name; pass
  109. /// `--force` to replace
  110. /// 14 — sandbox user provisioning failed
  111. /// 1 — other error (parse, elevation check, etc.)
  112. Install {
  113. /// Sublayer GUID (default: compile-time constant).
  114. #[arg(long)]
  115. sublayer_guid: Option<String>,
  116. /// Loopback port range (`LOW-HIGH`, default 60080-60089).
  117. #[arg(long, value_name = "LOW-HIGH")]
  118. proxy_port_range: Option<String>,
  119. /// Name for the sandbox user account. Default:
  120. /// `srt-sandbox`. srt-win only manages an account it
  121. /// created — a name that already resolves to a principal
  122. /// srt-win didn't provision is refused (exit 14).
  123. #[arg(long)]
  124. sandbox_user: Option<String>,
  125. /// Replace an existing install whose port-range or
  126. /// sandbox-user name differs (otherwise exits 13).
  127. #[arg(long)]
  128. force: bool,
  129. },
  130. /// Remove the srt-win WFP filters under the sublayer and the
  131. /// `srt-sandbox` account, its credential file, and the setup
  132. /// marker (unless `--keep-user`). Self-elevates via UAC if not
  133. /// already admin. Best-effort also removes the legacy
  134. /// `sandbox-runtime-net` discriminator group if a prior install
  135. /// left it behind.
  136. Uninstall {
  137. #[arg(long)]
  138. sublayer_guid: Option<String>,
  139. /// Keep the `srt-sandbox` account, its credential file,
  140. /// and the setup marker. Without this flag they are all
  141. /// removed (the credential is useless without the
  142. /// account and vice versa, so they're treated as one
  143. /// unit).
  144. #[arg(long)]
  145. keep_user: bool,
  146. },
  147. /// Print `{user: <user-status>, wfp: <wfp-status>}` as one line
  148. /// of JSON — the same objects `user status` and `wfp status`
  149. /// emit, in a single spawn. The host's readiness check calls
  150. /// this instead of two separate subprocesses. Exit 0.
  151. Status {
  152. #[arg(long)]
  153. sublayer_guid: Option<String>,
  154. },
  155. /// Inspect the sandbox user account that `srt-win install`
  156. /// provisions (and that the sandboxed child runs as).
  157. User {
  158. #[command(subcommand)]
  159. sub: UserCmd,
  160. },
  161. /// Inspect/remove the persistent WFP filters.
  162. Wfp {
  163. #[command(subcommand)]
  164. sub: WfpCmd,
  165. },
  166. /// Add/remove explicit ACEs for the sandbox user on file paths
  167. /// so the sandboxed child can (`grant`) or cannot (`stamp`)
  168. /// read/write them. State is persisted in the shared state
  169. /// per-user session DB so concurrent brokers refcount
  170. /// and a crash mid-session is recoverable by the next `acl`
  171. /// op.
  172. Acl {
  173. #[command(subcommand)]
  174. sub: AclCmd,
  175. },
  176. /// Spawn a process inside the sandbox.
  177. ///
  178. /// Two-hop launch: this process (the broker, real user) reads
  179. /// the credential then `CreateProcessWithLogonW`s `srt-win
  180. /// runner` under the `srt-sandbox` account. The runner builds a
  181. /// restricted token (LUA, Admins flipped deny-only, Medium IL,
  182. /// all privs stripped except SeChangeNotify), self-protects,
  183. /// assigns the child to a kill-on-close job with full UI
  184. /// lockdown, places it on a non-interactive desktop, applies
  185. /// process-mitigation policies + an explicit handle whitelist,
  186. /// and waits for it to exit. Propagates the child's exit code.
  187. ///
  188. /// The child inherits the runner's environment (= the sandbox
  189. /// user's `LOGON_WITH_PROFILE` defaults) with the `--env` overlay
  190. /// applied — proxy configuration is single-sourced by the caller
  191. /// (TS `generateProxyEnvVars`) and passed here via `--env`.
  192. ///
  193. /// Requires `srt-win install` to have provisioned the user;
  194. /// otherwise exits **15**.
  195. Exec {
  196. /// Per-exec read-deny: add an additive `(D;OICI;FA;;;<sb>)`
  197. /// ACE for the sandbox user on `<PATH>` (and a parent
  198. /// `FILE_DELETE_CHILD` DENY) for the lifetime of this exec
  199. /// — under THIS process's PID as holder, released after the
  200. /// child exits. Repeatable. Same chokepoint as `acl stamp`;
  201. /// fails the exec if any path cannot be stamped (per-exec
  202. /// is "deny THIS one command", so a missing path is a
  203. /// caller error, not a skip).
  204. #[arg(long = "deny-read")]
  205. deny_read: Vec<String>,
  206. /// Per-exec write-deny — see `--deny-read`.
  207. #[arg(long = "deny-write")]
  208. deny_write: Vec<String>,
  209. /// `KEY=VALUE` pair overlaid on the sandbox-user runner's
  210. /// profile environment when building the child's env block.
  211. /// Repeatable. The broker forwards exactly these — it does
  212. /// NOT enumerate its own environment for proxy/CA vars; the
  213. /// caller (whose `generateProxyEnvVars` is the single
  214. /// source) passes them here explicitly.
  215. #[arg(long = "env", value_name = "KEY=VALUE")]
  216. env: Vec<String>,
  217. /// Suppress informational stderr (progress lines,
  218. /// per-exec-deny summary, seclogon-job note). Actual
  219. /// errors still print. The host sets this by default so
  220. /// the sandboxed child's stderr is not polluted with
  221. /// broker chatter.
  222. #[arg(long)]
  223. quiet: bool,
  224. /// Target executable followed by its arguments. Use `--`
  225. /// to terminate srt-win's own option parsing.
  226. #[arg(
  227. trailing_var_arg = true,
  228. allow_hyphen_values = true,
  229. required = true,
  230. num_args = 1..,
  231. )]
  232. target: Vec<String>,
  233. },
  234. /// Inside-the-logon half of `exec`. Reads a length-prefixed
  235. /// `RunnerCmd` from stdin and dispatches as the current user —
  236. /// which, when launched by the broker via
  237. /// `CreateProcessWithLogonW`, is `srt-sandbox`. Not intended to
  238. /// be invoked directly.
  239. #[command(hide = true)]
  240. Runner,
  241. }
  242. #[derive(Subcommand)]
  243. enum UserCmd {
  244. /// Print the sandbox user's provisioning state as JSON:
  245. /// `{user: {exists, sid?, group_exists, group_sid?,
  246. /// in_builtin_users, in_sandbox_group, hidden_from_logon},
  247. /// cred_present, marker_version?, marker_user_sid?,
  248. /// ca_cert_thumb?, ca_cert_pem?}`.
  249. Status,
  250. /// Print the sandbox user's decrypted password (and only the
  251. /// password) to stdout. The broker uses this for
  252. /// `CreateProcessWithLogonW`. Fails when run as the sandbox
  253. /// user itself — the state-DB directory carries an explicit
  254. /// DENY for `sandbox-runtime-users`, and machine-scope DPAPI
  255. /// is **not** a confidentiality boundary without that DENY.
  256. ReadCred,
  257. /// Install (or replace) the MITM CA in the **sandbox user's**
  258. /// `CurrentUser\Root` and record it in the state DB. The cert
  259. /// has a separate lifecycle from `srt-win install` — install
  260. /// provisions the account/filters and never touches the CA;
  261. /// this is the only command that sets it. Does NOT require
  262. /// elevation. Persistent until `srt-win uninstall`.
  263. TrustCa {
  264. /// PEM- or DER-encoded CA certificate file.
  265. #[arg(value_name = "PATH")]
  266. path: String,
  267. },
  268. }
  269. #[derive(Subcommand)]
  270. enum AclCmd {
  271. /// Read `{denyRead:[…], denyWrite:[…]}` from stdin and add an
  272. /// additive `(D;OICI;mask;;;<sid>)` ACE for the sandbox user on
  273. /// each target plus a `(D;OICI;FILE_DELETE_CHILD;;;<sid>)` on
  274. /// the parent — NO PROTECTED rewrite, no SD snapshot.
  275. /// Refcounted per holder; `acl restore` removes the ACE when
  276. /// the last holder releases. Globs are rejected; directory
  277. /// targets get an `(OI)(CI)` inheriting ACE covering the
  278. /// subtree.
  279. Stamp {
  280. /// PID of the LONG-LIVED process that owns these ACEs —
  281. /// normally the Node host (sandbox-runtime), which calls
  282. /// `acl stamp` at initialize() and `acl restore` at reset()
  283. /// from a SEPARATE short-lived `srt-win` process. The ACE
  284. /// persists until this PID exits or restores. Required:
  285. /// the `srt-win acl` process exits immediately, so keying
  286. /// on its own PID would orphan the ACE instantly.
  287. #[arg(long)]
  288. holder_pid: u32,
  289. /// SID to deny — the dedicated sandbox user
  290. /// (`srt-win user status` → `marker_user_sid`).
  291. #[arg(long)]
  292. sandbox_user_sid: String,
  293. },
  294. /// Read `{read:[…], write:[…]}` from stdin and add an
  295. /// inheritable `(OI)(CI)` ALLOW ACE for `--sandbox-user-sid` on
  296. /// each path (`FILE_GENERIC_READ|EXECUTE` for `read`,
  297. /// `MODIFY_NO_FDC` for `write`). Additive — the path's
  298. /// existing DACL and inheritance are untouched. Refcounted per
  299. /// holder; `acl revoke` removes the ACE when the last holder
  300. /// releases.
  301. Grant {
  302. /// Holder PID (see `acl stamp`).
  303. #[arg(long)]
  304. holder_pid: u32,
  305. /// SID to grant — the dedicated sandbox user
  306. /// (`srt-win user status` → `marker_user_sid`).
  307. #[arg(long)]
  308. sandbox_user_sid: String,
  309. },
  310. /// Drop the holder's claim on every granted path; remove the
  311. /// sandbox-user ACE on any path whose refcount falls to zero.
  312. Revoke {
  313. #[arg(long)]
  314. holder_pid: u32,
  315. #[arg(long)]
  316. sandbox_user_sid: String,
  317. #[arg(long)]
  318. json: bool,
  319. },
  320. /// Drop the holder's claim on every DENY ACE it stamped;
  321. /// remove the sandbox-user ACE on any path whose refcount falls
  322. /// to zero.
  323. Restore {
  324. /// Holder PID whose stamps to release (see `acl stamp`).
  325. /// Must match the value passed at stamp time.
  326. #[arg(long)]
  327. holder_pid: u32,
  328. /// The sandbox user's SID — must match `acl stamp`.
  329. #[arg(long)]
  330. sandbox_user_sid: String,
  331. /// Emit a single JSON array of per-path
  332. /// `{path, status}` objects on stdout (exit 0 always); the
  333. /// host raises any error AFTER reading the array. Without
  334. /// this flag, the existing human-readable summary goes to
  335. /// stderr.
  336. #[arg(long)]
  337. json: bool,
  338. },
  339. /// Run crash-recovery only: prune dead holders, drop any
  340. /// orphaned sandbox-user ACEs.
  341. Recover {
  342. #[arg(long)]
  343. force: bool,
  344. /// Emit `{"deadBrokers": N, "acesRevoked": N}` on stdout.
  345. /// (Not the per-path array — recover sweeps by trustee SID
  346. /// and does not enumerate paths.)
  347. #[arg(long)]
  348. json: bool,
  349. },
  350. }
  351. #[derive(serde::Deserialize, Default)]
  352. #[serde(rename_all = "camelCase")]
  353. struct AclStampInput {
  354. #[serde(default)]
  355. deny_read: Vec<String>,
  356. #[serde(default)]
  357. deny_write: Vec<String>,
  358. }
  359. #[derive(serde::Deserialize, Default)]
  360. struct AclGrantInput {
  361. #[serde(default)]
  362. read: Vec<String>,
  363. #[serde(default)]
  364. write: Vec<String>,
  365. }
  366. /// One per-path entry of `acl revoke --json` / `acl restore
  367. /// --json`.
  368. #[derive(serde::Serialize)]
  369. struct AceReleaseEntry {
  370. path: String,
  371. status: &'static str,
  372. }
  373. /// Output of [`canonicalize_ace_targets`].
  374. struct AceTargets {
  375. /// `(canonical_path, ace)` to hand to `apply_aces`.
  376. targets: Vec<(String, srt_win::acl::SbAce)>,
  377. /// Inputs that could not be canonicalized (soft-skip → exit 2).
  378. bad_inputs: Vec<(String, String)>,
  379. }
  380. /// Canonicalize `(paths, ace)` pairs for `acl grant`/`acl stamp`
  381. /// (additive sandbox-user ACE). Per-path canonicalize failure is
  382. /// soft (skipped, exit 2); a glob is a HARD error. Directory
  383. /// targets are accepted (the inheritable ACE covers the subtree;
  384. /// stamping a root is allowed because the additive ACE on `C:\` is
  385. /// wide but not destructive — the user can remove it).
  386. ///
  387. /// A `Deny` target that does not exist is materialized via
  388. /// [`create_placeholder_chain`] (trailing `\`/`/` ⇒ directory
  389. /// leaf). The leaf gets the input's full deny mask; placeholder
  390. /// INTERMEDIATES — this call's and, via
  391. /// [`placeholder_ancestors_of`], any earlier holder's — get
  392. /// [`SbAce::DenyDelete`], so every holder holds the FULL chain and
  393. /// releasing any one holder cannot strip an intermediate another
  394. /// holder still depends on.
  395. ///
  396. /// A `Deny` target the broker cannot create (`PermissionDenied` —
  397. /// e.g. under `Program Files` non-elevated) or that names a UNC
  398. /// path is soft-DROPPED, not `bad_inputs`: the sandbox user
  399. /// cannot create there either. Approximation — an asymmetric ACL
  400. /// that grants the sandbox account create where the real user is
  401. /// denied is possible but rare. A `Grant` on a missing path stays
  402. /// a soft-skip (nothing to grant on).
  403. ///
  404. /// Runs under `with_init_lock` so placeholder creation, its DB
  405. /// record, and the ancestor-discovery query are all serialized
  406. /// with `apply_aces`.
  407. ///
  408. /// [`create_placeholder_chain`]: srt_win::path_id::create_placeholder_chain
  409. /// [`placeholder_ancestors_of`]: srt_win::state_db::Locked::placeholder_ancestors_of
  410. /// [`SbAce::DenyDelete`]: srt_win::acl::SbAce::DenyDelete
  411. fn canonicalize_ace_targets(
  412. db: &srt_win::state_db::Locked,
  413. label: &str,
  414. inputs: &[(&[String], srt_win::acl::SbAce)],
  415. ) -> anyhow::Result<AceTargets> {
  416. use anyhow::anyhow;
  417. use srt_win::acl::SbAce;
  418. use srt_win::path_id::{
  419. CanonError, canonicalize_path, create_placeholder_chain, is_unc_path, strip_extended_prefix,
  420. };
  421. use std::io::ErrorKind;
  422. let mut targets = Vec::new();
  423. let mut bad_inputs = Vec::new();
  424. // Deepest-first so overlapping non-existent denies (`['y',
  425. // 'y\secret']`) materialize as `y/` DIR + `secret` FILE, not
  426. // `y` FILE (which would then fail `y\secret` with "ancestor is
  427. // a FILE"). Strip any `\\?\` prefix and normalize `/`→`\`
  428. // before counting so `\\?\C:\y` and `C:/y` depth-compare
  429. // correctly, and trim a trailing separator so it doesn't skew
  430. // the sort.
  431. let mut flat: Vec<(&String, SbAce)> = inputs
  432. .iter()
  433. .flat_map(|(list, ace)| list.iter().map(move |p| (p, *ace)))
  434. .collect();
  435. flat.sort_by_cached_key(|(p, _)| {
  436. std::cmp::Reverse(
  437. strip_extended_prefix(p)
  438. .trim_end_matches(['\\', '/'])
  439. .bytes()
  440. .filter(|b| *b == b'\\' || *b == b'/')
  441. .count(),
  442. )
  443. });
  444. for (p, ace) in flat {
  445. let canon = match canonicalize_path(p) {
  446. Ok((c, _is_dir)) => c,
  447. Err(CanonError::Glob) => {
  448. return Err(anyhow!(
  449. "Windows fs {label} requires explicit file \
  450. or directory paths; got glob '{p}'."
  451. ));
  452. }
  453. Err(CanonError::NotFound(_)) if matches!(ace, SbAce::Deny(_)) => {
  454. if is_unc_path(p) {
  455. eprintln!(
  456. "srt-win: deny target '{p}' is a UNC path \
  457. and does not exist; dropping — the local \
  458. ACL model does not cover SMB shares"
  459. );
  460. continue;
  461. }
  462. let leaf_is_dir = p.ends_with(['\\', '/']);
  463. match create_placeholder_chain(p, leaf_is_dir, |c| db.record_placeholder(c)) {
  464. Ok((leaf_canon, chain)) => {
  465. if !chain.is_empty() {
  466. eprintln!(
  467. "srt-win: deny target '{p}' does \
  468. not exist; created {} placeholder \
  469. component(s) and stamping the chain",
  470. chain.len(),
  471. );
  472. }
  473. leaf_canon
  474. }
  475. Err(e) => {
  476. // Soft-drop per the doc above (NotFound =
  477. // unwind removed a half-built chain); any
  478. // other kind fails loudly via bad_inputs.
  479. let io_kind = e
  480. .root_cause()
  481. .downcast_ref::<std::io::Error>()
  482. .map(|io| io.kind());
  483. if matches!(
  484. io_kind,
  485. Some(ErrorKind::PermissionDenied | ErrorKind::NotFound)
  486. ) {
  487. eprintln!(
  488. "srt-win: cannot create placeholder \
  489. for deny target '{p}' ({e:#}); \
  490. dropping — the sandbox cannot \
  491. create there either"
  492. );
  493. } else {
  494. bad_inputs.push((p.clone(), format!("{e:#}")));
  495. }
  496. continue;
  497. }
  498. }
  499. }
  500. Err(CanonError::NotFound(e) | CanonError::Other(e)) => {
  501. bad_inputs.push((p.clone(), format!("{e:#}")));
  502. continue;
  503. }
  504. };
  505. targets.push((canon.clone(), ace));
  506. // Full-chain hold (see doc). Duplicates across inputs are
  507. // harmless — `apply_aces` is idempotent per
  508. // `(path, kind, holder)`.
  509. if matches!(ace, SbAce::Deny(_)) {
  510. for anc in db.placeholder_ancestors_of(&canon)? {
  511. targets.push((anc, SbAce::DenyDelete));
  512. }
  513. }
  514. }
  515. Ok(AceTargets {
  516. targets,
  517. bad_inputs,
  518. })
  519. }
  520. /// Build the `user status` JSON object (sandbox-user provisioning
  521. /// state + credential/marker/CA rows from `state.db`). Shared by
  522. /// `user status` and the top-level combined `status`.
  523. fn user_status_json() -> anyhow::Result<serde_json::Value> {
  524. use serde_json::json;
  525. use srt_win::{install, user};
  526. let setup = install::read_setup().ok().flatten();
  527. let name = setup
  528. .as_ref()
  529. .map(|s| s.sandbox_user.as_str())
  530. .unwrap_or(user::SANDBOX_USER);
  531. let st = user::status(name)?;
  532. let ca = install::read_ca_cert()?;
  533. let ca = ca.as_ref();
  534. Ok(json!({
  535. "user": st,
  536. // The HKLM Cred\Blob value (a SYSTEM/fleet install must
  537. // read as present from any user's session).
  538. "cred_present": setup.is_some() && install::cred_present(),
  539. "marker_version": setup.as_ref().map(|s| s.marker_version),
  540. "marker_user_sid": setup.as_ref()
  541. .map(|s| s.sandbox_user_sid.as_str()),
  542. // The calling (real) user's SID — surfaced for diagnostics.
  543. "real_user_sid": srt_win::sid::current_user_sid()?,
  544. "ca_cert_thumb": ca.map(|c| c.thumb()).transpose()?,
  545. "ca_cert_pem": ca.map(|c| c.to_pem()).transpose()?,
  546. }))
  547. }
  548. /// Install-time ambient write-deny state: the recorded paths (HKLM
  549. /// `AmbientDenies` — admin-written, trustworthy) plus whether each
  550. /// deny ACE is on disk (an admin `icacls /reset` clears it;
  551. /// re-running `srt-win install` repairs). Empty when no install.
  552. fn ambient_status_json() -> anyhow::Result<serde_json::Value> {
  553. use serde_json::json;
  554. use srt_win::{acl, install};
  555. // Degrade like user_status_json: a registry read error (beyond
  556. // not-found) must not abort the whole status document.
  557. let sid = install::read_setup()
  558. .ok()
  559. .flatten()
  560. .map(|s| s.sandbox_user_sid);
  561. let mut paths = Vec::new();
  562. for p in install::ambient_recorded_paths()? {
  563. let present = match &sid {
  564. Some(sid) => acl::sandbox_deny_present(&p, sid).unwrap_or(false),
  565. None => false,
  566. };
  567. paths.push(json!({ "path": p, "present": present }));
  568. }
  569. Ok(json!({ "paths": paths }))
  570. }
  571. /// Read `path` and decode it as a single DER-encoded X.509
  572. /// certificate (PEM, base64, or raw DER input — see
  573. /// [`srt_win::cert_store::CertDer::from_pem_or_der`]). Used by
  574. /// `user trust-ca`.
  575. fn read_ca_der(path: &str) -> anyhow::Result<srt_win::cert_store::CertDer> {
  576. use anyhow::Context;
  577. srt_win::cert_store::CertDer::from_pem_or_der(
  578. &std::fs::read(path).with_context(|| format!("read CA cert '{path}'"))?,
  579. )
  580. .with_context(|| format!("decode CA cert '{path}'"))
  581. }
  582. /// Drop-guarded per-exec restore. Constructed immediately after a
  583. /// successful per-exec deny-ACE so EVERY exit path between stamp
  584. /// and `process::exit` — `?`, panic, or normal return — runs the
  585. /// matching release for `holder`. A leaked ACE is fail-closed and
  586. /// crash-recovery reaps it once `holder` is observed dead by the
  587. /// next `with_init_lock`, so `failed > 0` is logged but never
  588. /// changes the child's exit code.
  589. struct PerExecRestore {
  590. holder: srt_win::state_db::HolderPid,
  591. sandbox_sid: String,
  592. quiet: bool,
  593. }
  594. impl Drop for PerExecRestore {
  595. fn drop(&mut self) {
  596. use srt_win::state_db;
  597. let (failed, err) = match state_db::with_init_lock(self.holder, false, |db| {
  598. db.release_aces(&self.sandbox_sid, state_db::KIND_DENY)
  599. }) {
  600. Ok(((_, failed), _)) => (failed, None),
  601. Err(e) => (0, Some(e)),
  602. };
  603. // `failed > 0` is fail-closed (leftover ACEs are reaped by
  604. // the next `acl` op) so it's informational; `err` is a real
  605. // state-DB failure and prints regardless of `--quiet`.
  606. if failed > 0 && !self.quiet {
  607. eprintln!(
  608. "srt-win: WARNING: per-exec restore left {failed} \
  609. path(s) stamped (fail-closed) — see prior \
  610. per-path warnings; `acl recover` will clear \
  611. them once pid {} is dead",
  612. self.holder.0,
  613. );
  614. }
  615. if let Some(e) = err {
  616. eprintln!(
  617. "srt-win: WARNING: per-exec restore failed \
  618. ({e:#}); leftover stamps stay fail-closed and \
  619. are reaped by the next `acl` op once pid {} is \
  620. dead",
  621. self.holder.0,
  622. );
  623. }
  624. }
  625. }
  626. #[derive(Subcommand)]
  627. enum WfpCmd {
  628. /// Print WFP fence state as JSON: `{state, filters,
  629. /// port_range?, user_sid?, hint?}`. BFE's
  630. /// `FwpmFilterCreateEnumHandle0` is admin-gated, so a
  631. /// non-elevated caller gets `{state:"cannot-read", hint:…}`
  632. /// (exit 0). The non-elevated readiness check is `wfp verify`.
  633. Status {
  634. #[arg(long)]
  635. sublayer_guid: Option<String>,
  636. },
  637. /// Behavioral egress-block probe — the non-elevated readiness
  638. /// check for the WFP fence. Spawns the runner as `srt-sandbox`
  639. /// (via `CreateProcessWithLogonW`) which attempts a direct TCP
  640. /// connect to `target`.
  641. ///
  642. /// Prints `{"egress_probe":"blocked"|"connected"|"unreachable",
  643. /// "target":…}` and exits **0** (blocked = fence active),
  644. /// **3** (connected = fence MISSING), **2** (unreachable =
  645. /// timeout/no-route; treat as failure), or **15** when the
  646. /// sandbox user is not provisioned. Any other code (including
  647. /// 1, the runner's own anyhow `Err` path) maps to
  648. /// `egress_probe:"error"`. Does not require elevation. This
  649. /// is the non-elevated readiness check the host's
  650. /// `initialize()` runs; `wfp status` is the elevated
  651. /// ground-truth enum.
  652. Verify {
  653. /// Probe target (`host:port`). The host binds a local
  654. /// listener on an ephemeral loopback port OUTSIDE the WFP
  655. /// loopback-permit range and passes it here, so the
  656. /// fence-inactive case is deterministic without depending
  657. /// on any external host.
  658. #[arg(long)]
  659. target: String,
  660. },
  661. /// Remove every srt-win-tagged WFP filter under the sublayer.
  662. /// Self-elevates via UAC if not already admin.
  663. Uninstall {
  664. #[arg(long)]
  665. sublayer_guid: Option<String>,
  666. },
  667. }
  668. fn run(cli: Cli, args: &[OsString]) -> anyhow::Result<()> {
  669. use anyhow::{Context, anyhow};
  670. use serde_json::json;
  671. use srt_win::wfp;
  672. let resolve_sublayer = |s: &Option<String>| -> anyhow::Result<windows::core::GUID> {
  673. match s {
  674. Some(g) => wfp::parse_guid(g),
  675. None => Ok(wfp::DEFAULT_SUBLAYER_GUID),
  676. }
  677. };
  678. match cli.cmd {
  679. // ─── install / uninstall ───────────────────────────────────
  680. Cmd::Install {
  681. sublayer_guid,
  682. proxy_port_range,
  683. sandbox_user,
  684. force,
  685. } => {
  686. use srt_win::{install, user};
  687. if let Some(code) = maybe_self_elevate(args)? {
  688. std::process::exit(code);
  689. }
  690. let sl = resolve_sublayer(&sublayer_guid)?;
  691. let range = match &proxy_port_range {
  692. Some(s) => wfp::parse_port_range(s)
  693. .with_context(|| format!("invalid --proxy-port-range '{s}'"))?,
  694. None => wfp::DEFAULT_PROXY_PORT_RANGE,
  695. };
  696. let name = sandbox_user.as_deref().unwrap_or(user::SANDBOX_USER);
  697. // Idempotency / conflict pre-check. With a DIFFERENT
  698. // port-range or sandbox-user name and no --force, refuse
  699. // (exit 13) so an unintended config drift surfaces
  700. // instead of silently overwriting. With the SAME config,
  701. // only return early when the install is COMPLETE — i.e.
  702. // the sandbox user is provisioned and the marker is
  703. // current. A partial install falls through and the
  704. // (idempotent) steps below complete it. A pre-existing
  705. // install whose tags lack a port_range (legacy) is
  706. // treated as "different" and requires --force.
  707. let existing = install::read_setup().ok().flatten();
  708. // Shared by the early-out completeness check and the
  709. // stamping step below (env reads + a stat per entry).
  710. let ambient_targets = srt_win::ambient::ambient_deny_targets();
  711. let name_changed = existing.as_ref().is_some_and(|s| s.sandbox_user != name);
  712. if !force
  713. && let Ok(st) = wfp::filter_status(&sl)
  714. && st.state == "installed"
  715. {
  716. let want = [range.0, range.1];
  717. if st.port_range != Some(want) || name_changed {
  718. let have_range = st
  719. .port_range
  720. .map(|[l, h]| format!("{l}-{h}"))
  721. .unwrap_or_else(|| "<unknown>".into());
  722. let have_name = existing
  723. .as_ref()
  724. .map(|s| s.sandbox_user.as_str())
  725. .unwrap_or("<none>");
  726. eprintln!(
  727. "srt-win: error: already installed under \
  728. sublayer {sl:?} with port_range={have_range}, \
  729. sandbox_user='{have_name}'; requested \
  730. port_range={}-{}, sandbox_user='{name}'. \
  731. Pass --force to replace, or run `srt-win \
  732. uninstall` first.",
  733. range.0, range.1,
  734. );
  735. std::process::exit(13);
  736. }
  737. // Same config — early-out only if COMPLETE. The
  738. // ambient half is part of completeness (an install
  739. // that failed between the setup marker and the
  740. // stamps must fall through and finish; a drifted
  741. // ACE makes re-running install the repair), and is
  742. // checked last: it reads a DACL per target, so it
  743. // only runs once the cheap conjuncts pass.
  744. let us = user::status(name)?;
  745. let mv = existing.as_ref().map(|s| s.marker_version);
  746. let ambient_ok = || match &existing {
  747. Some(s) => install::ambient_complete(&s.sandbox_user_sid, &ambient_targets),
  748. None => false,
  749. };
  750. // The credential is part of completeness: a
  751. // missing/undecryptable Cred\Blob with a healthy
  752. // marker must fall through and be rewritten rather
  753. // than early-outing on "already installed".
  754. if us.exists
  755. && us.in_sandbox_group
  756. && mv == Some(install::SETUP_VERSION)
  757. && install::cred_present()
  758. && ambient_ok()
  759. {
  760. // Re-assert the logon-type denials BEFORE the
  761. // early-out: they must reach installs from
  762. // binaries that predate them, and a domain GPO
  763. // refresh can strip local LSA user-right
  764. // assignments between runs. Idempotent and
  765. // cheap; a failure falls through to the full
  766. // (also idempotent) install steps.
  767. if let Some(gsid) = us.group_sid.as_deref() {
  768. if let Err(e) = user::apply_logon_denials(gsid) {
  769. eprintln!(
  770. "srt-win: warning: re-asserting logon denials: {e:#} — completing full install",
  771. );
  772. } else {
  773. eprintln!(
  774. "srt-win: already installed (sublayer={sl:?}, \
  775. port_range={}-{}, sandbox_user='{name}', \
  776. filters={}); no changes",
  777. range.0, range.1, st.filters,
  778. );
  779. return Ok(());
  780. }
  781. }
  782. }
  783. eprintln!(
  784. "srt-win: partial install detected \
  785. (user_provisioned={}, marker_version={:?}) — \
  786. completing",
  787. us.exists, mv,
  788. );
  789. // Fall through; the steps are idempotent.
  790. }
  791. // With --force and a changed name, do NOT delete the
  792. // prior account — it may be enterprise-managed. The old
  793. // WFP filters are replaced (they key on the new SID);
  794. // write_setup_info clears the old row. The account
  795. // itself is left for the operator.
  796. if force && name_changed {
  797. let old = &existing.as_ref().unwrap().sandbox_user;
  798. eprintln!(
  799. "srt-win: WARNING: replacing install with \
  800. sandbox_user='{old}' → '{name}'. The prior \
  801. '{old}' account is NOT deleted (may be \
  802. enterprise-managed) — remove it manually if \
  803. unused.",
  804. );
  805. }
  806. // Sandbox user account + credential file + setup marker
  807. // + user-SID-keyed WFP filters. `we_own_it` gates
  808. // provision()'s create-or-rotate: the DEFAULT name is
  809. // ours by definition (so a stale/absent marker — e.g.
  810. // schema-upgrade re-install — still rotates); an
  811. // EXPLICIT `--sandbox-user` is create-only unless the
  812. // marker records that name from a prior install.
  813. let we_own_it =
  814. sandbox_user.is_none() || existing.as_ref().is_some_and(|s| s.sandbox_user == name);
  815. let pu = match (|| -> anyhow::Result<srt_win::user::ProvisionedUser> {
  816. let pu = user::provision(name, we_own_it).context("provision sandbox user")?;
  817. // Machine store BEFORE write_setup: the dir must
  818. // exist with its install-owned ACLs before the
  819. // credential file is written into it.
  820. install::provision_machine_store(&pu.group_sid)
  821. .context("provision machine state store")?;
  822. install::write_setup(&pu)
  823. .context("write sandbox credential + setup marker to state DB")?;
  824. Ok(pu)
  825. })() {
  826. Ok(pu) => pu,
  827. Err(e) => {
  828. eprintln!("srt-win: error: sandbox user step: {e:#}");
  829. std::process::exit(14);
  830. }
  831. };
  832. // Ambient write-deny stamps: Windows' stock world-
  833. // writable system dirs (`ambient.rs`), stamped
  834. // `(D;OICI;WriteDeny)` for the sandbox SID only and
  835. // recorded in the state DB so session recomposes and
  836. // crash recovery preserve them. Idempotent; runs before
  837. // the WFP step so a failure here leaves the install
  838. // visibly partial (filters absent) rather than
  839. // marker-complete with the stamps missing.
  840. match install::set_ambient_denies(&pu.sid, &ambient_targets) {
  841. Ok(r) if r.applied.is_empty() && !r.failed.is_empty() => {
  842. // Every stamp failed — treat as a real install
  843. // failure (per-path oddities are best-effort, a
  844. // clean sweep of failures is not).
  845. eprintln!(
  846. "srt-win: error: ambient write-deny stamps: all \
  847. {} target(s) failed (see warnings above)",
  848. r.failed.len(),
  849. );
  850. std::process::exit(17);
  851. }
  852. Ok(r) => eprintln!(
  853. "srt-win: ambient write-deny stamped on {} system \
  854. path(s){}",
  855. r.applied.len(),
  856. if r.failed.is_empty() {
  857. String::new()
  858. } else {
  859. format!(
  860. " ({} failed — recorded; `srt-win status` \
  861. shows present:false)",
  862. r.failed.len(),
  863. )
  864. },
  865. ),
  866. Err(e) => {
  867. eprintln!("srt-win: error: ambient write-deny stamps: {e:#}");
  868. std::process::exit(17);
  869. }
  870. }
  871. if let Err(e) = wfp::install_filters(&sl, &pu.sid, range) {
  872. eprintln!("srt-win: error: WFP install: {e:#}");
  873. std::process::exit(12);
  874. }
  875. // Best-effort migration: a pre-v2-e install left the
  876. // legacy `sandbox-runtime-net` discriminator group.
  877. // Remove it now (idempotent on NERR_GroupNotFound).
  878. // Uninstall does the same; doing it here means the
  879. // upgrade path (re-run install) cleans up without a
  880. // separate uninstall step.
  881. let _ = srt_win::sam::delete_local_group("sandbox-runtime-net");
  882. eprintln!(
  883. "srt-win: installed (sublayer={sl:?}, \
  884. proxy_port_range={}-{}, filters={})",
  885. range.0,
  886. range.1,
  887. wfp::FILTER_COUNT,
  888. );
  889. eprintln!(
  890. "srt-win: sandbox user '{}' provisioned (sid={}, \
  891. group={} sid={})",
  892. pu.username,
  893. pu.sid,
  894. srt_win::user::SANDBOX_GROUP,
  895. pu.group_sid,
  896. );
  897. }
  898. Cmd::Uninstall {
  899. sublayer_guid,
  900. keep_user,
  901. } => {
  902. if let Some(code) = maybe_self_elevate(args)? {
  903. std::process::exit(code);
  904. }
  905. let sl = resolve_sublayer(&sublayer_guid)?;
  906. let n = wfp::uninstall_filters(&sl)?;
  907. // Read setup up front: the ambient cleanup and the
  908. // deprovision fallback both need the recorded name/SID
  909. // before clear_setup wipes them.
  910. let recorded = srt_win::install::read_setup().ok().flatten();
  911. let user_note = if keep_user {
  912. // Ambient write-deny stamps key on the ACCOUNT, not
  913. // the sublayer, and this uninstall may be tearing
  914. // down one sublayer of several (the smoke/TS suites
  915. // do exactly that) — so --keep-user keeps the
  916. // account's ambient floor along with the account.
  917. // The full (account-removing) branch below is what
  918. // takes the stamps off.
  919. "Sandbox user kept (--keep-user; ambient write-deny stamps kept with it)."
  920. } else {
  921. use srt_win::user;
  922. // Use the recorded name (may not be the default),
  923. // then deprovision BEFORE clear_setup so a failed
  924. // NetUserDel is retryable with the recorded name
  925. // still intact. No marker (partial install that
  926. // bailed before write_setup, or a stale/corrupt
  927. // state DB) → fall back to the default name so
  928. // SANDBOX_GROUP and any default-named account are
  929. // still cleaned up; deprovision is idempotent on
  930. // absent state.
  931. // Ambient write-deny stamps come off with the
  932. // account they key on. Best-effort per path: an ACL
  933. // failure on one system dir must not wedge the
  934. // uninstall; a failed removal keeps its row so
  935. // `status` surfaces it. Runs BEFORE deprovision so
  936. // the SID's ACEs are removed while the account still
  937. // resolves.
  938. if let Some(s) = &recorded {
  939. match srt_win::install::clear_ambient_denies(&s.sandbox_user_sid) {
  940. Ok(n) if n > 0 => {
  941. eprintln!("srt-win: ambient write-deny removed from {n} system path(s)",)
  942. }
  943. Ok(_) => {}
  944. Err(e) => {
  945. eprintln!("srt-win: warning: ambient write-deny cleanup: {e:#}")
  946. }
  947. }
  948. }
  949. let name = recorded
  950. .as_ref()
  951. .map(|s| s.sandbox_user.clone())
  952. .unwrap_or_else(|| user::SANDBOX_USER.into());
  953. user::deprovision(&name).context("deprovision sandbox user")?;
  954. srt_win::install::clear_setup().context("clear credential + setup marker")?;
  955. "Sandbox user, credential, and setup marker removed."
  956. };
  957. // Migration: best-effort remove the legacy
  958. // discriminator group if a prior install left it.
  959. // Idempotent on already-absent.
  960. let _ = srt_win::sam::delete_local_group("sandbox-runtime-net");
  961. eprintln!("srt-win: uninstalled ({n} filter(s) removed). {user_note}");
  962. }
  963. // ─── status (combined) ─────────────────────────────────────
  964. Cmd::Status { sublayer_guid } => {
  965. let sl = resolve_sublayer(&sublayer_guid)?;
  966. println!(
  967. "{}",
  968. json!({
  969. "user": user_status_json()?,
  970. "wfp": wfp::filter_status(&sl)?,
  971. "ambient": ambient_status_json()?,
  972. })
  973. );
  974. }
  975. // ─── user ──────────────────────────────────────────────────
  976. Cmd::User {
  977. sub: UserCmd::Status,
  978. } => {
  979. println!("{}", user_status_json()?);
  980. }
  981. Cmd::User {
  982. sub: UserCmd::ReadCred,
  983. } => {
  984. let cred = srt_win::install::read_cred()?;
  985. // Password only, no trailing whitespace, so a caller
  986. // can capture stdout verbatim.
  987. print!("{}", cred.pw);
  988. }
  989. Cmd::User {
  990. sub: UserCmd::TrustCa { path },
  991. } => {
  992. use srt_win::install;
  993. let der = read_ca_der(&path)?;
  994. let cred = install::read_cred()?;
  995. let sb_sid = install::read_setup()?
  996. .ok_or_else(|| anyhow!("sandbox user not provisioned"))?
  997. .sandbox_user_sid;
  998. install::trust_ca(&der, &cred, &sb_sid)?;
  999. eprintln!(
  1000. "srt-win: CA installed into sandbox-user Root \
  1001. (thumb={})",
  1002. der.thumb()?,
  1003. );
  1004. }
  1005. // ─── wfp ───────────────────────────────────────────────────
  1006. Cmd::Wfp {
  1007. sub: WfpCmd::Status { sublayer_guid },
  1008. } => {
  1009. let sl = resolve_sublayer(&sublayer_guid)?;
  1010. let st = wfp::filter_status(&sl)?;
  1011. println!("{}", serde_json::to_string(&st)?);
  1012. }
  1013. Cmd::Wfp {
  1014. sub: WfpCmd::Verify { target },
  1015. } => {
  1016. use srt_win::{install, logon, runner};
  1017. // The WFP BLOCK fires at ALE_AUTH_CONNECT before any
  1018. // packet leaves, so an active fence gives WSAEACCES
  1019. // (~0ms, exit 0); a MISSING fence lets the connect
  1020. // succeed (exit 3). The host passes a local loopback
  1021. // listener bound outside the WFP permit range so
  1022. // fence-missing is distinguishable from fence-active
  1023. // without depending on any external host.
  1024. let r = install::read_cred().and_then(|c| {
  1025. let s = install::read_setup()?
  1026. .ok_or_else(|| anyhow!("sandbox user not provisioned"))?;
  1027. Ok((s.sandbox_user_sid, c))
  1028. });
  1029. let (sb_sid, cred) = match r {
  1030. Ok(v) => v,
  1031. Err(e) => {
  1032. eprintln!("srt-win: error: wfp verify: {e:#}");
  1033. std::process::exit(15);
  1034. }
  1035. };
  1036. let code = logon::spawn_runner(
  1037. &cred.user,
  1038. &cred.pw,
  1039. &sb_sid,
  1040. None,
  1041. &runner::RunnerCmd::ProbeEgress {
  1042. target: target.clone(),
  1043. },
  1044. false,
  1045. )
  1046. .context("spawn runner for egress probe")?;
  1047. let probe = match code {
  1048. 0 => "blocked",
  1049. 3 => "connected",
  1050. 2 => "unreachable",
  1051. // 1 is the runner's own anyhow `Err` path
  1052. // (`main()` → `eprintln!` + `exit(1)`); anything
  1053. // else is an unmapped runner state. Neither is a
  1054. // valid probe outcome.
  1055. _ => "error",
  1056. };
  1057. println!(
  1058. "{}",
  1059. json!({
  1060. "egress_probe": probe,
  1061. "target": target,
  1062. "runner_exit": code,
  1063. })
  1064. );
  1065. // `process::exit`'s rt::cleanup flushes stdout, but be
  1066. // explicit — this is the only arm that prints to stdout
  1067. // and then `process::exit`s instead of returning Ok(()).
  1068. let _ = std::io::Write::flush(&mut std::io::stdout());
  1069. std::process::exit(code as i32);
  1070. }
  1071. Cmd::Wfp {
  1072. sub: WfpCmd::Uninstall { sublayer_guid },
  1073. } => {
  1074. if let Some(code) = maybe_self_elevate(args)? {
  1075. std::process::exit(code);
  1076. }
  1077. let sl = resolve_sublayer(&sublayer_guid)?;
  1078. let n = wfp::uninstall_filters(&sl)?;
  1079. eprintln!("srt-win: removed {n} WFP filter(s)");
  1080. }
  1081. // ─── acl ───────────────────────────────────────────────────
  1082. Cmd::Acl {
  1083. sub:
  1084. AclCmd::Stamp {
  1085. holder_pid,
  1086. sandbox_user_sid,
  1087. },
  1088. } => {
  1089. // Deny is an additive DENY ACE for the sandbox user
  1090. // (plus parent-FDC DENY) — same lifecycle as
  1091. // `acl grant`, no PROTECTED rewrite.
  1092. use srt_win::{acl, state_db};
  1093. let holder = state_db::HolderPid(holder_pid);
  1094. let mut buf = String::new();
  1095. std::io::Read::read_to_string(&mut std::io::stdin(), &mut buf).context("read stdin")?;
  1096. let input: AclStampInput = serde_json::from_str(&buf)
  1097. .context("parse stdin JSON {denyRead:[…], denyWrite:[…]}")?;
  1098. let ((at, witnesses, failed), report) =
  1099. state_db::with_init_lock(holder, false, |db| {
  1100. let at = canonicalize_ace_targets(
  1101. db,
  1102. "deny",
  1103. &[
  1104. (&input.deny_read, acl::SbAce::Deny(acl::DenyMask::ReadDeny)),
  1105. (
  1106. &input.deny_write,
  1107. acl::SbAce::Deny(acl::DenyMask::WriteDeny),
  1108. ),
  1109. ],
  1110. )?;
  1111. for (p, e) in &at.bad_inputs {
  1112. eprintln!("srt-win: skipped: '{p}': {e}");
  1113. }
  1114. let (w, f) = db.apply_aces(&sandbox_user_sid, &at.targets)?;
  1115. Ok((at, w, f))
  1116. })?;
  1117. let AceTargets {
  1118. targets,
  1119. bad_inputs,
  1120. } = at;
  1121. let fresh = witnesses.iter().filter(|w| !w.already).count();
  1122. eprintln!(
  1123. "srt-win: acl stamp (deny-ace) — {} target(s) → {} \
  1124. ACE(s) ({} fresh{}{}); recovery pruned {} dead \
  1125. broker(s), revoked {} orphan ACE(s)",
  1126. targets.len(),
  1127. witnesses.len(),
  1128. fresh,
  1129. if !bad_inputs.is_empty() {
  1130. format!(", {} skipped", bad_inputs.len())
  1131. } else {
  1132. String::new()
  1133. },
  1134. if failed > 0 {
  1135. format!(", {failed} FAILED — rolled back")
  1136. } else {
  1137. String::new()
  1138. },
  1139. report.dead_brokers,
  1140. report.aces_revoked,
  1141. );
  1142. if failed > 0 {
  1143. return Err(anyhow!(
  1144. "{failed} of {} path(s) could not be stamped; \
  1145. batch rolled back",
  1146. targets.len(),
  1147. ));
  1148. }
  1149. if !bad_inputs.is_empty() {
  1150. eprintln!(
  1151. "srt-win: {} input path(s) skipped (see above); \
  1152. exiting 2 (partial)",
  1153. bad_inputs.len()
  1154. );
  1155. std::process::exit(2);
  1156. }
  1157. }
  1158. Cmd::Acl {
  1159. sub:
  1160. AclCmd::Grant {
  1161. holder_pid,
  1162. sandbox_user_sid,
  1163. },
  1164. } => {
  1165. use srt_win::{acl, state_db};
  1166. let holder = state_db::HolderPid(holder_pid);
  1167. let mut buf = String::new();
  1168. std::io::Read::read_to_string(&mut std::io::stdin(), &mut buf).context("read stdin")?;
  1169. let input: AclGrantInput =
  1170. serde_json::from_str(&buf).context("parse stdin JSON {read:[…], write:[…]}")?;
  1171. let ((at, witnesses, failed), report) =
  1172. state_db::with_init_lock(holder, false, |db| {
  1173. let at = canonicalize_ace_targets(
  1174. db,
  1175. "grant",
  1176. &[
  1177. (&input.read, acl::SbAce::Grant(acl::GrantMask::ReadOnly)),
  1178. (&input.write, acl::SbAce::Grant(acl::GrantMask::Modify)),
  1179. ],
  1180. )?;
  1181. for (p, e) in &at.bad_inputs {
  1182. eprintln!("srt-win: skipped: '{p}': {e}");
  1183. }
  1184. let (w, f) = db.apply_aces(&sandbox_user_sid, &at.targets)?;
  1185. Ok((at, w, f))
  1186. })?;
  1187. let AceTargets {
  1188. targets,
  1189. bad_inputs,
  1190. } = at;
  1191. let fresh = witnesses.iter().filter(|w| !w.already).count();
  1192. eprintln!(
  1193. "srt-win: acl grant — {} path(s) ({} fresh, {} \
  1194. already held{}{}); recovery pruned {} dead \
  1195. broker(s), revoked {} orphan ACE(s)",
  1196. targets.len(),
  1197. fresh,
  1198. witnesses.len() - fresh,
  1199. if !bad_inputs.is_empty() {
  1200. format!(", {} skipped", bad_inputs.len())
  1201. } else {
  1202. String::new()
  1203. },
  1204. if failed > 0 {
  1205. format!(", {failed} FAILED — rolled back")
  1206. } else {
  1207. String::new()
  1208. },
  1209. report.dead_brokers,
  1210. report.aces_revoked,
  1211. );
  1212. if failed > 0 {
  1213. return Err(anyhow!(
  1214. "{failed} of {} path(s) could not be granted; \
  1215. batch rolled back",
  1216. targets.len(),
  1217. ));
  1218. }
  1219. if !bad_inputs.is_empty() {
  1220. eprintln!(
  1221. "srt-win: {} input path(s) skipped (see above); \
  1222. exiting 2 (partial)",
  1223. bad_inputs.len()
  1224. );
  1225. std::process::exit(2);
  1226. }
  1227. }
  1228. Cmd::Acl {
  1229. sub:
  1230. AclCmd::Revoke {
  1231. holder_pid,
  1232. sandbox_user_sid,
  1233. json,
  1234. },
  1235. } => {
  1236. use srt_win::state_db;
  1237. let holder = state_db::HolderPid(holder_pid);
  1238. let ((entries, failed), report) = state_db::with_init_lock(holder, false, |db| {
  1239. db.release_aces(&sandbox_user_sid, state_db::KIND_GRANT)
  1240. })?;
  1241. eprintln!(
  1242. "srt-win: acl revoke — {} path(s){}; recovery \
  1243. revoked {} orphan grant(s)",
  1244. entries.len(),
  1245. if failed > 0 {
  1246. format!(", {failed} FAILED (ACE left in place)")
  1247. } else {
  1248. String::new()
  1249. },
  1250. report.aces_revoked,
  1251. );
  1252. if json {
  1253. let out: Vec<AceReleaseEntry> = entries
  1254. .iter()
  1255. .map(|(p, r)| AceReleaseEntry {
  1256. path: p.clone(),
  1257. status: r.as_str(),
  1258. })
  1259. .collect();
  1260. serde_json::to_writer(std::io::stdout(), &out)
  1261. .context("write --json revoke result")?;
  1262. println!();
  1263. }
  1264. if failed > 0 {
  1265. return Err(anyhow!("acl revoke: {failed} path(s) could not be revoked"));
  1266. }
  1267. }
  1268. Cmd::Acl {
  1269. sub:
  1270. AclCmd::Restore {
  1271. holder_pid,
  1272. sandbox_user_sid,
  1273. json,
  1274. },
  1275. } => {
  1276. // Restore = release the holder's DENY ACEs (target +
  1277. // parent-FDC) via walk-and-filter.
  1278. use srt_win::state_db;
  1279. let holder = state_db::HolderPid(holder_pid);
  1280. let ((entries, failed), report) = state_db::with_init_lock(holder, false, |db| {
  1281. db.release_aces(&sandbox_user_sid, state_db::KIND_DENY)
  1282. })?;
  1283. eprintln!(
  1284. "srt-win: acl restore (deny-ace) — {} ACE(s){}; \
  1285. recovery revoked {} orphan ACE(s)",
  1286. entries.len(),
  1287. if failed > 0 {
  1288. format!(", {failed} FAILED (ACE left in place)")
  1289. } else {
  1290. String::new()
  1291. },
  1292. report.aces_revoked,
  1293. );
  1294. if json {
  1295. let out: Vec<AceReleaseEntry> = entries
  1296. .iter()
  1297. .map(|(p, r)| AceReleaseEntry {
  1298. path: p.clone(),
  1299. status: r.as_str(),
  1300. })
  1301. .collect();
  1302. serde_json::to_writer(std::io::stdout(), &out)
  1303. .context("write --json restore result")?;
  1304. println!();
  1305. }
  1306. if failed > 0 {
  1307. return Err(anyhow!(
  1308. "acl restore: {failed} path(s) could not be \
  1309. restored (ACE left, fail-closed)"
  1310. ));
  1311. }
  1312. }
  1313. Cmd::Acl {
  1314. sub: AclCmd::Recover { force, json },
  1315. } => {
  1316. use srt_win::state_db;
  1317. // recover only runs crash-recovery (holder-agnostic);
  1318. // the holder PID is irrelevant, pass our own.
  1319. let ((), report) =
  1320. state_db::with_init_lock(state_db::HolderPid(std::process::id()), force, |_db| {
  1321. Ok(())
  1322. })?;
  1323. eprintln!(
  1324. "srt-win: acl recover — pruned {} dead broker(s), \
  1325. revoked {} orphan ACE(s)",
  1326. report.dead_brokers, report.aces_revoked,
  1327. );
  1328. if json {
  1329. println!(
  1330. "{}",
  1331. json!({
  1332. "deadBrokers": report.dead_brokers,
  1333. "acesRevoked": report.aces_revoked,
  1334. })
  1335. );
  1336. }
  1337. }
  1338. // ─── runner ────────────────────────────────────────────────
  1339. Cmd::Runner => {
  1340. let code = srt_win::runner::run()?;
  1341. std::process::exit(code as i32);
  1342. }
  1343. // ─── exec ──────────────────────────────────────────────────
  1344. Cmd::Exec {
  1345. deny_read,
  1346. deny_write,
  1347. env,
  1348. quiet,
  1349. target,
  1350. } => {
  1351. use srt_win::install;
  1352. // Credential + setup read happens FIRST so the
  1353. // exit-15 fast-fail (not provisioned / stale cred)
  1354. // fires before any WFP/ACL work.
  1355. let (cred, sb_sid) = match install::read_cred().and_then(|c| {
  1356. let s = install::read_setup()?
  1357. .ok_or_else(|| anyhow!("sandbox user not provisioned"))?;
  1358. Ok((c, s.sandbox_user_sid))
  1359. }) {
  1360. Ok(v) => v,
  1361. Err(e) => {
  1362. eprintln!(
  1363. "srt-win: error: sandbox user not \
  1364. provisioned ({e:#}). Run `srt-win install` \
  1365. (one UAC prompt)."
  1366. );
  1367. std::process::exit(15);
  1368. }
  1369. };
  1370. // Share-lock current_exe() so a sandboxed child can't
  1371. // rename/overwrite the broker binary mid-exec — see
  1372. // `self_protect::share_lock_current_exe` for the threat
  1373. // model. Acquired BEFORE per-exec stamps: held for the
  1374. // duration of the stamp attempt; on stamp failure the
  1375. // child never launches so lock release on unwind is
  1376. // moot. Warn-and-continue: defense-in-depth must not
  1377. // DoS the primary path when a third-party opener
  1378. // (AV/indexer/updater) holds DELETE access. `--quiet`
  1379. // gates the warning — that failure mode is a persistent
  1380. // per-machine condition that would otherwise print on
  1381. // every exec.
  1382. let _exe_lock = srt_win::self_protect::share_lock_current_exe()
  1383. .inspect_err(|e| {
  1384. if !quiet {
  1385. eprintln!(
  1386. "srt-win: WARNING: share-lock current_exe: \
  1387. {e:#} (proceeding; defense-in-depth only)"
  1388. )
  1389. }
  1390. })
  1391. .ok();
  1392. // No WFP pre-flight here: BFE enumeration is
  1393. // admin-gated, so a non-elevated broker can't read it.
  1394. // The fence is verified BEHAVIORALLY by `srt-win wfp
  1395. // verify` at the host's `initialize()` (it spawns the
  1396. // runner as the sandbox user and expects WSAEACCES on a
  1397. // direct connect). Standalone `srt-win exec` callers
  1398. // should run `srt-win wfp verify` once per session.
  1399. // Per-exec file deny — `--deny-read`/`--deny-write`. The
  1400. // session-level stamp (under `--holder-pid`) is applied
  1401. // once at the host's `initialize()`; these flags add
  1402. // PER-EXEC paths via the same additive DENY-ACE path as
  1403. // session `acl stamp`, under THIS exec process's own
  1404. // PID as a DISTINCT holder. Release downgrades the mask
  1405. // from the remaining holders' MAX(want_mask). Any stamp
  1406. // error (glob, canon-fail, apply-fail) FAILS the exec
  1407. // rather than running the child with an incomplete deny
  1408. // set.
  1409. let per_exec_guard = if deny_read.is_empty() && deny_write.is_empty() {
  1410. None
  1411. } else {
  1412. use srt_win::{acl, state_db};
  1413. let own = state_db::HolderPid(std::process::id());
  1414. let ((at, _w, failed), _r) = state_db::with_init_lock(own, false, |db| {
  1415. let at = canonicalize_ace_targets(
  1416. db,
  1417. "deny",
  1418. &[
  1419. (&deny_read, acl::SbAce::Deny(acl::DenyMask::ReadDeny)),
  1420. (&deny_write, acl::SbAce::Deny(acl::DenyMask::WriteDeny)),
  1421. ],
  1422. )?;
  1423. if let Some((p, e)) = at.bad_inputs.first() {
  1424. return Err(anyhow!("per-exec --deny-*: '{p}': {e}"));
  1425. }
  1426. let (w, f) = db.apply_aces(&sb_sid, &at.targets)?;
  1427. Ok((at, w, f))
  1428. })
  1429. .context("per-exec deny-ace")?;
  1430. let n = at.targets.len();
  1431. if failed > 0 {
  1432. return Err(anyhow!(
  1433. "per-exec deny: {failed} of {n} path(s) \
  1434. could not be stamped; rolled back"
  1435. ));
  1436. }
  1437. let guard = PerExecRestore {
  1438. holder: own,
  1439. sandbox_sid: sb_sid.clone(),
  1440. quiet,
  1441. };
  1442. if !quiet {
  1443. eprintln!(
  1444. "srt-win: per-exec deny (deny-ace): \
  1445. holder_pid={} → {n} target(s)",
  1446. own.0,
  1447. );
  1448. }
  1449. Some(guard)
  1450. };
  1451. // Self-protect the BROKER (real user) before the logon.
  1452. // The runner self-protects too; this covers the
  1453. // broker→child hop. `extra_allow = real-user SID` — the
  1454. // child runs as `srt-sandbox`, so this ACE doesn't match
  1455. // it; non-elevated real-user siblings can still
  1456. // query/debug the broker. Best-effort.
  1457. let real_user = srt_win::sid::current_user_sid()?;
  1458. if let Err(e) = srt_win::self_protect::install_broker_dacl(Some(&real_user)) {
  1459. eprintln!("srt-win: WARNING: install_broker_dacl: {e:#}");
  1460. }
  1461. // env_overlay = exactly what the caller passed via
  1462. // `--env`. The broker does not enumerate its own
  1463. // environment; the caller (whose proxy/CA-var builder
  1464. // is the single source) supplies the full overlay
  1465. // explicitly.
  1466. let env_overlay: Vec<(String, String)> = env
  1467. .iter()
  1468. .map(|kv| {
  1469. kv.split_once('=')
  1470. .map(|(k, v)| (k.to_string(), v.to_string()))
  1471. .ok_or_else(|| {
  1472. anyhow!(
  1473. "--env value '{kv}' has no '=' \
  1474. (expected KEY=VALUE)"
  1475. )
  1476. })
  1477. })
  1478. .collect::<anyhow::Result<_>>()?;
  1479. if !quiet {
  1480. eprintln!(
  1481. "srt-win: launching runner as '{}' (overlay={} var(s))",
  1482. cred.user,
  1483. env_overlay.len(),
  1484. );
  1485. }
  1486. use srt_win::{logon, runner};
  1487. let cwd = std::env::current_dir()
  1488. .ok()
  1489. .and_then(|p| p.to_str().map(String::from));
  1490. let code = match logon::spawn_runner(
  1491. &cred.user,
  1492. &cred.pw,
  1493. &sb_sid,
  1494. cwd.as_deref(),
  1495. &runner::RunnerCmd::Exec(runner::RunnerSpec {
  1496. argv: target,
  1497. env_overlay,
  1498. }),
  1499. quiet,
  1500. ) {
  1501. Ok(c) => c,
  1502. Err(e) => {
  1503. // Mapped/network-drive cwd (see
  1504. // `logon::MappedDriveCwd`): emit a one-line
  1505. // JSON error the TS caller can parse and exit
  1506. // 16 — distinct from the child's own exit
  1507. // status. `?` propagates any other
  1508. // spawn_runner error unchanged.
  1509. let m = e.downcast::<logon::MappedDriveCwd>()?;
  1510. eprintln!(
  1511. "{}",
  1512. json!({
  1513. "code": "mapped_drive_cwd",
  1514. "drive": m.drive,
  1515. "message": m.to_string(),
  1516. })
  1517. );
  1518. drop(per_exec_guard);
  1519. std::process::exit(16);
  1520. }
  1521. };
  1522. // `cred` drops here → `SandboxCred::Drop` zeroes the
  1523. // password. process::exit skips destructors, so the
  1524. // per-exec restore guard's Drop must be explicit
  1525. // BEFORE it.
  1526. drop(per_exec_guard);
  1527. std::process::exit(code as i32);
  1528. }
  1529. }
  1530. Ok(())
  1531. }
  1532. fn is_elevated() -> anyhow::Result<bool> {
  1533. use anyhow::Context;
  1534. use std::ffi::c_void;
  1535. use std::mem::size_of;
  1536. use windows::Win32::Foundation::{CloseHandle, HANDLE};
  1537. use windows::Win32::Security::{
  1538. GetTokenInformation, TOKEN_ELEVATION, TOKEN_QUERY, TokenElevation,
  1539. };
  1540. use windows::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
  1541. unsafe {
  1542. let mut tok = HANDLE::default();
  1543. OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut tok).context("OpenProcessToken")?;
  1544. let mut elev = TOKEN_ELEVATION::default();
  1545. let mut ret = 0u32;
  1546. let r = GetTokenInformation(
  1547. tok,
  1548. TokenElevation,
  1549. Some(&mut elev as *mut _ as *mut c_void),
  1550. size_of::<TOKEN_ELEVATION>() as u32,
  1551. &mut ret,
  1552. );
  1553. let _ = CloseHandle(tok);
  1554. r.context("GetTokenInformation(TokenElevation)")?;
  1555. Ok(elev.TokenIsElevated != 0)
  1556. }
  1557. }
  1558. /// Hard elevation gate: returns an error (no UAC relaunch) when not
  1559. /// admin. The granular admin mutators self-elevate via
  1560. /// [`maybe_self_elevate`], so this currently has no caller — it's
  1561. /// retained as the non-interactive counterpart for code paths that
  1562. /// must NOT pop a UAC prompt, hence `allow(dead_code)`.
  1563. #[allow(dead_code)]
  1564. fn require_elevated() -> anyhow::Result<()> {
  1565. if is_elevated()? {
  1566. Ok(())
  1567. } else {
  1568. Err(anyhow::anyhow!(
  1569. "this command requires elevation — run from an \
  1570. administrator prompt"
  1571. ))
  1572. }
  1573. }
  1574. /// If not already elevated, re-launch ourselves with the same
  1575. /// argv via `ShellExecuteExW(verb="runas")` — one UAC prompt —
  1576. /// wait for the elevated child, and return its exit code. If
  1577. /// already elevated, returns `Ok(None)` and the caller proceeds
  1578. /// in-process. If the user cancels the UAC dialog
  1579. /// (`ERROR_CANCELLED`), exits with code **10** so the caller's
  1580. /// exit-code contract holds without the caller needing a
  1581. /// separate match.
  1582. ///
  1583. /// The elevated child runs in its own (hidden) console, so its
  1584. /// stdout/stderr are NOT relayed to the parent. For
  1585. /// `install`/`uninstall` that's acceptable: the exit code is the
  1586. /// contract; the convenience commands' stderr is informational
  1587. /// only. `wfp uninstall` calls this too; its stderr is likewise
  1588. /// informational. Read-only subcommands (`user status`,
  1589. /// `wfp status`, `exec`) run as the broker and never self-elevate.
  1590. ///
  1591. /// `args` is the post-sentinel-strip argv [`run_from_args`] was
  1592. /// called with; the elevated parameters are rebuilt from `args[1..]`
  1593. /// (NOT `std::env::args()`, which in a multicall embedder is the
  1594. /// host's argv) with [`SRT_WIN_DISPATCH_ARG1`] prepended so the
  1595. /// elevated child's dispatcher routes back into `srt-win`.
  1596. fn maybe_self_elevate(args: &[OsString]) -> anyhow::Result<Option<i32>> {
  1597. use anyhow::Context;
  1598. use srt_win::launch::quote_arg;
  1599. use srt_win::util::wstr;
  1600. use windows::Win32::Foundation::{CloseHandle, ERROR_CANCELLED, GetLastError};
  1601. use windows::Win32::System::Threading::{GetExitCodeProcess, INFINITE, WaitForSingleObject};
  1602. use windows::Win32::UI::Shell::{
  1603. SEE_MASK_NO_CONSOLE, SEE_MASK_NOCLOSEPROCESS, SHELLEXECUTEINFOW, ShellExecuteExW,
  1604. };
  1605. use windows::Win32::UI::WindowsAndMessaging::SW_HIDE;
  1606. use windows::core::PCWSTR;
  1607. if is_elevated()? {
  1608. return Ok(None);
  1609. }
  1610. let exe = std::env::current_exe().context("current_exe")?;
  1611. let exe_str = exe.to_str().ok_or_else(|| {
  1612. anyhow::anyhow!(
  1613. "current_exe path '{}' is not representable as UTF-8 \
  1614. (contains unpaired surrogates); cannot self-elevate",
  1615. exe.display()
  1616. )
  1617. })?;
  1618. let exe_w = wstr(exe_str);
  1619. // Rebuild `args[1..]` (the post-sentinel-strip argv
  1620. // `run_from_args` was given — not `std::env::args()`) with
  1621. // CommandLineToArgvW-compatible quoting so the elevated child
  1622. // parses identically. `lpFile` fixes the elevated child's
  1623. // argv[0] to the real exe path (ShellExecuteExW has no argv0
  1624. // slot), so prepend `SRT_WIN_DISPATCH_ARG1` so a multicall
  1625. // dispatcher in the elevated child routes back here. Harmless
  1626. // for the standalone binary (`run_from_args` strips it).
  1627. let params = std::iter::once(SRT_WIN_DISPATCH_ARG1.into())
  1628. .chain(args.iter().skip(1).map(|a| quote_arg(&a.to_string_lossy())))
  1629. .collect::<Vec<_>>()
  1630. .join(" ");
  1631. let params_w = wstr(&params);
  1632. let verb_w = wstr("runas");
  1633. let mut sei = SHELLEXECUTEINFOW {
  1634. cbSize: std::mem::size_of::<SHELLEXECUTEINFOW>() as u32,
  1635. fMask: SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NO_CONSOLE,
  1636. lpVerb: PCWSTR(verb_w.as_ptr()),
  1637. lpFile: PCWSTR(exe_w.as_ptr()),
  1638. lpParameters: PCWSTR(params_w.as_ptr()),
  1639. nShow: SW_HIDE.0,
  1640. ..Default::default()
  1641. };
  1642. // SAFETY: sei is fully initialized; the wide-string buffers
  1643. // outlive the call.
  1644. let ok = unsafe { ShellExecuteExW(&mut sei) };
  1645. if ok.is_err() {
  1646. let err = unsafe { GetLastError() };
  1647. if err == ERROR_CANCELLED {
  1648. eprintln!("srt-win: UAC prompt cancelled by user");
  1649. std::process::exit(10);
  1650. }
  1651. return Err(anyhow::anyhow!(
  1652. "ShellExecuteExW(runas): {} ({}",
  1653. std::io::Error::from_raw_os_error(err.0 as i32),
  1654. err.0,
  1655. ));
  1656. }
  1657. let h = sei.hProcess;
  1658. if h.is_invalid() {
  1659. return Err(anyhow::anyhow!(
  1660. "ShellExecuteExW returned no process handle"
  1661. ));
  1662. }
  1663. let wait = unsafe { WaitForSingleObject(h, INFINITE) };
  1664. if wait == windows::Win32::Foundation::WAIT_FAILED {
  1665. let err = std::io::Error::last_os_error();
  1666. unsafe {
  1667. let _ = CloseHandle(h);
  1668. }
  1669. return Err(anyhow::anyhow!(
  1670. "WaitForSingleObject(elevated child): {err}"
  1671. ));
  1672. }
  1673. let mut code: u32 = 1;
  1674. unsafe {
  1675. GetExitCodeProcess(h, &mut code).context("GetExitCodeProcess(elevated child)")?;
  1676. let _ = CloseHandle(h);
  1677. }
  1678. // 259 (STILL_ACTIVE) after a successful wait is a real exit
  1679. // code (the wait already proved the process exited), not the
  1680. // still-running sentinel.
  1681. Ok(Some(code as i32))
  1682. }
  1683. #[cfg(test)]
  1684. mod tests {
  1685. use super::*;
  1686. /// `run_from_args` strips the `argv[1]` sentinel before clap so
  1687. /// the same argv shape works whether the embedder's dispatcher
  1688. /// or the standalone `srt-win.exe` is the entry. The CPWLW /
  1689. /// runas re-spawn hops are covered by smoke-exec.ps1; this
  1690. /// proves both shapes parse to the same `Cmd`. Uses
  1691. /// `try_parse_from` (not `run_from_args`) so the test doesn't
  1692. /// touch the host or `process::exit`.
  1693. #[test]
  1694. fn dispatch_sentinel_is_transparent_to_clap() {
  1695. let strip = |args: Vec<&str>| {
  1696. let mut v: Vec<OsString> = args.into_iter().map(OsString::from).collect();
  1697. if v.get(1).map(OsString::as_os_str) == Some(SRT_WIN_DISPATCH_ARG1.as_ref()) {
  1698. v.remove(1);
  1699. }
  1700. v
  1701. };
  1702. // Multicall shape: argv[0] = host exe, argv[1] = sentinel.
  1703. let with = Cli::try_parse_from(strip(vec![
  1704. "host.exe",
  1705. SRT_WIN_DISPATCH_ARG1,
  1706. "user",
  1707. "status",
  1708. ]))
  1709. .expect("with-sentinel should parse");
  1710. assert!(matches!(
  1711. with.cmd,
  1712. Cmd::User {
  1713. sub: UserCmd::Status
  1714. }
  1715. ));
  1716. // Standalone shape: no sentinel.
  1717. let without = Cli::try_parse_from(strip(vec!["srt-win.exe", "user", "status"]))
  1718. .expect("without-sentinel should parse");
  1719. assert!(matches!(
  1720. without.cmd,
  1721. Cmd::User {
  1722. sub: UserCmd::Status
  1723. }
  1724. ));
  1725. // The sentinel is NOT a clap flag — without the strip, it
  1726. // must be rejected (otherwise a typo'd dispatcher silently
  1727. // works on `try_parse_from` while the real binary errors).
  1728. assert!(
  1729. Cli::try_parse_from(["srt-win.exe", SRT_WIN_DISPATCH_ARG1, "user", "status",]).is_err()
  1730. );
  1731. }
  1732. /// Top-level `status` parses with and without `--sublayer-guid`.
  1733. #[test]
  1734. fn status_subcommand_parses() {
  1735. let bare = Cli::try_parse_from(["srt-win", "status"]).expect("parse");
  1736. assert!(matches!(
  1737. bare.cmd,
  1738. Cmd::Status {
  1739. sublayer_guid: None
  1740. }
  1741. ));
  1742. let with_sl = Cli::try_parse_from([
  1743. "srt-win",
  1744. "status",
  1745. "--sublayer-guid",
  1746. "12345678-1234-1234-1234-1234567890ab",
  1747. ])
  1748. .expect("parse");
  1749. assert!(matches!(
  1750. with_sl.cmd,
  1751. Cmd::Status {
  1752. sublayer_guid: Some(_)
  1753. }
  1754. ));
  1755. }
  1756. /// `--quiet` on `exec` parses and defaults false. Placement
  1757. /// before `--` (where the TS wrapper puts it) is accepted.
  1758. #[test]
  1759. fn exec_quiet_flag_parses() {
  1760. let with =
  1761. Cli::try_parse_from(["srt-win", "exec", "--quiet", "--", "cmd.exe"]).expect("parse");
  1762. assert!(matches!(with.cmd, Cmd::Exec { quiet: true, .. }));
  1763. let without = Cli::try_parse_from(["srt-win", "exec", "--", "cmd.exe"]).expect("parse");
  1764. assert!(matches!(without.cmd, Cmd::Exec { quiet: false, .. }));
  1765. }
  1766. }