#![allow(unsafe_code)]
mod acl;
use std::ffi::c_void;
use std::io;
use std::marker::PhantomData;
use std::mem::size_of;
use std::os::windows::io::{AsHandle, AsRawHandle, OwnedHandle, RawHandle};
use std::path::Path;
use std::ptr::{self, NonNull};
use std::sync::{Mutex, MutexGuard, PoisonError};
use windows_sys::Win32::Foundation::{
LocalFree, SetLastError, ERROR_INSUFFICIENT_BUFFER, ERROR_NOT_ALL_ASSIGNED, ERROR_SUCCESS, LUID,
};
use windows_sys::Win32::Security::Authorization::{
ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW,
GetNamedSecurityInfoW, GetSecurityInfo, TreeSetNamedSecurityInfoW, SDDL_REVISION_1,
SE_FILE_OBJECT, SE_KERNEL_OBJECT, TREE_SEC_INFO_RESET,
};
use windows_sys::Win32::Security::{
AdjustTokenPrivileges, CheckTokenMembership, GetSecurityDescriptorControl,
GetSecurityDescriptorDacl, GetSecurityDescriptorLength, GetSecurityDescriptorOwner,
GetTokenInformation, LookupPrivilegeValueW, TokenUser, DACL_SECURITY_INFORMATION,
LUID_AND_ATTRIBUTES, OWNER_SECURITY_INFORMATION, PROTECTED_DACL_SECURITY_INFORMATION,
PSECURITY_DESCRIPTOR, SECURITY_ATTRIBUTES, SE_PRIVILEGE_ENABLED, TOKEN_ADJUST_PRIVILEGES,
TOKEN_PRIVILEGES, TOKEN_QUERY, TOKEN_USER,
};
use windows_sys::Win32::System::Threading::OpenProcessToken;
pub use acl::{
AclValidationError, AllowedAce, OwnedSid, SecurityAclError, ValidatedDacl, ValidatedSid,
};
use crate::bounded_read::{probe_word_aligned, CallOutcome};
use crate::handle::{current_process, owned_from_creation};
use crate::wide::{bounded_units, wide_null};
const MAX_TOKEN_INFORMATION_BYTES: usize = 64 * 1024;
const MAX_SID_STRING_UNITS: usize = 32_768;
#[derive(Debug)]
pub struct SecurityDescriptor(NonNull<c_void>);
unsafe impl Send for SecurityDescriptor {}
unsafe impl Sync for SecurityDescriptor {}
impl SecurityDescriptor {
pub fn from_sddl(sddl: &str) -> io::Result<Self> {
let sddl = wide_null(sddl)?;
let mut descriptor = ptr::null_mut();
let converted = unsafe {
ConvertStringSecurityDescriptorToSecurityDescriptorW(
sddl.as_ptr(),
SDDL_REVISION_1,
&mut descriptor,
ptr::null_mut(),
)
};
if converted == 0 || descriptor.is_null() {
return Err(io::Error::last_os_error());
}
Ok(Self(
NonNull::new(descriptor).expect("checked non-null descriptor"),
))
}
pub(crate) fn attributes(&self, inherit_handle: bool) -> SecurityAttributes<'_> {
SecurityAttributes {
raw: SECURITY_ATTRIBUTES {
nLength: size_of::<SECURITY_ATTRIBUTES>() as u32,
lpSecurityDescriptor: self.0.as_ptr(),
bInheritHandle: i32::from(inherit_handle),
},
_descriptor: PhantomData,
}
}
pub fn apply_to_tree(&self, path: &Path, protect: bool) -> io::Result<()> {
let mut present = 0;
let mut defaulted = 0;
let mut dacl = ptr::null_mut();
let read = unsafe {
GetSecurityDescriptorDacl(self.0.as_ptr(), &mut present, &mut dacl, &mut defaulted)
};
if read == 0 {
return Err(io::Error::last_os_error());
}
if present == 0 || dacl.is_null() {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"the descriptor has no DACL to apply",
));
}
let information = if protect {
DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION
} else {
DACL_SECURITY_INFORMATION
};
let wide = wide_null(path)?;
let status = unsafe {
TreeSetNamedSecurityInfoW(
wide.as_ptr(),
SE_FILE_OBJECT,
information,
ptr::null_mut(),
ptr::null_mut(),
dacl,
ptr::null_mut(),
TREE_SEC_INFO_RESET,
None,
0,
ptr::null(),
)
};
if status != ERROR_SUCCESS {
return Err(io::Error::from_raw_os_error(status as i32));
}
Ok(())
}
}
impl Drop for SecurityDescriptor {
fn drop(&mut self) {
unsafe { LocalFree(self.0.as_ptr()) };
}
}
pub(crate) struct SecurityAttributes<'a> {
raw: SECURITY_ATTRIBUTES,
_descriptor: PhantomData<&'a SecurityDescriptor>,
}
impl SecurityAttributes<'_> {
pub(crate) fn as_ptr(&self) -> *const SECURITY_ATTRIBUTES {
&self.raw
}
}
#[derive(Debug)]
pub struct ObjectSecurityDescriptor(NonNull<c_void>);
unsafe impl Send for ObjectSecurityDescriptor {}
unsafe impl Sync for ObjectSecurityDescriptor {}
impl ObjectSecurityDescriptor {
pub fn query_file(path: &Path) -> io::Result<Self> {
let wide = wide_null(path)?;
let mut descriptor = ptr::null_mut();
let status = unsafe {
GetNamedSecurityInfoW(
wide.as_ptr(),
SE_FILE_OBJECT,
DACL_SECURITY_INFORMATION,
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
&mut descriptor,
)
};
Self::from_query_result(status, descriptor)
}
pub fn query_kernel_object(handle: &impl AsHandle) -> io::Result<Self> {
let raw = handle.as_handle().as_raw_handle();
let mut descriptor = ptr::null_mut();
let status = unsafe {
GetSecurityInfo(
raw,
SE_KERNEL_OBJECT,
OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
&mut descriptor,
)
};
Self::from_query_result(status, descriptor)
}
fn from_query_result(status: u32, descriptor: PSECURITY_DESCRIPTOR) -> io::Result<Self> {
if status != ERROR_SUCCESS || descriptor.is_null() {
if !descriptor.is_null() {
unsafe { LocalFree(descriptor) };
}
let status = if status == ERROR_SUCCESS {
io::Error::new(io::ErrorKind::InvalidData, "Windows returned no descriptor")
} else {
io::Error::from_raw_os_error(status as i32)
};
return Err(status);
}
Ok(Self(
NonNull::new(descriptor).expect("checked non-null descriptor"),
))
}
pub fn control(&self) -> io::Result<u16> {
let mut control = 0_u16;
let mut revision = 0_u32;
let read =
unsafe { GetSecurityDescriptorControl(self.0.as_ptr(), &mut control, &mut revision) };
if read == 0 {
return Err(io::Error::last_os_error());
}
Ok(control)
}
pub fn owner(&self) -> Result<ValidatedSid, SecurityAclError> {
let mut owner = ptr::null_mut();
let mut defaulted = 0;
let read =
unsafe { GetSecurityDescriptorOwner(self.0.as_ptr(), &mut owner, &mut defaulted) };
if read == 0 {
return Err(io::Error::last_os_error().into());
}
if owner.is_null() {
return Err(AclValidationError::MissingOwner.into());
}
ValidatedSid::from_bounded_bytes(self.bytes_from_pointer(owner.cast())?).map_err(Into::into)
}
pub fn dacl(&self) -> Result<ValidatedDacl, SecurityAclError> {
let mut present = 0;
let mut defaulted = 0;
let mut dacl = ptr::null_mut();
let read = unsafe {
GetSecurityDescriptorDacl(self.0.as_ptr(), &mut present, &mut dacl, &mut defaulted)
};
if read == 0 {
return Err(io::Error::last_os_error().into());
}
if present == 0 || dacl.is_null() {
return Err(AclValidationError::MissingDacl.into());
}
ValidatedDacl::from_bytes(self.bytes_from_pointer(dacl.cast())?).map_err(Into::into)
}
fn bytes_from_pointer(&self, pointer: *const u8) -> Result<&[u8], AclValidationError> {
let length = unsafe { GetSecurityDescriptorLength(self.0.as_ptr()) } as usize;
if length == 0 {
return Err(AclValidationError::DescriptorRange);
}
let offset = (pointer as usize)
.checked_sub(self.0.as_ptr() as usize)
.filter(|offset| *offset < length)
.ok_or(AclValidationError::DescriptorRange)?;
let bytes = unsafe { std::slice::from_raw_parts(self.0.as_ptr().cast::<u8>(), length) };
Ok(&bytes[offset..])
}
}
impl Drop for ObjectSecurityDescriptor {
fn drop(&mut self) {
unsafe { LocalFree(self.0.as_ptr()) };
}
}
pub fn current_user_sid_string() -> io::Result<String> {
let token = open_current_process_token(TOKEN_QUERY)?;
token_user_sid_string(token.as_raw_handle())
}
pub(crate) fn token_user_sid_string(raw: RawHandle) -> io::Result<String> {
let information = probe_word_aligned(
size_of::<TOKEN_USER>(),
MAX_TOKEN_INFORMATION_BYTES,
|buffer, capacity, needed| {
let result =
unsafe { GetTokenInformation(raw, TokenUser, buffer.cast(), capacity, needed) };
if result != 0 {
return Ok(CallOutcome::Complete);
}
let error = io::Error::last_os_error();
if error.raw_os_error() == Some(ERROR_INSUFFICIENT_BUFFER as i32) {
Ok(CallOutcome::MoreData(error))
} else {
Err(error)
}
},
)
.map_err(|error| error.into_io("token user information"))?;
let user = unsafe { information.read::<TOKEN_USER>() }
.expect("token information header size and alignment were checked");
let sid_offset = (user.User.Sid as usize).checked_sub(information.as_ptr() as usize);
if sid_offset.map_or(true, |offset| offset >= information.len()) {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"the token user SID lies outside the returned buffer",
));
}
let mut string = ptr::null_mut();
if unsafe { ConvertSidToStringSidW(user.User.Sid, &mut string) } == 0 || string.is_null() {
return Err(io::Error::last_os_error());
}
let units = unsafe { bounded_units(string, MAX_SID_STRING_UNITS) };
let result = units
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "SID string exceeds the bound"))
.and_then(|units| {
String::from_utf16(units).map_err(|_| {
io::Error::new(io::ErrorKind::InvalidData, "SID string is not valid UTF-16")
})
});
unsafe { LocalFree(string.cast()) };
result
}
pub fn current_token_is_member_of(group: &OwnedSid) -> io::Result<bool> {
let mut is_member = 0;
let checked = unsafe { CheckTokenMembership(ptr::null_mut(), group.as_ptr(), &mut is_member) };
if checked == 0 {
return Err(io::Error::last_os_error());
}
Ok(is_member != 0)
}
pub struct PrivilegeGuard {
token: OwnedHandle,
luid: LUID,
counted: bool,
}
static TURNED_ON: Mutex<Vec<((u32, i32), usize)>> = Mutex::new(Vec::new());
fn lock_turned_on() -> MutexGuard<'static, Vec<((u32, i32), usize)>> {
TURNED_ON.lock().unwrap_or_else(PoisonError::into_inner)
}
impl std::fmt::Debug for PrivilegeGuard {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("PrivilegeGuard")
.field("token", &self.token)
.field("luid_high", &self.luid.HighPart)
.field("luid_low", &self.luid.LowPart)
.finish()
}
}
impl PrivilegeGuard {
pub fn enable(name: &str) -> io::Result<PrivilegeGuard> {
let token = open_current_process_token(TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY)?;
let name_wide = wide_null(name)?;
let mut luid = LUID::default();
if unsafe { LookupPrivilegeValueW(ptr::null(), name_wide.as_ptr(), &mut luid) } == 0 {
return Err(io::Error::last_os_error());
}
let privileges = token_privileges(luid, SE_PRIVILEGE_ENABLED);
let mut previous = TOKEN_PRIVILEGES::default();
let mut previous_bytes = 0_u32;
let mut turned_on = lock_turned_on();
unsafe { SetLastError(ERROR_SUCCESS) };
let adjusted = unsafe {
AdjustTokenPrivileges(
token.as_raw_handle(),
0,
&privileges,
size_of::<TOKEN_PRIVILEGES>() as u32,
&mut previous,
&mut previous_bytes,
)
};
if adjusted == 0 {
return Err(io::Error::last_os_error());
}
let assignment = io::Error::last_os_error();
if assignment.raw_os_error() == Some(ERROR_NOT_ALL_ASSIGNED as i32) {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!("the current token does not hold {name}"),
));
}
let changed = previous.PrivilegeCount != 0;
let key = (luid.LowPart, luid.HighPart);
let counted = match turned_on.iter_mut().find(|entry| entry.0 == key) {
Some(entry) => {
entry.1 += 1;
true
}
None if changed => {
turned_on.push((key, 1));
true
}
None => false,
};
Ok(Self {
token,
luid,
counted,
})
}
}
impl Drop for PrivilegeGuard {
fn drop(&mut self) {
if !self.counted {
return;
}
let mut turned_on = lock_turned_on();
let key = (self.luid.LowPart, self.luid.HighPart);
let Some(index) = turned_on.iter().position(|entry| entry.0 == key) else {
return;
};
turned_on[index].1 -= 1;
if turned_on[index].1 != 0 {
return;
}
turned_on.swap_remove(index);
let privileges = token_privileges(self.luid, 0);
unsafe {
AdjustTokenPrivileges(
self.token.as_raw_handle(),
0,
&privileges,
0,
ptr::null_mut(),
ptr::null_mut(),
)
};
}
}
fn token_privileges(luid: LUID, attributes: u32) -> TOKEN_PRIVILEGES {
TOKEN_PRIVILEGES {
PrivilegeCount: 1,
Privileges: [LUID_AND_ATTRIBUTES {
Luid: luid,
Attributes: attributes,
}],
}
}
fn open_current_process_token(access: u32) -> io::Result<OwnedHandle> {
let mut token = ptr::null_mut();
if unsafe { OpenProcessToken(current_process(), access, &mut token) } == 0 {
return Err(io::Error::last_os_error());
}
owned_from_creation(token)
}
#[cfg(test)]
mod tests {
use std::os::windows::io::AsRawHandle;
use std::ptr::null;
use windows_sys::Win32::Foundation::{ERROR_INVALID_PARAMETER, LUID};
use windows_sys::Win32::Security::{
LookupPrivilegeValueW, PrivilegeCheck, LUID_AND_ATTRIBUTES, PRIVILEGE_SET, TOKEN_QUERY,
};
use windows_sys::Win32::System::SystemServices::PRIVILEGE_SET_ALL_NECESSARY;
use super::{
current_token_is_member_of, current_user_sid_string, open_current_process_token,
ObjectSecurityDescriptor, OwnedSid, PrivilegeGuard, SecurityDescriptor,
};
use crate::wide::wide_null;
#[test]
fn a_tree_reset_from_sddl_reads_back_as_the_same_allowed_aces() {
let directory = tempfile::tempdir().unwrap();
let child = directory.path().join("child");
std::fs::create_dir(&child).unwrap();
let current_user = current_user_sid_string().unwrap();
let sddl = format!("D:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FA;;;{current_user})");
let descriptor = SecurityDescriptor::from_sddl(&sddl).unwrap();
descriptor.apply_to_tree(directory.path(), true).unwrap();
let system = OwnedSid::from_string("S-1-5-18").unwrap();
let queried = ObjectSecurityDescriptor::query_file(&child).unwrap();
let dacl = queried.dacl().unwrap();
assert_eq!(dacl.len(), 3);
assert!(dacl.allowed_aces().any(|ace| ace.trustee_matches(&system)));
assert!(ObjectSecurityDescriptor::query_file(&directory.path().join("missing")).is_err());
}
#[test]
fn malformed_sddl_reports_invalid_parameter() {
let error = SecurityDescriptor::from_sddl("D:(not sddl").unwrap_err();
assert_eq!(error.raw_os_error(), Some(ERROR_INVALID_PARAMETER as i32));
}
#[test]
fn the_current_user_sid_has_a_decimal_sid_shape() {
let sid = current_user_sid_string().unwrap();
assert!(sid.starts_with("S-1-"), "unexpected SID {sid}");
assert!(sid[4..].split('-').all(|component| !component.is_empty()
&& component.bytes().all(|byte| byte.is_ascii_digit())));
}
#[test]
fn every_token_is_a_member_of_everyone() {
let everyone = OwnedSid::from_string("WD").unwrap();
assert!(current_token_is_member_of(&everyone).unwrap());
}
#[test]
fn held_privileges_enable_and_unknown_names_fail() {
drop(PrivilegeGuard::enable("SeChangeNotifyPrivilege").unwrap());
assert!(PrivilegeGuard::enable("SeNotARealPrivilege").is_err());
}
fn privilege_is_enabled(name: &str) -> bool {
let token = open_current_process_token(TOKEN_QUERY).unwrap();
let name = wide_null(name).unwrap();
let mut luid = LUID::default();
let found = unsafe { LookupPrivilegeValueW(null(), name.as_ptr(), &mut luid) };
assert_ne!(found, 0, "{}", std::io::Error::last_os_error());
let mut required = PRIVILEGE_SET {
PrivilegeCount: 1,
Control: PRIVILEGE_SET_ALL_NECESSARY,
Privilege: [LUID_AND_ATTRIBUTES {
Luid: luid,
Attributes: 0,
}],
};
let mut enabled = 0;
let checked = unsafe { PrivilegeCheck(token.as_raw_handle(), &mut required, &mut enabled) };
assert_ne!(checked, 0, "{}", std::io::Error::last_os_error());
enabled != 0
}
#[test]
fn a_guard_leaves_a_privilege_that_was_already_enabled_enabled() {
assert!(privilege_is_enabled("SeChangeNotifyPrivilege"));
drop(PrivilegeGuard::enable("SeChangeNotifyPrivilege").unwrap());
assert!(privilege_is_enabled("SeChangeNotifyPrivilege"));
}
#[test]
fn a_privilege_stays_enabled_until_its_last_guard_is_dropped() {
let name = "SeIncreaseWorkingSetPrivilege";
assert!(!privilege_is_enabled(name));
let first = PrivilegeGuard::enable(name).unwrap();
let second = PrivilegeGuard::enable(name).unwrap();
assert!(privilege_is_enabled(name));
drop(first);
assert!(privilege_is_enabled(name));
drop(second);
assert!(!privilege_is_enabled(name));
}
}