1163 lines
39 KiB
Rust
1163 lines
39 KiB
Rust
use crate::winutil::resolve_sid;
|
|
use crate::winutil::sid_bytes_from_string;
|
|
use crate::winutil::to_wide;
|
|
use anyhow::Context;
|
|
use anyhow::Result;
|
|
use anyhow::anyhow;
|
|
use anyhow::ensure;
|
|
use std::ffi::c_void;
|
|
use std::fs::OpenOptions;
|
|
use std::os::windows::fs::OpenOptionsExt;
|
|
use std::os::windows::io::AsRawHandle;
|
|
use std::path::Path;
|
|
use windows_sys::Win32::Foundation::CloseHandle;
|
|
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
|
|
use windows_sys::Win32::Foundation::HANDLE;
|
|
use windows_sys::Win32::Foundation::HLOCAL;
|
|
use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
|
|
use windows_sys::Win32::Foundation::LocalFree;
|
|
use windows_sys::Win32::Security::ACCESS_ALLOWED_ACE;
|
|
use windows_sys::Win32::Security::ACCESS_DENIED_ACE;
|
|
use windows_sys::Win32::Security::ACE_HEADER;
|
|
use windows_sys::Win32::Security::ACL;
|
|
use windows_sys::Win32::Security::ACL_SIZE_INFORMATION;
|
|
use windows_sys::Win32::Security::AclSizeInformation;
|
|
use windows_sys::Win32::Security::Authorization::ACCESS_MODE;
|
|
use windows_sys::Win32::Security::Authorization::EXPLICIT_ACCESS_W;
|
|
use windows_sys::Win32::Security::Authorization::GRANT_ACCESS;
|
|
use windows_sys::Win32::Security::Authorization::GetNamedSecurityInfoW;
|
|
use windows_sys::Win32::Security::Authorization::GetSecurityInfo;
|
|
use windows_sys::Win32::Security::Authorization::SET_ACCESS;
|
|
use windows_sys::Win32::Security::Authorization::SetEntriesInAclW;
|
|
use windows_sys::Win32::Security::Authorization::SetNamedSecurityInfoW;
|
|
use windows_sys::Win32::Security::Authorization::SetSecurityInfo;
|
|
use windows_sys::Win32::Security::Authorization::TRUSTEE_IS_SID;
|
|
use windows_sys::Win32::Security::Authorization::TRUSTEE_IS_UNKNOWN;
|
|
use windows_sys::Win32::Security::Authorization::TRUSTEE_W;
|
|
use windows_sys::Win32::Security::DACL_SECURITY_INFORMATION;
|
|
use windows_sys::Win32::Security::EqualSid;
|
|
use windows_sys::Win32::Security::GENERIC_MAPPING;
|
|
use windows_sys::Win32::Security::GetAce;
|
|
use windows_sys::Win32::Security::GetAclInformation;
|
|
use windows_sys::Win32::Security::IsValidAcl;
|
|
use windows_sys::Win32::Security::MapGenericMask;
|
|
use windows_sys::Win32::Security::OWNER_SECURITY_INFORMATION;
|
|
use windows_sys::Win32::Storage::FileSystem::CreateFileW;
|
|
use windows_sys::Win32::Storage::FileSystem::DELETE;
|
|
use windows_sys::Win32::Storage::FileSystem::FILE_ALL_ACCESS;
|
|
use windows_sys::Win32::Storage::FileSystem::FILE_APPEND_DATA;
|
|
use windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_NORMAL;
|
|
use windows_sys::Win32::Storage::FileSystem::FILE_DELETE_CHILD;
|
|
use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_BACKUP_SEMANTICS;
|
|
use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_EXECUTE;
|
|
use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_READ;
|
|
use windows_sys::Win32::Storage::FileSystem::FILE_GENERIC_WRITE;
|
|
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_DELETE;
|
|
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;
|
|
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_WRITE;
|
|
use windows_sys::Win32::Storage::FileSystem::FILE_WRITE_ATTRIBUTES;
|
|
use windows_sys::Win32::Storage::FileSystem::FILE_WRITE_DATA;
|
|
use windows_sys::Win32::Storage::FileSystem::FILE_WRITE_EA;
|
|
use windows_sys::Win32::Storage::FileSystem::GetFinalPathNameByHandleW;
|
|
use windows_sys::Win32::Storage::FileSystem::OPEN_EXISTING;
|
|
use windows_sys::Win32::Storage::FileSystem::READ_CONTROL;
|
|
use windows_sys::Win32::Storage::FileSystem::VOLUME_NAME_NONE;
|
|
use windows_sys::Win32::Storage::FileSystem::WRITE_DAC;
|
|
use windows_sys::Win32::Storage::FileSystem::WRITE_OWNER;
|
|
use windows_sys::Win32::System::SystemServices::MAXIMUM_ALLOWED;
|
|
const SE_KERNEL_OBJECT: u32 = 6;
|
|
const OBJECT_INHERIT_ACE_FLAG: u8 = 0x01;
|
|
const INHERIT_ONLY_ACE: u8 = 0x08;
|
|
const INHERITED_ACE: u8 = 0x10;
|
|
const ACCESS_ALLOWED_ACE_TYPE: u8 = 0;
|
|
const ACCESS_DENIED_ACE_TYPE: u8 = 1;
|
|
const GENERIC_READ_MASK: u32 = 0x8000_0000;
|
|
const GENERIC_WRITE_MASK: u32 = 0x4000_0000;
|
|
const GENERIC_EXECUTE_MASK: u32 = 0x2000_0000;
|
|
const GENERIC_ALL_MASK: u32 = 0x1000_0000;
|
|
const DENY_ACCESS: i32 = 3;
|
|
// TrustedInstaller is a deterministic service SID, not a machine-local account SID.
|
|
const TRUSTED_INSTALLER_SID: &str =
|
|
"S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464";
|
|
const STANDARD_USER_MUTATION_MASK: u32 = FILE_WRITE_DATA
|
|
| FILE_APPEND_DATA
|
|
| FILE_WRITE_EA
|
|
| FILE_WRITE_ATTRIBUTES
|
|
| DELETE
|
|
| FILE_DELETE_CHILD
|
|
| WRITE_DAC
|
|
| WRITE_OWNER;
|
|
|
|
fn acl_api_result(path: &Path, operation: &str, code: u32) -> Result<()> {
|
|
if code == ERROR_SUCCESS {
|
|
Ok(())
|
|
} else {
|
|
Err(anyhow!("{operation} failed for {}: {code}", path.display()))
|
|
}
|
|
}
|
|
|
|
/// Fetch DACL via handle-based query; caller must LocalFree the returned SD.
|
|
///
|
|
/// # Safety
|
|
/// Caller must free the returned security descriptor with `LocalFree` and pass an existing path.
|
|
pub unsafe fn fetch_dacl_handle(path: &Path) -> Result<(*mut ACL, *mut c_void)> {
|
|
// Rust's file opening supports extended-length paths without changing the
|
|
// caller's spelling or resolving links before the existing reparse checks.
|
|
let handle = OpenOptions::new()
|
|
.access_mode(READ_CONTROL)
|
|
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)
|
|
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
|
|
.open(path)
|
|
.with_context(|| format!("open ACL target {}", path.display()))?;
|
|
let mut p_sd: *mut c_void = std::ptr::null_mut();
|
|
let mut p_dacl: *mut ACL = std::ptr::null_mut();
|
|
let code = GetSecurityInfo(
|
|
handle.as_raw_handle() as _,
|
|
1, // SE_FILE_OBJECT
|
|
DACL_SECURITY_INFORMATION,
|
|
std::ptr::null_mut(),
|
|
std::ptr::null_mut(),
|
|
&mut p_dacl,
|
|
std::ptr::null_mut(),
|
|
&mut p_sd,
|
|
);
|
|
if code != ERROR_SUCCESS {
|
|
return Err(anyhow!(
|
|
"GetSecurityInfo failed for {}: {}",
|
|
path.display(),
|
|
code
|
|
));
|
|
}
|
|
Ok((p_dacl, p_sd))
|
|
}
|
|
|
|
/// Fast mask-based check: does an ACE for provided SIDs grant the desired mask? Skips inherit-only.
|
|
/// When `require_all_bits` is true, all bits in `desired_mask` must be present; otherwise any bit suffices.
|
|
pub unsafe fn dacl_mask_allows(
|
|
p_dacl: *mut ACL,
|
|
psids: &[*mut c_void],
|
|
desired_mask: u32,
|
|
require_all_bits: bool,
|
|
) -> bool {
|
|
dacl_mask_allows_with_scope(
|
|
p_dacl,
|
|
psids,
|
|
desired_mask,
|
|
require_all_bits,
|
|
AceScope::Effective,
|
|
)
|
|
}
|
|
|
|
#[derive(Clone, Copy)]
|
|
enum AceScope {
|
|
Effective,
|
|
Explicit,
|
|
EffectiveOrChildFile,
|
|
}
|
|
|
|
unsafe fn dacl_mask_allows_with_scope(
|
|
p_dacl: *mut ACL,
|
|
psids: &[*mut c_void],
|
|
desired_mask: u32,
|
|
require_all_bits: bool,
|
|
scope: AceScope,
|
|
) -> bool {
|
|
if p_dacl.is_null() {
|
|
return false;
|
|
}
|
|
let mut info: ACL_SIZE_INFORMATION = std::mem::zeroed();
|
|
let ok = GetAclInformation(
|
|
p_dacl as *const ACL,
|
|
&mut info as *mut _ as *mut c_void,
|
|
std::mem::size_of::<ACL_SIZE_INFORMATION>() as u32,
|
|
AclSizeInformation,
|
|
);
|
|
if ok == 0 {
|
|
return false;
|
|
}
|
|
let mapping = GENERIC_MAPPING {
|
|
GenericRead: FILE_GENERIC_READ,
|
|
GenericWrite: FILE_GENERIC_WRITE,
|
|
GenericExecute: FILE_GENERIC_EXECUTE,
|
|
GenericAll: FILE_ALL_ACCESS,
|
|
};
|
|
for i in 0..(info.AceCount as usize) {
|
|
let mut p_ace: *mut c_void = std::ptr::null_mut();
|
|
if GetAce(p_dacl as *const ACL, i as u32, &mut p_ace) == 0 {
|
|
continue;
|
|
}
|
|
let hdr = &*(p_ace as *const ACE_HEADER);
|
|
if hdr.AceType != ACCESS_ALLOWED_ACE_TYPE {
|
|
continue; // not ACCESS_ALLOWED
|
|
}
|
|
if (hdr.AceFlags & INHERIT_ONLY_ACE) != 0
|
|
&& (!matches!(scope, AceScope::EffectiveOrChildFile)
|
|
|| (hdr.AceFlags & OBJECT_INHERIT_ACE_FLAG) == 0)
|
|
{
|
|
continue;
|
|
}
|
|
// SET_ACCESS cannot replace an ACE inherited from an ancestor, so it cannot make
|
|
// an explicit-only repair converge when that inherited ACE contains stale rights.
|
|
if matches!(scope, AceScope::Explicit) && (hdr.AceFlags & INHERITED_ACE) != 0 {
|
|
continue;
|
|
}
|
|
let base = p_ace as usize;
|
|
let sid_ptr =
|
|
(base + std::mem::size_of::<ACE_HEADER>() + std::mem::size_of::<u32>()) as *mut c_void;
|
|
let mut matched = false;
|
|
for sid in psids {
|
|
if EqualSid(sid_ptr, *sid) != 0 {
|
|
matched = true;
|
|
break;
|
|
}
|
|
}
|
|
if !matched {
|
|
continue;
|
|
}
|
|
let ace = &*(p_ace as *const ACCESS_ALLOWED_ACE);
|
|
let mut mask = ace.Mask;
|
|
MapGenericMask(&mut mask, &mapping);
|
|
if (require_all_bits && (mask & desired_mask) == desired_mask)
|
|
|| (!require_all_bits && (mask & desired_mask) != 0)
|
|
{
|
|
return true;
|
|
}
|
|
}
|
|
false
|
|
}
|
|
|
|
/// Path-based wrapper around the mask check (single DACL fetch).
|
|
pub fn path_mask_allows(
|
|
path: &Path,
|
|
psids: &[*mut c_void],
|
|
desired_mask: u32,
|
|
require_all_bits: bool,
|
|
) -> Result<bool> {
|
|
path_mask_allows_with_scope(
|
|
path,
|
|
psids,
|
|
desired_mask,
|
|
require_all_bits,
|
|
AceScope::Effective,
|
|
)
|
|
}
|
|
|
|
/// Whether a broad standard-user principal has an allow ACE that can mutate
|
|
/// the path. This is intentionally conservative and does not evaluate deny
|
|
/// ACEs against a concrete token.
|
|
pub fn path_has_standard_user_mutation_allow(path: &Path) -> Result<bool> {
|
|
path_has_standard_user_mutation_allow_with_scope(path, AceScope::Effective)
|
|
}
|
|
|
|
/// Whether a broad standard-user principal has an allow ACE that can mutate
|
|
/// the path or a directly inherited child file.
|
|
pub fn path_or_child_file_has_standard_user_mutation_allow(path: &Path) -> Result<bool> {
|
|
path_has_standard_user_mutation_allow_with_scope(path, AceScope::EffectiveOrChildFile)
|
|
}
|
|
|
|
fn path_has_standard_user_mutation_allow_with_scope(path: &Path, scope: AceScope) -> Result<bool> {
|
|
// These canonical labels map to fixed SIDs before any localized account lookup.
|
|
let mut users = resolve_sid("Users")?;
|
|
let mut authenticated_users = resolve_sid("Authenticated Users")?;
|
|
let mut everyone = resolve_sid("Everyone")?;
|
|
let sids = [
|
|
users.as_mut_ptr().cast(),
|
|
authenticated_users.as_mut_ptr().cast(),
|
|
everyone.as_mut_ptr().cast(),
|
|
];
|
|
unsafe {
|
|
let (dacl, descriptor) = fetch_dacl_handle(path)?;
|
|
let result = if dacl.is_null() {
|
|
Ok(true)
|
|
} else if IsValidAcl(dacl) == 0 {
|
|
Err(anyhow!("invalid DACL for {}", path.display()))
|
|
} else {
|
|
Ok(dacl_mask_allows_with_scope(
|
|
dacl,
|
|
&sids,
|
|
STANDARD_USER_MUTATION_MASK,
|
|
/*require_all_bits*/ false,
|
|
scope,
|
|
))
|
|
};
|
|
if !descriptor.is_null() {
|
|
LocalFree(descriptor as HLOCAL);
|
|
}
|
|
result
|
|
}
|
|
}
|
|
|
|
/// Whether the path owner is one of the conservative administrator-controlled
|
|
/// principals used by the Windows system-config shadow check.
|
|
pub fn path_has_trusted_system_owner(path: &Path) -> Result<bool> {
|
|
// These canonical labels map to fixed SIDs before any localized account lookup.
|
|
let mut administrators = resolve_sid("Administrators")?;
|
|
let mut system = resolve_sid("SYSTEM")?;
|
|
let mut trusted_installer = sid_bytes_from_string(TRUSTED_INSTALLER_SID)?;
|
|
let trusted_sids = [
|
|
administrators.as_mut_ptr().cast(),
|
|
system.as_mut_ptr().cast(),
|
|
trusted_installer.as_mut_ptr().cast(),
|
|
];
|
|
path_owner_matches(path, &trusted_sids)
|
|
}
|
|
|
|
fn path_owner_matches(path: &Path, trusted_sids: &[*mut c_void]) -> Result<bool> {
|
|
let mut owner = std::ptr::null_mut();
|
|
let mut descriptor = std::ptr::null_mut();
|
|
let code = unsafe {
|
|
GetNamedSecurityInfoW(
|
|
to_wide(path).as_ptr(),
|
|
1, // SE_FILE_OBJECT
|
|
OWNER_SECURITY_INFORMATION,
|
|
&mut owner,
|
|
std::ptr::null_mut(),
|
|
std::ptr::null_mut(),
|
|
std::ptr::null_mut(),
|
|
&mut descriptor,
|
|
)
|
|
};
|
|
if code != ERROR_SUCCESS {
|
|
if !descriptor.is_null() {
|
|
unsafe { LocalFree(descriptor as HLOCAL) };
|
|
}
|
|
return Err(anyhow!(
|
|
"GetNamedSecurityInfoW failed for {}: {code}",
|
|
path.display()
|
|
));
|
|
}
|
|
if owner.is_null() {
|
|
if !descriptor.is_null() {
|
|
unsafe { LocalFree(descriptor as HLOCAL) };
|
|
}
|
|
return Err(anyhow!("missing owner for {}", path.display()));
|
|
}
|
|
let matches = trusted_sids
|
|
.iter()
|
|
.any(|trusted_sid| unsafe { EqualSid(owner, *trusted_sid) } != 0);
|
|
if !descriptor.is_null() {
|
|
unsafe { LocalFree(descriptor as HLOCAL) };
|
|
}
|
|
Ok(matches)
|
|
}
|
|
|
|
fn path_mask_allows_with_scope(
|
|
path: &Path,
|
|
psids: &[*mut c_void],
|
|
desired_mask: u32,
|
|
require_all_bits: bool,
|
|
scope: AceScope,
|
|
) -> Result<bool> {
|
|
unsafe {
|
|
let (p_dacl, sd) = fetch_dacl_handle(path)?;
|
|
let has = dacl_mask_allows_with_scope(p_dacl, psids, desired_mask, require_all_bits, scope);
|
|
if !sd.is_null() {
|
|
LocalFree(sd as HLOCAL);
|
|
}
|
|
Ok(has)
|
|
}
|
|
}
|
|
|
|
pub unsafe fn dacl_has_write_allow_for_sid(p_dacl: *mut ACL, psid: *mut c_void) -> bool {
|
|
if p_dacl.is_null() {
|
|
return false;
|
|
}
|
|
let mut info: ACL_SIZE_INFORMATION = std::mem::zeroed();
|
|
let ok = GetAclInformation(
|
|
p_dacl as *const ACL,
|
|
&mut info as *mut _ as *mut c_void,
|
|
std::mem::size_of::<ACL_SIZE_INFORMATION>() as u32,
|
|
AclSizeInformation,
|
|
);
|
|
if ok == 0 {
|
|
return false;
|
|
}
|
|
let count = info.AceCount as usize;
|
|
for i in 0..count {
|
|
let mut p_ace: *mut c_void = std::ptr::null_mut();
|
|
if GetAce(p_dacl as *const ACL, i as u32, &mut p_ace) == 0 {
|
|
continue;
|
|
}
|
|
let hdr = &*(p_ace as *const ACE_HEADER);
|
|
if hdr.AceType != ACCESS_ALLOWED_ACE_TYPE {
|
|
continue; // ACCESS_ALLOWED_ACE_TYPE
|
|
}
|
|
// Ignore ACEs that are inherit-only (do not apply to the current object)
|
|
if (hdr.AceFlags & INHERIT_ONLY_ACE) != 0 {
|
|
continue;
|
|
}
|
|
let ace = &*(p_ace as *const ACCESS_ALLOWED_ACE);
|
|
let mask = ace.Mask;
|
|
let base = p_ace as usize;
|
|
let sid_ptr =
|
|
(base + std::mem::size_of::<ACE_HEADER>() + std::mem::size_of::<u32>()) as *mut c_void;
|
|
let eq = EqualSid(sid_ptr, psid);
|
|
if eq != 0 && (mask & FILE_GENERIC_WRITE) != 0 {
|
|
return true;
|
|
}
|
|
}
|
|
false
|
|
}
|
|
|
|
pub unsafe fn dacl_has_write_deny_for_sid(p_dacl: *mut ACL, psid: *mut c_void) -> bool {
|
|
if p_dacl.is_null() {
|
|
return false;
|
|
}
|
|
let mut info: ACL_SIZE_INFORMATION = std::mem::zeroed();
|
|
let ok = GetAclInformation(
|
|
p_dacl as *const ACL,
|
|
&mut info as *mut _ as *mut c_void,
|
|
std::mem::size_of::<ACL_SIZE_INFORMATION>() as u32,
|
|
AclSizeInformation,
|
|
);
|
|
if ok == 0 {
|
|
return false;
|
|
}
|
|
let deny_write_mask = FILE_GENERIC_WRITE
|
|
| FILE_WRITE_DATA
|
|
| FILE_APPEND_DATA
|
|
| FILE_WRITE_EA
|
|
| FILE_WRITE_ATTRIBUTES
|
|
| GENERIC_WRITE_MASK
|
|
| DELETE
|
|
| FILE_DELETE_CHILD;
|
|
for i in 0..info.AceCount {
|
|
let mut p_ace: *mut c_void = std::ptr::null_mut();
|
|
if GetAce(p_dacl as *const ACL, i, &mut p_ace) == 0 {
|
|
continue;
|
|
}
|
|
let hdr = &*(p_ace as *const ACE_HEADER);
|
|
if hdr.AceType != ACCESS_DENIED_ACE_TYPE {
|
|
continue; // ACCESS_DENIED_ACE_TYPE
|
|
}
|
|
if (hdr.AceFlags & INHERIT_ONLY_ACE) != 0 {
|
|
continue;
|
|
}
|
|
let ace = &*(p_ace as *const ACCESS_DENIED_ACE);
|
|
let base = p_ace as usize;
|
|
let sid_ptr =
|
|
(base + std::mem::size_of::<ACE_HEADER>() + std::mem::size_of::<u32>()) as *mut c_void;
|
|
if EqualSid(sid_ptr, psid) != 0 && (ace.Mask & deny_write_mask) != 0 {
|
|
return true;
|
|
}
|
|
}
|
|
false
|
|
}
|
|
|
|
pub unsafe fn dacl_has_read_deny_for_sid(p_dacl: *mut ACL, psid: *mut c_void) -> bool {
|
|
dacl_has_deny_mask(
|
|
p_dacl,
|
|
DenyAceScope::EffectiveForSid(psid),
|
|
FILE_GENERIC_READ | GENERIC_READ_MASK,
|
|
)
|
|
}
|
|
|
|
enum DenyAceScope {
|
|
EffectiveForSid(*mut c_void),
|
|
Any,
|
|
}
|
|
|
|
unsafe fn dacl_has_deny_mask(p_dacl: *mut ACL, scope: DenyAceScope, deny_mask: u32) -> bool {
|
|
if p_dacl.is_null() {
|
|
return false;
|
|
}
|
|
let mut info: ACL_SIZE_INFORMATION = std::mem::zeroed();
|
|
let ok = GetAclInformation(
|
|
p_dacl as *const ACL,
|
|
&mut info as *mut _ as *mut c_void,
|
|
std::mem::size_of::<ACL_SIZE_INFORMATION>() as u32,
|
|
AclSizeInformation,
|
|
);
|
|
if ok == 0 {
|
|
return false;
|
|
}
|
|
let mapping = GENERIC_MAPPING {
|
|
GenericRead: FILE_GENERIC_READ,
|
|
GenericWrite: FILE_GENERIC_WRITE,
|
|
GenericExecute: FILE_GENERIC_EXECUTE,
|
|
GenericAll: FILE_ALL_ACCESS,
|
|
};
|
|
for i in 0..info.AceCount {
|
|
let mut p_ace: *mut c_void = std::ptr::null_mut();
|
|
if GetAce(p_dacl as *const ACL, i, &mut p_ace) == 0 {
|
|
continue;
|
|
}
|
|
let hdr = &*(p_ace as *const ACE_HEADER);
|
|
if hdr.AceType != ACCESS_DENIED_ACE_TYPE {
|
|
continue; // ACCESS_DENIED_ACE_TYPE
|
|
}
|
|
let ace = &*(p_ace as *const ACCESS_DENIED_ACE);
|
|
if let DenyAceScope::EffectiveForSid(psid) = scope
|
|
&& ((hdr.AceFlags & INHERIT_ONLY_ACE) != 0
|
|
|| EqualSid(std::ptr::addr_of!(ace.SidStart) as *mut c_void, psid) == 0)
|
|
{
|
|
continue;
|
|
}
|
|
let mut denied_mask = ace.Mask;
|
|
MapGenericMask(&mut denied_mask, &mapping);
|
|
if ((ace.Mask | denied_mask) & deny_mask) != 0 {
|
|
return true;
|
|
}
|
|
}
|
|
false
|
|
}
|
|
|
|
// Grant DELETE on each inheriting descendant instead of FILE_DELETE_CHILD on
|
|
// its parent. A parent delete-child grant would bypass a direct deny-write ACE
|
|
// on protected children such as `.git` or an explicit read-only subpath.
|
|
const WRITE_ALLOW_MASK: u32 =
|
|
FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE | DELETE;
|
|
|
|
unsafe fn dacl_allow_mask_needs_refresh(
|
|
p_dacl: *mut ACL,
|
|
psid: *mut c_void,
|
|
allow_mask: u32,
|
|
disallow_mask: u32,
|
|
) -> bool {
|
|
!dacl_mask_allows(p_dacl, &[psid], allow_mask, /*require_all_bits*/ true)
|
|
|| dacl_mask_allows_with_scope(
|
|
p_dacl,
|
|
&[psid],
|
|
disallow_mask,
|
|
/*require_all_bits*/ false,
|
|
AceScope::Explicit,
|
|
)
|
|
}
|
|
|
|
/// Returns whether any provided SID needs its writable-root allow ACE refreshed.
|
|
pub fn path_write_aces_need_refresh(path: &Path, psids: &[*mut c_void]) -> Result<bool> {
|
|
unsafe {
|
|
let (p_dacl, p_sd) = fetch_dacl_handle(path)?;
|
|
let needs_refresh = psids.iter().any(|psid| {
|
|
dacl_allow_mask_needs_refresh(p_dacl, *psid, WRITE_ALLOW_MASK, FILE_DELETE_CHILD)
|
|
});
|
|
if !p_sd.is_null() {
|
|
LocalFree(p_sd as HLOCAL);
|
|
}
|
|
Ok(needs_refresh)
|
|
}
|
|
}
|
|
|
|
unsafe fn ensure_allow_mask_aces_with_inheritance_impl(
|
|
path: &Path,
|
|
sids: &[*mut c_void],
|
|
allow_mask: u32,
|
|
disallow_mask: u32,
|
|
access_mode: ACCESS_MODE,
|
|
inheritance: u32,
|
|
) -> Result<bool> {
|
|
// Only directories need MAXIMUM_ALLOWED to suppress child ACL propagation.
|
|
// On active EXE/DLL files, it can request access that causes sharing violations.
|
|
let directory = if inheritance == 0
|
|
&& path
|
|
.metadata()
|
|
.with_context(|| format!("inspect ACL target {}", path.display()))?
|
|
.is_dir()
|
|
{
|
|
Some(
|
|
OpenOptions::new()
|
|
.access_mode(MAXIMUM_ALLOWED)
|
|
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)
|
|
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
|
|
.open(path)
|
|
.context("open ACL target for root-only update (MAXIMUM_ALLOWED)")?,
|
|
)
|
|
} else {
|
|
None
|
|
};
|
|
// A root-only grant must preserve existing permissions and deny ACEs.
|
|
let access_mode = if inheritance == 0 {
|
|
GRANT_ACCESS
|
|
} else {
|
|
access_mode
|
|
};
|
|
|
|
let (p_dacl, p_sd) = match directory.as_ref() {
|
|
Some(directory) => {
|
|
let mut security_descriptor: *mut c_void = std::ptr::null_mut();
|
|
let mut acl: *mut ACL = std::ptr::null_mut();
|
|
let code = GetSecurityInfo(
|
|
directory.as_raw_handle() as HANDLE,
|
|
/*objecttype*/ 1,
|
|
DACL_SECURITY_INFORMATION,
|
|
std::ptr::null_mut(),
|
|
std::ptr::null_mut(),
|
|
&mut acl,
|
|
std::ptr::null_mut(),
|
|
&mut security_descriptor,
|
|
);
|
|
if code != ERROR_SUCCESS {
|
|
if !security_descriptor.is_null() {
|
|
LocalFree(security_descriptor as HLOCAL);
|
|
}
|
|
return Err(anyhow!(
|
|
"read ACL for root-only update on {}: {code}",
|
|
path.display()
|
|
));
|
|
}
|
|
(acl, security_descriptor)
|
|
}
|
|
None => fetch_dacl_handle(path)?,
|
|
};
|
|
let mut entries: Vec<EXPLICIT_ACCESS_W> = Vec::new();
|
|
for sid in sids {
|
|
// A new allow can outrank another trustee's inherited deny, including a
|
|
// file-only deny on children. Without the complete token, preserve every deny.
|
|
if access_mode == GRANT_ACCESS
|
|
&& dacl_has_deny_mask(
|
|
p_dacl,
|
|
DenyAceScope::Any,
|
|
allow_mask
|
|
| GENERIC_READ_MASK
|
|
| GENERIC_WRITE_MASK
|
|
| GENERIC_EXECUTE_MASK
|
|
| GENERIC_ALL_MASK,
|
|
)
|
|
{
|
|
continue;
|
|
}
|
|
if !dacl_allow_mask_needs_refresh(p_dacl, *sid, allow_mask, disallow_mask)
|
|
|| inheritance == 0 && p_dacl.is_null()
|
|
{
|
|
continue;
|
|
}
|
|
entries.push(EXPLICIT_ACCESS_W {
|
|
grfAccessPermissions: allow_mask,
|
|
grfAccessMode: access_mode,
|
|
grfInheritance: inheritance,
|
|
Trustee: TRUSTEE_W {
|
|
pMultipleTrustee: std::ptr::null_mut(),
|
|
MultipleTrusteeOperation: 0,
|
|
TrusteeForm: TRUSTEE_IS_SID,
|
|
TrusteeType: TRUSTEE_IS_UNKNOWN,
|
|
ptstrName: *sid as *mut u16,
|
|
},
|
|
});
|
|
}
|
|
let mut p_new_dacl: *mut ACL = std::ptr::null_mut();
|
|
// Collect errors before releasing either allocation so every update path
|
|
// shares the same cleanup, including failure to open the write handle.
|
|
let result = (|| -> Result<bool> {
|
|
if entries.is_empty() {
|
|
return Ok(false);
|
|
}
|
|
let code2 = SetEntriesInAclW(
|
|
entries.len() as u32,
|
|
entries.as_ptr(),
|
|
p_dacl,
|
|
&mut p_new_dacl,
|
|
);
|
|
if code2 != ERROR_SUCCESS {
|
|
return Err(anyhow!("SetEntriesInAclW failed: {code2}"));
|
|
}
|
|
// For files and inheriting directory grants, request ACL-write access only
|
|
// when an update is needed. Use the same long-path support as the read handle.
|
|
let handle = match directory {
|
|
// MAXIMUM_ALLOWED suppresses propagation of existing inheritable ACEs too.
|
|
Some(directory) => directory,
|
|
None => OpenOptions::new()
|
|
.access_mode(READ_CONTROL | WRITE_DAC)
|
|
.share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)
|
|
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
|
|
.open(path)
|
|
.context("open ACL target for update (READ_CONTROL | WRITE_DAC)")?,
|
|
};
|
|
let code3 = SetSecurityInfo(
|
|
handle.as_raw_handle() as _,
|
|
1,
|
|
DACL_SECURITY_INFORMATION,
|
|
std::ptr::null_mut(),
|
|
std::ptr::null_mut(),
|
|
p_new_dacl,
|
|
std::ptr::null_mut(),
|
|
);
|
|
if code3 != ERROR_SUCCESS {
|
|
return Err(anyhow!("SetSecurityInfo failed: {code3}"));
|
|
}
|
|
Ok(true)
|
|
})();
|
|
if !p_new_dacl.is_null() {
|
|
LocalFree(p_new_dacl as HLOCAL);
|
|
}
|
|
if !p_sd.is_null() {
|
|
LocalFree(p_sd as HLOCAL);
|
|
}
|
|
result
|
|
}
|
|
|
|
/// Ensure all provided SIDs have an allow ACE with the requested mask on the path.
|
|
/// Returns true if any ACE was added.
|
|
/// Zero inheritance preserves existing ACEs without propagating changes to descendants.
|
|
///
|
|
/// # Safety
|
|
/// Caller must pass valid SID pointers and an existing path; free the returned security descriptor with `LocalFree`.
|
|
pub unsafe fn ensure_allow_mask_aces_with_inheritance(
|
|
path: &Path,
|
|
sids: &[*mut c_void],
|
|
allow_mask: u32,
|
|
inheritance: u32,
|
|
) -> Result<bool> {
|
|
ensure_allow_mask_aces_with_inheritance_impl(
|
|
path,
|
|
sids,
|
|
allow_mask,
|
|
/*disallow_mask*/ 0,
|
|
SET_ACCESS,
|
|
inheritance,
|
|
)
|
|
}
|
|
|
|
/// Ensure read/execute grants without replacing existing entries or overriding denies.
|
|
/// Returns true if any ACE was added.
|
|
///
|
|
/// # Safety
|
|
/// Caller must pass valid SID pointers and an existing path.
|
|
pub(crate) unsafe fn grant_read_execute_aces(
|
|
path: &Path,
|
|
sids: &[*mut c_void],
|
|
inheritance: u32,
|
|
) -> Result<bool> {
|
|
ensure_allow_mask_aces_with_inheritance_impl(
|
|
path,
|
|
sids,
|
|
FILE_GENERIC_READ | FILE_GENERIC_EXECUTE,
|
|
/*disallow_mask*/ 0,
|
|
GRANT_ACCESS,
|
|
inheritance,
|
|
)
|
|
}
|
|
|
|
/// Ensure all provided SIDs have an allow ACE with the requested mask on the path.
|
|
/// Returns true if any ACE was added.
|
|
///
|
|
/// # Safety
|
|
/// Caller must pass valid SID pointers and an existing path; free the returned security descriptor with `LocalFree`.
|
|
pub unsafe fn ensure_allow_mask_aces(
|
|
path: &Path,
|
|
sids: &[*mut c_void],
|
|
allow_mask: u32,
|
|
) -> Result<bool> {
|
|
ensure_allow_mask_aces_with_inheritance(
|
|
path,
|
|
sids,
|
|
allow_mask,
|
|
CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE,
|
|
)
|
|
}
|
|
|
|
/// Ensure all provided SIDs have a write-capable allow ACE on the path.
|
|
/// Returns true if any ACE was added.
|
|
///
|
|
/// # Safety
|
|
/// Caller must pass valid SID pointers and an existing path; free the returned security descriptor with `LocalFree`.
|
|
pub unsafe fn ensure_allow_write_aces(path: &Path, sids: &[*mut c_void]) -> Result<bool> {
|
|
ensure_allow_mask_aces_with_inheritance_impl(
|
|
path,
|
|
sids,
|
|
WRITE_ALLOW_MASK,
|
|
FILE_DELETE_CHILD,
|
|
SET_ACCESS,
|
|
CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE,
|
|
)
|
|
}
|
|
|
|
/// Adds an allow ACE granting read/write/execute to the given SID on the target path.
|
|
///
|
|
/// # Safety
|
|
/// Caller must ensure `psid` points to a valid SID and `path` refers to an existing file or directory.
|
|
pub unsafe fn add_allow_ace(path: &Path, psid: *mut c_void) -> Result<bool> {
|
|
let mut p_sd: *mut c_void = std::ptr::null_mut();
|
|
let mut p_dacl: *mut ACL = std::ptr::null_mut();
|
|
let code = GetNamedSecurityInfoW(
|
|
to_wide(path).as_ptr(),
|
|
1,
|
|
DACL_SECURITY_INFORMATION,
|
|
std::ptr::null_mut(),
|
|
std::ptr::null_mut(),
|
|
&mut p_dacl,
|
|
std::ptr::null_mut(),
|
|
&mut p_sd,
|
|
);
|
|
if code != ERROR_SUCCESS {
|
|
return Err(anyhow!("GetNamedSecurityInfoW failed: {code}"));
|
|
}
|
|
// Already has write? Skip costly DACL rewrite.
|
|
if dacl_has_write_allow_for_sid(p_dacl, psid) {
|
|
if !p_sd.is_null() {
|
|
LocalFree(p_sd as HLOCAL);
|
|
}
|
|
return Ok(false);
|
|
}
|
|
let mut added = false;
|
|
// Always ensure write is present: if an allow ACE exists without write, add one with write+RX.
|
|
let trustee = TRUSTEE_W {
|
|
pMultipleTrustee: std::ptr::null_mut(),
|
|
MultipleTrusteeOperation: 0,
|
|
TrusteeForm: TRUSTEE_IS_SID,
|
|
TrusteeType: TRUSTEE_IS_UNKNOWN,
|
|
ptstrName: psid as *mut u16,
|
|
};
|
|
let mut explicit: EXPLICIT_ACCESS_W = std::mem::zeroed();
|
|
explicit.grfAccessPermissions = FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE;
|
|
explicit.grfAccessMode = 2; // SET_ACCESS
|
|
explicit.grfInheritance = CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE;
|
|
explicit.Trustee = trustee;
|
|
let mut p_new_dacl: *mut ACL = std::ptr::null_mut();
|
|
let code2 = SetEntriesInAclW(1, &explicit, p_dacl, &mut p_new_dacl);
|
|
if code2 == ERROR_SUCCESS {
|
|
let code3 = SetNamedSecurityInfoW(
|
|
to_wide(path).as_ptr() as *mut u16,
|
|
1,
|
|
DACL_SECURITY_INFORMATION,
|
|
std::ptr::null_mut(),
|
|
std::ptr::null_mut(),
|
|
p_new_dacl,
|
|
std::ptr::null_mut(),
|
|
);
|
|
if code3 == ERROR_SUCCESS {
|
|
added = !dacl_has_write_allow_for_sid(p_dacl, psid);
|
|
}
|
|
if !p_new_dacl.is_null() {
|
|
LocalFree(p_new_dacl as HLOCAL);
|
|
}
|
|
}
|
|
if !p_sd.is_null() {
|
|
LocalFree(p_sd as HLOCAL);
|
|
}
|
|
Ok(added)
|
|
}
|
|
|
|
/// Adds a deny ACE to prevent write/append/delete for the given SID on the target path.
|
|
///
|
|
/// # Safety
|
|
/// Caller must ensure `psid` points to a valid SID and `path` refers to an existing file or directory.
|
|
pub unsafe fn add_deny_write_ace(path: &Path, psid: *mut c_void) -> Result<bool> {
|
|
add_deny_ace(path, psid, DenyAceKind::Write)
|
|
}
|
|
|
|
#[derive(Clone, Copy)]
|
|
enum DenyAceKind {
|
|
Read,
|
|
Write,
|
|
}
|
|
|
|
impl DenyAceKind {
|
|
fn mask(self) -> u32 {
|
|
match self {
|
|
Self::Read => FILE_GENERIC_READ | GENERIC_READ_MASK,
|
|
Self::Write => {
|
|
FILE_GENERIC_WRITE
|
|
| FILE_WRITE_DATA
|
|
| FILE_APPEND_DATA
|
|
| FILE_WRITE_EA
|
|
| FILE_WRITE_ATTRIBUTES
|
|
| GENERIC_WRITE_MASK
|
|
| DELETE
|
|
| FILE_DELETE_CHILD
|
|
}
|
|
}
|
|
}
|
|
|
|
unsafe fn already_present(self, p_dacl: *mut ACL, psid: *mut c_void) -> bool {
|
|
match self {
|
|
Self::Read => dacl_has_read_deny_for_sid(p_dacl, psid),
|
|
Self::Write => dacl_has_write_deny_for_sid(p_dacl, psid),
|
|
}
|
|
}
|
|
}
|
|
|
|
unsafe fn deny_ace_already_present(
|
|
handle: &std::fs::File,
|
|
path: &Path,
|
|
psid: *mut c_void,
|
|
kind: DenyAceKind,
|
|
) -> Result<bool> {
|
|
let (mut p_dacl, mut p_sd) = (std::ptr::null_mut(), std::ptr::null_mut());
|
|
let code = GetSecurityInfo(
|
|
handle.as_raw_handle() as _,
|
|
1,
|
|
DACL_SECURITY_INFORMATION,
|
|
std::ptr::null_mut(),
|
|
std::ptr::null_mut(),
|
|
&mut p_dacl,
|
|
std::ptr::null_mut(),
|
|
&mut p_sd,
|
|
);
|
|
let result =
|
|
acl_api_result(path, "GetSecurityInfo", code).map(|()| kind.already_present(p_dacl, psid));
|
|
if !p_sd.is_null() {
|
|
LocalFree(p_sd as HLOCAL);
|
|
}
|
|
result
|
|
}
|
|
|
|
unsafe fn add_deny_ace(path: &Path, psid: *mut c_void, kind: DenyAceKind) -> Result<bool> {
|
|
let handle = match OpenOptions::new()
|
|
.access_mode(READ_CONTROL | WRITE_DAC)
|
|
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
|
|
.open(path)
|
|
{
|
|
Ok(handle) => handle,
|
|
Err(write_error) => {
|
|
let read_handle = OpenOptions::new()
|
|
.access_mode(READ_CONTROL)
|
|
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
|
|
.open(path)
|
|
.with_context(|| format!("open deny ACL target {}", path.display()))?;
|
|
if matches!(kind, DenyAceKind::Read) {
|
|
ensure_handle_is_not_filesystem_root(&read_handle, path)?;
|
|
}
|
|
if deny_ace_already_present(&read_handle, path, psid, kind)? {
|
|
return Ok(false);
|
|
}
|
|
return Err(write_error)
|
|
.context("open deny ACL target for update (READ_CONTROL | WRITE_DAC)");
|
|
}
|
|
};
|
|
if matches!(kind, DenyAceKind::Read) {
|
|
ensure_handle_is_not_filesystem_root(&handle, path)?;
|
|
}
|
|
let mut p_sd: *mut c_void = std::ptr::null_mut();
|
|
let mut p_dacl: *mut ACL = std::ptr::null_mut();
|
|
let code = GetSecurityInfo(
|
|
handle.as_raw_handle() as _,
|
|
1,
|
|
DACL_SECURITY_INFORMATION,
|
|
std::ptr::null_mut(),
|
|
std::ptr::null_mut(),
|
|
&mut p_dacl,
|
|
std::ptr::null_mut(),
|
|
&mut p_sd,
|
|
);
|
|
if code != ERROR_SUCCESS {
|
|
if !p_sd.is_null() {
|
|
LocalFree(p_sd as HLOCAL);
|
|
}
|
|
return Err(anyhow!(
|
|
"GetSecurityInfo failed for {}: {code}",
|
|
path.display()
|
|
));
|
|
}
|
|
let result = if kind.already_present(p_dacl, psid) {
|
|
Ok(false)
|
|
} else {
|
|
let trustee = TRUSTEE_W {
|
|
pMultipleTrustee: std::ptr::null_mut(),
|
|
MultipleTrusteeOperation: 0,
|
|
TrusteeForm: TRUSTEE_IS_SID,
|
|
TrusteeType: TRUSTEE_IS_UNKNOWN,
|
|
ptstrName: psid as *mut u16,
|
|
};
|
|
let mut explicit: EXPLICIT_ACCESS_W = std::mem::zeroed();
|
|
explicit.grfAccessPermissions = kind.mask();
|
|
explicit.grfAccessMode = DENY_ACCESS;
|
|
explicit.grfInheritance = CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE;
|
|
explicit.Trustee = trustee;
|
|
let mut p_new_dacl: *mut ACL = std::ptr::null_mut();
|
|
let code2 = SetEntriesInAclW(1, &explicit, p_dacl, &mut p_new_dacl);
|
|
let result = if let Err(err) = acl_api_result(path, "SetEntriesInAclW", code2) {
|
|
Err(err)
|
|
} else {
|
|
let code3 = SetSecurityInfo(
|
|
handle.as_raw_handle() as _,
|
|
1,
|
|
DACL_SECURITY_INFORMATION,
|
|
std::ptr::null_mut(),
|
|
std::ptr::null_mut(),
|
|
p_new_dacl,
|
|
std::ptr::null_mut(),
|
|
);
|
|
acl_api_result(path, "SetSecurityInfo", code3).map(|()| true)
|
|
};
|
|
if !p_new_dacl.is_null() {
|
|
LocalFree(p_new_dacl as HLOCAL);
|
|
}
|
|
result
|
|
};
|
|
if !p_sd.is_null() {
|
|
LocalFree(p_sd as HLOCAL);
|
|
}
|
|
result
|
|
}
|
|
|
|
fn ensure_handle_is_not_filesystem_root(handle: &std::fs::File, path: &Path) -> Result<()> {
|
|
let mut buffer = [0_u16; 2];
|
|
let length = unsafe {
|
|
GetFinalPathNameByHandleW(
|
|
handle.as_raw_handle() as _,
|
|
buffer.as_mut_ptr(),
|
|
buffer.len() as u32,
|
|
VOLUME_NAME_NONE,
|
|
)
|
|
};
|
|
if length == 0 {
|
|
return Err(std::io::Error::last_os_error())
|
|
.with_context(|| format!("resolve deny-read ACL target {}", path.display()));
|
|
}
|
|
ensure!(
|
|
length != 1 || buffer[0] != b'\\' as u16,
|
|
"refusing to apply a deny-read ACE to filesystem root {}",
|
|
path.display()
|
|
);
|
|
Ok(())
|
|
}
|
|
|
|
/// Adds a deny ACE to prevent reads for the given SID on the target path.
|
|
///
|
|
/// `SetEntriesInAclW` places newly-created deny ACEs before allow ACEs, which
|
|
/// keeps the resulting DACL in the order Windows expects for denies to win.
|
|
/// The ACE is inheritable so a deny applied to a materialized directory also
|
|
/// covers files and directories later created underneath it.
|
|
///
|
|
/// # Safety
|
|
/// Caller must ensure `psid` points to a valid SID and `path` refers to an existing file or directory.
|
|
pub unsafe fn add_deny_read_ace(path: &Path, psid: *mut c_void) -> Result<bool> {
|
|
add_deny_ace(path, psid, DenyAceKind::Read)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
#[path = "acl_tests.rs"]
|
|
mod tests;
|
|
|
|
/// Removes explicit ACEs for one SID and propagates the updated inherited ACL.
|
|
///
|
|
/// # Safety
|
|
/// Caller must pass a valid SID pointer and have authority to edit the target DACL.
|
|
pub unsafe fn revoke_ace(path: &Path, psid: *mut c_void) -> Result<()> {
|
|
let mut p_sd: *mut c_void = std::ptr::null_mut();
|
|
let mut p_dacl: *mut ACL = std::ptr::null_mut();
|
|
let code = GetNamedSecurityInfoW(
|
|
to_wide(path).as_ptr(),
|
|
1,
|
|
DACL_SECURITY_INFORMATION,
|
|
std::ptr::null_mut(),
|
|
std::ptr::null_mut(),
|
|
&mut p_dacl,
|
|
std::ptr::null_mut(),
|
|
&mut p_sd,
|
|
);
|
|
if code != ERROR_SUCCESS {
|
|
if !p_sd.is_null() {
|
|
LocalFree(p_sd as HLOCAL);
|
|
}
|
|
return acl_api_result(path, "GetNamedSecurityInfoW", code);
|
|
}
|
|
if p_dacl.is_null() {
|
|
// A null DACL has no ACE to revoke; replacing it with an empty ACL would deny access.
|
|
if !p_sd.is_null() {
|
|
LocalFree(p_sd as HLOCAL);
|
|
}
|
|
return Ok(());
|
|
}
|
|
let trustee = TRUSTEE_W {
|
|
pMultipleTrustee: std::ptr::null_mut(),
|
|
MultipleTrusteeOperation: 0,
|
|
TrusteeForm: TRUSTEE_IS_SID,
|
|
TrusteeType: TRUSTEE_IS_UNKNOWN,
|
|
ptstrName: psid as *mut u16,
|
|
};
|
|
let mut explicit: EXPLICIT_ACCESS_W = std::mem::zeroed();
|
|
explicit.grfAccessPermissions = 0;
|
|
explicit.grfAccessMode = 4; // REVOKE_ACCESS
|
|
explicit.grfInheritance = CONTAINER_INHERIT_ACE | OBJECT_INHERIT_ACE;
|
|
explicit.Trustee = trustee;
|
|
let mut p_new_dacl: *mut ACL = std::ptr::null_mut();
|
|
let result = acl_api_result(
|
|
path,
|
|
"SetEntriesInAclW",
|
|
SetEntriesInAclW(1, &explicit, p_dacl, &mut p_new_dacl),
|
|
)
|
|
.and_then(|()| {
|
|
// REVOKE_ACCESS only removes ACEs. An unchanged ACL must not propagate inheritance.
|
|
if (*p_new_dacl).AceCount == (*p_dacl).AceCount {
|
|
return Ok(());
|
|
}
|
|
let code = SetNamedSecurityInfoW(
|
|
to_wide(path).as_ptr() as *mut u16,
|
|
1,
|
|
DACL_SECURITY_INFORMATION,
|
|
std::ptr::null_mut(),
|
|
std::ptr::null_mut(),
|
|
p_new_dacl,
|
|
std::ptr::null_mut(),
|
|
);
|
|
acl_api_result(path, "SetNamedSecurityInfoW", code)
|
|
});
|
|
if !p_new_dacl.is_null() {
|
|
LocalFree(p_new_dacl as HLOCAL);
|
|
}
|
|
if !p_sd.is_null() {
|
|
LocalFree(p_sd as HLOCAL);
|
|
}
|
|
result
|
|
}
|
|
|
|
/// Grants RX to the null device for the given SID to support stdout/stderr redirection.
|
|
///
|
|
/// # Safety
|
|
/// Caller must ensure `psid` is a valid SID pointer.
|
|
pub unsafe fn allow_null_device(psid: *mut c_void) {
|
|
let desired = 0x00020000 | 0x00040000; // READ_CONTROL | WRITE_DAC
|
|
let h = CreateFileW(
|
|
to_wide(r"\\\\.\\NUL").as_ptr(),
|
|
desired,
|
|
FILE_SHARE_READ | FILE_SHARE_WRITE,
|
|
std::ptr::null_mut(),
|
|
OPEN_EXISTING,
|
|
FILE_ATTRIBUTE_NORMAL,
|
|
std::ptr::null_mut(),
|
|
);
|
|
if h.is_null() || h == INVALID_HANDLE_VALUE {
|
|
return;
|
|
}
|
|
let mut p_sd: *mut c_void = std::ptr::null_mut();
|
|
let mut p_dacl: *mut ACL = std::ptr::null_mut();
|
|
let code = GetSecurityInfo(
|
|
h,
|
|
SE_KERNEL_OBJECT as i32,
|
|
DACL_SECURITY_INFORMATION,
|
|
std::ptr::null_mut(),
|
|
std::ptr::null_mut(),
|
|
&mut p_dacl,
|
|
std::ptr::null_mut(),
|
|
&mut p_sd,
|
|
);
|
|
if code == ERROR_SUCCESS {
|
|
let trustee = TRUSTEE_W {
|
|
pMultipleTrustee: std::ptr::null_mut(),
|
|
MultipleTrusteeOperation: 0,
|
|
TrusteeForm: TRUSTEE_IS_SID,
|
|
TrusteeType: TRUSTEE_IS_UNKNOWN,
|
|
ptstrName: psid as *mut u16,
|
|
};
|
|
let mut explicit: EXPLICIT_ACCESS_W = std::mem::zeroed();
|
|
explicit.grfAccessPermissions =
|
|
FILE_GENERIC_READ | FILE_GENERIC_WRITE | FILE_GENERIC_EXECUTE;
|
|
explicit.grfAccessMode = 2; // SET_ACCESS
|
|
explicit.grfInheritance = 0;
|
|
explicit.Trustee = trustee;
|
|
let mut p_new_dacl: *mut ACL = std::ptr::null_mut();
|
|
let code2 = SetEntriesInAclW(1, &explicit, p_dacl, &mut p_new_dacl);
|
|
if code2 == ERROR_SUCCESS {
|
|
let _ = SetSecurityInfo(
|
|
h,
|
|
SE_KERNEL_OBJECT as i32,
|
|
DACL_SECURITY_INFORMATION,
|
|
std::ptr::null_mut(),
|
|
std::ptr::null_mut(),
|
|
p_new_dacl,
|
|
std::ptr::null_mut(),
|
|
);
|
|
if !p_new_dacl.is_null() {
|
|
LocalFree(p_new_dacl as HLOCAL);
|
|
}
|
|
}
|
|
}
|
|
if !p_sd.is_null() {
|
|
LocalFree(p_sd as HLOCAL);
|
|
}
|
|
CloseHandle(h);
|
|
}
|
|
const CONTAINER_INHERIT_ACE: u32 = 0x2;
|
|
const OBJECT_INHERIT_ACE: u32 = 0x1;
|