util.rs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. //! Small Win32 helpers shared across the crate.
  2. use std::ffi::c_void;
  3. use windows::Win32::Foundation::{CloseHandle, HANDLE, HLOCAL, LocalFree};
  4. use windows::core::{PCWSTR, PWSTR};
  5. /// Owns a kernel `HANDLE`; `CloseHandle` on drop. For tokens, file
  6. /// handles, process handles — anything whose only cleanup is
  7. /// `CloseHandle`. `into_raw()` disarms the guard and returns the
  8. /// handle for callers that need to pass ownership upward.
  9. #[derive(Debug)]
  10. pub struct OwnedHandle(pub HANDLE);
  11. impl OwnedHandle {
  12. pub fn raw(&self) -> HANDLE {
  13. self.0
  14. }
  15. /// Disarm the guard and return the raw handle (caller takes
  16. /// ownership and is responsible for closing it).
  17. pub fn into_raw(self) -> HANDLE {
  18. let h = self.0;
  19. std::mem::forget(self);
  20. h
  21. }
  22. }
  23. impl Drop for OwnedHandle {
  24. fn drop(&mut self) {
  25. if !self.0.is_invalid() {
  26. unsafe {
  27. let _ = CloseHandle(self.0);
  28. }
  29. }
  30. }
  31. }
  32. /// UTF-8 → NUL-terminated UTF-16 buffer. Keep the returned `Vec`
  33. /// alive for as long as the resulting `PCWSTR` / `PWSTR` is in use.
  34. pub fn wstr(s: &str) -> Vec<u16> {
  35. s.encode_utf16().chain(std::iter::once(0)).collect()
  36. }
  37. /// Overwrite `buf` with zeros using volatile writes so LLVM
  38. /// dead-store elimination can't remove the scrub in release. For
  39. /// clearing UTF-16 password buffers after `LogonUserW` /
  40. /// `CreateProcessWithLogonW` has consumed them.
  41. pub fn scrub_wstr(buf: &mut [u16]) {
  42. for c in buf.iter_mut() {
  43. // SAFETY: `c` is a valid, aligned, exclusive `&mut u16`.
  44. unsafe { core::ptr::write_volatile(c, 0) };
  45. }
  46. }
  47. /// Encode `s` as a COUNTED (not NUL-terminated) UTF-16 buffer plus
  48. /// its length in BYTES — the shape `UNICODE_STRING` /
  49. /// `LSA_UNICODE_STRING` want in `Length`/`MaximumLength`. Callers
  50. /// build their (structurally identical, module-distinct) struct from
  51. /// the pair; the buffer must outlive it.
  52. pub fn counted_utf16(s: &str) -> (Vec<u16>, u16) {
  53. let buf: Vec<u16> = s.encode_utf16().collect();
  54. let bytes = (buf.len() * 2) as u16;
  55. (buf, bytes)
  56. }
  57. /// Borrow a `Vec<u16>` from `wstr` as a `PCWSTR`.
  58. pub fn pcwstr(buf: &[u16]) -> PCWSTR {
  59. PCWSTR(buf.as_ptr())
  60. }
  61. /// Read a NUL-terminated `PWSTR` (typically returned by a Win32 API
  62. /// that allocates) into an owned `String`. Caller still owns the
  63. /// underlying allocation.
  64. pub fn from_pwstr(p: PWSTR) -> String {
  65. if p.is_null() {
  66. return String::new();
  67. }
  68. let mut len = 0usize;
  69. unsafe {
  70. while *p.0.add(len) != 0 {
  71. len += 1;
  72. }
  73. }
  74. let slice = unsafe { std::slice::from_raw_parts(p.0, len) };
  75. String::from_utf16_lossy(slice)
  76. }
  77. /// `LocalFree` a pointer returned by a Win32 API documented to require
  78. /// it (e.g. `ConvertSidToStringSidW`,
  79. /// `ConvertStringSecurityDescriptorToSecurityDescriptorW`).
  80. pub fn local_free(p: *mut c_void) {
  81. unsafe {
  82. let _ = LocalFree(Some(HLOCAL(p)));
  83. }
  84. }
  85. use anyhow::{Result, anyhow, bail};
  86. use windows::Win32::Foundation::WIN32_ERROR;
  87. /// `Ok(())` if `r` is `ERROR_SUCCESS`, else `bail!("{label}:
  88. /// WIN32_ERROR=0x…")`. For Win32 APIs that return a bare
  89. /// `WIN32_ERROR` rather than a `windows::core::Result` (e.g.
  90. /// `Get`/`SetNamedSecurityInfoW`).
  91. pub(crate) fn win32_ok(r: WIN32_ERROR, label: &str) -> Result<()> {
  92. if r.is_err() {
  93. bail!("{label}: WIN32_ERROR=0x{:08x}", r.0)
  94. }
  95. Ok(())
  96. }
  97. use windows::Win32::System::Registry::{
  98. HKEY, KEY_SET_VALUE, REG_OPTION_NON_VOLATILE, REG_VALUE_TYPE, RegCloseKey, RegCreateKeyExW,
  99. RegSetValueExW,
  100. };
  101. /// `RegCreateKeyExW(root, subkey, KEY_SET_VALUE)` →
  102. /// `RegSetValueExW(value_name, ty, data)` → `RegCloseKey`. Creates
  103. /// intermediate subkeys. The single registry-write helper for
  104. /// `cert_store::install_root_ca` (`HKEY_USERS`, `REG_BINARY`) and
  105. /// `user::set_logon_ui_hidden` (`HKEY_LOCAL_MACHINE`, `REG_DWORD`).
  106. pub fn reg_set_value(
  107. root: HKEY,
  108. subkey: &str,
  109. value_name: &str,
  110. ty: REG_VALUE_TYPE,
  111. data: &[u8],
  112. ) -> Result<()> {
  113. let sub_w = wstr(subkey);
  114. let val_w = wstr(value_name);
  115. let mut hkey = HKEY::default();
  116. let r = unsafe {
  117. RegCreateKeyExW(
  118. root,
  119. pcwstr(&sub_w),
  120. None,
  121. PCWSTR::null(),
  122. REG_OPTION_NON_VOLATILE,
  123. KEY_SET_VALUE,
  124. None,
  125. &mut hkey,
  126. None,
  127. )
  128. };
  129. if r.is_err() {
  130. return Err(anyhow!("RegCreateKeyExW({subkey}): {r:?}"));
  131. }
  132. let r = unsafe { RegSetValueExW(hkey, pcwstr(&val_w), None, ty, Some(data)) };
  133. unsafe {
  134. let _ = RegCloseKey(hkey);
  135. }
  136. if r.is_err() {
  137. return Err(anyhow!("RegSetValueExW({subkey}\\{value_name}): {r:?}"));
  138. }
  139. Ok(())
  140. }
  141. use windows::Win32::Security::Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW;
  142. use windows::Win32::Security::{GetSecurityDescriptorLength, PSECURITY_DESCRIPTOR};
  143. const SDDL_REVISION_1: u32 = 1;
  144. /// Heap-allocated security descriptor owned by us; `LocalFree` on
  145. /// drop. Built from an SDDL string via [`OwnedSd::from_sddl`].
  146. /// Fields are `pub(crate)` so callers that need the byte view
  147. /// (e.g. `wfp.rs`'s `FWP_BYTE_BLOB` provider data) can read them
  148. /// without pulling subsystem-specific types into util.
  149. pub struct OwnedSd {
  150. pub(crate) ptr: PSECURITY_DESCRIPTOR,
  151. pub(crate) len: u32,
  152. }
  153. impl OwnedSd {
  154. pub fn from_sddl(sddl: &str) -> Result<Self> {
  155. let w = wstr(sddl);
  156. let mut psd = PSECURITY_DESCRIPTOR::default();
  157. let mut sz: u32 = 0;
  158. unsafe {
  159. ConvertStringSecurityDescriptorToSecurityDescriptorW(
  160. pcwstr(&w),
  161. SDDL_REVISION_1,
  162. &mut psd,
  163. Some(&mut sz),
  164. )
  165. .map_err(|e| {
  166. anyhow!("ConvertStringSecurityDescriptorToSecurityDescriptorW({sddl}): {e}")
  167. })?;
  168. if sz == 0 {
  169. sz = GetSecurityDescriptorLength(psd);
  170. }
  171. }
  172. Ok(Self { ptr: psd, len: sz })
  173. }
  174. /// Take ownership of a `PSECURITY_DESCRIPTOR` returned by a Win32
  175. /// API documented to require `LocalFree` (e.g.
  176. /// `GetNamedSecurityInfoW`). `len` is queried for completeness;
  177. /// callers that only need the free-on-drop guard can ignore it.
  178. pub fn from_raw(psd: PSECURITY_DESCRIPTOR) -> Self {
  179. let len = if psd.0.is_null() {
  180. 0
  181. } else {
  182. unsafe { GetSecurityDescriptorLength(psd) }
  183. };
  184. Self { ptr: psd, len }
  185. }
  186. }
  187. impl Drop for OwnedSd {
  188. fn drop(&mut self) {
  189. if !self.ptr.0.is_null() {
  190. local_free(self.ptr.0);
  191. }
  192. }
  193. }
  194. /// Enable a named privilege (e.g. `SeRestorePrivilege`) in the
  195. /// current process token. Returns `Ok(true)` when the privilege is
  196. /// now enabled, `Ok(false)` when the token does not hold it at all
  197. /// (`ERROR_NOT_ALL_ASSIGNED` — e.g. a non-elevated caller); errors
  198. /// only on API failure. Enabling is process-wide and deliberately
  199. /// not reverted: the callers (install-time ambient stamping) are
  200. /// short-lived CLI invocations.
  201. pub fn enable_privilege(name: &str) -> anyhow::Result<bool> {
  202. use anyhow::Context;
  203. use windows::Win32::Foundation::{ERROR_NOT_ALL_ASSIGNED, GetLastError, LUID};
  204. use windows::Win32::Security::{
  205. AdjustTokenPrivileges, LUID_AND_ATTRIBUTES, LookupPrivilegeValueW, SE_PRIVILEGE_ENABLED,
  206. TOKEN_ADJUST_PRIVILEGES, TOKEN_PRIVILEGES, TOKEN_QUERY,
  207. };
  208. use windows::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
  209. let mut luid = LUID::default();
  210. let w = wstr(name);
  211. unsafe { LookupPrivilegeValueW(PCWSTR::null(), pcwstr(&w), &mut luid) }
  212. .with_context(|| format!("LookupPrivilegeValue('{name}')"))?;
  213. let mut tok = HANDLE::default();
  214. unsafe {
  215. OpenProcessToken(
  216. GetCurrentProcess(),
  217. TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
  218. &mut tok,
  219. )
  220. }
  221. .context("OpenProcessToken(ADJUST_PRIVILEGES)")?;
  222. let tp = TOKEN_PRIVILEGES {
  223. PrivilegeCount: 1,
  224. Privileges: [LUID_AND_ATTRIBUTES {
  225. Luid: luid,
  226. Attributes: SE_PRIVILEGE_ENABLED,
  227. }],
  228. };
  229. let adjusted = unsafe { AdjustTokenPrivileges(tok, false, Some(&tp), 0, None, None) }
  230. .with_context(|| format!("AdjustTokenPrivileges('{name}')"));
  231. // Success return with ERROR_NOT_ALL_ASSIGNED means the token
  232. // doesn't hold the privilege. Read it before CloseHandle can
  233. // clobber the thread's last-error.
  234. let assigned = unsafe { GetLastError() } != ERROR_NOT_ALL_ASSIGNED;
  235. unsafe {
  236. let _ = CloseHandle(tok);
  237. }
  238. adjusted?;
  239. Ok(assigned)
  240. }