launch.rs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  1. //! `srt-win runner`'s lockdown stack: build the restricted token,
  2. //! self-protect the runner, spawn the target suspended under a
  3. //! locked-down job + non-interactive desktop + mitigation-policy
  4. //! stack + explicit handle whitelist, resume, wait, propagate exit
  5. //! code.
  6. //!
  7. //! Stateless — no marker file, no proxy thread, no FS-deny
  8. //! handling here. Network egress for the child reaches the host's
  9. //! JS-side proxies (whose ports the caller passes via the env
  10. //! overlay) via the WFP loopback permit installed by `srt-win
  11. //! install`.
  12. use anyhow::{Context, Result, anyhow};
  13. use std::ffi::c_void;
  14. use std::mem::{size_of, zeroed};
  15. use std::path::Path;
  16. use windows::Win32::Foundation::{
  17. CloseHandle, HANDLE, HANDLE_FLAG_INHERIT, SetHandleInformation, WAIT_OBJECT_0,
  18. };
  19. use windows::Win32::System::Console::{
  20. GetStdHandle, STD_ERROR_HANDLE, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,
  21. };
  22. use windows::Win32::System::Threading::{
  23. CREATE_BREAKAWAY_FROM_JOB, CREATE_NO_WINDOW, CREATE_SUSPENDED, CREATE_UNICODE_ENVIRONMENT,
  24. CreateProcessAsUserW, DeleteProcThreadAttributeList, EXTENDED_STARTUPINFO_PRESENT,
  25. GetCurrentProcess, GetExitCodeProcess, INFINITE, InitializeProcThreadAttributeList,
  26. LPPROC_THREAD_ATTRIBUTE_LIST, PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
  27. PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY, PROCESS_CREATION_FLAGS, PROCESS_INFORMATION,
  28. ResumeThread, STARTF_USESTDHANDLES, STARTUPINFOEXW, STARTUPINFOW, TerminateProcess,
  29. UpdateProcThreadAttribute, WaitForSingleObject,
  30. };
  31. use windows::core::{PCWSTR, PWSTR};
  32. use crate::job::{Job, is_process_in_job};
  33. use crate::self_protect;
  34. use crate::token::{self, open_self_token, to_primary};
  35. use crate::util::{pcwstr, wstr};
  36. use crate::winsta::{current_desktop_name, current_winsta_name, on_default_desktop};
  37. // ─── RAII handle wrappers ───────────────────────────────────────────
  38. use crate::util::OwnedHandle;
  39. /// Owns a freshly-spawned (suspended) child. If dropped before
  40. /// [`defuse`] is called, terminates the child — so an error
  41. /// between `CreateProcess*` and `WaitForSingleObject` can't orphan
  42. /// a suspended process that's not yet in the job. Always closes
  43. /// both handles on drop. Shared with [`crate::logon::spawn_runner`]
  44. /// for the same suspended-then-assign-then-resume window.
  45. pub(crate) struct SpawnedChild {
  46. pi: PROCESS_INFORMATION,
  47. armed: bool,
  48. }
  49. impl SpawnedChild {
  50. pub(crate) fn new(pi: PROCESS_INFORMATION) -> Self {
  51. Self { pi, armed: true }
  52. }
  53. pub(crate) fn process(&self) -> HANDLE {
  54. self.pi.hProcess
  55. }
  56. pub(crate) fn thread(&self) -> HANDLE {
  57. self.pi.hThread
  58. }
  59. /// Disarm the terminate-on-drop. Call after the child has been
  60. /// assigned to the job AND resumed — past that point
  61. /// `KILL_ON_JOB_CLOSE` covers cleanup.
  62. pub(crate) fn defuse(&mut self) {
  63. self.armed = false;
  64. }
  65. }
  66. impl Drop for SpawnedChild {
  67. fn drop(&mut self) {
  68. unsafe {
  69. if self.armed {
  70. let _ = TerminateProcess(self.pi.hProcess, 1);
  71. }
  72. let _ = CloseHandle(self.pi.hThread);
  73. let _ = CloseHandle(self.pi.hProcess);
  74. }
  75. }
  76. }
  77. // ─── Process-creation mitigation-policy bits ────────────────────────
  78. //
  79. // The `windows` crate exposes `PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY`
  80. // but not the per-bit DWORD64 macros (they're winnt.h preprocessor
  81. // `#define`s, still absent as of 0.62). Each policy occupies a 4-bit
  82. // slot in the u64; `..._ALWAYS_ON` flips bit 0 of its slot.
  83. //
  84. // Only mitigations that don't break Node/Python JIT or mingw-built
  85. // shells are enabled here. Specifically NOT enabled:
  86. // - `IMAGE_LOAD_PREFER_SYSTEM32` — flips DLL search-order so System32
  87. // wins over the EXE's directory; breaks the cygwin1.dll /
  88. // msys-2.0.dll resolution model.
  89. // - `CONTROL_FLOW_GUARD_ALWAYS_ON` — forces CFG even when the EXE
  90. // wasn't built with `/guard:cf`; stock mingw-built `bash.exe`
  91. // dies in `dofork`. CFG is defense-in-depth, not a primary
  92. // boundary.
  93. /// Bit 32 — block legacy AppInit / IME / Winsock-LSP DLL injection
  94. /// and `SetWindowsHookEx`.
  95. const MITIGATION_EXTENSION_POINT_DISABLE: u64 = 1u64 << 32;
  96. /// Bit 48 — block GDI from loading non-system fonts (historic
  97. /// kernel font-parser RCE surface; sandbox children are
  98. /// console/network workloads).
  99. const MITIGATION_FONT_DISABLE: u64 = 1u64 << 48;
  100. /// Bit 52 — refuse `LoadLibrary` from UNC / network paths.
  101. const MITIGATION_IMAGE_LOAD_NO_REMOTE: u64 = 1u64 << 52;
  102. /// Bit 56 — refuse `LoadLibrary` of any image whose mandatory label
  103. /// is Low IL.
  104. const MITIGATION_IMAGE_LOAD_NO_LOW_LABEL: u64 = 1u64 << 56;
  105. /// Run `target_exe target_args…` under the lockdown stack and
  106. /// return its exit code.
  107. ///
  108. /// Called only from `srt-win runner` — this process is the
  109. /// `srt-sandbox` user (via `CreateProcessWithLogonW`), has NO
  110. /// console (broker spawned it `CREATE_NO_WINDOW`; stdio are
  111. /// anonymous pipes), and the child runs under a restricted token
  112. /// with `BUILTIN\Administrators` flipped deny-only (LUA shape).
  113. ///
  114. /// `env_overlay` is `(KEY, VALUE)` pairs overlaid on the runner's
  115. /// own environment when building the child's env block. Overlay
  116. /// wins on case-insensitive key conflict; everything else is
  117. /// passed through verbatim — so the broker's `PATH` + proxy vars
  118. /// ride here while the sandbox-user-profile `USERPROFILE`/`TEMP`
  119. /// stay isolated.
  120. pub fn run_lockdown(
  121. target_exe: &Path,
  122. target_args: &[String],
  123. env_overlay: &[(String, String)],
  124. ) -> Result<u32> {
  125. // 1) Self-protect: rewrite this process's DACL so the child can't
  126. // `OpenProcess` us. The child shares the runner's user SID, so
  127. // without this it could open the runner with
  128. // `PROCESS_CREATE_PROCESS` and parent-spawn under the runner's
  129. // unrestricted token, escaping the job/winsta/mitigations.
  130. // `extra_allow = None` — we run as `srt-sandbox`; an
  131. // `srt-sandbox:FA` ACE here would match the child and undo the
  132. // protection. First so the protection holds on every later
  133. // error path. Best-effort — log on failure but don't abort,
  134. // since a runner without self-protect is still strictly safer
  135. // than no sandbox.
  136. if let Err(e) = self_protect::install_broker_dacl(None) {
  137. eprintln!("srt-win: WARNING: install_broker_dacl: {e:#}");
  138. }
  139. // 2) Restricted token. Each handle is RAII-owned so any `?`
  140. // below closes whatever was already opened.
  141. let self_tok = OwnedHandle(open_self_token()?);
  142. let restricted =
  143. OwnedHandle(token::make_sandbox_token(self_tok.raw()).context("make_sandbox_token")?);
  144. let primary = OwnedHandle(to_primary(restricted.raw()).context("to_primary")?);
  145. // 3) Job. `breakaway_ok = false` — this is the load-bearing
  146. // containment Job; the child must NOT be able to break away.
  147. let job = Job::new(false).context("Job::new")?;
  148. // `on_default` gates the fail-closed assertion; the breakaway
  149. // flag is gated separately on `IsProcessInJob(self)`. Computed
  150. // (and logged) BEFORE step 4 so the diagnostic identifies which
  151. // desktop the runner landed on.
  152. let on_default = on_default_desktop();
  153. let caller_in_job = is_process_in_job(unsafe { GetCurrentProcess() }, None);
  154. // Breakaway: the caller is in seclogon's job (and the
  155. // broker→runner job, both `BREAKAWAY_OK`); without breakaway
  156. // the child inherits them and `AssignProcessToJobObject` below
  157. // fails.
  158. let breakaway = if caller_in_job {
  159. CREATE_BREAKAWAY_FROM_JOB
  160. } else {
  161. PROCESS_CREATION_FLAGS(0)
  162. };
  163. let dbg = std::env::var_os("SANDBOX_RUNTIME_WIN_DEBUG").is_some();
  164. if dbg {
  165. eprintln!(
  166. "srt-win: run_lockdown: caller_in_job={} caller_desk={}\\{} \
  167. breakaway={}",
  168. caller_in_job,
  169. current_winsta_name().ok().as_deref().unwrap_or("?"),
  170. current_desktop_name().as_deref().unwrap_or("?"),
  171. breakaway.0 != 0,
  172. );
  173. }
  174. // 4) Desktop isolation — fail closed. The broker created a
  175. // `WinSta0\srt-sb-…` desktop and passed it via `lpDesktop` to
  176. // `CreateProcessWithLogonW`, so this runner is already on it
  177. // (not `Default`). The child inherits via `lpDesktop = NULL`
  178. // in step 8. If we're still on `Default`, the broker-side
  179. // creation/attach failed and the child would share the
  180. // interactive desktop — `WH_KEYBOARD_LL` keylogging is the
  181. // threat (the Job's `UILIMIT_HANDLES` does NOT gate low-level
  182. // hooks), so refuse rather than fall through.
  183. if on_default {
  184. return Err(anyhow!(
  185. "desktop isolation required: runner is on Default — \
  186. broker IsolatedDesk creation or WinSta0 grant failed"
  187. ));
  188. }
  189. // 5) Env block — this process's own environment (verbatim) with
  190. // the overlay applied on top; see `build_env_block`.
  191. let mut env = build_env_block(env_overlay);
  192. // 6) Command line + application name.
  193. let cmdline = build_cmdline(target_exe, target_args);
  194. let mut cmdline_w = wstr(&cmdline);
  195. let app_w = wstr(&target_exe.display().to_string());
  196. // 7) PROC_THREAD_ATTRIBUTE_LIST: mitigation policy + explicit
  197. // handle whitelist.
  198. let mitigation: u64 = MITIGATION_EXTENSION_POINT_DISABLE
  199. | MITIGATION_FONT_DISABLE
  200. | MITIGATION_IMAGE_LOAD_NO_REMOTE
  201. | MITIGATION_IMAGE_LOAD_NO_LOW_LABEL;
  202. let std_handles = collect_inheritable_std_handles();
  203. let mut handle_list: Vec<HANDLE> = std_handles
  204. .iter()
  205. .copied()
  206. .filter(|h| !h.0.is_null())
  207. .collect();
  208. if handle_list.is_empty() {
  209. return Err(anyhow!(
  210. "no std handle is inheritable; refusing to spawn. \
  211. srt-win runner requires at least one piped stdio stream."
  212. ));
  213. }
  214. let mut attrs = ProcThreadAttrs::new(2)?;
  215. attrs.set_mitigation_policy(&mitigation)?;
  216. attrs.set_handle_list(&mut handle_list)?;
  217. // 8) STARTUPINFOEXW. `STARTF_USESTDHANDLES` + the caller's std
  218. // handles is load-bearing: the runner has NO console (the
  219. // broker spawned it with `CREATE_NO_WINDOW`; its stdio are the
  220. // broker's anonymous pipes), so without an explicit `hStd*`
  221. // wiring the child would try to allocate a conhost on the
  222. // non-interactive desktop — which under the restricted token
  223. // hangs.
  224. let mut six: STARTUPINFOEXW = unsafe { zeroed() };
  225. six.StartupInfo.cb = size_of::<STARTUPINFOEXW>() as u32;
  226. six.StartupInfo.dwFlags = STARTF_USESTDHANDLES;
  227. six.StartupInfo.hStdInput = std_handles[0];
  228. six.StartupInfo.hStdOutput = std_handles[1];
  229. six.StartupInfo.hStdError = std_handles[2];
  230. six.lpAttributeList = attrs.list();
  231. // `lpDesktop = NULL` (zeroed) → child inherits this runner's
  232. // station+desktop, which is the broker-created `srt-sb-…` per
  233. // step 4's assertion.
  234. // 9) Spawn suspended. `breakaway` was derived above (gated on
  235. // `IsProcessInJob(self)`).
  236. let mut pi: PROCESS_INFORMATION = unsafe { zeroed() };
  237. unsafe {
  238. CreateProcessAsUserW(
  239. Some(primary.raw()),
  240. pcwstr(&app_w),
  241. Some(PWSTR(cmdline_w.as_mut_ptr())),
  242. None,
  243. None,
  244. // Must be TRUE for `PROC_THREAD_ATTRIBUTE_HANDLE_LIST`
  245. // to take effect (documented Vista-era quirk: with
  246. // FALSE the kernel ignores the attribute entirely).
  247. true,
  248. // `CREATE_NO_WINDOW`: the runner has no console for the
  249. // child to attach to.
  250. CREATE_SUSPENDED
  251. | CREATE_UNICODE_ENVIRONMENT
  252. | EXTENDED_STARTUPINFO_PRESENT
  253. | CREATE_NO_WINDOW
  254. | breakaway,
  255. Some(env.as_mut_ptr() as *const c_void),
  256. // Inherit cwd.
  257. PCWSTR::null(),
  258. // STARTUPINFOEXW is layout-compatible (StartupInfo is
  259. // first member); EXTENDED_STARTUPINFO_PRESENT tells the
  260. // kernel to read past it for lpAttributeList.
  261. &six.StartupInfo as *const STARTUPINFOW,
  262. &mut pi,
  263. )
  264. .with_context(|| format!("CreateProcessAsUserW({})", target_exe.display()))?;
  265. }
  266. // The child exists, suspended, NOT yet in the job. Wrap it
  267. // in a guard so any `?` from here to `defuse()` terminates
  268. // it — `KILL_ON_JOB_CLOSE` can't help until after `assign`.
  269. let mut child = SpawnedChild::new(pi);
  270. // 10) Assign to job → resume. ResumeThread returns the
  271. // previous suspend count, or u32::MAX on failure — a
  272. // failure here would leave the child suspended in the
  273. // job and `WaitForSingleObject(INFINITE)` below would
  274. // hang the broker forever. Check before defusing the
  275. // terminate-on-drop guard.
  276. if let Err(e) = job.assign(child.process()) {
  277. // Self-explaining diagnostics for the next CI run: which
  278. // job(s) the child landed in despite breakaway.
  279. let in_any = is_process_in_job(child.process(), None);
  280. let in_ours = is_process_in_job(child.process(), Some(job.raw()));
  281. return Err(e).with_context(|| {
  282. format!(
  283. "AssignProcessToJobObject(child) — \
  284. caller_in_job={caller_in_job} breakaway={} \
  285. child_in_any_job={in_any} child_in_our_job={in_ours}",
  286. breakaway.0 != 0,
  287. )
  288. });
  289. }
  290. let prev_suspend = unsafe { ResumeThread(child.thread()) };
  291. if prev_suspend == u32::MAX {
  292. return Err(anyhow!("ResumeThread: {}", std::io::Error::last_os_error()));
  293. }
  294. // From here the job owns lifetime; disarm terminate-on-drop.
  295. child.defuse();
  296. if dbg {
  297. // Post-spawn diagnostic — paired with the pre-spawn line above
  298. // so a hung CI run can tell whether `WaitForSingleObject` is
  299. // the wait point (this line present) or spawn/assign/resume
  300. // itself is the stall (this line absent).
  301. eprintln!(
  302. "srt-win: run_lockdown: child pid={} assigned+resumed \
  303. (prev_suspend={prev_suspend}); waiting",
  304. pi.dwProcessId,
  305. );
  306. }
  307. // 11) Wait + collect exit code.
  308. let rc = unsafe { WaitForSingleObject(child.process(), INFINITE) };
  309. if rc != WAIT_OBJECT_0 {
  310. eprintln!("srt-win: WaitForSingleObject returned 0x{:x}", rc.0);
  311. }
  312. let mut code: u32 = 0;
  313. unsafe {
  314. GetExitCodeProcess(child.process(), &mut code).context("GetExitCodeProcess")?;
  315. }
  316. // `child` (closes hProcess/hThread), `primary`/`restricted`/
  317. // `self_tok` (CloseHandle) all drop here.
  318. // Keep `attrs` (its backing buffer + the borrowed `mitigation`
  319. // and `handle_list`) and `job` alive until here. The kernel
  320. // snapshots the attribute list at CreateProcess time, but
  321. // DeleteProcThreadAttributeList (in attrs.drop) may re-read
  322. // pointers.
  323. drop(attrs);
  324. drop(handle_list);
  325. drop(job);
  326. Ok(code)
  327. }
  328. // ─── Environment block ──────────────────────────────────────────────
  329. /// Build a `CREATE_UNICODE_ENVIRONMENT` block from the runner's own
  330. /// environment, **verbatim**.
  331. ///
  332. /// `srt-win exec` is a dumb passthrough for proxy configuration: it
  333. /// does NOT synthesize `HTTP_PROXY` / `ALL_PROXY` / `NO_PROXY` and has
  334. /// no `--http-proxy` / `--socks-proxy` flags. The single source of
  335. /// proxy env is the TS `generateProxyEnvVars`, which the caller passes
  336. /// via `--env`; this function just forwards the runner's environment
  337. /// (= the sandbox user's `LOGON_WITH_PROFILE` defaults) with the
  338. /// overlay applied on top to the child. No proxy value is invented,
  339. /// no inherited var is stripped or blanked.
  340. ///
  341. /// Entries are sorted case-insensitively by name for block ordering —
  342. /// not the strict case-insensitive Unicode collation the
  343. /// `CreateProcess` docs describe, but in practice the loader and
  344. /// `GetEnvironmentVariableW` don't enforce ordering; `cmd /c set` and
  345. /// every consumer we've tested work regardless. Names are NOT folded
  346. /// or deduplicated, so if both `HTTP_PROXY` and `http_proxy` are
  347. /// present both survive into the child.
  348. ///
  349. /// Two adjustments on top of the verbatim copy: (a) restoring the
  350. /// missing-case variants of `*_PROXY` variables (see
  351. /// [`add_proxy_case_twins`]) — casing repair of caller-provided
  352. /// values, not proxy synthesis; (b) applying `overlay` on top, where
  353. /// each `(KEY, VALUE)` REPLACES any base entry whose name matches
  354. /// case-insensitively (so the runner's broker-supplied `PATH`
  355. /// supersedes the sandbox-user default `PATH` while everything else
  356. /// passes through). Nothing else is added: consumers that need the
  357. /// broker's identity (e.g. the self-protect probe) discover it by
  358. /// walking the parent-process chain rather than via an environment
  359. /// variable.
  360. fn build_env_block(overlay: &[(String, String)]) -> Vec<u16> {
  361. use std::os::windows::ffi::OsStrExt;
  362. // Lossless base set — `env::vars()` PANICS on any entry whose
  363. // key or value is not valid UTF-8 (e.g. a PATH segment with an
  364. // unpaired surrogate from a profile path). Build from
  365. // `vars_os()` and encode each via `encode_wide` so nothing is
  366. // dropped and nothing panics.
  367. let overlay_upper: std::collections::HashSet<String> = overlay
  368. .iter()
  369. .map(|(k, _)| k.to_ascii_uppercase())
  370. .collect();
  371. let mut entries: Vec<(std::ffi::OsString, std::ffi::OsString)> = std::env::vars_os()
  372. .filter(|(k, _)| {
  373. // Drop base entries the overlay replaces. The
  374. // overlay keys are ASCII (PATH, *_PROXY, …); a base
  375. // key that doesn't round-trip as UTF-8 cannot match
  376. // one and is kept.
  377. k.to_str()
  378. .map(|s| !overlay_upper.contains(&s.to_ascii_uppercase()))
  379. .unwrap_or(true)
  380. })
  381. .collect();
  382. for (k, v) in overlay {
  383. entries.push((k.into(), v.into()));
  384. }
  385. // Proxy case-twin repair operates on the UTF-8-decodable
  386. // subset: proxy variable NAMES are ASCII by convention so
  387. // filtering to entries whose key round-trips as UTF-8 misses
  388. // nothing relevant; values are passed through lossily (the
  389. // helper only inspects names, never values). Built from the
  390. // post-overlay `entries` so an overlay-supplied `HTTP_PROXY`
  391. // gets its lowercase twin too.
  392. let mut twin_view: Vec<(String, String)> = entries
  393. .iter()
  394. .filter_map(|(k, v)| Some((k.to_str()?.to_owned(), v.to_string_lossy().into_owned())))
  395. .collect();
  396. let before = twin_view.len();
  397. add_proxy_case_twins(&mut twin_view);
  398. for (k, v) in twin_view.into_iter().skip(before) {
  399. entries.push((k.into(), v.into()));
  400. }
  401. // Order the block case-insensitively by name; values pass
  402. // through verbatim. No dedup — case-variant duplicates are
  403. // preserved. The sort key uses `to_string_lossy` only for
  404. // ordering; the encoded bytes use `encode_wide` losslessly.
  405. entries.sort_by_cached_key(|(k, _)| k.to_string_lossy().to_ascii_uppercase());
  406. // Encode: `KEY=VALUE\0`… `\0`.
  407. let mut out: Vec<u16> = Vec::new();
  408. for (k, v) in entries {
  409. out.extend(k.encode_wide());
  410. out.push(b'=' as u16);
  411. out.extend(v.encode_wide());
  412. out.push(0);
  413. }
  414. out.push(0);
  415. out
  416. }
  417. /// Re-add the missing-case variants of `*_PROXY` variables (the host
  418. /// spawn layer collapses case-duplicate keys) so that Cygwin/MSYS2
  419. /// programs — which see a case-sensitive environment — still find
  420. /// them. For every entry whose name ends with `_PROXY`
  421. /// (case-insensitively), the all-uppercase and all-lowercase forms of
  422. /// that name are appended where missing, with the same value. Existing
  423. /// keys are never overwritten and nothing is added for names that are
  424. /// not `*_PROXY`.
  425. fn add_proxy_case_twins(entries: &mut Vec<(String, String)>) {
  426. let mut names: std::collections::HashSet<String> =
  427. entries.iter().map(|(k, _)| k.clone()).collect();
  428. let mut twins: Vec<(String, String)> = Vec::new();
  429. for (k, v) in entries.iter() {
  430. if !k.to_ascii_uppercase().ends_with("_PROXY") {
  431. continue;
  432. }
  433. for form in [k.to_ascii_uppercase(), k.to_ascii_lowercase()] {
  434. if !names.contains(&form) {
  435. names.insert(form.clone());
  436. twins.push((form, v.clone()));
  437. }
  438. }
  439. }
  440. entries.extend(twins);
  441. }
  442. // ─── Command-line quoting ───────────────────────────────────────────
  443. /// MSVCRT / `CommandLineToArgvW` quoting for one argument.
  444. /// Public so `main.rs`'s self-elevate path can rebuild
  445. /// `lpParameters` from `std::env::args()`.
  446. pub fn quote_arg(a: &str) -> String {
  447. if !a.is_empty() && !a.chars().any(|c| matches!(c, ' ' | '\t' | '"' | '\\')) {
  448. return a.to_string();
  449. }
  450. let mut out = String::with_capacity(a.len() + 2);
  451. out.push('"');
  452. let mut backslashes = 0usize;
  453. for c in a.chars() {
  454. match c {
  455. '\\' => {
  456. backslashes += 1;
  457. out.push('\\');
  458. }
  459. '"' => {
  460. // Double the run of backslashes, then escape the
  461. // quote.
  462. for _ in 0..backslashes {
  463. out.push('\\');
  464. }
  465. out.push('\\');
  466. out.push('"');
  467. backslashes = 0;
  468. }
  469. _ => {
  470. backslashes = 0;
  471. out.push(c);
  472. }
  473. }
  474. }
  475. // Trailing backslash run before the closing quote must double.
  476. for _ in 0..backslashes {
  477. out.push('\\');
  478. }
  479. out.push('"');
  480. out
  481. }
  482. fn target_is_cmd(exe: &Path) -> bool {
  483. exe.file_name()
  484. .and_then(|n| n.to_str())
  485. .map(|s| {
  486. // Win32 strips trailing dots/spaces from the final
  487. // path component, so `cmd.exe.` launches real cmd —
  488. // match it here so it gets cmd quoting, not MSVCRT.
  489. let s = s.trim_end_matches(['.', ' ']);
  490. s.eq_ignore_ascii_case("cmd.exe") || s.eq_ignore_ascii_case("cmd")
  491. })
  492. .unwrap_or(false)
  493. }
  494. /// Build the full command line.
  495. ///
  496. /// **Non-cmd targets:** every arg is MSVCRT-quoted via
  497. /// [`quote_arg`] so `CommandLineToArgvW` in the child recovers
  498. /// the exact argv.
  499. ///
  500. /// **`cmd.exe` targets:** cmd does NOT use `CommandLineToArgvW`;
  501. /// it parses `lpCommandLine` itself. With `/s`, it strips the
  502. /// first and last `"` of the post-`/c` portion and runs what's
  503. /// between *verbatim* under cmd's own rules. The caller is
  504. /// expected to include `/s`; without it cmd falls back to the
  505. /// legacy "if exactly two quotes and they wrap a runnable
  506. /// command, strip them; otherwise leave alone" heuristic, and
  507. /// the wrapper quote may not strip cleanly. (The TS
  508. /// `wrapWithSandboxArgv` always passes `/d /s /c`.) So we:
  509. /// 1. Emit the exe + flags up to and including `/c|/k|/r`
  510. /// using `quote_arg` (these are simple tokens; quoting is
  511. /// a no-op unless the exe path has spaces).
  512. /// 2. Join the remaining argv elements with single spaces —
  513. /// this is the user's cmd command string, reconstructed.
  514. /// 3. Wrap that in ONE outer `"…"` pair for `/s` to strip.
  515. ///
  516. /// The post-`/c` content is **passed through unmodified**. We
  517. /// do NOT caret-escape `& | < > ^ ( )` and do NOT touch `"` —
  518. /// the contract is "this is a cmd.exe command string" and the
  519. /// caller (the TS `wrapWithSandboxArgv`) supplies it as such.
  520. /// `&` chains commands, `"…"` quotes — exactly as the user
  521. /// typed. The child IS the sandbox, so cmd metachars here are
  522. /// the user's tool, not an escape vector. (The host-shell
  523. /// injection concern is about the OUTER spawn, which is solved
  524. /// by argv-mode in the TS layer; this is the inner sandboxed
  525. /// cmd.)
  526. ///
  527. /// An earlier revision per-arg-doubled `"` → `""`, which cmd
  528. /// treats as a quote-state *toggle*, not a literal — that
  529. /// mis-parsed payloads containing `&` and was reverted.
  530. pub fn build_cmdline(exe: &Path, args: &[String]) -> String {
  531. let cmd_split = if target_is_cmd(exe) {
  532. args.iter()
  533. .position(|a| matches!(a.to_ascii_lowercase().as_str(), "/c" | "/k" | "/r"))
  534. } else {
  535. None
  536. };
  537. let mut s = quote_arg(&exe.display().to_string());
  538. match cmd_split {
  539. Some(p) => {
  540. for a in &args[..=p] {
  541. s.push(' ');
  542. s.push_str(&quote_arg(a));
  543. }
  544. // One outer pair of quotes around the whole post-/c
  545. // command for `/s` to strip; contents verbatim.
  546. s.push_str(" \"");
  547. s.push_str(&args[p + 1..].join(" "));
  548. s.push('"');
  549. }
  550. None => {
  551. for a in args {
  552. s.push(' ');
  553. s.push_str(&quote_arg(a));
  554. }
  555. }
  556. }
  557. s
  558. }
  559. // ─── PROC_THREAD_ATTRIBUTE_LIST helper ──────────────────────────────
  560. /// RAII wrapper over an opaque `LPPROC_THREAD_ATTRIBUTE_LIST`.
  561. /// `Drop` calls `DeleteProcThreadAttributeList`. The values passed
  562. /// to [`set_*`] must outlive `self` — the kernel reads them by
  563. /// pointer at `CreateProcess` time.
  564. struct ProcThreadAttrs {
  565. storage: Vec<u8>,
  566. }
  567. impl ProcThreadAttrs {
  568. fn new(count: u32) -> Result<Self> {
  569. let mut size = 0usize;
  570. // Sizing call — expected to fail with
  571. // ERROR_INSUFFICIENT_BUFFER and write the required size.
  572. unsafe {
  573. let _ = InitializeProcThreadAttributeList(None, count, None, &mut size);
  574. }
  575. if size == 0 {
  576. return Err(anyhow!(
  577. "InitializeProcThreadAttributeList sizing returned 0"
  578. ));
  579. }
  580. let mut storage = vec![0u8; size];
  581. unsafe {
  582. InitializeProcThreadAttributeList(
  583. Some(LPPROC_THREAD_ATTRIBUTE_LIST(
  584. storage.as_mut_ptr() as *mut c_void
  585. )),
  586. count,
  587. None,
  588. &mut size,
  589. )
  590. .context("InitializeProcThreadAttributeList")?;
  591. }
  592. Ok(Self { storage })
  593. }
  594. fn list(&mut self) -> LPPROC_THREAD_ATTRIBUTE_LIST {
  595. LPPROC_THREAD_ATTRIBUTE_LIST(self.storage.as_mut_ptr() as *mut c_void)
  596. }
  597. fn set_mitigation_policy(&mut self, policy: &u64) -> Result<()> {
  598. unsafe {
  599. UpdateProcThreadAttribute(
  600. self.list(),
  601. 0,
  602. PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY as usize,
  603. Some(policy as *const u64 as *const c_void),
  604. size_of::<u64>(),
  605. None,
  606. None,
  607. )
  608. .context("UpdateProcThreadAttribute(MITIGATION_POLICY)")
  609. }
  610. }
  611. /// `UpdateProcThreadAttribute(HANDLE_LIST)` requires at least
  612. /// one entry — Windows rejects an empty list with
  613. /// `ERROR_BAD_LENGTH`. The caller is expected to have filtered
  614. /// already.
  615. fn set_handle_list(&mut self, handles: &mut [HANDLE]) -> Result<()> {
  616. debug_assert!(!handles.is_empty());
  617. unsafe {
  618. UpdateProcThreadAttribute(
  619. self.list(),
  620. 0,
  621. PROC_THREAD_ATTRIBUTE_HANDLE_LIST as usize,
  622. Some(handles.as_ptr() as *const c_void),
  623. std::mem::size_of_val(handles),
  624. None,
  625. None,
  626. )
  627. .context("UpdateProcThreadAttribute(HANDLE_LIST)")
  628. }
  629. }
  630. }
  631. impl Drop for ProcThreadAttrs {
  632. fn drop(&mut self) {
  633. unsafe {
  634. DeleteProcThreadAttributeList(self.list());
  635. }
  636. }
  637. }
  638. /// Mark this process's std handles inheritable and return them as
  639. /// `[stdin, stdout, stderr]`. A slot whose handle is unavailable
  640. /// (null / `INVALID_HANDLE_VALUE` / `SetHandleInformation` refused)
  641. /// is `HANDLE::default()`.
  642. ///
  643. /// `run_lockdown` plugs the array into BOTH `STARTUPINFO.hStd*`
  644. /// (`STARTF_USESTDHANDLES`) and the `PROC_THREAD_ATTRIBUTE_HANDLE_LIST`
  645. /// inherit whitelist — one source of truth so a handle that didn't
  646. /// make the whitelist is also `default()` in `hStd*` (the child sees
  647. /// a null std handle for that stream rather than a stale value the
  648. /// kernel never duplicated).
  649. fn collect_inheritable_std_handles() -> [HANDLE; 3] {
  650. let mut out = [HANDLE::default(); 3];
  651. for (i, which) in [STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE]
  652. .into_iter()
  653. .enumerate()
  654. {
  655. let h = match unsafe { GetStdHandle(which) } {
  656. Ok(h) => h,
  657. Err(_) => continue,
  658. };
  659. if h.0.is_null() || (h.0 as isize) == -1 {
  660. continue;
  661. }
  662. // Best-effort: a detached caller may have non-inheritable
  663. // (or pseudo) handles here; skip rather than fail.
  664. let r = unsafe { SetHandleInformation(h, HANDLE_FLAG_INHERIT.0, HANDLE_FLAG_INHERIT) };
  665. if r.is_ok() {
  666. out[i] = h;
  667. }
  668. }
  669. out
  670. }
  671. #[cfg(test)]
  672. mod tests {
  673. use super::*;
  674. #[test]
  675. fn quote_arg_simple() {
  676. assert_eq!(quote_arg("foo"), "foo");
  677. assert_eq!(quote_arg(""), "\"\"");
  678. assert_eq!(quote_arg("a b"), "\"a b\"");
  679. }
  680. #[test]
  681. fn quote_arg_backslash_quote() {
  682. // a\"b → "a\\\"b"
  683. assert_eq!(quote_arg(r#"a\"b"#), r#""a\\\"b""#);
  684. // trailing backslashes double before closing quote
  685. assert_eq!(quote_arg(r"a\"), r#""a\\""#);
  686. assert_eq!(quote_arg(r"a\\"), r#""a\\\\""#);
  687. }
  688. #[test]
  689. fn build_cmdline_cmd_passthrough() {
  690. let exe = Path::new(r"C:\Windows\System32\cmd.exe");
  691. // post-/c content is wrapped once in "…" for /s to strip;
  692. // inner quotes and metachars are NOT touched.
  693. let line = build_cmdline(
  694. exe,
  695. &[
  696. "/d".into(),
  697. "/s".into(),
  698. "/c".into(),
  699. r#"echo "x & y""#.into(),
  700. ],
  701. );
  702. assert_eq!(
  703. line,
  704. r#""C:\Windows\System32\cmd.exe" /d /s /c "echo "x & y"""#
  705. );
  706. // Multiple post-/c argv elements are joined with a space.
  707. let line2 = build_cmdline(
  708. exe,
  709. &[
  710. "/c".into(),
  711. "echo".into(),
  712. "a".into(),
  713. "&".into(),
  714. "echo".into(),
  715. "b".into(),
  716. ],
  717. );
  718. assert_eq!(
  719. line2,
  720. r#""C:\Windows\System32\cmd.exe" /c "echo a & echo b""#
  721. );
  722. }
  723. #[test]
  724. fn build_cmdline_cmd_no_split_when_no_c_flag() {
  725. // cmd.exe without /c|/k|/r → MSVCRT quoting throughout.
  726. let exe = Path::new("cmd.exe");
  727. let line = build_cmdline(exe, &["/?".into()]);
  728. assert_eq!(line, r#"cmd.exe /?"#);
  729. }
  730. #[test]
  731. fn build_cmdline_non_cmd_uses_msvcrt_quoting() {
  732. let exe = Path::new(r"C:\foo\bar.exe");
  733. let args = vec![r#"a "b"#.into()];
  734. let line = build_cmdline(exe, &args);
  735. assert!(line.ends_with(r#""a \"b""#), "got: {line}");
  736. }
  737. #[test]
  738. fn proxy_case_twins_suffix_rule_covers_any_proxy_var() {
  739. let mut entries = vec![
  740. // Any *_PROXY name is twinned, not just the standard trio.
  741. (
  742. "GRPC_PROXY".to_string(),
  743. "socks5h://localhost:60081".to_string(),
  744. ),
  745. // Mixed-case input → BOTH canonical forms appended.
  746. (
  747. "Http_Proxy".to_string(),
  748. "http://localhost:60080".to_string(),
  749. ),
  750. // Names that merely contain or extend the suffix are not.
  751. ("FOO_PROXYX".to_string(), "x".to_string()),
  752. ("PATH".to_string(), r"C:\Windows".to_string()),
  753. ];
  754. add_proxy_case_twins(&mut entries);
  755. let matching = |name: &str| {
  756. entries
  757. .iter()
  758. .filter(|(k, _)| k == name)
  759. .collect::<Vec<_>>()
  760. };
  761. assert_eq!(matching("grpc_proxy").len(), 1);
  762. assert_eq!(matching("grpc_proxy")[0].1, "socks5h://localhost:60081");
  763. assert_eq!(matching("GRPC_PROXY").len(), 1);
  764. // Mixed-case original is preserved AND both canonical forms added.
  765. assert_eq!(matching("Http_Proxy").len(), 1);
  766. assert_eq!(matching("HTTP_PROXY").len(), 1);
  767. assert_eq!(matching("http_proxy").len(), 1);
  768. assert_eq!(matching("http_proxy")[0].1, "http://localhost:60080");
  769. // Non-matching names untouched, nothing appended for them.
  770. assert_eq!(matching("FOO_PROXYX").len(), 1);
  771. assert!(matching("foo_proxyx").is_empty());
  772. assert_eq!(matching("PATH").len(), 1);
  773. assert!(matching("path").is_empty());
  774. }
  775. }