token.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. //! Restricted-token construction for the runner→child lockdown.
  2. //!
  3. //! Token shape:
  4. //! - `SidsToDisable = [BUILTIN\Administrators, <every
  5. //! SE_GROUP_LOGON_ID SID in the base token>]` — flips them to
  6. //! `SE_GROUP_USE_FOR_DENY_ONLY`. Admins is belt-and-braces (the
  7. //! runner runs as `srt-sandbox`, so it normally lacks Admins;
  8. //! covers elevated brokers / CI runners where the sandbox user
  9. //! was added to Admins out-of-band). The **logon SID(s) are the
  10. //! load-bearing strip**: seclogon stamps the broker's
  11. //! interactive logon SID into the runner's token (so the runner
  12. //! can attach to `WinSta0\Default`), and that SID matches the
  13. //! default per-process logon-session ACE
  14. //! (`VM_READ | QUERY | TERMINATE`) on every default-DACL process
  15. //! in the broker's session. Left enabled, the child can
  16. //! `OpenProcess(VM_READ)` + `ReadProcessMemory` any same-session
  17. //! real-user process — browser heap, shell, the host
  18. //! orchestrator. Nothing in the sandbox keys on the logon SID
  19. //! (FS/WFP key on user SID; the isolated desktop's DACL grants
  20. //! the sandbox user explicitly), so disabling it loses nothing.
  21. //! - `LUA_TOKEN` flag — token reads as a normal limited-user token
  22. //! to NT components.
  23. //! - All privileges deleted except `SeChangeNotifyPrivilege`.
  24. //! - Integrity Level = Medium (same as a normal user process).
  25. //! - No `RestrictingSids` array — that breaks Schannel/LSA RPC.
  26. use anyhow::{Context, Result, anyhow};
  27. use std::ffi::c_void;
  28. use std::mem::size_of;
  29. use windows::Win32::Foundation::{HANDLE, LUID};
  30. use windows::Win32::Security::{
  31. ACL, ACL_REVISION, AddAccessAllowedAce, AllocateAndInitializeSid, CreateRestrictedToken,
  32. DuplicateTokenEx, FreeSid, GetLengthSid, GetTokenInformation, InitializeAcl, LUA_TOKEN,
  33. LUID_AND_ATTRIBUTES, LookupPrivilegeValueW, PSID, SID_AND_ATTRIBUTES, SID_IDENTIFIER_AUTHORITY,
  34. SecurityImpersonation, SetTokenInformation, TOKEN_ALL_ACCESS, TOKEN_DEFAULT_DACL, TOKEN_GROUPS,
  35. TOKEN_INFORMATION_CLASS, TOKEN_MANDATORY_LABEL, TOKEN_PRIVILEGES, TOKEN_USER, TokenDefaultDacl,
  36. TokenGroups, TokenIntegrityLevel, TokenPrimary, TokenPrivileges, TokenUser,
  37. };
  38. use windows::Win32::System::SystemServices::SE_GROUP_LOGON_ID;
  39. use windows::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
  40. use crate::sid::LocalPsid;
  41. use crate::util::{pcwstr, wstr};
  42. /// Medium IL (`SECURITY_MANDATORY_MEDIUM_RID`). The sandbox child
  43. /// runs at Medium — same as normal user processes — so Schannel /
  44. /// LSA / registry edge cases that fire at Low IL don't apply.
  45. pub const IL_MEDIUM: u32 = 0x2000;
  46. /// `BUILTIN\Administrators`. Always added to `SidsToDisable` so an
  47. /// elevated broker still produces a non-admin child.
  48. const SID_BUILTIN_ADMINS: &str = "S-1-5-32-544";
  49. /// `SE_GROUP_INTEGRITY` attribute (winnt.h). Required on the
  50. /// `TOKEN_MANDATORY_LABEL.Label.Attributes` field.
  51. const SE_GROUP_INTEGRITY: u32 = 0x0000_0020;
  52. /// Every `SE_GROUP_LOGON_ID` SID in `token`'s `TokenGroups`, copied
  53. /// into owned byte buffers (each is a self-relative SID; cast
  54. /// `.as_ptr()` to `PSID` for Win32 calls). `SE_GROUP_LOGON_ID` is a
  55. /// 2-bit value (`0xC000_0000`); both bits are required, not `!= 0`.
  56. fn logon_sids_of(token: HANDLE) -> Result<Vec<Vec<u8>>> {
  57. let buf = get_token_info(token, TokenGroups)?;
  58. unsafe {
  59. let tg = &*(buf.as_ptr() as *const TOKEN_GROUPS);
  60. Ok(
  61. std::slice::from_raw_parts(tg.Groups.as_ptr(), tg.GroupCount as usize)
  62. .iter()
  63. .filter(|g| g.Attributes & (SE_GROUP_LOGON_ID as u32) == SE_GROUP_LOGON_ID as u32)
  64. .map(|g| {
  65. let len = GetLengthSid(g.Sid) as usize;
  66. std::slice::from_raw_parts(g.Sid.0 as *const u8, len).to_vec()
  67. })
  68. .collect(),
  69. )
  70. }
  71. }
  72. /// Open this process's primary token with full access.
  73. pub fn open_self_token() -> Result<HANDLE> {
  74. unsafe {
  75. let mut h = HANDLE::default();
  76. OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &mut h)
  77. .context("OpenProcessToken")?;
  78. Ok(h)
  79. }
  80. }
  81. /// Build the restricted child token from `base`. Returns a
  82. /// non-primary token; the caller duplicates to primary via
  83. /// [`to_primary`].
  84. pub fn make_sandbox_token(base: HANDLE) -> Result<HANDLE> {
  85. // SIDs to disable: `BUILTIN\Administrators` + every
  86. // `SE_GROUP_LOGON_ID` group in `base` (see module doc — the
  87. // logon-SID strip is what stops the child reading same-session
  88. // real-user process memory). `logon_sids` owns the logon-SID
  89. // bytes and must outlive `CreateRestrictedToken`; `admins` is
  90. // RAII over `ConvertStringSidToSidW` (`LocalFree` on drop).
  91. let admins = LocalPsid::from_string(SID_BUILTIN_ADMINS)?;
  92. let logon_sids = logon_sids_of(base)?;
  93. let disable: Vec<SID_AND_ATTRIBUTES> = std::iter::once(admins.as_psid())
  94. .chain(logon_sids.iter().map(|s| PSID(s.as_ptr() as *mut c_void)))
  95. .map(|sid| SID_AND_ATTRIBUTES {
  96. Sid: sid,
  97. Attributes: 0,
  98. })
  99. .collect();
  100. // Privileges to delete: everything in `base` except
  101. // SeChangeNotifyPrivilege.
  102. let to_delete = privileges_except(base, &["SeChangeNotifyPrivilege"])?;
  103. let mut out = HANDLE::default();
  104. unsafe {
  105. CreateRestrictedToken(
  106. base,
  107. LUA_TOKEN,
  108. Some(&disable),
  109. if to_delete.is_empty() {
  110. None
  111. } else {
  112. Some(&to_delete)
  113. },
  114. None, // RestrictingSids — intentionally empty
  115. &mut out,
  116. )
  117. .context("CreateRestrictedToken(disable=[Admins, logon-SIDs])")?;
  118. }
  119. // `admins` + `logon_sids` (which back the disable-array PSIDs) drop here.
  120. // RAII-own `out` so a `?` from set_il/set_default_dacl below
  121. // closes it.
  122. let guard = crate::util::OwnedHandle(out);
  123. set_il(guard.raw(), IL_MEDIUM)?;
  124. set_default_dacl(guard.raw(), base)?;
  125. Ok(guard.into_raw())
  126. }
  127. /// Duplicate to a primary token (`CreateProcessAsUserW` requires a
  128. /// primary).
  129. pub fn to_primary(token: HANDLE) -> Result<HANDLE> {
  130. unsafe {
  131. let mut out = HANDLE::default();
  132. DuplicateTokenEx(
  133. token,
  134. TOKEN_ALL_ACCESS,
  135. None,
  136. SecurityImpersonation,
  137. TokenPrimary,
  138. &mut out,
  139. )
  140. .context("DuplicateTokenEx(primary)")?;
  141. Ok(out)
  142. }
  143. }
  144. /// Set the token's integrity level via a mandatory-label SID built
  145. /// with `AllocateAndInitializeSid` (so [`FreeSid`] is the correct
  146. /// release fn — the one place in this crate where it is).
  147. fn set_il(tok: HANDLE, rid: u32) -> Result<()> {
  148. unsafe {
  149. let ml_auth = SID_IDENTIFIER_AUTHORITY {
  150. Value: [0, 0, 0, 0, 0, 16],
  151. };
  152. let mut sid = PSID::default();
  153. AllocateAndInitializeSid(&ml_auth, 1, rid, 0, 0, 0, 0, 0, 0, 0, &mut sid)
  154. .context("AllocateAndInitializeSid(mandatory label)")?;
  155. let tml = TOKEN_MANDATORY_LABEL {
  156. Label: SID_AND_ATTRIBUTES {
  157. Sid: sid,
  158. Attributes: SE_GROUP_INTEGRITY,
  159. },
  160. };
  161. let r = SetTokenInformation(
  162. tok,
  163. TokenIntegrityLevel,
  164. &tml as *const _ as *const c_void,
  165. size_of::<TOKEN_MANDATORY_LABEL>() as u32 + GetLengthSid(sid),
  166. );
  167. // Free regardless of outcome.
  168. FreeSid(sid);
  169. r.context("SetTokenInformation(IntegrityLevel)")?;
  170. Ok(())
  171. }
  172. }
  173. /// Rewrite the token's default DACL so objects the child *creates*
  174. /// (process, thread, mutex, …) are accessible to SYSTEM and to the
  175. /// **sandbox user** (`base`'s `TokenUser`). The donor leaked the
  176. /// SYSTEM SID here; this version uses [`LocalPsid`] so it's freed on
  177. /// return.
  178. ///
  179. /// Keyed on the user SID, not the logon SID: every logon SID in the
  180. /// child token is deny-only (see [`make_sandbox_token`]), so a
  181. /// logon-SID ALLOW ACE here would be ignored at access-check.
  182. /// Siblings inside the sandbox (e.g. a parallel build's worker
  183. /// processes) share the `srt-sandbox` user SID, so the user-SID grant
  184. /// covers them — and the broker (different user, two hops away) never
  185. /// opens child-created objects directly.
  186. fn set_default_dacl(tok: HANDLE, base: HANDLE) -> Result<()> {
  187. let system = LocalPsid::from_string("S-1-5-18")?;
  188. let user_buf = get_token_info(base, TokenUser)?;
  189. let user = unsafe { (*(user_buf.as_ptr() as *const TOKEN_USER)).User.Sid };
  190. let sids = [system.as_psid(), user];
  191. // Sized ACL: header + per-ACE (8-byte fixed prefix + SID body).
  192. const ACE_FIXED: usize = 8;
  193. let mut total = size_of::<ACL>();
  194. for s in &sids {
  195. total += ACE_FIXED + unsafe { GetLengthSid(*s) } as usize;
  196. }
  197. total = (total + 3) & !3;
  198. let mut buf = vec![0u8; total];
  199. let acl = buf.as_mut_ptr() as *mut ACL;
  200. unsafe {
  201. InitializeAcl(acl, total as u32, ACL_REVISION).context("InitializeAcl(default DACL)")?;
  202. // GENERIC_ALL.
  203. const GENERIC_ALL: u32 = 0x1000_0000;
  204. for s in &sids {
  205. AddAccessAllowedAce(acl, ACL_REVISION, GENERIC_ALL, *s)
  206. .context("AddAccessAllowedAce(default DACL)")?;
  207. }
  208. let tdd = TOKEN_DEFAULT_DACL { DefaultDacl: acl };
  209. SetTokenInformation(
  210. tok,
  211. TokenDefaultDacl,
  212. &tdd as *const _ as *const c_void,
  213. size_of::<TOKEN_DEFAULT_DACL>() as u32,
  214. )
  215. .context("SetTokenInformation(DefaultDacl)")?;
  216. }
  217. // `user_buf` (which backs `user`) and `system` both drop here.
  218. Ok(())
  219. }
  220. fn get_token_info(tok: HANDLE, cls: TOKEN_INFORMATION_CLASS) -> Result<Vec<u8>> {
  221. unsafe {
  222. let mut len = 0u32;
  223. let _ = GetTokenInformation(tok, cls, None, 0, &mut len);
  224. if len == 0 {
  225. return Err(anyhow!("GetTokenInformation({cls:?}) sizing returned 0"));
  226. }
  227. let mut buf = vec![0u8; len as usize];
  228. GetTokenInformation(
  229. tok,
  230. cls,
  231. Some(buf.as_mut_ptr() as *mut c_void),
  232. len,
  233. &mut len,
  234. )
  235. .with_context(|| format!("GetTokenInformation({cls:?})"))?;
  236. Ok(buf)
  237. }
  238. }
  239. /// Every privilege LUID in `base` except those named in `keep`.
  240. fn privileges_except(base: HANDLE, keep: &[&str]) -> Result<Vec<LUID_AND_ATTRIBUTES>> {
  241. let keep_luids: Vec<LUID> = keep
  242. .iter()
  243. .filter_map(|n| {
  244. let mut l = LUID::default();
  245. let w = wstr(n);
  246. unsafe { LookupPrivilegeValueW(None, pcwstr(&w), &mut l).ok()? };
  247. Some(l)
  248. })
  249. .collect();
  250. let buf = get_token_info(base, TokenPrivileges)?;
  251. unsafe {
  252. let tp = &*(buf.as_ptr() as *const TOKEN_PRIVILEGES);
  253. let arr = std::slice::from_raw_parts(tp.Privileges.as_ptr(), tp.PrivilegeCount as usize);
  254. Ok(arr
  255. .iter()
  256. .filter(|p| {
  257. !keep_luids
  258. .iter()
  259. .any(|k| k.LowPart == p.Luid.LowPart && k.HighPart == p.Luid.HighPart)
  260. })
  261. .map(|p| LUID_AND_ATTRIBUTES {
  262. Luid: p.Luid,
  263. Attributes: Default::default(),
  264. })
  265. .collect())
  266. }
  267. }
  268. #[cfg(test)]
  269. mod tests {
  270. use super::*;
  271. use windows::Win32::Foundation::CloseHandle;
  272. #[test]
  273. fn restricted_token_builds() {
  274. let base = open_self_token().expect("open_self_token");
  275. let r = make_sandbox_token(base);
  276. unsafe {
  277. let _ = CloseHandle(base);
  278. }
  279. let tok = r.expect("make_sandbox_token");
  280. let prim = to_primary(tok).expect("to_primary");
  281. unsafe {
  282. let _ = CloseHandle(tok);
  283. let _ = CloseHandle(prim);
  284. }
  285. }
  286. #[test]
  287. fn privileges_except_keeps_change_notify() {
  288. let base = open_self_token().expect("open_self_token");
  289. let to_delete = privileges_except(base, &["SeChangeNotifyPrivilege"]).unwrap();
  290. // Resolve SeChangeNotifyPrivilege's LUID and assert it's NOT
  291. // in the deletion set.
  292. let mut keep = LUID::default();
  293. let w = wstr("SeChangeNotifyPrivilege");
  294. unsafe {
  295. LookupPrivilegeValueW(None, pcwstr(&w), &mut keep).unwrap();
  296. let _ = CloseHandle(base);
  297. }
  298. assert!(
  299. !to_delete
  300. .iter()
  301. .any(|p| p.Luid.LowPart == keep.LowPart && p.Luid.HighPart == keep.HighPart),
  302. "SeChangeNotifyPrivilege must not be in the deletion set"
  303. );
  304. }
  305. }