wfp.rs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  1. //! Windows Filtering Platform (WFP) filter management for the
  2. //! sandbox-runtime Windows network fence.
  3. //!
  4. //! ## Design
  5. //!
  6. //! At install time we provision the dedicated `srt-sandbox` local
  7. //! user account ([`crate::user`]) and persist **one machine-wide**
  8. //! filter set — two filters at each of `FWPM_LAYER_ALE_AUTH_CONNECT_V4`
  9. //! and `_V6` (4 total), all under one persistent sublayer:
  10. //!
  11. //! - **PERMIT loopback** (weight [`W_LOOPBACK`]) —
  12. //! `IP_REMOTE_ADDRESS` is `127.0.0.0/8` (v4) / `::1` (v6) **and**
  13. //! `IP_REMOTE_PORT` is in `[low, high]` (default 60080–60089). No
  14. //! user condition. The sandboxed child reaches the host proxies —
  15. //! which on Windows bind inside this range — but not arbitrary
  16. //! loopback listeners. (Linux/macOS restrict the child to exactly
  17. //! the two proxy ports; this range is the closest Windows
  18. //! analogue without per-`initialize()` admin.)
  19. //!
  20. //! - **BLOCK sandbox user** (weight [`W_BLOCK`]) — `ALE_USER_ID` SD
  21. //! = [`sddl_sandbox_user`]. Matches only tokens whose user SID is
  22. //! `<srt-sandbox SID>`. Everyone else (the broker, services,
  23. //! SYSTEM, the real user) carries a different user SID → no match
  24. //! → falls through to default-permit.
  25. //!
  26. //! WFP's `ALE_USER_ID` condition with `FWP_MATCH_EQUAL` evaluates the
  27. //! supplied security descriptor via `AccessCheck` against the
  28. //! connecting token: the filter *matches* iff the check grants
  29. //! access. Keying on the **user SID** means the surrogate-spawn
  30. //! class (schtasks, `PROC_THREAD_ATTRIBUTE_PARENT_PROCESS`, BITS,
  31. //! RunAs="Interactive User" COM) cannot defeat it: a process spawned
  32. //! under `srt-sandbox` by ANY mechanism still has the user SID and
  33. //! still matches the BLOCK.
  34. //!
  35. //! Filters carry a small JSON tag in `providerData` (`{tool, kind,
  36. //! port_range?, user_sid}`) so install/uninstall/status can locate
  37. //! them by enumeration. BFE enumeration is admin-gated (see
  38. //! [`WfpAccessDenied`]) — `wfp status` returns `cannot-read` for a
  39. //! non-elevated caller; the non-elevated readiness check is `srt-win
  40. //! wfp verify` (a behavioral connect probe).
  41. // The WFP structs are large and partially-initialised; the
  42. // `..Default::default()` struct-update form clippy suggests is
  43. // significantly less readable here than field-by-field assignment.
  44. #![allow(clippy::field_reassign_with_default)]
  45. use crate::util::wstr;
  46. use anyhow::{Context, Result, anyhow};
  47. use serde::{Deserialize, Serialize};
  48. use std::ffi::c_void;
  49. use windows::Win32::Foundation::HANDLE;
  50. use windows::Win32::NetworkManagement::WindowsFilteringPlatform::{
  51. FWP_ACTION_BLOCK, FWP_ACTION_PERMIT, FWP_ACTION_TYPE, FWP_BYTE_ARRAY16, FWP_BYTE_ARRAY16_TYPE,
  52. FWP_BYTE_BLOB, FWP_CONDITION_VALUE0, FWP_CONDITION_VALUE0_0, FWP_FILTER_ENUM_OVERLAPPING,
  53. FWP_MATCH_EQUAL, FWP_MATCH_RANGE, FWP_RANGE_TYPE, FWP_RANGE0, FWP_SECURITY_DESCRIPTOR_TYPE,
  54. FWP_UINT16, FWP_UINT64, FWP_V4_ADDR_AND_MASK, FWP_V4_ADDR_MASK, FWP_VALUE0, FWP_VALUE0_0,
  55. FWPM_ACTION0, FWPM_ACTION0_0, FWPM_CONDITION_ALE_USER_ID, FWPM_CONDITION_IP_REMOTE_ADDRESS,
  56. FWPM_CONDITION_IP_REMOTE_PORT, FWPM_DISPLAY_DATA0, FWPM_FILTER_CONDITION0,
  57. FWPM_FILTER_ENUM_TEMPLATE0, FWPM_FILTER_FLAG_PERSISTENT, FWPM_FILTER0,
  58. FWPM_LAYER_ALE_AUTH_CONNECT_V4, FWPM_LAYER_ALE_AUTH_CONNECT_V6, FWPM_SUBLAYER_FLAG_PERSISTENT,
  59. FWPM_SUBLAYER0, FwpmEngineClose0, FwpmEngineOpen0, FwpmFilterAdd0, FwpmFilterCreateEnumHandle0,
  60. FwpmFilterDeleteByKey0, FwpmFilterDestroyEnumHandle0, FwpmFilterEnum0, FwpmFreeMemory0,
  61. FwpmSubLayerAdd0, FwpmSubLayerDeleteByKey0, FwpmTransactionAbort0, FwpmTransactionBegin0,
  62. FwpmTransactionCommit0,
  63. };
  64. use windows::core::{GUID, PCWSTR, PWSTR};
  65. /// Default sublayer GUID. Stable so uninstall can find filters from a
  66. /// previous install. Overridable via `--sublayer-guid` so an
  67. /// enterprise that provisions WFP via its own tooling can point us at
  68. /// theirs. {2c5d0ad6-5f3b-4d4e-9b8f-1a3e7c9d0b21}
  69. pub const DEFAULT_SUBLAYER_GUID: GUID = GUID::from_u128(0x2c5d0ad6_5f3b_4d4e_9b8f_1a3e7c9d0b21);
  70. /// Default loopback port range for the PERMIT filter. The JS mux
  71. /// proxy (front-end + http backend) binds inside this range on
  72. /// Windows so the sandboxed child can reach it. Ten ports leaves
  73. /// headroom for both listeners and for `EADDRINUSE` retries.
  74. /// Overridable via `--proxy-port-range`.
  75. pub const DEFAULT_PROXY_PORT_RANGE: (u16, u16) = (60080, 60089);
  76. /// Sanity cap on `--proxy-port-range` width (`high - low`). The
  77. /// range exists to *narrow* loopback exposure relative to a
  78. /// blanket all-of-127/8 PERMIT; an unbounded range would defeat
  79. /// that.
  80. pub const MAX_PROXY_PORT_RANGE_WIDTH: u16 = 64;
  81. // WFP error codes we treat as benign idempotency outcomes.
  82. const FWP_E_ALREADY_EXISTS: u32 = 0x80320009;
  83. const FWP_E_FILTER_NOT_FOUND: u32 = 0x80320003;
  84. const FWP_E_SUBLAYER_NOT_FOUND: u32 = 0x80320007;
  85. const FWP_E_IN_USE: u32 = 0x8032000A;
  86. // `FwpmEngineOpen0` / `FwpmFilterCreateEnumHandle0` are admin-gated
  87. // by BFE; non-elevated callers get one of these.
  88. const FWP_E_ACCESS_DENIED: u32 = 0x8032_0028;
  89. const ERROR_ACCESS_DENIED: u32 = 5;
  90. use crate::util::OwnedSd;
  91. /// Typed marker for an admin-gated BFE call returning access-denied.
  92. /// `FwpmFilterCreateEnumHandle0` (and on some configurations
  93. /// `FwpmEngineOpen0`) require elevation; a non-elevated `wfp status`
  94. /// hits this. [`filter_status`] downcasts and degrades to
  95. /// `state:"cannot-read"`; the host's behavioral check is `wfp
  96. /// verify`, not the enum.
  97. #[derive(Debug)]
  98. pub struct WfpAccessDenied {
  99. pub call: &'static str,
  100. pub rc: u32,
  101. }
  102. impl std::fmt::Display for WfpAccessDenied {
  103. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  104. write!(
  105. f,
  106. "{}: 0x{:08x} (BFE filter enumeration is admin-only)",
  107. self.call, self.rc
  108. )
  109. }
  110. }
  111. impl std::error::Error for WfpAccessDenied {}
  112. fn is_bfe_access_denied(rc: u32) -> bool {
  113. rc == ERROR_ACCESS_DENIED || rc == FWP_E_ACCESS_DENIED
  114. }
  115. // ────────────────────── small RAII helpers ──────────────────────
  116. /// Borrow an `OwnedSd` as the `FWP_BYTE_BLOB` shape WFP wants for
  117. /// provider data. The caller must keep `sd` alive for the duration.
  118. fn sd_byte_blob(sd: &OwnedSd) -> FWP_BYTE_BLOB {
  119. FWP_BYTE_BLOB {
  120. size: sd.len,
  121. data: sd.ptr.0 as *mut u8,
  122. }
  123. }
  124. /// WFP engine handle; closed on drop.
  125. struct EngineHandle(HANDLE);
  126. impl EngineHandle {
  127. fn open() -> Result<Self> {
  128. let mut h = HANDLE::default();
  129. // RPC_C_AUTHN_DEFAULT
  130. let rc = unsafe { FwpmEngineOpen0(PCWSTR::null(), 0xFFFF_FFFF, None, None, &mut h) };
  131. if rc != 0 {
  132. if is_bfe_access_denied(rc) {
  133. return Err(anyhow::Error::new(WfpAccessDenied {
  134. call: "FwpmEngineOpen0",
  135. rc,
  136. }));
  137. }
  138. return Err(anyhow!("FwpmEngineOpen0 failed: 0x{rc:08x}"));
  139. }
  140. Ok(Self(h))
  141. }
  142. fn h(&self) -> HANDLE {
  143. self.0
  144. }
  145. }
  146. impl Drop for EngineHandle {
  147. fn drop(&mut self) {
  148. if !self.0.is_invalid() {
  149. unsafe {
  150. let _ = FwpmEngineClose0(self.0);
  151. }
  152. }
  153. }
  154. }
  155. /// Open the engine, run `f` inside one WFP transaction
  156. /// (`FwpmTransactionBegin0` … `Commit0`). Aborts the transaction if
  157. /// `f` returns an error or panics, then closes the engine. Single
  158. /// owner of the txn-envelope shape so the install/uninstall sites
  159. /// can't drift.
  160. fn with_wfp_txn<T>(f: impl FnOnce(&EngineHandle) -> Result<T>) -> Result<T> {
  161. let engine = EngineHandle::open()?;
  162. let rc = unsafe { FwpmTransactionBegin0(engine.h(), 0) };
  163. if rc != 0 {
  164. return Err(anyhow!("FwpmTransactionBegin0: 0x{rc:08x}"));
  165. }
  166. // Abort-on-unwind: if `f` panics, this guard's Drop aborts the
  167. // open txn before EngineHandle's Drop closes the session. On
  168. // the success path we `forget` it after Commit.
  169. struct AbortOnDrop(HANDLE);
  170. impl Drop for AbortOnDrop {
  171. fn drop(&mut self) {
  172. unsafe {
  173. let _ = FwpmTransactionAbort0(self.0);
  174. }
  175. }
  176. }
  177. let abort = AbortOnDrop(engine.h());
  178. let out = f(&engine)?;
  179. let rc = unsafe { FwpmTransactionCommit0(engine.h()) };
  180. if rc != 0 {
  181. // `abort` drops → Abort0 (no-op after a failed Commit, but
  182. // harmless).
  183. return Err(anyhow!("FwpmTransactionCommit0: 0x{rc:08x}"));
  184. }
  185. std::mem::forget(abort);
  186. Ok(out)
  187. }
  188. // ────────────────────── condition builders ──────────────────────
  189. fn fwp_uint64(slot: &mut u64) -> FWP_VALUE0 {
  190. FWP_VALUE0 {
  191. r#type: FWP_UINT64,
  192. Anonymous: FWP_VALUE0_0 {
  193. uint64: slot as *mut u64,
  194. },
  195. }
  196. }
  197. fn cond_sd(field_key: GUID, blob: &mut FWP_BYTE_BLOB) -> FWPM_FILTER_CONDITION0 {
  198. FWPM_FILTER_CONDITION0 {
  199. fieldKey: field_key,
  200. matchType: FWP_MATCH_EQUAL,
  201. conditionValue: FWP_CONDITION_VALUE0 {
  202. r#type: FWP_SECURITY_DESCRIPTOR_TYPE,
  203. Anonymous: FWP_CONDITION_VALUE0_0 { sd: blob as *mut _ },
  204. },
  205. }
  206. }
  207. fn cond_v4_subnet(field_key: GUID, am: &mut FWP_V4_ADDR_AND_MASK) -> FWPM_FILTER_CONDITION0 {
  208. FWPM_FILTER_CONDITION0 {
  209. fieldKey: field_key,
  210. matchType: FWP_MATCH_EQUAL,
  211. conditionValue: FWP_CONDITION_VALUE0 {
  212. r#type: FWP_V4_ADDR_MASK,
  213. Anonymous: FWP_CONDITION_VALUE0_0 {
  214. v4AddrMask: am as *mut _,
  215. },
  216. },
  217. }
  218. }
  219. fn cond_v6_addr(field_key: GUID, addr: &mut FWP_BYTE_ARRAY16) -> FWPM_FILTER_CONDITION0 {
  220. FWPM_FILTER_CONDITION0 {
  221. fieldKey: field_key,
  222. matchType: FWP_MATCH_EQUAL,
  223. conditionValue: FWP_CONDITION_VALUE0 {
  224. r#type: FWP_BYTE_ARRAY16_TYPE,
  225. Anonymous: FWP_CONDITION_VALUE0_0 {
  226. byteArray16: addr as *mut _,
  227. },
  228. },
  229. }
  230. }
  231. fn fwp_uint16(v: u16) -> FWP_VALUE0 {
  232. FWP_VALUE0 {
  233. r#type: FWP_UINT16,
  234. Anonymous: FWP_VALUE0_0 { uint16: v },
  235. }
  236. }
  237. fn cond_port_range(field_key: GUID, range: &mut FWP_RANGE0) -> FWPM_FILTER_CONDITION0 {
  238. FWPM_FILTER_CONDITION0 {
  239. fieldKey: field_key,
  240. matchType: FWP_MATCH_RANGE,
  241. conditionValue: FWP_CONDITION_VALUE0 {
  242. r#type: FWP_RANGE_TYPE,
  243. Anonymous: FWP_CONDITION_VALUE0_0 {
  244. rangeValue: range as *mut _,
  245. },
  246. },
  247. }
  248. }
  249. // ────────────────────── filter tagging ──────────────────────
  250. /// JSON payload stored in each filter's `providerData` so we can
  251. /// identify our own filters during enumerate/uninstall without fixed
  252. /// filter GUIDs. The optional `port_range` mirrors the
  253. /// `IP_REMOTE_PORT` range condition on `permit-loopback-user` so
  254. /// `wfp status` can report it without unsafe condition-walking.
  255. /// `user_sid` is always set on filters this version writes; legacy
  256. /// installs (the discriminator-group filter set this version
  257. /// supersedes) wrote it as `None`, and [`install_filters`]/
  258. /// [`uninstall_filters`] clean those up too.
  259. #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
  260. pub struct FilterTag {
  261. /// Discriminator: `"srt-win"`. Anything else means the filter
  262. /// belongs to some other tool that happens to share our sublayer.
  263. pub tool: String,
  264. /// `permit-loopback-user` / `block-user`.
  265. pub kind: String,
  266. /// `[low, high]` for `permit-loopback-user`; `None` otherwise.
  267. #[serde(default, skip_serializing_if = "Option::is_none")]
  268. pub port_range: Option<[u16; 2]>,
  269. /// Sandbox user SID. `None` only on legacy installs that predate
  270. /// the user-SID-keyed design.
  271. #[serde(default, skip_serializing_if = "Option::is_none")]
  272. pub user_sid: Option<String>,
  273. }
  274. impl FilterTag {
  275. fn user(kind: &str, sid: &str, range: Option<(u16, u16)>) -> Self {
  276. Self {
  277. tool: "srt-win".into(),
  278. kind: kind.into(),
  279. port_range: range.map(|(l, h)| [l, h]),
  280. user_sid: Some(sid.into()),
  281. }
  282. }
  283. fn to_blob_bytes(&self) -> Vec<u8> {
  284. serde_json::to_vec(self).expect("FilterTag is always serialisable")
  285. }
  286. }
  287. /// Number of filters in the user-SID-keyed set (2 per layer × v4/v6).
  288. pub const FILTER_COUNT: usize = 4;
  289. // Filter weights — kept below 2^60 so they stay in WFP's
  290. // "manual weight" class (top 4 bits are auto-classifier). The
  291. // loopback PERMIT must sit **above** the user-SID BLOCK so the
  292. // sandbox user can still reach the host proxies. Module-level so
  293. // [`install_filters`] and the const-asserts in `tests` share one
  294. // source of truth.
  295. pub(crate) const W_LOOPBACK: u64 = 0x0F80_0000_0000_0000;
  296. pub(crate) const W_BLOCK: u64 = 0x0F40_0000_0000_0000;
  297. // ────────────────────── filter enumeration ──────────────────────
  298. const ALE_LAYERS: [(GUID, &str); 2] = [
  299. (FWPM_LAYER_ALE_AUTH_CONNECT_V4, "ale_auth_connect_v4"),
  300. (FWPM_LAYER_ALE_AUTH_CONNECT_V6, "ale_auth_connect_v6"),
  301. ];
  302. /// Walk every filter at the two ALE connect layers under
  303. /// `sublayer` that carries a parseable `srt-win` providerData tag,
  304. /// invoking `f(layer_name, filterKey, &tag)` for each. Owns the
  305. /// enum-handle and per-batch `FwpmFreeMemory0` lifecycle so callers
  306. /// don't duplicate the unsafe FFI walk.
  307. ///
  308. /// Errors are propagated (with the enum handle destroyed first) —
  309. /// don't swallow them: inside `install_filters`' txn, a missed enum
  310. /// error would skip stale-filter cleanup and the fresh set would be
  311. /// added on top, growing the filter count every install.
  312. fn for_each_tagged_filter(
  313. engine: &EngineHandle,
  314. sublayer: &GUID,
  315. mut f: impl FnMut(&'static str, GUID, &FilterTag),
  316. ) -> Result<()> {
  317. for (layer, layer_name) in ALE_LAYERS {
  318. let mut tmpl = FWPM_FILTER_ENUM_TEMPLATE0::default();
  319. tmpl.layerKey = layer;
  320. tmpl.enumType = FWP_FILTER_ENUM_OVERLAPPING;
  321. tmpl.actionMask = 0xFFFF_FFFF;
  322. let mut h = HANDLE::default();
  323. let rc = unsafe { FwpmFilterCreateEnumHandle0(engine.h(), Some(&tmpl), &mut h) };
  324. if rc != 0 {
  325. if is_bfe_access_denied(rc) {
  326. return Err(anyhow::Error::new(WfpAccessDenied {
  327. call: "FwpmFilterCreateEnumHandle0",
  328. rc,
  329. }));
  330. }
  331. return Err(anyhow!(
  332. "FwpmFilterCreateEnumHandle0({layer_name}): 0x{rc:08x}"
  333. ));
  334. }
  335. loop {
  336. let mut entries: *mut *mut FWPM_FILTER0 = std::ptr::null_mut();
  337. let mut n: u32 = 0;
  338. let rc = unsafe { FwpmFilterEnum0(engine.h(), h, 256, &mut entries, &mut n) };
  339. if rc != 0 {
  340. unsafe {
  341. let _ = FwpmFilterDestroyEnumHandle0(engine.h(), h);
  342. }
  343. return Err(anyhow!("FwpmFilterEnum0({layer_name}): 0x{rc:08x}"));
  344. }
  345. if n == 0 {
  346. if !entries.is_null() {
  347. unsafe {
  348. FwpmFreeMemory0(&mut (entries as *mut c_void));
  349. }
  350. }
  351. break;
  352. }
  353. let slice = unsafe { std::slice::from_raw_parts(entries, n as usize) };
  354. for &fp in slice {
  355. if fp.is_null() {
  356. continue;
  357. }
  358. let flt = unsafe { &*fp };
  359. if &flt.subLayerKey != sublayer {
  360. continue;
  361. }
  362. if flt.providerData.size == 0 || flt.providerData.data.is_null() {
  363. continue;
  364. }
  365. let bytes = unsafe {
  366. std::slice::from_raw_parts(
  367. flt.providerData.data,
  368. flt.providerData.size as usize,
  369. )
  370. };
  371. if let Ok(tag) = serde_json::from_slice::<FilterTag>(bytes)
  372. && tag.tool == "srt-win"
  373. {
  374. // `tag` is owned (parsed from bytes); the
  375. // `flt`/`bytes` borrows are released before
  376. // FwpmFreeMemory0 below, so no FFI lifetime
  377. // hazard for the closure.
  378. f(layer_name, flt.filterKey, &tag);
  379. }
  380. }
  381. unsafe {
  382. FwpmFreeMemory0(&mut (entries as *mut c_void));
  383. }
  384. if (n as usize) < 256 {
  385. break;
  386. }
  387. }
  388. unsafe {
  389. let _ = FwpmFilterDestroyEnumHandle0(engine.h(), h);
  390. }
  391. }
  392. Ok(())
  393. }
  394. /// Delete every srt-win-tagged filter under `sublayer`. Returns the
  395. /// number deleted. Does not delete the sublayer itself.
  396. fn delete_tagged_filters(engine: &EngineHandle, sublayer: &GUID) -> Result<usize> {
  397. // Collect across both layers, then delete. Deletion is by global
  398. // filterKey GUID inside one txn, so per-layer ordering is not
  399. // load-bearing.
  400. let mut to_delete: Vec<GUID> = Vec::new();
  401. for_each_tagged_filter(engine, sublayer, |_, key, _| {
  402. to_delete.push(key);
  403. })?;
  404. let mut deleted = 0usize;
  405. for key in to_delete {
  406. let rc = unsafe { FwpmFilterDeleteByKey0(engine.h(), &key) };
  407. if rc == 0 {
  408. deleted += 1;
  409. } else if rc != FWP_E_FILTER_NOT_FOUND {
  410. return Err(anyhow!("FwpmFilterDeleteByKey0({key:?}): 0x{rc:08x}"));
  411. }
  412. }
  413. Ok(deleted)
  414. }
  415. // ────────────────────── install / uninstall ──────────────────────
  416. #[allow(clippy::too_many_arguments)]
  417. fn add_filter(
  418. engine: HANDLE,
  419. sublayer: &GUID,
  420. layer: GUID,
  421. name: &str,
  422. weight: u64,
  423. action: FWP_ACTION_TYPE,
  424. conditions: &mut [FWPM_FILTER_CONDITION0],
  425. tag_bytes: &mut [u8],
  426. ) -> Result<()> {
  427. let mut name_w = wstr(name);
  428. let mut desc_w = wstr("sandbox-runtime WFP filter");
  429. let mut weight_slot = weight;
  430. let mut filter = FWPM_FILTER0::default();
  431. // filterKey left zeroed → WFP assigns a fresh GUID. We identify
  432. // our filters via providerData, not by fixed key.
  433. filter.displayData = FWPM_DISPLAY_DATA0 {
  434. name: PWSTR(name_w.as_mut_ptr()),
  435. description: PWSTR(desc_w.as_mut_ptr()),
  436. };
  437. filter.flags = FWPM_FILTER_FLAG_PERSISTENT;
  438. filter.layerKey = layer;
  439. filter.subLayerKey = *sublayer;
  440. filter.weight = fwp_uint64(&mut weight_slot);
  441. filter.numFilterConditions = conditions.len() as u32;
  442. filter.filterCondition = if conditions.is_empty() {
  443. std::ptr::null_mut()
  444. } else {
  445. conditions.as_mut_ptr()
  446. };
  447. filter.action = FWPM_ACTION0 {
  448. r#type: action,
  449. Anonymous: FWPM_ACTION0_0 {
  450. filterType: GUID::zeroed(),
  451. },
  452. };
  453. filter.providerData = FWP_BYTE_BLOB {
  454. size: tag_bytes.len() as u32,
  455. data: tag_bytes.as_mut_ptr(),
  456. };
  457. let rc = unsafe { FwpmFilterAdd0(engine, &filter, None, None) };
  458. if rc != 0 && rc != FWP_E_ALREADY_EXISTS {
  459. return Err(anyhow!("FwpmFilterAdd0({name}): 0x{rc:08x}"));
  460. }
  461. Ok(())
  462. }
  463. // SDDL builder for the `ALE_USER_ID` security descriptor.
  464. //
  465. // Carries `O:LS G:LS` (owner + primary group = LocalService).
  466. // WFP's kernel-side ALE_USER_ID match doesn't require the primary
  467. // group to be set, but user-mode `AccessCheck` — which
  468. // `tests/sd_access_check_matrix.rs` uses to prove this SD does
  469. // what we claim — returns ERROR_INVALID_SECURITY_DESCR for an SD
  470. // with no `G:`. The group's value is irrelevant to DACL
  471. // evaluation; LS is just a stable, always-present principal.
  472. /// SDDL for the BLOCK filter — ALLOW `<sandbox_user_sid>`. Matches
  473. /// iff the connecting token carries that SID **enabled**, which for
  474. /// a *user* SID means "is that user". The broker, services, and
  475. /// every other process carry a different user SID → no match → fall
  476. /// through to default-permit.
  477. pub fn sddl_sandbox_user(sid: &str) -> String {
  478. format!("O:LSG:LSD:(A;;CC;;;{sid})")
  479. }
  480. /// Install (or refresh) the user-SID-keyed filter set under
  481. /// `sublayer`. Two filters at each of the v4/v6 ALE-connect layers
  482. /// ([`FILTER_COUNT`] total) — see the module doc for the design.
  483. ///
  484. /// Idempotent: any existing srt-win-tagged filters under `sublayer`
  485. /// — including legacy discriminator-group-keyed filters from a
  486. /// pre-separate-user install — are deleted first, then a fresh set
  487. /// is added, all inside one WFP transaction.
  488. pub fn install_filters(
  489. sublayer: &GUID,
  490. sandbox_user_sid: &str,
  491. port_range: (u16, u16),
  492. ) -> Result<()> {
  493. debug_assert!(port_range.0 <= port_range.1);
  494. let sd_user = OwnedSd::from_sddl(&sddl_sandbox_user(sandbox_user_sid))
  495. .context("build sandbox-user SD")?;
  496. with_wfp_txn(|engine| {
  497. // Sublayer (idempotent). Display name identifies the owning
  498. // tool, not the user.
  499. let mut sl_name = wstr("srt-win");
  500. let mut sl_desc = wstr("sandbox-runtime WFP sublayer (sandbox-user fence)");
  501. let sl = FWPM_SUBLAYER0 {
  502. subLayerKey: *sublayer,
  503. displayData: FWPM_DISPLAY_DATA0 {
  504. name: PWSTR(sl_name.as_mut_ptr()),
  505. description: PWSTR(sl_desc.as_mut_ptr()),
  506. },
  507. flags: FWPM_SUBLAYER_FLAG_PERSISTENT,
  508. providerKey: std::ptr::null_mut(),
  509. providerData: FWP_BYTE_BLOB {
  510. size: 0,
  511. data: std::ptr::null_mut(),
  512. },
  513. weight: 0x8000,
  514. };
  515. let rc = unsafe { FwpmSubLayerAdd0(engine.h(), &sl, None) };
  516. if rc != 0 && rc != FWP_E_ALREADY_EXISTS {
  517. return Err(anyhow!("FwpmSubLayerAdd0: 0x{rc:08x}"));
  518. }
  519. // Idempotency + migration: drop EVERY stale srt-win filter
  520. // (both this version's user-keyed shape and any legacy
  521. // group-keyed filters from a prior install) before
  522. // re-adding. Inside the transaction so a crash leaves the
  523. // previous state intact.
  524. delete_tagged_filters(engine, sublayer)?;
  525. let mut sd_user_blob = sd_byte_blob(&sd_user);
  526. let mut v4_loop = FWP_V4_ADDR_AND_MASK {
  527. addr: 0x7F00_0000,
  528. mask: 0xFF00_0000,
  529. };
  530. let mut v6_loop = FWP_BYTE_ARRAY16 {
  531. byteArray16: [0; 16],
  532. };
  533. v6_loop.byteArray16[15] = 1;
  534. let mut port_range_slot = FWP_RANGE0 {
  535. valueLow: fwp_uint16(port_range.0),
  536. valueHigh: fwp_uint16(port_range.1),
  537. };
  538. let mut tag_lb =
  539. FilterTag::user("permit-loopback-user", sandbox_user_sid, Some(port_range))
  540. .to_blob_bytes();
  541. let mut tag_bk = FilterTag::user("block-user", sandbox_user_sid, None).to_blob_bytes();
  542. for (layer, label) in [
  543. (FWPM_LAYER_ALE_AUTH_CONNECT_V4, "v4"),
  544. (FWPM_LAYER_ALE_AUTH_CONNECT_V6, "v6"),
  545. ] {
  546. // PERMIT loopback ∩ port-range (no user condition).
  547. let addr_cond = if label == "v4" {
  548. cond_v4_subnet(FWPM_CONDITION_IP_REMOTE_ADDRESS, &mut v4_loop)
  549. } else {
  550. cond_v6_addr(FWPM_CONDITION_IP_REMOTE_ADDRESS, &mut v6_loop)
  551. };
  552. let mut c_lb = [
  553. addr_cond,
  554. cond_port_range(FWPM_CONDITION_IP_REMOTE_PORT, &mut port_range_slot),
  555. ];
  556. add_filter(
  557. engine.h(),
  558. sublayer,
  559. layer,
  560. &format!("srt-win-{label}-permit-loopback-user"),
  561. W_LOOPBACK,
  562. FWP_ACTION_PERMIT,
  563. &mut c_lb,
  564. &mut tag_lb,
  565. )?;
  566. // BLOCK sandbox user.
  567. let mut c_bk = [cond_sd(FWPM_CONDITION_ALE_USER_ID, &mut sd_user_blob)];
  568. add_filter(
  569. engine.h(),
  570. sublayer,
  571. layer,
  572. &format!("srt-win-{label}-block-user"),
  573. W_BLOCK,
  574. FWP_ACTION_BLOCK,
  575. &mut c_bk,
  576. &mut tag_bk,
  577. )?;
  578. }
  579. Ok(())
  580. })
  581. }
  582. /// Remove every srt-win-tagged filter under `sublayer`, then attempt
  583. /// to delete the sublayer itself (best-effort; `FWP_E_IN_USE` means
  584. /// foreign filters are still under it).
  585. pub fn uninstall_filters(sublayer: &GUID) -> Result<usize> {
  586. with_wfp_txn(|engine| {
  587. let n = delete_tagged_filters(engine, sublayer)?;
  588. let rc = unsafe { FwpmSubLayerDeleteByKey0(engine.h(), sublayer) };
  589. if rc != 0
  590. && rc != FWP_E_SUBLAYER_NOT_FOUND
  591. && rc != FWP_E_FILTER_NOT_FOUND
  592. && rc != FWP_E_IN_USE
  593. {
  594. return Err(anyhow!("FwpmSubLayerDeleteByKey0: 0x{rc:08x}"));
  595. }
  596. Ok(n)
  597. })
  598. }
  599. /// Status of the WFP fence under `sublayer`. `installed` iff at
  600. /// least one `block-user` srt-win filter exists. (We don't insist
  601. /// on the exact count so enterprise tooling that adds extras under
  602. /// the same sublayer doesn't break detection.) `port_range` is read
  603. /// from the first `permit-loopback-user` tag.
  604. ///
  605. /// `cannot-read` is the graceful-degrade state when BFE
  606. /// enumeration is admin-gated ([`WfpAccessDenied`]). The
  607. /// non-elevated readiness check is `srt-win wfp verify` (a
  608. /// behavioral probe — spawns the runner as the sandbox user and
  609. /// expects WSAEACCES on a direct connect), not this enum.
  610. #[derive(Debug, Serialize)]
  611. pub struct WfpStatus {
  612. pub state: &'static str,
  613. pub filters: usize,
  614. #[serde(skip_serializing_if = "Option::is_none")]
  615. pub port_range: Option<[u16; 2]>,
  616. /// Sandbox-user SID read from the first user-keyed tag.
  617. #[serde(skip_serializing_if = "Option::is_none")]
  618. pub user_sid: Option<String>,
  619. /// Populated only on `cannot-read`.
  620. #[serde(skip_serializing_if = "Option::is_none")]
  621. pub hint: Option<String>,
  622. }
  623. /// Live BFE enumeration. Admin-gated — a non-elevated caller gets
  624. /// `state:"cannot-read"` (not an error) so `wfp status` exits 0
  625. /// with a hint pointing at `wfp verify`. Elevated callers
  626. /// (`install`'s early-return, the smoke scripts) get the real
  627. /// per-filter counts.
  628. pub fn filter_status(sublayer: &GUID) -> Result<WfpStatus> {
  629. let engine = match EngineHandle::open() {
  630. Ok(e) => e,
  631. Err(e) if e.downcast_ref::<WfpAccessDenied>().is_some() => {
  632. return Ok(cannot_read(e));
  633. }
  634. Err(e) => return Err(e),
  635. };
  636. let mut filters = 0usize;
  637. let mut have_block = false;
  638. let mut port_range: Option<[u16; 2]> = None;
  639. let mut user_sid: Option<String> = None;
  640. let enum_result = for_each_tagged_filter(&engine, sublayer, |_, _, tag| {
  641. filters += 1;
  642. if user_sid.is_none() {
  643. user_sid.clone_from(&tag.user_sid);
  644. }
  645. match tag.kind.as_str() {
  646. "block-user" => have_block = true,
  647. "permit-loopback-user" => port_range = tag.port_range,
  648. _ => {}
  649. }
  650. });
  651. if let Err(e) = enum_result {
  652. if e.downcast_ref::<WfpAccessDenied>().is_some() {
  653. return Ok(cannot_read(e));
  654. }
  655. return Err(e);
  656. }
  657. Ok(WfpStatus {
  658. state: if have_block { "installed" } else { "absent" },
  659. filters,
  660. port_range,
  661. user_sid,
  662. hint: None,
  663. })
  664. }
  665. fn cannot_read(e: anyhow::Error) -> WfpStatus {
  666. WfpStatus {
  667. state: "cannot-read",
  668. filters: 0,
  669. port_range: None,
  670. user_sid: None,
  671. hint: Some(format!(
  672. "{e}; elevation required for filter enum — run `srt-win \
  673. wfp verify` for a behavioral check"
  674. )),
  675. }
  676. }
  677. /// Parse a `--proxy-port-range LOW-HIGH` argument. Both ends are
  678. /// inclusive. Validates `low <= high` and width `<=
  679. /// MAX_PROXY_PORT_RANGE_WIDTH`.
  680. pub fn parse_port_range(s: &str) -> Result<(u16, u16)> {
  681. let (lo_s, hi_s) = s
  682. .split_once('-')
  683. .ok_or_else(|| anyhow!("expected LOW-HIGH (e.g. 60080-60089)"))?;
  684. let lo: u16 = lo_s
  685. .trim()
  686. .parse()
  687. .map_err(|_| anyhow!("invalid low port '{lo_s}'"))?;
  688. let hi: u16 = hi_s
  689. .trim()
  690. .parse()
  691. .map_err(|_| anyhow!("invalid high port '{hi_s}'"))?;
  692. if lo == 0 {
  693. // Port 0 is "any" at bind time and never appears as a
  694. // remote port, so it's a dead slot in the range.
  695. return Err(anyhow!("low port must be >= 1"));
  696. }
  697. if lo > hi {
  698. return Err(anyhow!("low ({lo}) > high ({hi})"));
  699. }
  700. if hi - lo > MAX_PROXY_PORT_RANGE_WIDTH {
  701. return Err(anyhow!(
  702. "range too wide ({} ports); max width {}",
  703. hi - lo + 1,
  704. MAX_PROXY_PORT_RANGE_WIDTH + 1
  705. ));
  706. }
  707. Ok((lo, hi))
  708. }
  709. /// Parse a `--sublayer-guid` argument. Accepts braced or unbraced
  710. /// canonical form. `GUID::try_from` only takes the unbraced form and
  711. /// returns an unhelpful error on failure, so strip braces and
  712. /// pre-validate the shape for a friendlier message.
  713. pub fn parse_guid(s: &str) -> Result<GUID> {
  714. let t = s.trim().trim_start_matches('{').trim_end_matches('}');
  715. // 8-4-4-4-12 hex with hyphens, exactly 36 chars.
  716. let ok = t.len() == 36
  717. && t.bytes().enumerate().all(|(i, b)| match i {
  718. 8 | 13 | 18 | 23 => b == b'-',
  719. _ => b.is_ascii_hexdigit(),
  720. });
  721. if !ok {
  722. return Err(anyhow!(
  723. "invalid GUID '{s}': expected xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
  724. ));
  725. }
  726. GUID::try_from(t).map_err(|e| anyhow!("invalid GUID '{s}': {e}"))
  727. }
  728. #[cfg(test)]
  729. mod tests {
  730. use super::*;
  731. /// The SDDL template used by `install_filters` must parse for a
  732. /// representative SID. Catches template typos without needing a
  733. /// live WFP engine.
  734. #[test]
  735. fn sddl_template_parses() {
  736. let sd = OwnedSd::from_sddl(&sddl_sandbox_user("S-1-5-32-545")).expect("sddl");
  737. assert!(!sd.ptr.0.is_null());
  738. assert!(sd.len > 0);
  739. }
  740. #[test]
  741. fn sddl_rejects_garbage() {
  742. assert!(OwnedSd::from_sddl("O:LSG:LSD:(A;;CC;;;NOT-A-SID)").is_err());
  743. }
  744. #[test]
  745. fn filter_tag_round_trip() {
  746. let sid = "S-1-5-21-1-2-3-1005";
  747. let bk = FilterTag::user("block-user", sid, None);
  748. assert_eq!(bk.user_sid.as_deref(), Some(sid));
  749. assert_eq!(bk.port_range, None);
  750. let lb = FilterTag::user("permit-loopback-user", sid, Some((60080, 60089)));
  751. assert_eq!(lb.port_range, Some([60080, 60089]));
  752. // Round-trips through JSON.
  753. let back: FilterTag = serde_json::from_slice(&lb.to_blob_bytes()).unwrap();
  754. assert_eq!(back, lb);
  755. }
  756. #[test]
  757. fn filter_tag_parses_legacy() {
  758. // A pre-port-range / pre-user-sid tag (the legacy
  759. // discriminator-group shape) must still parse so
  760. // uninstall/install can clean it up.
  761. let legacy = br#"{"tool":"srt-win","kind":"permit-loopback"}"#;
  762. let t: FilterTag = serde_json::from_slice(legacy).unwrap();
  763. assert_eq!(t.kind, "permit-loopback");
  764. assert_eq!(t.port_range, None);
  765. assert_eq!(t.user_sid, None);
  766. }
  767. /// const-assert the weight invariant directly so a reshuffle in
  768. /// `install_filters` fails to compile here.
  769. #[test]
  770. fn weight_invariant() {
  771. const { assert!(W_LOOPBACK > W_BLOCK) };
  772. }
  773. #[test]
  774. fn parse_port_range_ok() {
  775. assert_eq!(parse_port_range("60080-60089").unwrap(), (60080, 60089));
  776. assert_eq!(parse_port_range(" 1 - 1 ").unwrap(), (1, 1));
  777. assert_eq!(
  778. parse_port_range("1-65").unwrap(),
  779. (1, 1 + MAX_PROXY_PORT_RANGE_WIDTH)
  780. );
  781. }
  782. #[test]
  783. fn parse_port_range_rejects() {
  784. assert!(parse_port_range("60089-60080").is_err()); // low>high
  785. assert!(parse_port_range("1-1000").is_err()); // too wide
  786. assert!(parse_port_range("60080").is_err()); // no dash
  787. assert!(parse_port_range("a-b").is_err()); // not u16
  788. assert!(parse_port_range("0-65536").is_err()); // overflow
  789. assert!(parse_port_range("0-9").is_err()); // port 0
  790. }
  791. #[test]
  792. fn parse_guid_accepts_both_forms() {
  793. let g1 = parse_guid("2c5d0ad6-5f3b-4d4e-9b8f-1a3e7c9d0b21").unwrap();
  794. let g2 = parse_guid("{2c5d0ad6-5f3b-4d4e-9b8f-1a3e7c9d0b21}").unwrap();
  795. assert_eq!(g1, g2);
  796. assert_eq!(g1, DEFAULT_SUBLAYER_GUID);
  797. }
  798. #[test]
  799. fn parse_guid_rejects_garbage() {
  800. assert!(parse_guid("not-a-guid").is_err());
  801. }
  802. }