#![deny(clippy::undocumented_unsafe_blocks)]
#![allow(clippy::unwrap_used, clippy::expect_used)]
use std::fs::OpenOptions;
use std::io;
use std::mem::MaybeUninit;
use std::mem::offset_of;
use std::mem::size_of;
use std::os::windows::fs::OpenOptionsExt;
use std::os::windows::io::AsRawHandle;
use std::path::Path;
use std::ptr::NonNull;
use std::ptr::null_mut;
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
use windows_sys::Win32::Foundation::LocalFree;
use windows_sys::Win32::Security::ACCESS_ALLOWED_ACE;
use windows_sys::Win32::Security::ACE_HEADER;
use windows_sys::Win32::Security::ACL;
use windows_sys::Win32::Security::ACL_REVISION;
use windows_sys::Win32::Security::ACL_SIZE_INFORMATION;
use windows_sys::Win32::Security::AclSizeInformation;
use windows_sys::Win32::Security::AddAccessAllowedAceEx;
use windows_sys::Win32::Security::Authorization::ConvertSecurityDescriptorToStringSecurityDescriptorW;
use windows_sys::Win32::Security::Authorization::ConvertSidToStringSidW;
use windows_sys::Win32::Security::Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW;
use windows_sys::Win32::Security::Authorization::ConvertStringSidToSidW;
use windows_sys::Win32::Security::Authorization::GetSecurityInfo;
use windows_sys::Win32::Security::Authorization::SDDL_REVISION_1;
use windows_sys::Win32::Security::Authorization::SE_FILE_OBJECT;
use windows_sys::Win32::Security::Authorization::SetNamedSecurityInfoW;
use windows_sys::Win32::Security::DACL_SECURITY_INFORMATION;
use windows_sys::Win32::Security::GetAce;
use windows_sys::Win32::Security::GetAclInformation;
use windows_sys::Win32::Security::GetSecurityDescriptorControl;
use windows_sys::Win32::Security::GetSecurityDescriptorDacl;
use windows_sys::Win32::Security::ImpersonateSelf;
use windows_sys::Win32::Security::InitializeAcl;
use windows_sys::Win32::Security::PROTECTED_DACL_SECURITY_INFORMATION;
use windows_sys::Win32::Security::PSECURITY_DESCRIPTOR;
use windows_sys::Win32::Security::RevertToSelf;
use windows_sys::Win32::Security::SE_DACL_AUTO_INHERITED;
use windows_sys::Win32::Security::SE_DACL_PROTECTED;
use windows_sys::Win32::Security::SecurityImpersonation;
use windows_sys::Win32::Security::UNPROTECTED_DACL_SECURITY_INFORMATION;
use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS;
use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT;
use super::nt::security::EffectiveToken;
use super::nt::security::TokenUser;
use super::nt::win32;
const ACCESS_ALLOWED_ACE_TYPE: u8 = 0;
const READ_CONTROL: u32 = 0x0002_0000;
pub(crate) const FILE_ALL_ACCESS: u32 = 0x001F_01FF;
const OBJECT_INHERIT_ACE: u8 = 0x01;
const CONTAINER_INHERIT_ACE: u8 = 0x02;
pub(crate) const OICI: u8 = OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE;
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Ace {
pub(crate) allows: bool,
pub(crate) flags: u8,
pub(crate) mask: u32,
pub(crate) sid: String,
}
impl Ace {
pub(crate) const fn inherited(&self) -> bool {
self.flags & 0x10 != 0
}
pub(crate) const fn inheritable(&self) -> bool {
self.flags & (OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE) != 0
}
}
#[derive(Debug)]
pub(crate) struct Dacl {
pub(crate) protected: bool,
pub(crate) auto_inherited: bool,
pub(crate) null: bool,
pub(crate) aces: Vec<Ace>,
}
impl Dacl {
pub(crate) fn same_as(&self, other: &Self) -> bool {
self.protected == other.protected
&& self.auto_inherited == other.auto_inherited
&& self.null == other.null
&& self.aces == other.aces
}
}
pub(crate) struct Impersonation;
impl Impersonation {
pub(crate) fn start() -> Self {
let ok = unsafe { ImpersonateSelf(SecurityImpersonation) };
assert_ne!(ok, 0, "ImpersonateSelf failed");
Self
}
}
impl Drop for Impersonation {
fn drop(&mut self) {
unsafe { RevertToSelf() };
}
}
pub(crate) fn current_user() -> String {
sid_string_of(&EffectiveToken::open().unwrap().user().unwrap())
}
pub(in crate::formats) fn sid_string_of(user: &TokenUser) -> String {
unsafe { sid_to_string(user.sid()) }.unwrap()
}
unsafe fn sid_to_string(sid: *mut std::ffi::c_void) -> io::Result<String> {
let mut slot = MaybeUninit::<*mut u16>::uninit();
win32(unsafe { ConvertSidToStringSidW(sid, slot.as_mut_ptr()) })?;
let text = NonNull::new(unsafe { slot.assume_init() })
.ok_or_else(|| io::Error::from(io::ErrorKind::InvalidData))?;
let parsed = String::from_utf16(&wide_text(text.as_ptr()))
.map_err(|_| io::Error::from(io::ErrorKind::InvalidData));
unsafe { LocalFree(text.as_ptr().cast()) };
parsed
}
fn wide_text(text: *const u16) -> Vec<u16> {
unsafe {
let mut len = 0;
while *text.add(len) != 0 {
len += 1;
}
std::slice::from_raw_parts(text, len).to_vec()
}
}
pub(crate) fn read(path: &Path) -> Dacl {
read_with(path, FILE_FLAG_BACKUP_SEMANTICS)
}
pub(crate) fn read_itself(path: &Path) -> Dacl {
read_with(
path,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
)
}
fn read_with(path: &Path, flags: u32) -> Dacl {
let file = OpenOptions::new()
.access_mode(READ_CONTROL)
.custom_flags(flags)
.open(path)
.unwrap();
let mut acl: *mut ACL = null_mut();
let mut descriptor: PSECURITY_DESCRIPTOR = null_mut();
let code = unsafe {
GetSecurityInfo(
file.as_raw_handle(),
SE_FILE_OBJECT,
DACL_SECURITY_INFORMATION,
null_mut(),
null_mut(),
&raw mut acl,
null_mut(),
&raw mut descriptor,
)
};
assert_eq!(code, ERROR_SUCCESS, "GetSecurityInfo failed");
let control = control(descriptor);
let dacl = Dacl {
protected: control & SE_DACL_PROTECTED != 0,
auto_inherited: control & SE_DACL_AUTO_INHERITED != 0,
null: acl.is_null(),
aces: entries(acl).unwrap(),
};
unsafe { LocalFree(descriptor) };
dacl
}
pub(crate) fn restrict_to_current_user_without_inheritance(path: &Path) {
use std::os::windows::ffi::OsStrExt;
let mut sid = MaybeUninit::<*mut std::ffi::c_void>::uninit();
let text: Vec<u16> = current_user()
.encode_utf16()
.chain(std::iter::once(0))
.collect();
let ok = unsafe { ConvertStringSidToSidW(text.as_ptr(), sid.as_mut_ptr()) };
assert_ne!(ok, 0, "ConvertStringSidToSidW failed");
let sid = unsafe { sid.assume_init() };
let mut acl = [0_u32; 32];
let ok = unsafe {
InitializeAcl(
acl.as_mut_ptr().cast(),
u32::try_from(size_of_val(&acl)).unwrap(),
ACL_REVISION,
)
};
assert_ne!(ok, 0, "InitializeAcl failed");
let ok = unsafe {
AddAccessAllowedAceEx(
acl.as_mut_ptr().cast(),
ACL_REVISION,
0,
FILE_ALL_ACCESS,
sid,
)
};
assert_ne!(ok, 0, "AddAccessAllowedAceEx failed");
let name: Vec<u16> = path
.as_os_str()
.encode_wide()
.chain(std::iter::once(0))
.collect();
let code = unsafe {
SetNamedSecurityInfoW(
name.as_ptr(),
SE_FILE_OBJECT,
DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
null_mut(),
null_mut(),
acl.as_ptr().cast(),
std::ptr::null(),
)
};
unsafe { LocalFree(sid) };
assert_eq!(code, ERROR_SUCCESS, "SetNamedSecurityInfoW failed");
let dacl = read(path);
assert!(
dacl.aces.iter().all(|ace| !ace.inheritable()),
"the fixture parent still has inheritable entries: {:?}",
dacl.aces
);
}
pub(crate) fn set_dacl_from_sddl(path: &Path, sddl: &str) {
use std::os::windows::ffi::OsStrExt;
let descriptor = parse_sddl(sddl);
let mut present = 0;
let mut defaulted = 0;
let mut acl: *mut ACL = null_mut();
let ok = unsafe {
GetSecurityDescriptorDacl(
descriptor,
&raw mut present,
&raw mut acl,
&raw mut defaulted,
)
};
assert_ne!(ok, 0, "GetSecurityDescriptorDacl failed");
let protection = if control(descriptor) & SE_DACL_PROTECTED == 0 {
UNPROTECTED_DACL_SECURITY_INFORMATION
} else {
PROTECTED_DACL_SECURITY_INFORMATION
};
let name: Vec<u16> = path
.as_os_str()
.encode_wide()
.chain(std::iter::once(0))
.collect();
let code = unsafe {
SetNamedSecurityInfoW(
name.as_ptr(),
SE_FILE_OBJECT,
DACL_SECURITY_INFORMATION | protection,
null_mut(),
null_mut(),
acl,
std::ptr::null(),
)
};
unsafe { LocalFree(descriptor) };
assert_eq!(code, ERROR_SUCCESS, "SetNamedSecurityInfoW failed");
}
fn parse_sddl(sddl: &str) -> PSECURITY_DESCRIPTOR {
let text: Vec<u16> = sddl.encode_utf16().chain(std::iter::once(0)).collect();
let mut descriptor: PSECURITY_DESCRIPTOR = null_mut();
let ok = unsafe {
ConvertStringSecurityDescriptorToSecurityDescriptorW(
text.as_ptr(),
SDDL_REVISION_1,
&raw mut descriptor,
null_mut(),
)
};
assert_ne!(ok, 0, "the SDDL string {sddl} does not parse");
descriptor
}
pub(crate) fn dacl_sddl_of(descriptor: *const std::ffi::c_void) -> String {
let mut text: *mut u16 = null_mut();
let ok = unsafe {
ConvertSecurityDescriptorToStringSecurityDescriptorW(
descriptor.cast_mut(),
SDDL_REVISION_1,
DACL_SECURITY_INFORMATION,
&raw mut text,
null_mut(),
)
};
assert_ne!(
ok, 0,
"ConvertSecurityDescriptorToStringSecurityDescriptorW failed"
);
let sddl = String::from_utf16(&wide_text(text)).unwrap();
unsafe { LocalFree(text.cast()) };
sddl
}
pub(crate) fn normalized_sddl(sddl: &str) -> String {
let descriptor = parse_sddl(sddl);
let normalized = dacl_sddl_of(descriptor);
unsafe { LocalFree(descriptor) };
normalized
}
fn control(descriptor: PSECURITY_DESCRIPTOR) -> u16 {
let mut control = 0_u16;
let mut revision = 0_u32;
let ok =
unsafe { GetSecurityDescriptorControl(descriptor, &raw mut control, &raw mut revision) };
assert_ne!(ok, 0, "GetSecurityDescriptorControl failed");
control
}
fn entries(acl: *const ACL) -> io::Result<Vec<Ace>> {
if acl.is_null() {
return Ok(Vec::new());
}
let mut size = ACL_SIZE_INFORMATION::default();
let ok = unsafe {
GetAclInformation(
acl,
(&raw mut size).cast(),
u32::try_from(size_of::<ACL_SIZE_INFORMATION>()).unwrap(),
AclSizeInformation,
)
};
win32(ok)?;
(0..size.AceCount).map(|index| entry(acl, index)).collect()
}
fn entry(acl: *const ACL, index: u32) -> io::Result<Ace> {
let mut slot = MaybeUninit::uninit();
win32(unsafe { GetAce(acl, index, slot.as_mut_ptr()) })?;
let ace = NonNull::new(unsafe { slot.assume_init() })
.ok_or_else(|| io::Error::from(io::ErrorKind::InvalidData))?;
let header = unsafe { ace.as_ptr().cast::<ACE_HEADER>().read_unaligned() };
let allows = header.AceType == ACCESS_ALLOWED_ACE_TYPE;
Ok(Ace {
allows,
flags: header.AceFlags,
mask: if allows {
unsafe {
ace.as_ptr()
.cast::<u8>()
.add(offset_of!(ACCESS_ALLOWED_ACE, Mask))
.cast::<u32>()
.read_unaligned()
}
} else {
0
},
sid: if allows {
let sid = unsafe {
ace.as_ptr()
.cast::<u8>()
.add(offset_of!(ACCESS_ALLOWED_ACE, SidStart))
};
unsafe { sid_to_string(sid.cast())? }
} else {
String::new()
},
})
}