winsta.rs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. //! Broker-side grants on the session's kernel objects so the two-hop
  2. //! runner+child can attach them: the per-exec [`IsolatedDesk`] on
  3. //! `WinSta0`, [`grant_sandbox_on_winsta`] on the station itself, and
  4. //! [`grant_sandbox_on_session_bno`] on
  5. //! `\Sessions\<TS>\BaseNamedObjects`.
  6. //!
  7. //! **Isolated desktop.** The broker creates a per-exec named desktop
  8. //! on its current window station, passes the `<winsta>\<desk>` path
  9. //! via `CreateProcessWithLogonW`'s `lpDesktop`, the runner lands
  10. //! there, the lockdown child inherits it (`lpDesktop = NULL` in
  11. //! `CreateProcessAsUserW`); neither can enumerate or message
  12. //! top-level windows on the interactive `WinSta0\Default`, and a
  13. //! co-located human's keystrokes are not capturable
  14. //! (`WH_KEYBOARD_LL` is per-desktop; the Job's `UILIMIT_HANDLES` does
  15. //! NOT gate low-level hooks, so desktop separation is the only
  16. //! fence for that vector).
  17. //!
  18. //! Why the broker creates it (not the runner): the interactive user
  19. //! has `WINSTA_CREATEDESKTOP` on `WinSta0` non-elevated (verified by
  20. //! probe). When `lpDesktop != NULL`, seclogon **skips** its station
  21. //! auto-grant for the new logon, so the runner cannot attach
  22. //! `WinSta0` without an explicit ACE (verified by probe — child
  23. //! `DLL_INIT_FAILED` without it) — hence
  24. //! [`grant_sandbox_on_winsta`]: the broker adds attach-level rights
  25. //! for the `srt-sandbox` **user** SID before resume. The grant is on
  26. //! the user SID (not the per-logon SID) because seclogon stamps the
  27. //! **broker's** interactive logon SID into the runner's
  28. //! `TokenGroups` (`whoami /logonid` is identical for broker and
  29. //! runner; the per-CPWLW logon session exists only at the
  30. //! `AuthenticationId` LUID level, not as a distinct `S-1-5-5-*`
  31. //! group), so there is no separate runner logon SID to grant. The
  32. //! lockdown child inherits the runner's already-attached
  33. //! station+desktop, so its deny-only logon SID never matters for
  34. //! station attach.
  35. //!
  36. //! **Session BNO.** The lockdown child has every `SE_GROUP_LOGON_ID`
  37. //! SID deny-only ([`crate::token::make_sandbox_token`]). The session
  38. //! `BaseNamedObjects` directory grants `CREATE_OBJECT |
  39. //! CREATE_SUBDIRECTORY` only to the broker's logon SID; Everyone gets
  40. //! `QUERY | TRAVERSE`. So the child can open existing named objects
  41. //! but cannot create the per-DLL **subdirectory** msys2/cygwin needs
  42. //! for its shared heap (`NtCreateDirectoryObject … 0xC0000022`).
  43. //! [`grant_sandbox_on_session_bno`] adds `(A;;DIRECTORY_QUERY|
  44. //! TRAVERSE|CREATE_OBJECT|CREATE_SUBDIRECTORY;;;<srt-sandbox>)` so
  45. //! the **user** SID carries the create rights independently of the
  46. //! disabled logon SID. Unlike `WinSta0`, the BNO is an ordinary
  47. //! object-manager directory whose access check honours user-SID ACEs;
  48. //! and the broker's user SID has full control on it (verified by
  49. //! probe), so the broker can write the DACL non-elevated.
  50. //!
  51. //! **Both grants persist for the session — no revoke-on-drop.**
  52. //! Concurrent brokers (parallel `srt-win exec`, the normal case for a
  53. //! parallel build) share one station and one BNO; the first to finish
  54. //! revoking the only `srt-sandbox` ACE would kill the second's
  55. //! still-running child. The ACE is on a per-logon-session object
  56. //! (gone at logoff) and grants `srt-sandbox` no more than what
  57. //! seclogon would have granted for `lpDesktop = NULL`, so leaving it
  58. //! is harmless. The grant is idempotent (drop-then-readd), so the
  59. //! first broker per session does one read+write and later brokers
  60. //! converge to a no-op.
  61. //!
  62. //! Desktop-only — no `CreateWindowStationW`. Creating a new window
  63. //! station requires create rights on the session's
  64. //! `\Windows\WindowStations` object directory, which a non-elevated
  65. //! token does not have on a standard interactive session
  66. //! (`CreateWindowStationW → ACCESS_DENIED`, verified by probe). A
  67. //! separate desktop already provides the isolation that matters: a
  68. //! window's message queue is per-desktop, so processes on different
  69. //! desktops cannot `SendMessage`/enumerate/`WH_*`-hook each other.
  70. //! The clipboard- and atom-table separation a separate station would
  71. //! add is already covered by the Job's UI limits
  72. //! (`JOB_OBJECT_UILIMIT_READCLIPBOARD | WRITECLIPBOARD | GLOBALATOMS`).
  73. //!
  74. //! The kernel reference-counts a desktop by attached threads/handles.
  75. //! The broker keeps the [`IsolatedDesk`] handle open from creation
  76. //! until after the runner exits — dropping it then releases the
  77. //! kernel object.
  78. use anyhow::{Context, Result, anyhow};
  79. use std::ffi::c_void;
  80. use std::mem::size_of;
  81. use windows::Wdk::Foundation::OBJECT_ATTRIBUTES;
  82. use windows::Wdk::Storage::FileSystem::{
  83. NtOpenDirectoryObject, NtQuerySecurityObject, NtSetSecurityObject,
  84. };
  85. use windows::Win32::Foundation::{
  86. HANDLE, OBJ_CASE_INSENSITIVE, STATUS_ACCESS_DENIED, UNICODE_STRING,
  87. };
  88. use windows::Win32::Security::Cryptography::{BCRYPT_USE_SYSTEM_PREFERRED_RNG, BCryptGenRandom};
  89. use windows::Win32::Security::{
  90. ACL, DACL_SECURITY_INFORMATION, GetSecurityDescriptorDacl, GetUserObjectSecurity,
  91. InitializeSecurityDescriptor, PSECURITY_DESCRIPTOR, PSID, SECURITY_DESCRIPTOR,
  92. SetSecurityDescriptorDacl, SetUserObjectSecurity,
  93. };
  94. use windows::Win32::System::RemoteDesktop::ProcessIdToSessionId;
  95. use windows::Win32::System::StationsAndDesktops::{
  96. CloseDesktop, CreateDesktopW, DESKTOP_CONTROL_FLAGS, GetProcessWindowStation, GetThreadDesktop,
  97. GetUserObjectInformationW, HDESK, UOI_NAME,
  98. };
  99. use windows::Win32::System::SystemServices::SECURITY_DESCRIPTOR_REVISION;
  100. use windows::Win32::System::Threading::GetCurrentThreadId;
  101. use windows::core::PCWSTR;
  102. use crate::acl::{
  103. Allow, Mask, NO_INHERIT, NewAce, SID_SYSTEM, ace_sid_is, build_allow_dacl, filter_aces,
  104. rebuild_acl,
  105. };
  106. use crate::sid::{current_user_sid, sid_bytes};
  107. use crate::util::{OwnedHandle, wstr};
  108. // winuser.h: DESKTOP_ALL_ACCESS = 0x1FF. OR with
  109. // STANDARD_RIGHTS_REQUIRED so the creator holds full control on the
  110. // object it just made.
  111. const STANDARD_RIGHTS_REQUIRED: u32 = 0x000F_0000;
  112. const DESK_ALL_ACCESS: u32 = STANDARD_RIGHTS_REQUIRED | 0x0000_01FF;
  113. /// `WINSTA_ALL_ACCESS | READ_CONTROL` (`0x2037F`). NOT `WRITE_DAC |
  114. /// WRITE_OWNER | DELETE`: the sandbox-user SID is enabled in the
  115. /// child token, so granting those would let the child rewrite the
  116. /// station's DACL. `READ_CONTROL` is harmless and **load-bearing** —
  117. /// without it the runner hangs during process init when the loader
  118. /// opens the station for the `lpDesktop` attach (verified on the
  119. /// Windows CI runner).
  120. const WINSTA_GRANT_MASK: u32 = 0x0002_037F;
  121. /// `DIRECTORY_QUERY | TRAVERSE | CREATE_OBJECT | CREATE_SUBDIRECTORY`
  122. /// — the rights the broker's logon SID carries on the session BNO,
  123. /// re-granted to the `srt-sandbox` user SID. NOT `WRITE_DAC`: the
  124. /// sandbox child must not be able to widen the session BNO's DACL.
  125. const BNO_GRANT_MASK: u32 = 0x0000_000F;
  126. /// RAII holder for a per-exec desktop on the caller's current window
  127. /// station, plus the wide `<winsta>\<desk>` buffer that backs
  128. /// `STARTUPINFOW.lpDesktop`.
  129. pub struct IsolatedDesk {
  130. desktop: HDESK,
  131. /// `STARTUPINFOW.lpDesktop` is `PWSTR` (mutable wide pointer per
  132. /// the API contract), so we keep the buffer here and hand out a
  133. /// raw pointer via [`desktop_name_ptr`]. Null-terminated.
  134. desk_path: Vec<u16>,
  135. }
  136. impl IsolatedDesk {
  137. /// Create a fresh per-exec desktop on the **current** window
  138. /// station — no `SetProcessWindowStation` dance. Explicit DACL
  139. /// `[broker-user, srt-sandbox, SYSTEM] : GENERIC_ALL` so the
  140. /// runner and lockdown child (both `srt-sandbox`) can attach.
  141. ///
  142. /// Name = `srt-sb-<pid>-<rand32>` (random suffix so concurrent
  143. /// execs in the same process — e.g. tests — don't collide; the
  144. /// kernel-assigned name is read back for the `lpDesktop` path).
  145. pub fn new(sb_sid: &str) -> Result<Self> {
  146. // Current station name (for the `<winsta>\<desk>` path). The
  147. // child's `lpDesktop` carries this name verbatim, so if the
  148. // read failed a guessed `WinSta0` would point the child at a
  149. // station the runner may not even be on — propagate.
  150. let ws_name = current_winsta_name().context("read caller's window-station name")?;
  151. // pid + 32 random bits (system CSPRNG). The random suffix
  152. // is what makes concurrent same-process callers (e.g. test
  153. // threads) collision-free, so don't quietly fall back to a
  154. // zero suffix on RNG failure — surface it. `BCryptGenRandom`
  155. // with `USE_SYSTEM_PREFERRED_RNG` essentially never fails.
  156. let mut r = [0u8; 4];
  157. unsafe { BCryptGenRandom(None, &mut r, BCRYPT_USE_SYSTEM_PREFERRED_RNG) }
  158. .ok()
  159. .context("BCryptGenRandom (desktop name suffix)")?;
  160. let req = format!(
  161. "srt-sb-{}-{:08x}",
  162. std::process::id(),
  163. u32::from_le_bytes(r),
  164. );
  165. let req_w = wstr(&req);
  166. // Explicit DACL — the broker is a different user from the
  167. // runner/child, so the default DACL (broker's TokenDefaultDacl)
  168. // would deny `srt-sandbox`. `OwnedSa` heap-pins the SD; keep
  169. // it alive until `CreateDesktopW` returns.
  170. let me = current_user_sid()?;
  171. let sa = build_allow_dacl(&[
  172. Allow(&me, Mask::GENERIC_ALL, NO_INHERIT),
  173. Allow(sb_sid, Mask::GENERIC_ALL, NO_INHERIT),
  174. Allow(SID_SYSTEM, Mask::GENERIC_ALL, NO_INHERIT),
  175. ])?
  176. .into_security_attributes()?;
  177. let desktop = unsafe {
  178. CreateDesktopW(
  179. PCWSTR(req_w.as_ptr()),
  180. PCWSTR::null(),
  181. None,
  182. DESKTOP_CONTROL_FLAGS(0),
  183. DESK_ALL_ACCESS,
  184. Some(sa.as_ptr()),
  185. )
  186. }
  187. .with_context(|| format!("CreateDesktopW({req}) on {ws_name}"))?;
  188. // `sa` (OwnedSa: ACL + SD + SECURITY_ATTRIBUTES) drops here.
  189. // Read back the actual assigned name.
  190. let desk_name = match object_name(HANDLE(desktop.0)) {
  191. Ok(n) => n,
  192. Err(e) => {
  193. unsafe {
  194. let _ = CloseDesktop(desktop);
  195. }
  196. return Err(e.context("UOI_NAME on new desktop"));
  197. }
  198. };
  199. let desk_path = wstr(&format!("{ws_name}\\{desk_name}"));
  200. Ok(Self { desktop, desk_path })
  201. }
  202. /// Pointer to the wide name buffer for `STARTUPINFOW.lpDesktop`.
  203. /// Caller must keep `self` alive until after the create-process
  204. /// call returns.
  205. pub fn desktop_name_ptr(&mut self) -> *mut u16 {
  206. self.desk_path.as_mut_ptr()
  207. }
  208. }
  209. impl Drop for IsolatedDesk {
  210. fn drop(&mut self) {
  211. unsafe {
  212. let _ = CloseDesktop(self.desktop);
  213. }
  214. }
  215. }
  216. /// Add `(A;;WINSTA_ALL_ACCESS;;;<sb_sid>)` to the broker's window
  217. /// station. Idempotent (any existing `<sb_sid>` ACE is dropped before
  218. /// the fresh one is appended). Persists for the broker's logon
  219. /// session — see module doc for why there is no revoke.
  220. pub fn grant_sandbox_on_winsta(sb_sid: &str) -> Result<()> {
  221. let ws = unsafe { GetProcessWindowStation() }.context("GetProcessWindowStation")?;
  222. if ws.0.is_null() {
  223. return Err(anyhow!("GetProcessWindowStation returned null"));
  224. }
  225. let h = HANDLE(ws.0);
  226. // The windows-crate bindings type Get's `psirequested` as
  227. // `*const u32` and Set's as `*const OBJECT_SECURITY_INFORMATION`;
  228. // both are the same `DACL_SECURITY_INFORMATION` value.
  229. let si = DACL_SECURITY_INFORMATION;
  230. recompose_dacl(
  231. "WinSta0",
  232. &sid_bytes(sb_sid)?,
  233. WINSTA_GRANT_MASK,
  234. || {
  235. let mut needed = 0u32;
  236. unsafe {
  237. let _ = GetUserObjectSecurity(h, &si.0, None, 0, &mut needed);
  238. }
  239. if needed == 0 {
  240. return Err(anyhow!("GetUserObjectSecurity sizing returned 0"));
  241. }
  242. let mut sd = vec![0u8; needed as usize];
  243. unsafe {
  244. GetUserObjectSecurity(
  245. h,
  246. &si.0,
  247. Some(PSECURITY_DESCRIPTOR(sd.as_mut_ptr() as *mut c_void)),
  248. needed,
  249. &mut needed,
  250. )
  251. .context("GetUserObjectSecurity(DACL)")?;
  252. }
  253. Ok(sd)
  254. },
  255. |psd| unsafe { SetUserObjectSecurity(h, &si, psd).context("SetUserObjectSecurity(DACL)") },
  256. )
  257. .context("grant srt-sandbox on WinSta0")
  258. }
  259. /// Add `(A;;0xF;;;<sb_sid>)` to `\Sessions\<broker-TS>\
  260. /// BaseNamedObjects`. Idempotent. Persists for the broker's logon
  261. /// session — see module doc for why there is no revoke. The broker's
  262. /// **user** SID has full control on the session BNO (verified by
  263. /// probe), so this works non-elevated.
  264. pub fn grant_sandbox_on_session_bno(sb_sid: &str) -> Result<()> {
  265. let bno = open_session_bno()?;
  266. let si = DACL_SECURITY_INFORMATION.0;
  267. recompose_dacl(
  268. "session BNO",
  269. &sid_bytes(sb_sid)?,
  270. BNO_GRANT_MASK,
  271. || {
  272. // Two-call sizing — `NtQuerySecurityObject` returns
  273. // STATUS_BUFFER_TOO_SMALL and writes the needed length.
  274. let mut needed = 0u32;
  275. unsafe {
  276. let _ = NtQuerySecurityObject(bno.raw(), si, None, 0, &mut needed);
  277. }
  278. if needed == 0 {
  279. return Err(anyhow!("NtQuerySecurityObject sizing returned 0"));
  280. }
  281. let mut sd = vec![0u8; needed as usize];
  282. unsafe {
  283. NtQuerySecurityObject(
  284. bno.raw(),
  285. si,
  286. Some(PSECURITY_DESCRIPTOR(sd.as_mut_ptr() as *mut c_void)),
  287. needed,
  288. &mut needed,
  289. )
  290. }
  291. .ok()
  292. .context("NtQuerySecurityObject(DACL)")?;
  293. Ok(sd)
  294. },
  295. |psd| unsafe {
  296. NtSetSecurityObject(bno.raw(), si, psd)
  297. .ok()
  298. .context("NtSetSecurityObject(DACL)")
  299. },
  300. )
  301. .context("grant srt-sandbox on session BaseNamedObjects")
  302. }
  303. /// `NtOpenDirectoryObject(\Sessions\<broker-TS>\BaseNamedObjects,
  304. /// READ_CONTROL | WRITE_DAC)`. The direct path (not via the
  305. /// `\Sessions\BNOLINKS\<TS>` symlink) so the open targets the
  306. /// directory object itself.
  307. fn open_session_bno() -> Result<OwnedHandle> {
  308. const READ_CONTROL: u32 = 0x0002_0000;
  309. const WRITE_DAC: u32 = 0x0004_0000;
  310. let mut ts = 0u32;
  311. unsafe { ProcessIdToSessionId(std::process::id(), &mut ts) }
  312. .context("ProcessIdToSessionId(broker)")?;
  313. let path = format!("\\Sessions\\{ts}\\BaseNamedObjects");
  314. let (mut path_w, bytes) = crate::util::counted_utf16(&path);
  315. let name = UNICODE_STRING {
  316. Length: bytes,
  317. MaximumLength: bytes,
  318. Buffer: windows::core::PWSTR(path_w.as_mut_ptr()),
  319. };
  320. let oa = OBJECT_ATTRIBUTES {
  321. Length: size_of::<OBJECT_ATTRIBUTES>() as u32,
  322. ObjectName: &name,
  323. Attributes: OBJ_CASE_INSENSITIVE,
  324. ..Default::default()
  325. };
  326. let mut h = HANDLE::default();
  327. let st = unsafe { NtOpenDirectoryObject(&mut h, READ_CONTROL | WRITE_DAC, &oa) };
  328. if st.is_err() {
  329. // STATUS_ACCESS_DENIED → the broker is not the interactive
  330. // user (e.g. service context with no full-control ACE on
  331. // this session's BNO). The grant is what makes msys2/cygwin
  332. // work under the lockdown token, so surface why.
  333. let why = if st == STATUS_ACCESS_DENIED {
  334. " — broker lacks WRITE_DAC on the session BNO (not the \
  335. interactive user?)"
  336. } else {
  337. ""
  338. };
  339. return Err(anyhow!(
  340. "NtOpenDirectoryObject({path}, READ_CONTROL|WRITE_DAC): \
  341. NTSTATUS 0x{:08X}{why}",
  342. st.0
  343. ));
  344. }
  345. Ok(OwnedHandle(h))
  346. }
  347. /// Walk-and-rebuild a kernel-object DACL: `read` returns the current
  348. /// self-relative SD; drop any existing ACE for `target_sid`, append
  349. /// one `(A;;mask;;;<target_sid>)`, then `write` the resulting
  350. /// absolute SD. Shared by the WinSta0 grant (user-object SD APIs)
  351. /// and the session-BNO grant (NT-native SD APIs). The broker is the
  352. /// interactive user → it has `READ_CONTROL | WRITE_DAC` on both
  353. /// objects non-elevated.
  354. ///
  355. /// Walk-and-rebuild (not `SetEntriesInAclW`) so the round-trip is
  356. /// byte-faithful for ACEs we don't touch. The walk is
  357. /// [`crate::acl::filter_aces`] with a SID-match predicate; unlike
  358. /// `apply_sandbox_aces` this **keeps** inherited ACEs (kernel
  359. /// objects don't get the `UNPROTECTED`-re-derive treatment).
  360. fn recompose_dacl(
  361. what: &str,
  362. target_sid: &[u8],
  363. mask: u32,
  364. read: impl FnOnce() -> Result<Vec<u8>>,
  365. write: impl FnOnce(PSECURITY_DESCRIPTOR) -> Result<()>,
  366. ) -> Result<()> {
  367. // 1) Read the current SD (self-relative).
  368. let sd_buf = read()?;
  369. let mut present = Default::default();
  370. let mut defaulted = Default::default();
  371. let mut old: *mut ACL = std::ptr::null_mut();
  372. unsafe {
  373. GetSecurityDescriptorDacl(
  374. PSECURITY_DESCRIPTOR(sd_buf.as_ptr() as *mut c_void),
  375. &mut present,
  376. &mut old,
  377. &mut defaulted,
  378. )
  379. .with_context(|| format!("GetSecurityDescriptorDacl({what})"))?;
  380. }
  381. // A present-but-NULL DACL is "grant everyone everything" —
  382. // `target_sid` already has access; rewriting it as a one-ACE
  383. // DACL would lock out every other principal. Shouldn't happen on
  384. // a csrss-created session object, but don't make it worse.
  385. if present.as_bool() && old.is_null() {
  386. return Ok(());
  387. }
  388. // 2) Walk `old`: keep ACEs whose SID isn't `target_sid`
  389. // (INHERITED ACEs are kept too). `sd_buf` backs the kept ACE
  390. // pointers until step 4's write.
  391. let kept = filter_aces(old, |_, body| !ace_sid_is(body, target_sid))
  392. .with_context(|| format!("filter_aces({what})"))?;
  393. // 3) New ACL = kept ACEs + one ALLOW for `target_sid`. Kept ACEs
  394. // first (preserves the original ACE order — DENYs, if any,
  395. // stay ahead of our appended ALLOW).
  396. let sid = PSID(target_sid.as_ptr() as *mut c_void);
  397. let new = rebuild_acl(kept.2, &[], &kept, &[NewAce::Allow(sid, mask, NO_INHERIT)])
  398. .with_context(|| format!("rebuild_acl({what})"))?;
  399. // 4) Write back via a fresh absolute SD.
  400. let mut sd: SECURITY_DESCRIPTOR = Default::default();
  401. let psd = PSECURITY_DESCRIPTOR(&mut sd as *mut _ as *mut c_void);
  402. unsafe {
  403. InitializeSecurityDescriptor(psd, SECURITY_DESCRIPTOR_REVISION)
  404. .with_context(|| format!("InitializeSecurityDescriptor({what})"))?;
  405. SetSecurityDescriptorDacl(psd, true, Some(new.as_ptr()), false)
  406. .with_context(|| format!("SetSecurityDescriptorDacl({what})"))?;
  407. }
  408. write(psd)
  409. }
  410. /// Name of the window station this process is attached to (e.g.
  411. /// `WinSta0`, `Service-0x0-<logonid>$`).
  412. pub fn current_winsta_name() -> Result<String> {
  413. let ws = unsafe { GetProcessWindowStation() }.context("GetProcessWindowStation")?;
  414. if ws.0.is_null() {
  415. return Err(anyhow!("GetProcessWindowStation returned null"));
  416. }
  417. object_name(HANDLE(ws.0))
  418. }
  419. /// Name of this thread's current desktop (e.g. `Default`,
  420. /// `srt-sb-…`). `None` on failure.
  421. pub fn current_desktop_name() -> Option<String> {
  422. let d = unsafe { GetThreadDesktop(GetCurrentThreadId()) }.ok()?;
  423. if d.0.is_null() {
  424. return None;
  425. }
  426. object_name(HANDLE(d.0)).ok()
  427. }
  428. /// `true` when this thread is on the interactive `Default` desktop.
  429. ///
  430. /// `run_lockdown` **fails closed** when this returns `true`: the
  431. /// broker passes its `WinSta0\srt-sb-…` desktop via `lpDesktop` to
  432. /// `CreateProcessWithLogonW`, so the runner is never on `Default`
  433. /// in the two-hop path. A `Default` runner means the broker-side
  434. /// creation failed and the child would share the interactive
  435. /// desktop (`WH_KEYBOARD_LL` keylogging risk). Name-based — a
  436. /// non-`Default` custom desktop is assumed isolated. Any read
  437. /// failure → `true` (fail closed).
  438. pub fn on_default_desktop() -> bool {
  439. current_desktop_name()
  440. .map(|n| n.eq_ignore_ascii_case("Default"))
  441. .unwrap_or(true)
  442. }
  443. /// Read a user-object's `UOI_NAME` (returned as a wide
  444. /// NUL-terminated string).
  445. fn object_name(h: HANDLE) -> Result<String> {
  446. let mut needed = 0u32;
  447. // Sizing call — expected to fail with ERROR_INSUFFICIENT_BUFFER
  448. // and write the required byte count.
  449. unsafe {
  450. let _ = GetUserObjectInformationW(h, UOI_NAME, None, 0, Some(&mut needed));
  451. }
  452. if needed == 0 {
  453. return Err(anyhow!("GetUserObjectInformationW sizing returned 0"));
  454. }
  455. let mut buf = vec![0u8; needed as usize];
  456. unsafe {
  457. GetUserObjectInformationW(
  458. h,
  459. UOI_NAME,
  460. Some(buf.as_mut_ptr() as *mut c_void),
  461. needed,
  462. Some(&mut needed),
  463. )
  464. .context("GetUserObjectInformationW(UOI_NAME)")?;
  465. }
  466. // SAFETY: `buf` is `needed` bytes, even-length (UTF-16);
  467. // reinterpret as u16.
  468. let wide =
  469. unsafe { std::slice::from_raw_parts(buf.as_ptr() as *const u16, (needed as usize) / 2) };
  470. let end = wide.iter().position(|&c| c == 0).unwrap_or(wide.len());
  471. Ok(String::from_utf16_lossy(&wide[..end]))
  472. }