logon.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. //! Broker-side `CreateProcessWithLogonW` wrapper for the
  2. //! broker→runner two-hop launch.
  3. //!
  4. //! Spawns `srt-win.exe runner` under the `srt-sandbox` account
  5. //! (via the Secondary Logon service — no
  6. //! `SeAssignPrimaryTokenPrivilege` needed on the broker), wires
  7. //! three anonymous pipes to its stdio, writes the
  8. //! [`crate::runner::RunnerCmd`] over stdin, pumps stdout/stderr
  9. //! back to the broker's own stdio, waits, and returns the runner's
  10. //! exit code.
  11. //!
  12. //! `lpEnvironment = NULL` + `LOGON_WITH_PROFILE` means the runner
  13. //! starts with the **sandbox user's** profile environment
  14. //! (`USERPROFILE`/`TEMP`/`LOCALAPPDATA` isolated; `PATH` = machine
  15. //! `PATH`). The broker's `PATH` and the proxy var set ride to the
  16. //! child via the spec's `env_overlay` instead, applied by the
  17. //! runner's `build_env_block` — so profile-scoped vars stay the
  18. //! sandbox user's while tool-resolution `PATH` is the broker's.
  19. //!
  20. //! **Do not key any ACL/WFP on the logon SID:** seclogon stamps the
  21. //! broker's interactive logon SID into the runner's token. Key on
  22. //! the **user SID** only.
  23. use anyhow::{Context, Result, anyhow};
  24. use std::ffi::c_void;
  25. use std::mem::{size_of, zeroed};
  26. use windows::Win32::Foundation::{
  27. CloseHandle, ERROR_DIRECTORY, ERROR_LOGON_FAILURE, ERROR_NOT_SUPPORTED, HANDLE,
  28. HANDLE_FLAG_INHERIT, HANDLE_FLAGS, SetHandleInformation, WAIT_OBJECT_0,
  29. };
  30. use windows::Win32::Security::SECURITY_ATTRIBUTES;
  31. use windows::Win32::Storage::FileSystem::{GetDriveTypeW, ReadFile, WriteFile};
  32. use windows::Win32::System::Pipes::CreatePipe;
  33. use windows::Win32::System::Threading::{
  34. CREATE_NO_WINDOW, CREATE_SUSPENDED, CREATE_UNICODE_ENVIRONMENT, CreateProcessWithLogonW,
  35. GetExitCodeProcess, INFINITE, LOGON_WITH_PROFILE, PROCESS_INFORMATION, ResumeThread,
  36. STARTF_USESTDHANDLES, STARTUPINFOW, WaitForSingleObject,
  37. };
  38. use windows::core::{PCWSTR, PWSTR};
  39. use crate::job::Job;
  40. use crate::launch::{SpawnedChild, quote_arg};
  41. use crate::util::{OwnedHandle, scrub_wstr, wstr};
  42. use crate::winsta::{IsolatedDesk, grant_sandbox_on_session_bno, grant_sandbox_on_winsta};
  43. /// Typed error for [`spawn_runner`] with a mapped/network-drive
  44. /// working directory. Per-user drive mappings and SMB share
  45. /// authentication belong to the **real** user's logon session; the
  46. /// `srt-sandbox` logon that seclogon creates for
  47. /// `CreateProcessWithLogonW` has neither, so `lpCurrentDirectory`
  48. /// pointing at a mapped drive fails inside seclogon with
  49. /// `ERROR_DIRECTORY` (`0x8007010B`). A mechanism failure, not a
  50. /// security block — typed so callers can present an actionable
  51. /// message instead of a bare HRESULT.
  52. #[derive(Debug)]
  53. pub struct MappedDriveCwd {
  54. /// The drive root that resolved as `DRIVE_REMOTE` (`Z:\` for a
  55. /// mapped drive letter, `\\server\share\` for a raw UNC cwd).
  56. pub drive: String,
  57. }
  58. impl std::fmt::Display for MappedDriveCwd {
  59. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  60. write!(
  61. f,
  62. "the sandbox cannot start with a mapped/network-drive \
  63. working directory ({} is DRIVE_REMOTE — per-user drive \
  64. mappings do not exist under the sandbox logon). Use a \
  65. local-drive workspace.",
  66. self.drive,
  67. )
  68. }
  69. }
  70. impl std::error::Error for MappedDriveCwd {}
  71. /// `GetDriveTypeW` return value for a network drive. The `windows`
  72. /// crate parks this constant under `Win32_System_WindowsProgramming`
  73. /// (a grab-bag feature we don't otherwise need); the value is a
  74. /// stable Win32 ABI constant.
  75. const DRIVE_REMOTE: u32 = 4;
  76. /// Extract the drive root of `cwd` in the form `GetDriveTypeW`
  77. /// wants: `X:\` for a drive-letter path, `\\server\share\` for a
  78. /// UNC path. `None` for anything else (relative, device path
  79. /// `\\.\…` / `\\?\…`, or malformed) — the caller falls through to
  80. /// the `CreateProcessWithLogonW` attempt and the post-check catches
  81. /// the `ERROR_DIRECTORY` case.
  82. fn cwd_drive_root(cwd: &str) -> Option<String> {
  83. let b = cwd.as_bytes();
  84. if b.len() >= 3 && b[0].is_ascii_alphabetic() && b[1] == b':' && (b[2] == b'\\' || b[2] == b'/')
  85. {
  86. return Some(format!("{}:\\", (b[0] as char).to_ascii_uppercase()));
  87. }
  88. if let Some(rest) = cwd.strip_prefix(r"\\") {
  89. // `\\?\…` / `\\.\…` are extended/device prefixes, not a
  90. // server name — leave to the post-check.
  91. if rest.starts_with(['?', '.']) {
  92. return None;
  93. }
  94. let mut it = rest.splitn(3, ['\\', '/']);
  95. if let (Some(srv), Some(share)) = (it.next(), it.next())
  96. && !srv.is_empty()
  97. && !share.is_empty()
  98. {
  99. return Some(format!(r"\\{srv}\{share}\"));
  100. }
  101. }
  102. None
  103. }
  104. /// One anonymous pipe pair. The end the runner gets is created
  105. /// inheritable; the broker's end is flipped non-inheritable so the
  106. /// runner doesn't get a copy of it (which would keep the pipe open
  107. /// past the runner's exit and hang the pump).
  108. struct PipePair {
  109. broker: OwnedHandle,
  110. runner: OwnedHandle,
  111. }
  112. fn make_pipe(runner_writes: bool) -> Result<PipePair> {
  113. let sa = SECURITY_ATTRIBUTES {
  114. nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
  115. bInheritHandle: true.into(),
  116. ..Default::default()
  117. };
  118. let mut read = HANDLE::default();
  119. let mut write = HANDLE::default();
  120. unsafe {
  121. CreatePipe(&mut read, &mut write, Some(&sa), 0).context("CreatePipe")?;
  122. }
  123. // Wrap immediately so the `?` below can't leak either end.
  124. let (broker, runner) = if runner_writes {
  125. (OwnedHandle(read), OwnedHandle(write))
  126. } else {
  127. (OwnedHandle(write), OwnedHandle(read))
  128. };
  129. // Broker end must NOT be inherited by the runner.
  130. unsafe {
  131. SetHandleInformation(broker.raw(), HANDLE_FLAG_INHERIT.0, HANDLE_FLAGS(0))
  132. .context("SetHandleInformation(broker end)")?;
  133. }
  134. Ok(PipePair { broker, runner })
  135. }
  136. /// Pump `src` to `dst` until `src` reaches EOF (broken pipe). Runs
  137. /// on a dedicated thread per stream so a slow consumer on one
  138. /// doesn't block the other.
  139. fn pump(src: HANDLE, dst: HANDLE) {
  140. let mut buf = [0u8; 8192];
  141. loop {
  142. let mut read = 0u32;
  143. let r = unsafe { ReadFile(src, Some(&mut buf), Some(&mut read), None) };
  144. if r.is_err() || read == 0 {
  145. break;
  146. }
  147. let mut off = 0u32;
  148. while off < read {
  149. let mut wrote = 0u32;
  150. let chunk = &buf[off as usize..read as usize];
  151. if unsafe { WriteFile(dst, Some(chunk), Some(&mut wrote), None) }.is_err() || wrote == 0
  152. {
  153. return;
  154. }
  155. off += wrote;
  156. }
  157. }
  158. }
  159. /// Spawn `srt-win runner` as `username`, send `cmd` over stdin, and
  160. /// return its exit code. `cwd` is set as the runner's working
  161. /// directory; `None` inherits the broker's. `sb_sid` is the
  162. /// `srt-sandbox` user-SID string (for the desktop DACL and the
  163. /// `WinSta0` station grant). `quiet` suppresses the informational
  164. /// stderr lines (the seclogon-job note); `SANDBOX_RUNTIME_WIN_DEBUG`
  165. /// checkpoints are gated separately on `dbg` and are unaffected.
  166. pub fn spawn_runner(
  167. username: &str,
  168. password: &str,
  169. sb_sid: &str,
  170. cwd: Option<&str>,
  171. cmd: &crate::runner::RunnerCmd,
  172. quiet: bool,
  173. ) -> Result<u32> {
  174. // Mapped/network-drive cwd pre-check: `DRIVE_REMOTE` on the
  175. // cwd's root means CPWLW would fail inside seclogon with
  176. // `ERROR_DIRECTORY` — fail fast with the typed error. The
  177. // post-CPWLW arm below maps `ERROR_DIRECTORY` to the same
  178. // error for shapes this pre-check doesn't recognise.
  179. if let Some(root) = cwd.and_then(cwd_drive_root)
  180. && unsafe { GetDriveTypeW(PCWSTR(wstr(&root).as_ptr())) } == DRIVE_REMOTE
  181. {
  182. return Err(MappedDriveCwd { drive: root }.into());
  183. }
  184. let cmd_bytes = crate::runner::encode_cmd(cmd)?;
  185. let stdin = make_pipe(false)?;
  186. let stdout = make_pipe(true)?;
  187. let stderr = make_pipe(true)?;
  188. // Broker-side per-exec desktop on `WinSta0` with an explicit
  189. // `[broker, srt-sandbox, SY]:GA` DACL. The broker (interactive
  190. // user) has `WINSTA_CREATEDESKTOP` non-elevated; the runner does
  191. // not — so this MUST happen here, not inside the runner. Held
  192. // open until the runner exits so the kernel object survives the
  193. // whole two-hop chain. See `winsta.rs` module doc.
  194. let dbg = std::env::var_os("SANDBOX_RUNTIME_WIN_DEBUG").is_some();
  195. let mut desk = IsolatedDesk::new(sb_sid).context("broker IsolatedDesk")?;
  196. let exe = std::env::current_exe().context("current_exe")?;
  197. let exe_s = exe
  198. .to_str()
  199. .ok_or_else(|| anyhow!("current_exe is not UTF-8"))?;
  200. let exe_w = wstr(exe_s);
  201. // `lpCommandLine` is parsed via `CommandLineToArgvW`; quote
  202. // argv[0] so a path with spaces survives. The
  203. // `SRT_WIN_DISPATCH_ARG1` sentinel at argv[1] is what a
  204. // multicall embedder's dispatcher routes on (`argv[0]` cannot be
  205. // spoofed across CPWLW); `run_from_args` strips it before clap so
  206. // the standalone binary accepts it harmlessly. `runner` is the
  207. // only real argument.
  208. let mut cmdline_w = wstr(&format!(
  209. "{} {} runner",
  210. quote_arg(exe_s),
  211. crate::cli::SRT_WIN_DISPATCH_ARG1,
  212. ));
  213. let user_w = wstr(username);
  214. let domain_w = wstr(".");
  215. let mut pw_w = wstr(password);
  216. let cwd_w = cwd.map(wstr);
  217. // Broker→runner kill-on-close Job: broker dies → runner dies →
  218. // runner's Job → child dies. The assign succeeds on current
  219. // Windows (rc=0, live-probed 2026-07-16); if a future seclogon
  220. // job refused nesting (ERROR_NOT_SUPPORTED), the always-armed
  221. // `SpawnedChild` guard below is the fallback.
  222. // `breakaway_ok = true`: the runner's child must break away
  223. // past the inherited [seclogon, broker] job stack onto the
  224. // runner's own Job, which requires every containing job to
  225. // allow it.
  226. let job = Job::new(true).context("broker→runner job")?;
  227. let mut si: STARTUPINFOW = unsafe { zeroed() };
  228. si.cb = size_of::<STARTUPINFOW>() as u32;
  229. si.dwFlags = STARTF_USESTDHANDLES;
  230. si.hStdInput = stdin.runner.raw();
  231. si.hStdOutput = stdout.runner.raw();
  232. si.hStdError = stderr.runner.raw();
  233. // `lpDesktop = "WinSta0\srt-sb-…"`. The runner never touches
  234. // `Default`; `run_lockdown` fail-closes if it somehow lands there.
  235. si.lpDesktop = PWSTR(desk.desktop_name_ptr());
  236. let mut pi: PROCESS_INFORMATION = unsafe { zeroed() };
  237. // `CreateProcessWithLogonW` has no `bInheritHandles` parameter:
  238. // seclogon duplicates the `STARTF_USESTDHANDLES` handles into
  239. // the new logon, and nothing else. So no
  240. // `PROC_THREAD_ATTRIBUTE_HANDLE_LIST` is needed (or possible —
  241. // there's no `STARTUPINFOEX` overload).
  242. let r = unsafe {
  243. CreateProcessWithLogonW(
  244. PCWSTR(user_w.as_ptr()),
  245. PCWSTR(domain_w.as_ptr()),
  246. PCWSTR(pw_w.as_ptr()),
  247. LOGON_WITH_PROFILE,
  248. PCWSTR(exe_w.as_ptr()),
  249. Some(PWSTR(cmdline_w.as_mut_ptr())),
  250. CREATE_UNICODE_ENVIRONMENT | CREATE_NO_WINDOW | CREATE_SUSPENDED,
  251. // `NULL` → seclogon builds the sandbox user's profile
  252. // env (with `LOGON_WITH_PROFILE`). The broker's PATH
  253. // and proxy vars travel via the spec's env_overlay.
  254. None,
  255. match &cwd_w {
  256. Some(w) => PCWSTR(w.as_ptr()),
  257. None => PCWSTR::null(),
  258. },
  259. &si,
  260. &mut pi,
  261. )
  262. };
  263. // Scrub the UTF-16 password buffer now that seclogon has it.
  264. // (The UTF-8 source is zeroed by `SandboxCred::Drop`; this is a
  265. // separate heap allocation.) Before any `?` so the scrub runs
  266. // regardless of `r`. Volatile so DSE can't remove it in release.
  267. scrub_wstr(&mut pw_w);
  268. if let Err(e) = r {
  269. if e.code() == ERROR_LOGON_FAILURE.to_hresult() {
  270. return Err(anyhow!(
  271. "CreateProcessWithLogonW({username}): logon failure \
  272. — the sandbox user's password is wrong or the \
  273. account is disabled. Re-run `srt-win install` (one \
  274. UAC prompt) to rotate the credential."
  275. ));
  276. }
  277. // `ERROR_DIRECTORY` = seclogon couldn't set the requested
  278. // cwd under the sandbox logon (mapped drive / unreachable
  279. // UNC share) — same typed error as the pre-check above,
  280. // catching shapes it didn't classify.
  281. if e.code() == ERROR_DIRECTORY.to_hresult() {
  282. let drive = cwd
  283. .and_then(cwd_drive_root)
  284. .or_else(|| cwd.map(str::to_owned))
  285. .unwrap_or_else(|| "<unknown>".into());
  286. return Err(MappedDriveCwd { drive }.into());
  287. }
  288. return Err(anyhow!(
  289. "CreateProcessWithLogonW({username}): {e} — ensure the \
  290. Secondary Logon service (seclogon) is running."
  291. ));
  292. }
  293. if dbg {
  294. eprintln!(
  295. "srt-win: spawn_runner: CPWLW ok pid={} (suspended)",
  296. pi.dwProcessId
  297. );
  298. }
  299. // Runner exists, suspended. The guard is never defused: its
  300. // `Drop` `TerminateProcess`es the runner on every in-process
  301. // exit — `?`/panic reap directly; on normal return the runner
  302. // has already exited and the terminate is a no-op on the held
  303. // handle. It cannot cover an external kill of the broker —
  304. // that is the Job's role; if a build ever regresses the assign
  305. // above, elevated `taskkill /F /FI "USERNAME eq srt-sandbox"`
  306. // is the operator fallback (admins hold SeDebugPrivilege and
  307. // BA is in every sandbox process's DACL — the by-user-filter
  308. // denial is non-elevated-only). Declared after `job` so it
  309. // drops first: terminate before job-close.
  310. let child = SpawnedChild::new(pi);
  311. // Grant `srt-sandbox` on the broker's `WinSta0` (with a non-NULL
  312. // `lpDesktop`, seclogon skips its station auto-grant for the new
  313. // logon, so the runner can't attach without this) and on the
  314. // session `BaseNamedObjects` directory (so the lockdown child —
  315. // whose logon SIDs are deny-only — can still create the
  316. // named-object subdirectory msys2/cygwin needs). Both persist for
  317. // the broker's logon session: revoking on drop would race against
  318. // a concurrent `srt-win exec`. See `winsta.rs`.
  319. grant_sandbox_on_winsta(sb_sid)?;
  320. grant_sandbox_on_session_bno(sb_sid)?;
  321. if dbg {
  322. eprintln!("srt-win: spawn_runner: WinSta0 + BNO grants applied");
  323. }
  324. // Assign before resuming so there is no window where broker
  325. // death orphans it. ERROR_NOT_SUPPORTED (seclogon's job won't
  326. // nest) → log + continue; any OTHER error → propagate (the guard
  327. // terminates the suspended runner).
  328. if let Err(e) = job.assign(child.process()) {
  329. if e.root_cause()
  330. .downcast_ref::<windows::core::Error>()
  331. .map(|we| we.code() == ERROR_NOT_SUPPORTED.to_hresult())
  332. .unwrap_or(false)
  333. {
  334. if !quiet {
  335. eprintln!(
  336. "srt-win: broker→runner Job assign not supported \
  337. (seclogon job); relying on runner→child Job for \
  338. kill-chain"
  339. );
  340. }
  341. } else {
  342. return Err(e.context("assign runner to job"));
  343. }
  344. }
  345. if unsafe { ResumeThread(child.thread()) } == u32::MAX {
  346. return Err(anyhow!(
  347. "ResumeThread(runner): {}",
  348. std::io::Error::last_os_error()
  349. ));
  350. }
  351. if dbg {
  352. eprintln!("srt-win: spawn_runner: runner resumed; writing spec");
  353. }
  354. // No `child.defuse()` — the guard stays armed (see its decl).
  355. // Close the runner-side pipe ends in the broker so the pumps
  356. // see EOF when the runner exits.
  357. drop(stdin.runner);
  358. drop(stdout.runner);
  359. drop(stderr.runner);
  360. // Write the spec, then close stdin so the runner's
  361. // `read_exact` doesn't block waiting for more.
  362. {
  363. let mut wrote = 0u32;
  364. unsafe {
  365. WriteFile(stdin.broker.raw(), Some(&cmd_bytes), Some(&mut wrote), None)
  366. .context("write RunnerCmd to runner stdin")?;
  367. }
  368. if wrote as usize != cmd_bytes.len() {
  369. return Err(anyhow!(
  370. "short write of RunnerCmd ({}/{} bytes)",
  371. wrote,
  372. cmd_bytes.len()
  373. ));
  374. }
  375. }
  376. drop(stdin.broker);
  377. // Pump stdout/stderr on dedicated threads. `HANDLE` wraps a
  378. // `*mut c_void` which is `!Send`; the value is just an opaque
  379. // index into the process's handle table, so cast to `isize` for
  380. // the move and reconstruct inside the thread. Broker stdio
  381. // handles are not OwnedHandle — they're owned by the process,
  382. // not us.
  383. let bout = std::io::stdout().as_raw().0 as isize;
  384. let berr = std::io::stderr().as_raw().0 as isize;
  385. let so = stdout.broker.into_raw().0 as isize;
  386. let se = stderr.broker.into_raw().0 as isize;
  387. let h = |v: isize| HANDLE(v as *mut c_void);
  388. let t_out = std::thread::spawn(move || {
  389. pump(h(so), h(bout));
  390. unsafe {
  391. let _ = CloseHandle(h(so));
  392. }
  393. });
  394. let t_err = std::thread::spawn(move || {
  395. pump(h(se), h(berr));
  396. unsafe {
  397. let _ = CloseHandle(h(se));
  398. }
  399. });
  400. let rc = unsafe { WaitForSingleObject(child.process(), INFINITE) };
  401. if rc != WAIT_OBJECT_0 {
  402. eprintln!("srt-win: WaitForSingleObject(runner) returned 0x{:x}", rc.0);
  403. }
  404. let _ = t_out.join();
  405. let _ = t_err.join();
  406. let mut code: u32 = 1;
  407. unsafe {
  408. GetExitCodeProcess(child.process(), &mut code).context("GetExitCodeProcess(runner)")?;
  409. }
  410. // Implicit drop order: `child` (armed, no-op on the exited
  411. // runner) then `job`. An explicit `drop(job)` here would close
  412. // the Job before the fallback terminate.
  413. Ok(code)
  414. }
  415. /// `std::io::Stdout`/`Stderr` → raw `HANDLE` for [`pump`].
  416. trait AsRawHandle {
  417. fn as_raw(&self) -> HANDLE;
  418. }
  419. impl AsRawHandle for std::io::Stdout {
  420. fn as_raw(&self) -> HANDLE {
  421. HANDLE(std::os::windows::io::AsRawHandle::as_raw_handle(self))
  422. }
  423. }
  424. impl AsRawHandle for std::io::Stderr {
  425. fn as_raw(&self) -> HANDLE {
  426. HANDLE(std::os::windows::io::AsRawHandle::as_raw_handle(self))
  427. }
  428. }
  429. #[cfg(test)]
  430. mod tests {
  431. use super::cwd_drive_root;
  432. #[test]
  433. fn drive_letter_root() {
  434. assert_eq!(cwd_drive_root(r"Z:\work\repo"), Some(r"Z:\".into()));
  435. assert_eq!(cwd_drive_root("c:/work"), Some(r"C:\".into()));
  436. assert_eq!(cwd_drive_root("relative"), None);
  437. }
  438. #[test]
  439. fn unc_root() {
  440. assert_eq!(
  441. cwd_drive_root(r"\\srv\share\dir\f"),
  442. Some(r"\\srv\share\".into()),
  443. );
  444. assert_eq!(cwd_drive_root(r"\\srv\share"), Some(r"\\srv\share\".into()));
  445. // server-only (no share) is not a valid UNC root
  446. assert_eq!(cwd_drive_root(r"\\srv"), None);
  447. }
  448. #[test]
  449. fn device_and_extended_prefix_skipped() {
  450. // `\\?\` / `\\.\` are extended/device prefixes, not UNC —
  451. // left to the CPWLW post-check.
  452. assert_eq!(cwd_drive_root(r"\\?\C:\x"), None);
  453. assert_eq!(cwd_drive_root(r"\\.\pipe\x"), None);
  454. }
  455. }