user.rs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. //! Sandbox user account lifecycle.
  2. //!
  3. //! `srt-win install` provisions a dedicated local user
  4. //! ([`SANDBOX_USER`]) and a local group ([`SANDBOX_GROUP`]) that
  5. //! holds it. The sandboxed child runs **as that user** (via
  6. //! `CreateProcessWithLogonW` from a non-elevated broker), so its
  7. //! token carries a different user SID and a fresh logon session —
  8. //! which structurally closes the surrogate-spawn class (schtasks,
  9. //! `PROC_THREAD_ATTRIBUTE_PARENT_PROCESS`, BITS, RunAs="Interactive
  10. //! User" COM) that a same-user restricted token cannot.
  11. //!
  12. //! This module is the **provisioning** half only: create/delete the
  13. //! account, set/rotate its password, hide it from the logon UI, and
  14. //! report status. The runner that actually launches the child under
  15. //! this account lives in [`crate::runner`] / [`crate::logon`].
  16. //!
  17. //! ## Why a group AND a user
  18. //!
  19. //! [`SANDBOX_GROUP`] is the trustee for the credential-file DENY
  20. //! ACE. Keying that on the *group* rather than the user SID means a
  21. //! future multi-account design (e.g. per-session sandbox users)
  22. //! only adds members; the DACLs don't change.
  23. use anyhow::{Context, Result, anyhow, bail};
  24. use serde::Serialize;
  25. use std::ffi::c_void;
  26. use windows::Win32::Foundation::ERROR_FILE_NOT_FOUND;
  27. use windows::Win32::NetworkManagement::NetManagement::{
  28. NERR_PasswordTooShort, NERR_UserExists, NERR_UserNotFound, NetApiBufferFree, NetUserAdd,
  29. NetUserDel, NetUserGetInfo, NetUserModalsGet, NetUserSetInfo, UF_DONT_EXPIRE_PASSWD, UF_SCRIPT,
  30. USER_INFO_1, USER_INFO_1003, USER_INFO_1008, USER_MODALS_INFO_0, USER_PRIV_USER,
  31. };
  32. use windows::Win32::Security::Cryptography::{BCRYPT_USE_SYSTEM_PREFERRED_RNG, BCryptGenRandom};
  33. use windows::Win32::System::Registry::{
  34. HKEY, HKEY_LOCAL_MACHINE, KEY_READ, KEY_SET_VALUE, REG_DWORD, RegCloseKey, RegDeleteValueW,
  35. RegOpenKeyExW, RegQueryValueExW,
  36. };
  37. use windows::Win32::UI::Shell::DeleteProfileW;
  38. use windows::core::{PCWSTR, PWSTR};
  39. use crate::util::{pcwstr, wstr};
  40. use crate::{sam, sid};
  41. /// Default name for the dedicated local account the sandboxed child
  42. /// runs as. Overridable at install time via `--sandbox-user`; the
  43. /// active name is recorded in the setup marker
  44. /// ([`crate::install::read_setup`]).
  45. pub const SANDBOX_USER: &str = "srt-sandbox";
  46. /// Local group that holds [`SANDBOX_USER`]. Trustee for the
  47. /// credential-file DENY ACE.
  48. pub const SANDBOX_GROUP: &str = "sandbox-runtime-users";
  49. /// Result of [`provision`] — the password is returned in clear so
  50. /// the caller can DPAPI-encrypt and persist it; it is not stored
  51. /// anywhere by this module.
  52. #[derive(Debug)]
  53. pub struct ProvisionedUser {
  54. pub username: String,
  55. /// `S-1-5-21-…` of [`SANDBOX_USER`].
  56. pub sid: String,
  57. /// `S-1-5-21-…` of [`SANDBOX_GROUP`].
  58. pub group_sid: String,
  59. /// 32 chars, freshly generated on every [`provision`] call (so
  60. /// re-running install rotates it).
  61. pub password: String,
  62. }
  63. /// Result of [`status`]. Every field is independently observed so a
  64. /// half-provisioned state (e.g. user exists but not in the group) is
  65. /// surfaced rather than collapsed to a single boolean.
  66. #[derive(Debug, Serialize)]
  67. pub struct UserStatus {
  68. /// The account name that was queried (from the setup marker, or
  69. /// [`SANDBOX_USER`] when no install has run).
  70. pub name: String,
  71. pub exists: bool,
  72. #[serde(skip_serializing_if = "Option::is_none")]
  73. pub sid: Option<String>,
  74. pub group_exists: bool,
  75. #[serde(skip_serializing_if = "Option::is_none")]
  76. pub group_sid: Option<String>,
  77. /// In `BUILTIN\Users` — required for interactive logon rights.
  78. pub in_builtin_users: bool,
  79. /// In [`SANDBOX_GROUP`].
  80. pub in_sandbox_group: bool,
  81. /// Winlogon `SpecialAccounts\UserList\srt-sandbox` = 0.
  82. pub hidden_from_logon: bool,
  83. }
  84. const WINLOGON_USERLIST: &str =
  85. r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList";
  86. /// `BUILTIN\Users` — well-known SID that's stable across locales,
  87. /// unlike the *name* "Users" / "Benutzer" / "Utilisateurs".
  88. const SID_BUILTIN_USERS: &str = "S-1-5-32-545";
  89. /// Create [`SANDBOX_GROUP`] and the local user `name` (idempotent),
  90. /// set a fresh random password (rotated only if `we_own_it` — see
  91. /// [`ensure_user`]), add the user to `BUILTIN\Users` and
  92. /// [`SANDBOX_GROUP`], hide it from the Winlogon user-picker, and
  93. /// return both SIDs plus the password.
  94. ///
  95. /// `we_own_it` — the setup marker records `name` as the account a
  96. /// prior `srt-win install` created. When false, a pre-existing
  97. /// principal by that name is refused rather than adopted.
  98. ///
  99. /// Requires elevation (NetUserAdd → `ERROR_ACCESS_DENIED` otherwise).
  100. pub fn provision(name: &str, we_own_it: bool) -> Result<ProvisionedUser> {
  101. sam::ensure_local_group(SANDBOX_GROUP, "sandbox-runtime sandbox-user group")?;
  102. let password = ensure_user(name, we_own_it)?;
  103. // Resolve the freshly-created user's SID so group membership is
  104. // added by PSID — see [`sam::add_member`].
  105. let sid = sid::lookup_account_sid(name).context("resolve sandbox user SID")?;
  106. let user_psid = sid::LocalPsid::from_string(&sid)?;
  107. // BUILTIN\Users membership is required for the account to hold
  108. // the interactive-logon right that `CreateProcessWithLogonW`
  109. // depends on. Resolve the **localised** group name from the
  110. // well-known SID so this works on non-English Windows.
  111. let builtin_users =
  112. sid::lookup_account_name(SID_BUILTIN_USERS).context("resolve BUILTIN\\Users name")?;
  113. sam::add_member(&builtin_users, &user_psid)?;
  114. sam::add_member(SANDBOX_GROUP, &user_psid)?;
  115. set_logon_ui_hidden(name, true)?;
  116. let group_sid = sid::lookup_account_sid(SANDBOX_GROUP).context("resolve sandbox group SID")?;
  117. apply_logon_denials(&group_sid).context("stamp logon-type denials on the sandbox group")?;
  118. Ok(ProvisionedUser {
  119. username: name.into(),
  120. sid,
  121. group_sid,
  122. password,
  123. })
  124. }
  125. /// Delete `name`'s roaming/local profile (best-effort), the account
  126. /// itself, [`SANDBOX_GROUP`], and the Winlogon hide value.
  127. /// Idempotent — every step tolerates already-absent state.
  128. pub fn deprovision(name: &str) -> Result<()> {
  129. // LSA account-rights entries would linger in the policy DB after
  130. // the group SID is deleted; strip them first. Best-effort — the
  131. // group may already be gone on a re-run.
  132. if let Ok(gsid) = sid::lookup_account_sid(SANDBOX_GROUP)
  133. && let Err(e) = remove_logon_denials(&gsid)
  134. {
  135. eprintln!("srt-win: warning: removing logon denials: {e:#}");
  136. }
  137. // Profile delete needs the SID *string*; resolve before
  138. // NetUserDel removes the SAM mapping. Failure to resolve (user
  139. // already gone) is fine — no profile to delete.
  140. if let Ok(s) = sid::lookup_account_sid(name) {
  141. let sid_w = wstr(&s);
  142. // Best-effort: profile may never have been created (no
  143. // `LOGON_WITH_PROFILE` yet), or may be locked by a stuck
  144. // child. Either way the account delete below still works.
  145. unsafe {
  146. let _ = DeleteProfileW(pcwstr(&sid_w), PCWSTR::null(), PCWSTR::null());
  147. }
  148. }
  149. let user_w = wstr(name);
  150. let rc = unsafe { NetUserDel(PCWSTR::null(), pcwstr(&user_w)) };
  151. if rc != 0 && rc != NERR_UserNotFound {
  152. return Err(anyhow!("NetUserDel({name}): {rc}"));
  153. }
  154. sam::delete_local_group(SANDBOX_GROUP)?;
  155. // Best-effort: the key may never have been created.
  156. let _ = set_logon_ui_hidden(name, false);
  157. Ok(())
  158. }
  159. /// Observe each piece of `name`'s provisioned state independently.
  160. /// Does not require elevation.
  161. pub fn status(name: &str) -> Result<UserStatus> {
  162. let sid = sid::lookup_account_sid(name).ok();
  163. let group_sid = sid::lookup_account_sid(SANDBOX_GROUP).ok();
  164. let in_builtin_users = sid
  165. .as_deref()
  166. .map(|s| sam::is_member_of(SID_BUILTIN_USERS, s))
  167. .transpose()?
  168. .unwrap_or(false);
  169. let in_sandbox_group = match (&sid, &group_sid) {
  170. (Some(u), Some(g)) => sam::is_member_of(g, u)?,
  171. _ => false,
  172. };
  173. Ok(UserStatus {
  174. name: name.into(),
  175. exists: sid.is_some(),
  176. sid,
  177. group_exists: group_sid.is_some(),
  178. group_sid,
  179. in_builtin_users,
  180. in_sandbox_group,
  181. hidden_from_logon: is_logon_ui_hidden(name),
  182. })
  183. }
  184. // ────────────────────── internals ──────────────────────
  185. /// 32 characters drawn uniformly from an 85-symbol alphabet via
  186. /// `BCryptGenRandom` (system CSPRNG). Excludes characters that
  187. /// quoting layers between here and `CreateProcessWithLogonW` are
  188. /// known to mishandle (`"`, `\`, ``` ` ```, whitespace) and the
  189. /// shell-special `&|<>^` set, so the password survives any cmd /
  190. /// PowerShell relay the runner spec may go through. ≈ 32 × log₂ 85
  191. /// ≈ 205 bits; Windows local-account max length is 127.
  192. fn gen_password() -> Result<String> {
  193. const ALPHA: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
  194. abcdefghijklmnopqrstuvwxyz\
  195. 0123456789!#$%()*+,-./:;=?@[]_{}~";
  196. const N: usize = 32;
  197. const { assert!(ALPHA.len() == 85) };
  198. let mut raw = [0u8; N];
  199. let st = unsafe { BCryptGenRandom(None, &mut raw, BCRYPT_USE_SYSTEM_PREFERRED_RNG) };
  200. if st.0 != 0 {
  201. return Err(anyhow!("BCryptGenRandom: NTSTATUS=0x{:08x}", st.0));
  202. }
  203. // Rejection sample so each output byte is a uniform pick from
  204. // ALPHA (85 doesn't divide 256). One refill is overwhelmingly
  205. // enough — the loop is a correctness backstop, not a hot path.
  206. let bound = (u8::MAX - (u8::MAX % ALPHA.len() as u8)) as usize;
  207. let mut out = Vec::with_capacity(N);
  208. let mut i = 0usize;
  209. while out.len() < N {
  210. if i == raw.len() {
  211. let st = unsafe { BCryptGenRandom(None, &mut raw, BCRYPT_USE_SYSTEM_PREFERRED_RNG) };
  212. if st.0 != 0 {
  213. return Err(anyhow!("BCryptGenRandom (refill): NTSTATUS=0x{:08x}", st.0));
  214. }
  215. i = 0;
  216. }
  217. let b = raw[i] as usize;
  218. i += 1;
  219. if b < bound {
  220. out.push(ALPHA[b % ALPHA.len()]);
  221. }
  222. }
  223. // Belt-and-suspenders for tightened complexity policies: if any of
  224. // the four classes is absent, seed four consecutive positions
  225. // (random base offset) with one forced pick from each. The retry
  226. // loop in [`ensure_user`] is the primary defence; this makes the
  227. // first attempt overwhelmingly likely to pass on its own.
  228. const CLASSES: [&[u8]; 4] = [
  229. b"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
  230. b"abcdefghijklmnopqrstuvwxyz",
  231. b"0123456789",
  232. b"!#$%()*+,-./:;=?@[]_{}~",
  233. ];
  234. if CLASSES.iter().any(|c| !out.iter().any(|b| c.contains(b))) {
  235. let mut extra = [0u8; 5];
  236. let st = unsafe { BCryptGenRandom(None, &mut extra, BCRYPT_USE_SYSTEM_PREFERRED_RNG) };
  237. if st.0 != 0 {
  238. return Err(anyhow!("BCryptGenRandom (seed): NTSTATUS=0x{:08x}", st.0));
  239. }
  240. let base = extra[0] as usize;
  241. for (k, class) in CLASSES.iter().enumerate() {
  242. out[(base + k) % N] = class[extra[1 + k] as usize % class.len()];
  243. }
  244. }
  245. Ok(String::from_utf8(out).expect("ALPHA is ASCII"))
  246. }
  247. /// `NetUserAdd(level=1)` if absent; on `NERR_UserExists`,
  248. /// `NetUserSetInfo(level=1003)` to rotate the password and
  249. /// `NetUserSetInfo(level=1008)` to OR `UF_DONT_EXPIRE_PASSWD` into
  250. /// the existing flags. Either way the account ends up with the
  251. /// returned password and a non-expiring password — even if an older
  252. /// build or a domain GPO cleared the flag since the previous install.
  253. ///
  254. /// Both password-bearing calls retry on `NERR_PasswordTooShort`
  255. /// (2245) with a fresh [`gen_password`] draw — despite the name, SAM
  256. /// returns 2245 for *any* local-policy rejection (complexity /
  257. /// history / filter DLL), so a policy tightened between builds can
  258. /// bounce an otherwise-valid 32-char draw.
  259. ///
  260. /// `we_own_it` — the setup marker records `name` as an account a
  261. /// prior install created. When **false**, any principal that already
  262. /// resolves under `name` (local user, group, alias, domain
  263. /// principal) is refused rather than adopted: srt-win will not
  264. /// rotate the password of an account it didn't create.
  265. fn ensure_user(name: &str, we_own_it: bool) -> Result<String> {
  266. let mut name_w = wstr(name);
  267. // Ownership guard runs FIRST, before any mutation, via
  268. // `LookupAccountNameW` (resolves users, groups, aliases, domain
  269. // principals alike) — so the friendly message is emitted
  270. // regardless of which rc `NetUserAdd` would return for the name
  271. // (`NERR_UserExists`/`NERR_GroupExists`/`ERROR_ALIAS_EXISTS`
  272. // vary by kind). Not-found → create path.
  273. if !we_own_it && sid::lookup_account_sid(name).is_ok() {
  274. bail!(
  275. "account '{name}' already exists and was not created by \
  276. srt-win. Pick a different --sandbox-user name (or omit \
  277. it for the default '{SANDBOX_USER}', which srt-win \
  278. manages)."
  279. );
  280. }
  281. let mut comment_w = wstr("sandbox-runtime sandboxed-child account");
  282. // Bound in the header (defense-in-depth) *and* in the inner
  283. // `attempt + 1 < MAX_PW_ATTEMPTS` guards — the last iteration
  284. // falls through to the standard error branches, and if a future
  285. // edit widens the guard the header still stops the loop.
  286. for attempt in 0..MAX_PW_ATTEMPTS {
  287. let password = gen_password().context("generate sandbox password")?;
  288. let mut pw_w = wstr(&password);
  289. let info = USER_INFO_1 {
  290. usri1_name: PWSTR(name_w.as_mut_ptr()),
  291. usri1_password: PWSTR(pw_w.as_mut_ptr()),
  292. usri1_password_age: 0,
  293. usri1_priv: USER_PRIV_USER,
  294. usri1_home_dir: PWSTR::null(),
  295. usri1_comment: PWSTR(comment_w.as_mut_ptr()),
  296. // UF_SCRIPT is required by SAM on workstation SKUs (legacy
  297. // LAN-Manager flag); without it NetUserAdd returns
  298. // NERR_BadUsername / ERROR_INVALID_PARAMETER.
  299. usri1_flags: UF_SCRIPT | UF_DONT_EXPIRE_PASSWD,
  300. usri1_script_path: PWSTR::null(),
  301. };
  302. let rc = unsafe { NetUserAdd(PCWSTR::null(), 1, &info as *const _ as *const u8, None) };
  303. if rc == 0 {
  304. return Ok(password);
  305. }
  306. if rc == NERR_PasswordTooShort && attempt + 1 < MAX_PW_ATTEMPTS {
  307. diag_2245("NetUserAdd", attempt, &password);
  308. continue;
  309. }
  310. if rc != NERR_UserExists {
  311. return Err(anyhow!("NetUserAdd({name}): {rc}"));
  312. }
  313. // Already exists — rotate the password so the credential file
  314. // about to be (re)written matches.
  315. let info1003 = USER_INFO_1003 {
  316. usri1003_password: PWSTR(pw_w.as_mut_ptr()),
  317. };
  318. let rc = unsafe {
  319. NetUserSetInfo(
  320. PCWSTR::null(),
  321. pcwstr(&name_w),
  322. 1003,
  323. &info1003 as *const _ as *const u8,
  324. None,
  325. )
  326. };
  327. if rc == NERR_PasswordTooShort && attempt + 1 < MAX_PW_ATTEMPTS {
  328. diag_2245("NetUserSetInfo(1003)", attempt, &password);
  329. continue;
  330. }
  331. if rc != 0 {
  332. return Err(anyhow!(
  333. "NetUserSetInfo({name}, level=1003 password rotate): {rc}"
  334. ));
  335. }
  336. ensure_dont_expire(name, &name_w)?;
  337. return Ok(password);
  338. }
  339. bail!(
  340. "ensure_user({name}): password rejected by local policy after \
  341. {MAX_PW_ATTEMPTS} attempts (NERR_PasswordTooShort=2245)"
  342. )
  343. }
  344. const MAX_PW_ATTEMPTS: usize = 5;
  345. /// Dump the local password policy and the failing password's class
  346. /// composition (never the password itself) to stderr, so a 2245 on a
  347. /// runner or a customer box is diagnosable from logs alone.
  348. fn diag_2245(op: &str, attempt: usize, password: &str) {
  349. let (mut u, mut l, mut d, mut s) = (0u32, 0u32, 0u32, 0u32);
  350. for b in password.bytes() {
  351. match b {
  352. b'A'..=b'Z' => u += 1,
  353. b'a'..=b'z' => l += 1,
  354. b'0'..=b'9' => d += 1,
  355. _ => s += 1,
  356. }
  357. }
  358. let mut buf: *mut u8 = std::ptr::null_mut();
  359. let (min_len, hist) = if unsafe { NetUserModalsGet(PCWSTR::null(), 0, &mut buf) } == 0 {
  360. let m = unsafe { *(buf as *const USER_MODALS_INFO_0) };
  361. unsafe {
  362. let _ = NetApiBufferFree(Some(buf as *const c_void));
  363. }
  364. (
  365. m.usrmod0_min_passwd_len as i64,
  366. m.usrmod0_password_hist_len as i64,
  367. )
  368. } else {
  369. (-1, -1)
  370. };
  371. eprintln!(
  372. "srt-win: {op} 2245 (attempt {}/{MAX_PW_ATTEMPTS}) — policy: min_len={min_len} hist={hist}; \
  373. pw classes: U={u} L={l} D={d} S={s}; retrying",
  374. attempt + 1
  375. );
  376. }
  377. fn ensure_dont_expire(name: &str, name_w: &[u16]) -> Result<()> {
  378. // Re-assert UF_DONT_EXPIRE_PASSWD: read level-1 flags, OR in,
  379. // write back via level-1008 (flags only — level-1 SetInfo would
  380. // overwrite priv/home_dir/comment).
  381. let mut buf: *mut u8 = std::ptr::null_mut();
  382. let rc = unsafe { NetUserGetInfo(PCWSTR::null(), pcwstr(name_w), 1, &mut buf) };
  383. if rc != 0 {
  384. return Err(anyhow!("NetUserGetInfo({name}, level=1): {rc}"));
  385. }
  386. let cur_flags = unsafe { (*(buf as *const USER_INFO_1)).usri1_flags };
  387. unsafe {
  388. let _ = NetApiBufferFree(Some(buf as *const c_void));
  389. }
  390. let info1008 = USER_INFO_1008 {
  391. usri1008_flags: cur_flags | UF_DONT_EXPIRE_PASSWD,
  392. };
  393. let rc = unsafe {
  394. NetUserSetInfo(
  395. PCWSTR::null(),
  396. pcwstr(name_w),
  397. 1008,
  398. &info1008 as *const _ as *const u8,
  399. None,
  400. )
  401. };
  402. if rc != 0 {
  403. return Err(anyhow!("NetUserSetInfo({name}, level=1008 flags): {rc}"));
  404. }
  405. Ok(())
  406. }
  407. /// Write (or delete) `HKLM\…\Winlogon\SpecialAccounts\UserList\<user>
  408. /// = 0` so the account doesn't appear on the lock-screen user
  409. /// picker. Cosmetic only — the account is still fully usable via
  410. /// `CreateProcessWithLogonW`.
  411. fn set_logon_ui_hidden(user: &str, hide: bool) -> Result<()> {
  412. if hide {
  413. crate::util::reg_set_value(
  414. HKEY_LOCAL_MACHINE,
  415. WINLOGON_USERLIST,
  416. user,
  417. REG_DWORD,
  418. &0u32.to_ne_bytes(),
  419. )?;
  420. } else {
  421. let sub_w = wstr(WINLOGON_USERLIST);
  422. let val_w = wstr(user);
  423. let mut hkey = HKEY::default();
  424. // Open (not create) — if the key was never made there's
  425. // nothing to delete.
  426. let r = unsafe {
  427. RegOpenKeyExW(
  428. HKEY_LOCAL_MACHINE,
  429. pcwstr(&sub_w),
  430. None,
  431. KEY_SET_VALUE,
  432. &mut hkey,
  433. )
  434. };
  435. if r.is_err() {
  436. return Ok(());
  437. }
  438. unsafe {
  439. let _ = RegDeleteValueW(hkey, pcwstr(&val_w));
  440. let _ = RegCloseKey(hkey);
  441. }
  442. }
  443. Ok(())
  444. }
  445. fn is_logon_ui_hidden(user: &str) -> bool {
  446. let sub_w = wstr(WINLOGON_USERLIST);
  447. let val_w = wstr(user);
  448. let mut hkey = HKEY::default();
  449. let r = unsafe {
  450. RegOpenKeyExW(
  451. HKEY_LOCAL_MACHINE,
  452. pcwstr(&sub_w),
  453. None,
  454. KEY_READ,
  455. &mut hkey,
  456. )
  457. };
  458. if r.is_err() {
  459. return false;
  460. }
  461. let mut data = [0u8; 4];
  462. let mut cb: u32 = 4;
  463. let r = unsafe {
  464. RegQueryValueExW(
  465. hkey,
  466. pcwstr(&val_w),
  467. None,
  468. None,
  469. Some(data.as_mut_ptr()),
  470. Some(&mut cb),
  471. )
  472. };
  473. unsafe {
  474. let _ = RegCloseKey(hkey);
  475. }
  476. // Hidden iff the value exists AND is 0 (a value of 1 explicitly
  477. // shows the account; absence = default = shown).
  478. r != ERROR_FILE_NOT_FOUND && r.is_ok() && cb == 4 && u32::from_ne_bytes(data) == 0
  479. }
  480. /// The logon-type denials stamped on [`SANDBOX_GROUP`]. Everything
  481. /// except INTERACTIVE — which `CreateProcessWithLogonW`'s
  482. /// `LOGON_WITH_PROFILE` logon performs and the sandbox launch
  483. /// depends on (the account holds it via `BUILTIN\Users`).
  484. ///
  485. /// - `SeDenyNetworkLogonRight`: the SMB redirector dials as SYSTEM
  486. /// from kernel mode, so the SID-keyed WFP fence never classifies
  487. /// its connects — red-teaming confirmed `net use \\127.0.0.1\IPC$`
  488. /// succeeded from inside the sandbox, and the same mechanism
  489. /// reaches remote shares (an exfil channel) and SMB-hosted RPC
  490. /// pipes. SMB *authenticates* as the sandbox account though, so
  491. /// denying it the network-logon right refuses the session at the
  492. /// server regardless of which process carried the bytes.
  493. /// CAVEAT (verified): LOOPBACK SMB stays reachable — NTLM
  494. /// loopback auth reuses the client's existing logon session, so
  495. /// no new network logon happens and the deny right never fires;
  496. /// `LogonUser(NETWORK)` (what any REMOTE server's LSA runs)
  497. /// returns 1385. Content behind loopback shares is still governed
  498. /// by the same NTFS ACLs the sandbox is stamped with.
  499. /// - `SeDenyBatchLogonRight`: a sandboxed child can REGISTER a
  500. /// scheduled task (the service's DACL allows it); the task then
  501. /// needs a batch logon to RUN. Denying it turns registration into
  502. /// inert persistence-spam.
  503. /// - `SeDenyServiceLogonRight` / `SeDenyRemoteInteractiveLogonRight`:
  504. /// no legitimate flow runs the account as a service or over RDP.
  505. const LOGON_DENIALS: [&str; 4] = [
  506. "SeDenyNetworkLogonRight",
  507. "SeDenyBatchLogonRight",
  508. "SeDenyServiceLogonRight",
  509. "SeDenyRemoteInteractiveLogonRight",
  510. ];
  511. /// Open the local LSA policy, marshal [`LOGON_DENIALS`] as
  512. /// LSA_UNICODE_STRINGs (each backed by its OWN allocation so the
  513. /// pointers cannot dangle if the list grows), run `f`, and close the
  514. /// policy on every path.
  515. fn with_lsa_rights<F>(f: F) -> Result<()>
  516. where
  517. F: FnOnce(
  518. windows::Win32::Security::Authentication::Identity::LSA_HANDLE,
  519. &[windows::Win32::Security::Authentication::Identity::LSA_UNICODE_STRING],
  520. ) -> windows::Win32::Foundation::NTSTATUS,
  521. {
  522. use windows::Win32::Security::Authentication::Identity::{
  523. LSA_OBJECT_ATTRIBUTES, LSA_UNICODE_STRING, LsaClose, LsaNtStatusToWinError, LsaOpenPolicy,
  524. POLICY_CREATE_ACCOUNT, POLICY_LOOKUP_NAMES,
  525. };
  526. let attrs = LSA_OBJECT_ATTRIBUTES::default();
  527. let mut policy = Default::default();
  528. let status = unsafe {
  529. LsaOpenPolicy(
  530. None,
  531. &attrs,
  532. (POLICY_CREATE_ACCOUNT | POLICY_LOOKUP_NAMES) as u32,
  533. &mut policy,
  534. )
  535. };
  536. if status.is_err() {
  537. let gle = unsafe { LsaNtStatusToWinError(status) };
  538. anyhow::bail!("LsaOpenPolicy: win32 error {gle}");
  539. }
  540. // One owned buffer per right: growth of LOGON_DENIALS can never
  541. // invalidate an earlier entry's Buffer pointer.
  542. let bufs: Vec<(Vec<u16>, u16)> = LOGON_DENIALS
  543. .iter()
  544. .map(|r| crate::util::counted_utf16(r))
  545. .collect();
  546. let rights: Vec<LSA_UNICODE_STRING> = bufs
  547. .iter()
  548. .map(|(b, bytes)| LSA_UNICODE_STRING {
  549. Length: *bytes,
  550. MaximumLength: *bytes,
  551. Buffer: windows::core::PWSTR(b.as_ptr() as *mut u16),
  552. })
  553. .collect();
  554. let status = f(policy, &rights);
  555. let ret = if status.is_err() {
  556. let gle = unsafe { LsaNtStatusToWinError(status) };
  557. Err(anyhow::anyhow!(
  558. "LSA account-rights call: win32 error {gle}"
  559. ))
  560. } else {
  561. Ok(())
  562. };
  563. unsafe {
  564. let _ = LsaClose(policy);
  565. }
  566. ret
  567. }
  568. /// Stamp [`LOGON_DENIALS`] on `group_sid` via LSA policy. Idempotent
  569. /// (adding an already-held right succeeds). Applied to the GROUP so
  570. /// custom-named accounts (`--sandbox-user`) inherit without extra
  571. /// plumbing. Local LSA policy — domain GPO can overwrite user-right
  572. /// assignments on refresh, which is why the install path re-asserts
  573. /// this on EVERY run (including the already-installed early-out),
  574. /// not only at first provisioning.
  575. pub fn apply_logon_denials(group_sid: &str) -> Result<()> {
  576. use windows::Win32::Security::Authentication::Identity::LsaAddAccountRights;
  577. let psid = sid::LocalPsid::from_string(group_sid)?;
  578. with_lsa_rights(|policy, rights| unsafe { LsaAddAccountRights(policy, psid.as_psid(), rights) })
  579. .context("LsaAddAccountRights")
  580. }
  581. /// Remove [`LOGON_DENIALS`] from `group_sid` (uninstall hygiene —
  582. /// the group is deleted right after, but orphaned LSA account-rights
  583. /// entries linger in the policy database otherwise). Best-effort.
  584. pub fn remove_logon_denials(group_sid: &str) -> Result<()> {
  585. use windows::Win32::Security::Authentication::Identity::LsaRemoveAccountRights;
  586. let psid = sid::LocalPsid::from_string(group_sid)?;
  587. with_lsa_rights(|policy, rights| unsafe {
  588. LsaRemoveAccountRights(policy, psid.as_psid(), false, Some(rights))
  589. })
  590. .context("LsaRemoveAccountRights")
  591. }
  592. #[cfg(test)]
  593. mod tests {
  594. use super::*;
  595. #[test]
  596. fn password_shape() {
  597. let p = gen_password().expect("gen");
  598. assert_eq!(p.len(), 32);
  599. assert!(p.is_ascii());
  600. // No characters from the excluded set.
  601. for c in ['"', '\\', '`', ' ', '&', '|', '<', '>', '^'] {
  602. assert!(!p.contains(c), "password contains '{c}': {p}");
  603. }
  604. // At least one from each complexity class (post-seed guarantee).
  605. assert!(p.bytes().any(|b| b.is_ascii_uppercase()), "{p}");
  606. assert!(p.bytes().any(|b| b.is_ascii_lowercase()), "{p}");
  607. assert!(p.bytes().any(|b| b.is_ascii_digit()), "{p}");
  608. assert!(p.bytes().any(|b| !b.is_ascii_alphanumeric()), "{p}");
  609. // Two calls differ (overwhelmingly).
  610. assert_ne!(p, gen_password().unwrap());
  611. }
  612. #[test]
  613. fn builtin_users_name_resolves() {
  614. // The exact name is locale-dependent; just check it's
  615. // non-empty and round-trips back to the well-known SID.
  616. let name = sid::lookup_account_name(SID_BUILTIN_USERS).expect("name");
  617. assert!(!name.is_empty());
  618. let back = sid::lookup_account_sid(&name).expect("sid");
  619. assert_eq!(back, SID_BUILTIN_USERS);
  620. }
  621. #[test]
  622. fn status_for_absent_user_is_falsey() {
  623. // The CI smoke installs/uninstalls under the real names, so
  624. // here we only sanity-check that status() doesn't error and
  625. // its booleans agree with `exists`.
  626. let st = status(SANDBOX_USER).expect("status");
  627. assert_eq!(st.name, SANDBOX_USER);
  628. if !st.exists {
  629. assert!(st.sid.is_none());
  630. assert!(!st.in_builtin_users);
  631. assert!(!st.in_sandbox_group);
  632. }
  633. }
  634. }