use super::*;
use std::marker::PhantomData;
use std::os::windows::ffi::OsStrExt;
use windows::core::{Owned, PCWSTR};
use windows::Win32::Foundation::{LocalFree, ERROR_NO_TOKEN, HANDLE, HLOCAL, LUID};
use windows::Win32::Security::Authorization::{
BuildTrusteeWithSidW, GetNamedSecurityInfoW, SetEntriesInAclW, SetNamedSecurityInfoW, DENY_ACCESS,
EXPLICIT_ACCESS_W, SE_FILE_OBJECT, TRUSTEE_W,
};
use windows::Win32::Security::{
AdjustTokenPrivileges, DuplicateTokenEx, GetTokenInformation, LookupPrivilegeValueW, SecurityImpersonation,
TokenImpersonation, TokenPrivileges, TokenUser, ACL, DACL_SECURITY_INFORMATION, LUID_AND_ATTRIBUTES,
NO_INHERITANCE, PSECURITY_DESCRIPTOR, PSID, SE_CHANGE_NOTIFY_NAME, SE_PRIVILEGE_REMOVED, TOKEN_ADJUST_PRIVILEGES,
TOKEN_DUPLICATE, TOKEN_IMPERSONATE, TOKEN_PRIVILEGES, TOKEN_QUERY, TOKEN_USER,
};
use windows::Win32::Storage::FileSystem::{FILE_LIST_DIRECTORY, FILE_TRAVERSE};
use windows::Win32::System::Threading::{
GetCurrentProcess, GetCurrentThread, OpenProcessToken, OpenThreadToken, SetThreadToken,
};
fn search_tool(path_var: &OsStr, loadable_only: bool) -> Result<PathBuf, Error> {
resolve(ResolveInput {
program: Path::new("tool"),
cwd: None,
system_dirs: &no_system_dirs,
path_var: Some(path_var),
windows: true,
loadable_only,
normalise: &as_written,
})
}
fn wrapped_raw_os_error(e: &std::io::Error) -> Option<i32> {
std::error::Error::source(e)
.and_then(|s| s.downcast_ref::<std::io::Error>())
.and_then(std::io::Error::raw_os_error)
}
fn open_process_token(access: windows::Win32::Security::TOKEN_ACCESS_MASK) -> windows::core::Result<HANDLE> {
let mut token = HANDLE::default();
unsafe { OpenProcessToken(GetCurrentProcess(), access, &mut token) }?;
Ok(token)
}
mod current_user_sid {
use super::*;
pub(super) struct CurrentUserSid(Vec<u64>);
impl CurrentUserSid {
pub(super) fn query() -> Self {
let raw_token = open_process_token(TOKEN_QUERY).expect("OpenProcessToken(TOKEN_QUERY)");
let token = unsafe { Owned::new(raw_token) };
let mut needed = 0u32;
_ = unsafe { GetTokenInformation(*token, TokenUser, None, 0, &mut needed) };
let mut buf = vec![0u64; (needed as usize).div_ceil(8).max(1)];
unsafe {
GetTokenInformation(
*token,
TokenUser,
Some(buf.as_mut_ptr().cast()),
(buf.len() * 8) as u32,
&mut needed,
)
}
.expect("GetTokenInformation(TokenUser)");
CurrentUserSid(buf)
}
pub(super) fn sid(&self) -> PSID {
assert!(
self.0.len() * std::mem::size_of::<u64>() >= std::mem::size_of::<TOKEN_USER>(),
"CurrentUserSid holds only {} bytes, too few for a TOKEN_USER",
self.0.len() * std::mem::size_of::<u64>()
);
unsafe { (*self.0.as_ptr().cast::<TOKEN_USER>()).User.Sid }
}
}
}
use current_user_sid::CurrentUserSid;
fn panic_or_eprint(msg: String) {
if std::thread::panicking() {
eprintln!("{msg}");
} else {
panic!("{msg}");
}
}
struct ImpersonationGuard(PhantomData<*const ()>);
impl ImpersonationGuard {
fn without_change_notify() -> Self {
Self::assert_not_already_impersonating();
let raw_token = open_process_token(TOKEN_DUPLICATE).expect("OpenProcessToken(TOKEN_DUPLICATE)");
let token = unsafe { Owned::new(raw_token) };
let mut raw_dup = HANDLE::default();
unsafe {
DuplicateTokenEx(
*token,
TOKEN_ADJUST_PRIVILEGES | TOKEN_IMPERSONATE | TOKEN_QUERY,
None,
SecurityImpersonation,
TokenImpersonation,
&mut raw_dup,
)
}
.expect("DuplicateTokenEx");
let dup = unsafe { Owned::new(raw_dup) };
drop(token);
let mut luid = LUID::default();
unsafe { LookupPrivilegeValueW(None, SE_CHANGE_NOTIFY_NAME, &mut luid) }.expect("LookupPrivilegeValueW");
let privileges = TOKEN_PRIVILEGES {
PrivilegeCount: 1,
Privileges: [LUID_AND_ATTRIBUTES {
Luid: luid,
Attributes: SE_PRIVILEGE_REMOVED,
}],
};
unsafe { AdjustTokenPrivileges(*dup, false, Some(&privileges), 0, None, None) }
.expect("AdjustTokenPrivileges(SE_CHANGE_NOTIFY_NAME, SE_PRIVILEGE_REMOVED)");
assert!(
!token_has_privilege(*dup, luid),
"AdjustTokenPrivileges(SE_PRIVILEGE_REMOVED) reported success, but \
SeChangeNotifyPrivilege is still present on the duplicate token"
);
let guard = unsafe { SetThreadToken(None, Some(*dup)) }.map(|()| ImpersonationGuard(PhantomData));
drop(dup);
guard.expect("SetThreadToken")
}
fn assert_not_already_impersonating() {
let mut existing = HANDLE::default();
match unsafe { OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, false, &mut existing) } {
Err(e) if e.code() == windows::core::HRESULT::from_win32(ERROR_NO_TOKEN.0) => {} Err(e) => panic!("OpenThreadToken: unexpected error probing for prior impersonation: {e}"),
Ok(()) => {
let _existing = unsafe { Owned::new(existing) };
panic!(
"this thread is already impersonating — ImpersonationGuard::drop only knows \
how to revert to NO impersonation, so nesting would discard the caller's own"
);
}
}
}
}
impl Drop for ImpersonationGuard {
fn drop(&mut self) {
if let Err(e) = unsafe { SetThreadToken(None, None) } {
panic_or_eprint(format!("could not revert thread impersonation: {e}"));
}
}
}
fn token_has_privilege(token: HANDLE, luid: LUID) -> bool {
let mut needed = 0u32;
_ = unsafe { GetTokenInformation(token, TokenPrivileges, None, 0, &mut needed) };
let mut buf = vec![0u32; (needed as usize).div_ceil(4).max(1)];
unsafe {
GetTokenInformation(
token,
TokenPrivileges,
Some(buf.as_mut_ptr().cast()),
(buf.len() * 4) as u32,
&mut needed,
)
}
.expect("GetTokenInformation(TokenPrivileges)");
let count = unsafe { *buf.as_ptr().cast::<u32>() } as usize;
assert!(
std::mem::size_of::<u32>() + count * std::mem::size_of::<LUID_AND_ATTRIBUTES>()
<= buf.len() * std::mem::size_of::<u32>(),
"GetTokenInformation(TokenPrivileges) reported PrivilegeCount {count} that does not fit \
in the {}-byte buffer actually allocated",
buf.len() * std::mem::size_of::<u32>()
);
let privileges = unsafe { std::slice::from_raw_parts(buf.as_ptr().add(1).cast::<LUID_AND_ATTRIBUTES>(), count) };
privileges.iter().any(|p| p.Luid == luid)
}
struct DenyAclGuard {
path: PathBuf,
wide: Vec<u16>,
#[allow(dead_code, reason = "never read after construction; kept alive purely for its Drop")]
original_sd: Owned<HLOCAL>,
original_dacl: *mut ACL,
}
impl DenyAclGuard {
fn deny_traversal_and_listing(dir: &Path) -> Self {
let path = dir.to_path_buf();
let wide: Vec<u16> = dir.as_os_str().encode_wide().chain(std::iter::once(0)).collect();
let mut original_dacl: *mut ACL = std::ptr::null_mut();
let mut raw_sd = PSECURITY_DESCRIPTOR::default();
unsafe {
GetNamedSecurityInfoW(
PCWSTR(wide.as_ptr()),
SE_FILE_OBJECT,
DACL_SECURITY_INFORMATION,
None,
None,
Some(&mut original_dacl),
None,
&mut raw_sd,
)
}
.ok()
.expect("GetNamedSecurityInfoW");
let original_sd = unsafe { Owned::new(HLOCAL(raw_sd.0)) };
let current_sid = CurrentUserSid::query();
let sid = current_sid.sid();
let mut trustee = TRUSTEE_W::default();
unsafe { BuildTrusteeWithSidW(&mut trustee, Some(sid)) };
let entry = EXPLICIT_ACCESS_W {
grfAccessPermissions: FILE_TRAVERSE.0 | FILE_LIST_DIRECTORY.0,
grfAccessMode: DENY_ACCESS,
grfInheritance: NO_INHERITANCE,
Trustee: trustee,
};
let mut new_dacl: *mut ACL = std::ptr::null_mut();
let entries_set = unsafe { SetEntriesInAclW(Some(&[entry]), Some(original_dacl.cast_const()), &mut new_dacl) };
entries_set.ok().expect("SetEntriesInAclW");
let set = unsafe {
SetNamedSecurityInfoW(
PCWSTR(wide.as_ptr()),
SE_FILE_OBJECT,
DACL_SECURITY_INFORMATION,
None,
None,
Some(new_dacl.cast_const()),
None,
)
};
unsafe { LocalFree(Some(HLOCAL(new_dacl.cast()))) };
let guard = DenyAclGuard {
path,
wide,
original_sd,
original_dacl,
};
set.ok().expect("SetNamedSecurityInfoW");
guard
}
}
impl Drop for DenyAclGuard {
fn drop(&mut self) {
let restored = unsafe {
SetNamedSecurityInfoW(
PCWSTR(self.wide.as_ptr()),
SE_FILE_OBJECT,
DACL_SECURITY_INFORMATION,
None,
None,
Some(self.original_dacl.cast_const()),
None,
)
};
if let Err(e) = restored.ok() {
panic_or_eprint(format!(
"could not restore the original ACL on {:?}: {e} — it may be left locked in %TEMP%",
self.path
));
}
}
}
struct LockedThenOpen {
impersonation: Option<ImpersonationGuard>,
guard: Option<DenyAclGuard>,
root: Option<tempfile::TempDir>,
open: PathBuf,
path: std::ffi::OsString,
}
impl Drop for LockedThenOpen {
fn drop(&mut self) {
drop(self.impersonation.take());
drop(self.guard.take());
if let Some(root) = self.root.take() {
if let Err(e) = root.close() {
panic_or_eprint(format!("could not remove the tempdir: {e}"));
}
}
}
}
fn locked_then_open() -> LockedThenOpen {
let root = tempfile::tempdir().unwrap();
let locked = root.path().join("locked");
let open = root.path().join("open");
std::fs::create_dir(&locked).unwrap();
std::fs::create_dir(&open).unwrap();
std::fs::write(open.join("tool.exe"), b"x").unwrap();
let locked_tool = locked.join("tool.exe");
std::fs::write(&locked_tool, b"x").unwrap();
let path = std::env::join_paths([&locked, &open]).unwrap();
let guard = DenyAclGuard::deny_traversal_and_listing(&locked);
let impersonation = ImpersonationGuard::without_change_notify();
let probe = std::fs::metadata(&locked_tool).unwrap_err();
assert_eq!(probe.raw_os_error(), Some(5), "precondition: {probe}");
LockedThenOpen {
impersonation: Some(impersonation),
guard: Some(guard),
root: Some(root),
open,
path,
}
}
#[skuld::test]
fn an_undeterminable_windows_acl_fails_a_loadable_only_search_closed() {
let fixture = locked_then_open();
match search_tool(&fixture.path, true) {
Err(Error::Io(e)) => {
assert_eq!(e.kind(), std::io::ErrorKind::PermissionDenied, "{e}");
assert_eq!(wrapped_raw_os_error(&e), Some(5), "{e}");
}
other => panic!("a loadable_only search must not skip an undeterminable candidate: {other:?}"),
}
}
#[skuld::test]
fn an_undeterminable_windows_acl_is_skipped_by_an_ordinary_search() {
let fixture = locked_then_open();
assert_eq!(
search_tool(&fixture.path, false).unwrap(),
fixture.open.join("tool.exe")
);
}