sid.rs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. //! PSID ↔ string-SID helpers and token-membership queries.
  2. //!
  3. //! All `PSID` values returned by `ConvertStringSidToSidW` are
  4. //! heap-allocated by the OS via `LocalAlloc` and **must** be freed
  5. //! with `LocalFree` — never `FreeSid`, which is only valid for SIDs
  6. //! built by `AllocateAndInitializeSid`. The `LocalPsid` RAII wrapper
  7. //! enforces that.
  8. use anyhow::{Context, Result, anyhow};
  9. use std::ffi::c_void;
  10. use windows::Win32::Foundation::{CloseHandle, HANDLE, HLOCAL, LocalFree};
  11. use windows::Win32::Security::Authorization::{ConvertSidToStringSidW, ConvertStringSidToSidW};
  12. use windows::Win32::Security::{
  13. GetLengthSid, GetTokenInformation, LookupAccountNameW, LookupAccountSidW, PSID, SID_NAME_USE,
  14. TOKEN_QUERY, TOKEN_USER, TokenUser,
  15. };
  16. use windows::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
  17. use windows::core::PWSTR;
  18. use crate::util::{from_pwstr, local_free, pcwstr, wstr};
  19. /// RAII wrapper for a `PSID` returned by `ConvertStringSidToSidW`.
  20. /// Freed via `LocalFree` on drop.
  21. pub struct LocalPsid(PSID);
  22. impl LocalPsid {
  23. /// Parse a string SID like `"S-1-5-32-544"`.
  24. pub fn from_string(sid_str: &str) -> Result<Self> {
  25. let mut sid = PSID::default();
  26. let w = wstr(sid_str);
  27. unsafe {
  28. ConvertStringSidToSidW(pcwstr(&w), &mut sid)
  29. .map_err(|e| anyhow!("ConvertStringSidToSidW({sid_str}): {e}"))?;
  30. }
  31. Ok(Self(sid))
  32. }
  33. pub fn as_psid(&self) -> PSID {
  34. self.0
  35. }
  36. /// The SID's binary form (`GetLengthSid` bytes at the PSID).
  37. /// Borrow lives as long as `self`.
  38. pub fn as_bytes(&self) -> &[u8] {
  39. let len = unsafe { GetLengthSid(self.0) } as usize;
  40. unsafe { std::slice::from_raw_parts(self.0.0 as *const u8, len) }
  41. }
  42. }
  43. impl Drop for LocalPsid {
  44. fn drop(&mut self) {
  45. if !self.0.0.is_null() {
  46. unsafe {
  47. let _ = LocalFree(Some(HLOCAL(self.0.0)));
  48. }
  49. }
  50. }
  51. }
  52. /// String SID → owned self-relative SID bytes. Cast `.as_ptr()` to
  53. /// `PSID` for Win32 calls; the buffer is the canonical wire form so
  54. /// byte-equality is SID-equality.
  55. pub fn sid_bytes(sid_str: &str) -> Result<Vec<u8>> {
  56. Ok(LocalPsid::from_string(sid_str)?.as_bytes().to_vec())
  57. }
  58. /// Stringify a `PSID`. Used for serialisation and logging.
  59. pub fn psid_to_string(sid: PSID) -> Result<String> {
  60. let mut p = PWSTR::null();
  61. unsafe {
  62. ConvertSidToStringSidW(sid, &mut p).map_err(|e| anyhow!("ConvertSidToStringSidW: {e}"))?;
  63. }
  64. let s = from_pwstr(p);
  65. local_free(p.0 as *mut c_void);
  66. Ok(s)
  67. }
  68. /// Resolve an account name (local or domain) to a string SID via
  69. /// `LookupAccountNameW` with a NULL system name (local SAM first,
  70. /// then domain). Errors if the name is not found.
  71. pub fn lookup_account_sid(name: &str) -> Result<String> {
  72. unsafe {
  73. let mut cb_sid: u32 = 0;
  74. let mut cch_dom: u32 = 0;
  75. let mut use_: SID_NAME_USE = SID_NAME_USE::default();
  76. let name_w = wstr(name);
  77. // Sizing call. Expected to fail with ERROR_INSUFFICIENT_BUFFER.
  78. let _ = LookupAccountNameW(
  79. windows::core::PCWSTR::null(),
  80. pcwstr(&name_w),
  81. None,
  82. &mut cb_sid,
  83. None,
  84. &mut cch_dom,
  85. &mut use_,
  86. );
  87. if cb_sid == 0 {
  88. return Err(anyhow!("LookupAccountNameW({name}): account not found"));
  89. }
  90. let mut sid_buf = vec![0u8; cb_sid as usize];
  91. let mut dom_buf = vec![0u16; cch_dom.max(1) as usize];
  92. LookupAccountNameW(
  93. windows::core::PCWSTR::null(),
  94. pcwstr(&name_w),
  95. Some(PSID(sid_buf.as_mut_ptr() as *mut c_void)),
  96. &mut cb_sid,
  97. Some(PWSTR(dom_buf.as_mut_ptr())),
  98. &mut cch_dom,
  99. &mut use_,
  100. )
  101. .map_err(|e| anyhow!("LookupAccountNameW({name}): {e}"))?;
  102. psid_to_string(PSID(sid_buf.as_mut_ptr() as *mut c_void))
  103. }
  104. }
  105. /// Outcome of a SID → account reverse lookup.
  106. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  107. pub enum SidExistence {
  108. /// `LookupAccountSidW` resolved the SID to an account.
  109. Mapped,
  110. /// `LookupAccountSidW` returned `ERROR_NONE_MAPPED` — well-formed
  111. /// SID with no corresponding account. Treat as "absent".
  112. Unmapped,
  113. /// Lookup failed for a transient reason (e.g. domain controller
  114. /// unreachable). Caller should fall through to other checks
  115. /// rather than report absent.
  116. Unknown,
  117. }
  118. /// Reverse-lookup: does any account correspond to `sid_str`?
  119. /// SAM/LSA liveness probe when resolving the sandbox group for the
  120. /// state-dir DENY ACE.
  121. pub fn sid_account_exists(sid_str: &str) -> Result<SidExistence> {
  122. use windows::Win32::Foundation::{ERROR_INSUFFICIENT_BUFFER, ERROR_NONE_MAPPED, GetLastError};
  123. let psid = LocalPsid::from_string(sid_str)?;
  124. unsafe {
  125. let mut cch_name: u32 = 0;
  126. let mut cch_dom: u32 = 0;
  127. let mut use_: SID_NAME_USE = SID_NAME_USE::default();
  128. // Sizing call — we only care about the error code.
  129. let r = LookupAccountSidW(
  130. windows::core::PCWSTR::null(),
  131. psid.as_psid(),
  132. None,
  133. &mut cch_name,
  134. None,
  135. &mut cch_dom,
  136. &mut use_,
  137. );
  138. if r.is_ok() {
  139. // Shouldn't happen with zero-length buffers, but treat as
  140. // mapped if it does.
  141. return Ok(SidExistence::Mapped);
  142. }
  143. match GetLastError() {
  144. ERROR_INSUFFICIENT_BUFFER => Ok(SidExistence::Mapped),
  145. ERROR_NONE_MAPPED => Ok(SidExistence::Unmapped),
  146. // RPC_S_SERVER_UNAVAILABLE, ERROR_TRUSTED_RELATIONSHIP_FAILURE,
  147. // etc. — don't claim absence on a transient lookup failure.
  148. _ => Ok(SidExistence::Unknown),
  149. }
  150. }
  151. }
  152. /// Reverse of [`lookup_account_sid`]: SID string → account name
  153. /// (without domain). Used to find the localised name of well-known
  154. /// groups (`BUILTIN\Users` is "Benutzer" on de-DE) so SAM calls
  155. /// that take a group *name* work on non-English Windows.
  156. pub fn lookup_account_name(sid_str: &str) -> Result<String> {
  157. let psid = LocalPsid::from_string(sid_str)?;
  158. let mut cch_name: u32 = 0;
  159. let mut cch_dom: u32 = 0;
  160. let mut use_: SID_NAME_USE = SID_NAME_USE::default();
  161. unsafe {
  162. let _ = LookupAccountSidW(
  163. windows::core::PCWSTR::null(),
  164. psid.as_psid(),
  165. None,
  166. &mut cch_name,
  167. None,
  168. &mut cch_dom,
  169. &mut use_,
  170. );
  171. }
  172. if cch_name == 0 {
  173. return Err(anyhow!("LookupAccountSidW({sid_str}): sizing returned 0"));
  174. }
  175. let mut name = vec![0u16; cch_name as usize];
  176. let mut dom = vec![0u16; cch_dom.max(1) as usize];
  177. unsafe {
  178. LookupAccountSidW(
  179. windows::core::PCWSTR::null(),
  180. psid.as_psid(),
  181. Some(PWSTR(name.as_mut_ptr())),
  182. &mut cch_name,
  183. Some(PWSTR(dom.as_mut_ptr())),
  184. &mut cch_dom,
  185. &mut use_,
  186. )
  187. .map_err(|e| anyhow!("LookupAccountSidW({sid_str}): {e}"))?;
  188. }
  189. Ok(String::from_utf16_lossy(&name[..cch_name as usize]))
  190. }
  191. /// String SID of the current process token's user.
  192. pub fn current_user_sid() -> Result<String> {
  193. unsafe {
  194. let mut tok = HANDLE::default();
  195. OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut tok).context("OpenProcessToken")?;
  196. let mut len = 0u32;
  197. let _ = GetTokenInformation(tok, TokenUser, None, 0, &mut len);
  198. let mut buf = vec![0u8; len as usize];
  199. let r = GetTokenInformation(
  200. tok,
  201. TokenUser,
  202. Some(buf.as_mut_ptr() as *mut c_void),
  203. len,
  204. &mut len,
  205. );
  206. let _ = CloseHandle(tok);
  207. r.context("GetTokenInformation(TokenUser)")?;
  208. let tu = &*(buf.as_ptr() as *const TOKEN_USER);
  209. psid_to_string(tu.User.Sid)
  210. }
  211. }
  212. #[cfg(test)]
  213. mod tests {
  214. use super::*;
  215. #[test]
  216. fn psid_string_round_trip() {
  217. // Well-known Everyone SID.
  218. let p = LocalPsid::from_string("S-1-1-0").expect("from_string");
  219. let s = psid_to_string(p.as_psid()).expect("to_string");
  220. assert_eq!(s, "S-1-1-0");
  221. }
  222. #[test]
  223. fn lookup_builtin_users() {
  224. // BUILTIN\Users exists on every Windows install.
  225. let s = lookup_account_sid("BUILTIN\\Users").expect("lookup");
  226. assert_eq!(s, "S-1-5-32-545");
  227. }
  228. #[test]
  229. fn lookup_missing_account_errors() {
  230. let r = lookup_account_sid("no-such-group-srt-win-test");
  231. assert!(r.is_err());
  232. }
  233. #[test]
  234. fn current_user_sid_is_nonempty() {
  235. let s = current_user_sid().expect("current_user_sid");
  236. assert!(s.starts_with("S-1-"), "got {s}");
  237. }
  238. }