runner.rs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. //! `srt-win runner` — the inside-the-logon half of the two-hop
  2. //! launch.
  3. //!
  4. //! The broker (running as the **real** user) decrypts the sandbox
  5. //! user's password and `CreateProcessWithLogonW`s **this**
  6. //! subcommand under the `srt-sandbox` account. The runner reads a
  7. //! [`RunnerCmd`] from stdin and either runs
  8. //! [`crate::launch::run_lockdown`] (restricted token, job, desktop,
  9. //! mitigations, handle whitelist), or — at install time — writes
  10. //! the MITM CA into the sandbox user's `CurrentUser\Root` (see
  11. //! [`crate::cert_store`]). The child inherits the runner's stdio,
  12. //! which are the broker's pipes, so stdout/stderr flow broker ←
  13. //! runner ← child without an extra pump.
  14. //!
  15. //! All state-DB work happens in the **broker**, never here: the
  16. //! state-DB directory carries an explicit DENY for
  17. //! `sandbox-runtime-users`, so the runner cannot open it.
  18. use anyhow::{Context, Result, anyhow};
  19. use serde::{Deserialize, Serialize};
  20. use std::io::Read;
  21. use crate::launch;
  22. /// What the broker asks the runner to do. Passed over stdin (4-byte
  23. /// LE length prefix + JSON). Stdin — not argv or env — because the
  24. /// env overlay can exceed what `lpCommandLine` reliably carries, and
  25. /// a temp file would need a path the sandbox user can read (the
  26. /// broker's `%TEMP%` may not be).
  27. #[derive(Debug, Serialize, Deserialize)]
  28. pub enum RunnerCmd {
  29. /// Per-exec: run the target under [`crate::launch::run_lockdown`].
  30. Exec(RunnerSpec),
  31. /// Install-time, one-shot: write the DER-encoded CA into the
  32. /// **sandbox user's** `CurrentUser\Root` (direct
  33. /// `HKEY_USERS\<own-SID>\…\Root\Certificates\<thumb>` registry
  34. /// write — see [`crate::cert_store`]). Persistent until
  35. /// `srt-win uninstall` deletes the profile. Exit non-zero on
  36. /// failure.
  37. InstallCa { der: crate::cert_store::CertDer },
  38. /// `wfp verify` probe: attempt a direct TCP connect to `target`
  39. /// (`host:port`) **as the sandbox user**. The WFP block-user
  40. /// filter fires at `ALE_AUTH_CONNECT` — before any packet
  41. /// leaves — so an active fence yields WSAEACCES immediately;
  42. /// a missing fence lets the connect through. Exit **0** =
  43. /// WSAEACCES (fence active), **3** = connected (fence
  44. /// MISSING), **2** = any other error (timeout/unreachable —
  45. /// the broker treats it as failure). Exit 1 is reserved for
  46. /// the runner's own anyhow `Err` path so a malformed target
  47. /// or future runner bug isn't misread as `connected`. No
  48. /// desk/grants/lockdown — the probe runs as the bare runner
  49. /// (same as [`InstallCa`](Self::InstallCa)); the WFP filter
  50. /// keys on the user SID, which the runner already carries.
  51. ProbeEgress { target: String },
  52. }
  53. /// Inputs to a single [`RunnerCmd::Exec`].
  54. #[derive(Debug, Serialize, Deserialize)]
  55. pub struct RunnerSpec {
  56. /// `argv[0]` = target executable; `argv[1..]` = its arguments.
  57. pub argv: Vec<String>,
  58. /// `(KEY, VALUE)` pairs overlaid on the runner's own environment
  59. /// (= the sandbox user's `LOGON_WITH_PROFILE` defaults) when
  60. /// building the child's env block. Overlay wins on key conflict
  61. /// (case-insensitive), so the broker's `PATH` replaces the
  62. /// sandbox user's machine-only `PATH` while `USERPROFILE` /
  63. /// `TEMP` stay isolated. The proxy var set rides here too.
  64. pub env_overlay: Vec<(String, String)>,
  65. }
  66. /// Read a 4-byte little-endian length prefix followed by that many
  67. /// bytes of JSON from stdin. The length prefix lets the runner know
  68. /// when the spec ends without the broker closing the write end
  69. /// (which it does anyway — the prefix is just robustness against a
  70. /// future stdin-after-spec use).
  71. fn read_cmd_from_stdin() -> Result<RunnerCmd> {
  72. let mut stdin = std::io::stdin().lock();
  73. let mut len_buf = [0u8; 4];
  74. stdin
  75. .read_exact(&mut len_buf)
  76. .context("runner: read spec length prefix from stdin")?;
  77. let len = u32::from_le_bytes(len_buf) as usize;
  78. // Sanity cap — the spec is a few KB; anything in the MB range
  79. // means the broker/runner are out of sync.
  80. if len > 4 * 1024 * 1024 {
  81. return Err(anyhow!(
  82. "runner: spec length {len} exceeds 4 MiB sanity cap"
  83. ));
  84. }
  85. let mut buf = vec![0u8; len];
  86. stdin
  87. .read_exact(&mut buf)
  88. .context("runner: read spec body from stdin")?;
  89. serde_json::from_slice(&buf).context("runner: parse spec JSON")
  90. }
  91. /// Serialize `cmd` as `<u32 LE length><JSON>`. Broker-side helper —
  92. /// lives here so the wire format has one definition.
  93. pub fn encode_cmd(cmd: &RunnerCmd) -> Result<Vec<u8>> {
  94. let json = serde_json::to_vec(cmd).context("runner: encode cmd")?;
  95. let mut out = Vec::with_capacity(4 + json.len());
  96. out.extend_from_slice(&(json.len() as u32).to_le_bytes());
  97. out.extend_from_slice(&json);
  98. Ok(out)
  99. }
  100. /// Entry point for `srt-win runner`. Reads the command from stdin,
  101. /// dispatches, and returns the exit code.
  102. pub fn run() -> Result<u32> {
  103. match read_cmd_from_stdin()? {
  104. RunnerCmd::Exec(spec) => {
  105. if spec.argv.is_empty() {
  106. return Err(anyhow!("runner: spec.argv is empty"));
  107. }
  108. if std::env::var_os("SANDBOX_RUNTIME_WIN_DEBUG").is_some() {
  109. eprintln!(
  110. "srt-win: runner: spec read (argv={} env_overlay={})",
  111. spec.argv.len(),
  112. spec.env_overlay.len(),
  113. );
  114. }
  115. let exe = std::path::PathBuf::from(&spec.argv[0]);
  116. launch::run_lockdown(&exe, &spec.argv[1..], &spec.env_overlay)
  117. }
  118. RunnerCmd::InstallCa { der } => {
  119. let thumb = crate::cert_store::install_root_ca(&der)?;
  120. eprintln!(
  121. "srt-win: runner: CA installed into sandbox-user \
  122. CurrentUser\\Root (thumb={thumb})"
  123. );
  124. Ok(0)
  125. }
  126. RunnerCmd::ProbeEgress { target } => {
  127. use std::net::{SocketAddr, TcpStream};
  128. use std::time::Duration;
  129. // WSAEACCES — what WFP returns from ALE_AUTH_CONNECT
  130. // when the block-user filter denies the connect. Match
  131. // on the raw code (not `ErrorKind::PermissionDenied`)
  132. // so `ERROR_ACCESS_DENIED` (5) — which would mean
  133. // something OTHER than the WFP fence — falls through
  134. // to `unreachable`.
  135. const WSAEACCES: i32 = 10013;
  136. let addr: SocketAddr = target
  137. .parse()
  138. .with_context(|| format!("runner: ProbeEgress target '{target}'"))?;
  139. // stderr (not stdout): `spawn_runner` pumps the
  140. // runner's stdout straight to the broker's stdout, and
  141. // the broker writes its own JSON there. The exit code
  142. // is the contract; the line is diagnostic.
  143. match TcpStream::connect_timeout(&addr, Duration::from_secs(2)) {
  144. Err(e) if e.raw_os_error() == Some(WSAEACCES) => {
  145. eprintln!(
  146. "srt-win: runner: egress probe {target}: \
  147. BLOCKED ({e})"
  148. );
  149. Ok(0)
  150. }
  151. Ok(_) => {
  152. eprintln!(
  153. "srt-win: runner: egress probe {target}: \
  154. CONNECTED — WFP block-user filter is NOT in \
  155. effect"
  156. );
  157. Ok(3)
  158. }
  159. Err(e) => {
  160. eprintln!(
  161. "srt-win: runner: egress probe {target}: \
  162. UNREACHABLE: {e} (kind={:?}, os={:?})",
  163. e.kind(),
  164. e.raw_os_error(),
  165. );
  166. Ok(2)
  167. }
  168. }
  169. }
  170. }
  171. }
  172. #[cfg(test)]
  173. mod tests {
  174. use super::*;
  175. #[test]
  176. fn cmd_roundtrip() {
  177. let s = RunnerCmd::Exec(RunnerSpec {
  178. argv: vec!["cmd.exe".into(), "/c".into(), "echo hi".into()],
  179. env_overlay: vec![("PATH".into(), r"C:\a;C:\b".into())],
  180. });
  181. let bytes = encode_cmd(&s).unwrap();
  182. assert_eq!(
  183. u32::from_le_bytes(bytes[..4].try_into().unwrap()) as usize,
  184. bytes.len() - 4
  185. );
  186. let back: RunnerCmd = serde_json::from_slice(&bytes[4..]).unwrap();
  187. match back {
  188. RunnerCmd::Exec(r) => {
  189. assert_eq!(r.argv, ["cmd.exe", "/c", "echo hi"]);
  190. assert_eq!(r.env_overlay.len(), 1);
  191. }
  192. _ => panic!("wrong variant"),
  193. }
  194. let ca = RunnerCmd::InstallCa {
  195. der: crate::cert_store::CertDer::raw(vec![0x30, 0x82]),
  196. };
  197. let bytes = encode_cmd(&ca).unwrap();
  198. let back: RunnerCmd = serde_json::from_slice(&bytes[4..]).unwrap();
  199. assert!(matches!(
  200. back, RunnerCmd::InstallCa { der } if der.as_bytes() == [0x30, 0x82]
  201. ));
  202. let probe = RunnerCmd::ProbeEgress {
  203. target: "127.0.0.1:49999".into(),
  204. };
  205. let bytes = encode_cmd(&probe).unwrap();
  206. let back: RunnerCmd = serde_json::from_slice(&bytes[4..]).unwrap();
  207. assert!(matches!(
  208. back, RunnerCmd::ProbeEgress { target } if target == "127.0.0.1:49999"
  209. ));
  210. }
  211. }