use std::ffi::c_void;
use std::fs;
use std::io::{self, Write};
use std::os::windows::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use std::ptr::{self, NonNull};
use std::sync::OnceLock;
use std::time::{SystemTime, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
use windows::core::{PCWSTR, PWSTR};
use windows::Win32::Foundation::{
CloseHandle, GetLastError, LocalFree, ERROR_SUCCESS, FILETIME, HANDLE, HLOCAL, WAIT_ABANDONED,
WAIT_FAILED, WAIT_OBJECT_0, WAIT_TIMEOUT, WIN32_ERROR,
};
use windows::Win32::Security::Authorization::{
ConvertSidToStringSidW, ConvertStringSidToSidW, GetNamedSecurityInfoW, SetEntriesInAclW,
SetNamedSecurityInfoW, EXPLICIT_ACCESS_W, GRANT_ACCESS, SE_FILE_OBJECT, TRUSTEE_IS_SID,
TRUSTEE_IS_UNKNOWN, TRUSTEE_W,
};
use windows::Win32::Security::Authorization::DENY_ACCESS;
use windows::Win32::Security::{
AclSizeInformation, AddAccessAllowedAceEx, AddAccessDeniedAceEx, AddAce, EqualSid, GetAce,
GetAclInformation, GetLengthSid, GetTokenInformation, InitializeAcl, IsValidSid, TokenOwner,
TokenUser, ACCESS_ALLOWED_ACE, ACCESS_DENIED_ACE, ACE_FLAGS, ACE_HEADER, ACL, ACL_REVISION,
ACL_SIZE_INFORMATION, CONTAINER_INHERIT_ACE, DACL_SECURITY_INFORMATION, INHERITED_ACE,
OBJECT_INHERIT_ACE, OBJECT_SECURITY_INFORMATION, OWNER_SECURITY_INFORMATION,
PROTECTED_DACL_SECURITY_INFORMATION, PSECURITY_DESCRIPTOR, PSID, TOKEN_INFORMATION_CLASS,
TOKEN_OWNER, TOKEN_QUERY, TOKEN_USER,
};
use windows::Win32::Storage::FileSystem::{
DELETE, FILE_ALL_ACCESS, FILE_GENERIC_EXECUTE, FILE_GENERIC_READ, FILE_GENERIC_WRITE,
};
use windows::Win32::System::Threading::{
CreateMutexW, GetCurrentProcess, GetProcessTimes, OpenProcess, QueryFullProcessImageNameW,
ReleaseMutex, WaitForSingleObject, PROCESS_NAME_FORMAT, PROCESS_QUERY_LIMITED_INFORMATION,
};
pub const RW_MASK: u32 =
FILE_GENERIC_READ.0 | FILE_GENERIC_WRITE.0 | FILE_GENERIC_EXECUTE.0 | DELETE.0;
pub const RO_MASK: u32 = FILE_GENERIC_READ.0 | FILE_GENERIC_EXECUTE.0;
const _: () = {
assert!(
RW_MASK == FILE_GENERIC_READ.0 | FILE_GENERIC_WRITE.0 | FILE_GENERIC_EXECUTE.0 | DELETE.0
);
assert!(RO_MASK == FILE_GENERIC_READ.0 | FILE_GENERIC_EXECUTE.0);
assert!((RW_MASK & RO_MASK) == RO_MASK);
};
#[derive(Debug, thiserror::Error)]
pub enum DaclError {
#[error("path is not local (network/UNC paths not supported): {0}")]
NetworkPathRejected(PathBuf),
#[error("path does not exist: {0}")]
PathNotFound(PathBuf),
#[error("WRITE_DAC denied on {path}: {reason}")]
WriteDacDenied {
path: PathBuf,
reason: String,
},
#[error("path is not owned by this process identity: {0}")]
ForeignOwner(PathBuf),
#[error("Win32 error on {path}: {reason}")]
Win32 {
path: PathBuf,
reason: String,
},
#[error("state file I/O error: {0}")]
StateIo(#[from] io::Error),
#[error("state file parse error: {0}")]
StateParse(String),
#[error("invalid SID string: {0}")]
InvalidSid(String),
#[error("timed out acquiring DACL mutex on {path} after {timeout_ms} ms")]
MutexTimeout {
path: PathBuf,
timeout_ms: u32,
},
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum AceType {
Allow,
Deny,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub struct PriorAce {
pub ace_type: AceType,
pub access_mask: u32,
pub inherit_flags: u8,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppliedAce {
pub canonical_path: PathBuf,
pub sid_string: String,
pub access_mask: u32,
pub ace_type: AceType,
pub inheritable: bool,
#[serde(default)]
pub prior_state: Vec<PriorAce>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StateFile {
pub run_id: String,
pub pid: u32,
pub image_name: String,
pub started_at_filetime: u64,
pub applied: Vec<AppliedAce>,
}
#[derive(Debug)]
pub struct DaclManager {
run_id: String,
state_path: PathBuf,
applied: Vec<AppliedAce>,
warnings: Vec<String>,
process_start_filetime: u64,
}
#[derive(Debug, Default)]
pub struct RecoveryReport {
pub files_processed: usize,
pub aces_restored: usize,
pub aces_pruned_missing: usize,
pub errors: Vec<String>,
}
impl DaclManager {
pub fn new() -> Result<Self, DaclError> {
let state_dir = state_dir()?;
fs::create_dir_all(&state_dir)?;
let run_id = generate_run_id();
let state_path = state_dir.join(format!("{run_id}.json"));
let process_start_filetime = process_creation_filetime()?;
Ok(Self {
run_id,
state_path,
applied: Vec::new(),
warnings: Vec::new(),
process_start_filetime,
})
}
pub fn warnings(&self) -> &[String] {
&self.warnings
}
pub fn grant_appcontainer_access(
&mut self,
appcontainer_sid_str: &str,
readwrite: &[PathBuf],
readonly: &[PathBuf],
) -> Result<(), DaclError> {
for p in readwrite {
self.apply_one(appcontainer_sid_str, p, RW_MASK, AceType::Allow)?;
}
for p in readonly {
self.apply_one(appcontainer_sid_str, p, RO_MASK, AceType::Allow)?;
}
Ok(())
}
pub fn add_deny_aces(
&mut self,
appcontainer_sid_str: &str,
denied: &[PathBuf],
) -> Result<(), DaclError> {
let deny_mask: u32 = 0x001F_01FF;
for p in denied {
self.apply_one(appcontainer_sid_str, p, deny_mask, AceType::Deny)?;
}
Ok(())
}
pub fn restore(&mut self) -> Result<(), DaclError> {
let mut remaining: Vec<AppliedAce> = Vec::new();
while let Some(entry) = self.applied.pop() {
match restore_one(&entry) {
Ok(note) => {
if let Some(n) = note {
self.warnings.push(n);
}
}
Err(e) => {
self.warnings.push(format!(
"restore failed for {} (entry retained for retry): {}",
entry.canonical_path.display(),
e
));
remaining.push(entry);
}
}
}
remaining.reverse();
self.applied = remaining;
if self.applied.is_empty() {
let _ = fs::remove_file(&self.state_path);
} else {
self.persist_state()?;
}
Ok(())
}
fn apply_one(
&mut self,
sid_str: &str,
path: &Path,
mask: u32,
ace_type: AceType,
) -> Result<(), DaclError> {
let canonical = canonicalize_local(path)?;
let inheritable = fs::metadata(&canonical)
.map_err(|e| DaclError::Win32 {
path: canonical.clone(),
reason: format!("metadata: {e}"),
})?
.is_dir();
let _guard = PathMutexGuard::acquire(&canonical)?;
let prior_state = scan_explicit_aces_for_sid(&canonical, sid_str)?;
let entry = AppliedAce {
canonical_path: canonical.clone(),
sid_string: sid_str.to_string(),
access_mask: mask,
ace_type,
inheritable,
prior_state,
};
self.applied.push(entry.clone());
if let Err(e) = self.persist_state() {
self.applied.pop();
return Err(e);
}
apply_ace(&entry)
}
fn persist_state(&self) -> Result<(), DaclError> {
let state = StateFile {
run_id: self.run_id.clone(),
pid: std::process::id(),
image_name: current_image_basename(),
started_at_filetime: self.process_start_filetime,
applied: self.applied.clone(),
};
write_state_file(&self.state_path, &state)
}
}
impl Drop for DaclManager {
fn drop(&mut self) {
if let Err(e) = self.restore() {
eprintln!("DaclManager drop: restore failed: {e}");
}
}
}
pub fn recover_orphaned_state() -> Result<RecoveryReport, DaclError> {
let mut report = RecoveryReport::default();
let dir = match state_dir() {
Ok(d) => d,
Err(_) => return Ok(report),
};
let entries = match fs::read_dir(&dir) {
Ok(e) => e,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(report),
Err(e) => return Err(DaclError::StateIo(e)),
};
for entry in entries.flatten() {
let path = entry.path();
if path.extension().and_then(|s| s.to_str()) != Some("json") {
continue;
}
report.files_processed += 1;
let state = match read_state_file(&path) {
Ok(s) => s,
Err(e) => {
report
.errors
.push(format!("parse {}: {}", path.display(), e));
let corrupt = path.with_extension("json.corrupt");
if let Err(e2) = fs::rename(&path, &corrupt) {
report.errors.push(format!(
"quarantine {} -> {}: {}",
path.display(),
corrupt.display(),
e2
));
}
continue;
}
};
if process_alive_with_image(
state.pid,
&state.image_name,
Some(state.started_at_filetime),
) {
continue;
}
let mut remaining: Vec<AppliedAce> = Vec::new();
for ace in state.applied.iter().rev() {
if matches!(ace.canonical_path.try_exists(), Ok(false)) {
report.aces_pruned_missing += 1;
continue;
}
match restore_one(ace) {
Ok(_) => report.aces_restored += 1,
Err(e) => {
if matches!(ace.canonical_path.try_exists(), Ok(false)) {
report.aces_pruned_missing += 1;
} else {
report.errors.push(format!(
"restore {} (pid {}): {}",
ace.canonical_path.display(),
state.pid,
e
));
remaining.push(ace.clone());
}
}
}
}
if remaining.is_empty() {
if let Err(e) = fs::remove_file(&path) {
report
.errors
.push(format!("remove {}: {}", path.display(), e));
}
} else {
remaining.reverse();
let pending = StateFile {
run_id: state.run_id,
pid: state.pid,
image_name: state.image_name,
started_at_filetime: state.started_at_filetime,
applied: remaining,
};
if let Err(e) = write_state_file(&path, &pending) {
report
.errors
.push(format!("rewrite {}: {}", path.display(), e));
}
}
}
Ok(report)
}
fn state_dir() -> Result<PathBuf, DaclError> {
if let Some(d) = std::env::var_os("MXC_DACL_STATE_DIR") {
return Ok(PathBuf::from(d));
}
let base = std::env::var_os("LOCALAPPDATA")
.map(PathBuf::from)
.or_else(|| {
std::env::var_os("USERPROFILE").map(|p| PathBuf::from(p).join("AppData").join("Local"))
})
.ok_or_else(|| {
DaclError::StateIo(io::Error::new(
io::ErrorKind::NotFound,
"LOCALAPPDATA and USERPROFILE both unset",
))
})?;
Ok(base.join("Microsoft").join("MXC").join("dacl-restore"))
}
fn write_state_file(path: &Path, state: &StateFile) -> Result<(), DaclError> {
let json = serde_json::to_vec_pretty(state)
.map_err(|e| DaclError::StateParse(format!("serialize: {e}")))?;
let tmp = tmp_path_for(path);
match fs::remove_file(&tmp) {
Ok(()) => {}
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => {
eprintln!(
"DaclManager: pre-write cleanup of {} failed ({e}); \
if subsequent create_new fails, this file is the obstruction",
tmp.display()
);
}
}
{
let mut f = fs::OpenOptions::new()
.create_new(true)
.write(true)
.open(&tmp)?;
f.write_all(&json)?;
f.sync_all()?;
}
if let Err(e) = fs::rename(&tmp, path) {
let _ = fs::remove_file(&tmp);
return Err(DaclError::StateIo(e));
}
Ok(())
}
fn tmp_path_for(path: &Path) -> PathBuf {
let mut s = path.as_os_str().to_owned();
s.push(".tmp");
PathBuf::from(s)
}
fn read_state_file(path: &Path) -> Result<StateFile, DaclError> {
use windows::Win32::Foundation::{ERROR_LOCK_VIOLATION, ERROR_SHARING_VIOLATION};
const ATTEMPTS: u32 = 3;
let mut last_err: Option<io::Error> = None;
for i in 0..ATTEMPTS {
match fs::read(path) {
Ok(bytes) => {
return serde_json::from_slice(&bytes)
.map_err(|e| DaclError::StateParse(format!("{}: {e}", path.display())));
}
Err(e) => {
let transient = matches!(
e.raw_os_error().map(|c| c as u32),
Some(c) if c == ERROR_SHARING_VIOLATION.0 || c == ERROR_LOCK_VIOLATION.0
);
if !transient {
return Err(e.into());
}
last_err = Some(e);
if i + 1 < ATTEMPTS {
std::thread::sleep(std::time::Duration::from_millis(20u64 << i));
}
}
}
}
Err(DaclError::StateIo(last_err.unwrap_or_else(|| {
io::Error::other("read_state_file: retries exhausted on transient error")
})))
}
fn generate_run_id() -> String {
let pid = std::process::id();
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for b in pid.to_le_bytes().iter().chain(nanos.to_le_bytes().iter()) {
h ^= *b as u64;
h = h.wrapping_mul(0x100_0000_01b3);
}
format!("pid-{pid}-{:016x}", h)
}
fn current_image_basename() -> String {
std::env::current_exe()
.ok()
.and_then(|p| {
p.file_name()
.and_then(|s| s.to_str())
.map(|s| s.to_string())
})
.unwrap_or_else(|| "wxc-exec.exe".to_string())
}
fn ensure_local_canonical_prefix(canonical: &Path) -> Result<(), DaclError> {
let s = canonical.to_string_lossy();
let bytes = s.as_bytes();
if bytes.len() >= 8
&& &bytes[..4] == b"\\\\?\\"
&& bytes[4].eq_ignore_ascii_case(&b'U')
&& bytes[5].eq_ignore_ascii_case(&b'N')
&& bytes[6].eq_ignore_ascii_case(&b'C')
&& bytes[7] == b'\\'
{
return Err(DaclError::NetworkPathRejected(canonical.to_path_buf()));
}
if s.starts_with(r"\\?\") || s.starts_with(r"\\.\") {
return Ok(());
}
if s.starts_with(r"\\") {
return Err(DaclError::NetworkPathRejected(canonical.to_path_buf()));
}
Ok(())
}
fn canonicalize_local(path: &Path) -> Result<PathBuf, DaclError> {
let canonical = match fs::canonicalize(path) {
Ok(p) => p,
Err(e) if e.kind() == io::ErrorKind::NotFound => {
return Err(DaclError::PathNotFound(path.to_path_buf()));
}
Err(e) => {
return Err(DaclError::Win32 {
path: path.to_path_buf(),
reason: format!("canonicalize: {e}"),
});
}
};
ensure_local_canonical_prefix(&canonical)?;
Ok(canonical)
}
struct OwnedSid(PSID);
const MAX_SID_STRING_LEN: usize = 256;
impl OwnedSid {
fn parse(s: &str) -> Result<Self, DaclError> {
if s.is_empty() {
return Err(DaclError::InvalidSid("(empty)".to_string()));
}
if s.len() > MAX_SID_STRING_LEN {
return Err(DaclError::InvalidSid(format!(
"SID string too long ({} bytes, max {})",
s.len(),
MAX_SID_STRING_LEN
)));
}
let wide: Vec<u16> = s.encode_utf16().chain(std::iter::once(0)).collect();
let mut psid = PSID(ptr::null_mut());
unsafe {
ConvertStringSidToSidW(PCWSTR(wide.as_ptr()), &mut psid)
.map_err(|e| DaclError::InvalidSid(format!("{s}: {e}")))?;
if psid.0.is_null() || !IsValidSid(psid).as_bool() {
if !psid.0.is_null() {
let _ = LocalFree(Some(HLOCAL(psid.0)));
}
return Err(DaclError::InvalidSid(s.to_string()));
}
}
Ok(Self(psid))
}
fn as_psid(&self) -> PSID {
self.0
}
}
impl Drop for OwnedSid {
fn drop(&mut self) {
if !self.0 .0.is_null() {
unsafe {
let _ = LocalFree(Some(HLOCAL(self.0 .0)));
}
}
}
}
unsafe impl Send for OwnedSid {}
unsafe impl Sync for OwnedSid {}
fn well_known_ac_sids() -> &'static [OwnedSid] {
static CACHE: OnceLock<Vec<OwnedSid>> = OnceLock::new();
CACHE
.get_or_init(|| {
WELL_KNOWN_AC_SIDS
.iter()
.map(|s| OwnedSid::parse(s).expect("well-known AC SID must parse"))
.collect()
})
.as_slice()
}
fn fnv1a64(s: &str) -> u64 {
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for b in s.bytes() {
h ^= b as u64;
h = h.wrapping_mul(0x100_0000_01b3);
}
h
}
fn mutex_name_for(canonical: &Path) -> String {
let key = canonical.to_string_lossy().to_lowercase();
let h = fnv1a64(&key);
format!("Local\\Microsoft.MXC.Dacl.{:016x}", h)
}
struct PathMutexGuard {
handle: HANDLE,
acquired: bool,
}
const PATH_MUTEX_WAIT_MS: u32 = 30_000;
impl PathMutexGuard {
fn acquire(canonical: &Path) -> Result<Self, DaclError> {
let name = mutex_name_for(canonical);
let wide: Vec<u16> = name.encode_utf16().chain(std::iter::once(0)).collect();
let handle = unsafe { CreateMutexW(None, false, PCWSTR(wide.as_ptr())) }.map_err(|e| {
DaclError::Win32 {
path: canonical.to_path_buf(),
reason: format!("CreateMutexW: {e}"),
}
})?;
let wait = unsafe { WaitForSingleObject(handle, PATH_MUTEX_WAIT_MS) };
if wait == WAIT_OBJECT_0 {
return Ok(Self {
handle,
acquired: true,
});
}
if wait == WAIT_ABANDONED {
eprintln!(
"DaclManager: acquired abandoned mutex for {} (previous holder \
terminated without releasing; orphan recovery will reconcile)",
canonical.display()
);
return Ok(Self {
handle,
acquired: true,
});
}
let err = if wait == WAIT_TIMEOUT {
DaclError::MutexTimeout {
path: canonical.to_path_buf(),
timeout_ms: PATH_MUTEX_WAIT_MS,
}
} else if wait == WAIT_FAILED {
let last = unsafe { GetLastError() };
DaclError::Win32 {
path: canonical.to_path_buf(),
reason: format!("WaitForSingleObject failed: {last:?}"),
}
} else {
DaclError::Win32 {
path: canonical.to_path_buf(),
reason: format!("WaitForSingleObject unexpected result: {wait:?}"),
}
};
unsafe {
let _ = CloseHandle(handle);
}
Err(err)
}
}
impl Drop for PathMutexGuard {
fn drop(&mut self) {
unsafe {
if self.acquired {
let _ = ReleaseMutex(self.handle);
}
let _ = CloseHandle(self.handle);
}
}
}
fn wide(p: &Path) -> Vec<u16> {
p.as_os_str()
.encode_wide()
.chain(std::iter::once(0))
.collect()
}
fn trustee_for(sid: &OwnedSid) -> TRUSTEE_W {
TRUSTEE_W {
pMultipleTrustee: ptr::null_mut(),
MultipleTrusteeOperation: windows::Win32::Security::Authorization::NO_MULTIPLE_TRUSTEE,
TrusteeForm: TRUSTEE_IS_SID,
TrusteeType: TRUSTEE_IS_UNKNOWN,
ptstrName: PWSTR(sid.as_psid().0 as *mut u16),
}
}
fn apply_ace(entry: &AppliedAce) -> Result<(), DaclError> {
apply_explicit_ace(
&entry.canonical_path,
&entry.sid_string,
entry.access_mask,
entry.ace_type,
entry.inheritable,
)
}
pub fn apply_explicit_ace(
path: &Path,
sid_str: &str,
access_mask: u32,
ace_type: AceType,
inheritable: bool,
) -> Result<(), DaclError> {
let sid = OwnedSid::parse(sid_str)?;
let inheritance: u32 = if inheritable {
OBJECT_INHERIT_ACE.0 | CONTAINER_INHERIT_ACE.0
} else {
0
};
let mode = match ace_type {
AceType::Allow => GRANT_ACCESS,
AceType::Deny => DENY_ACCESS,
};
let ea = EXPLICIT_ACCESS_W {
grfAccessPermissions: access_mask,
grfAccessMode: mode,
grfInheritance: ACE_FLAGS(inheritance),
Trustee: trustee_for(&sid),
};
let path_w = wide(path);
let object_name = PCWSTR(path_w.as_ptr());
let mut existing_dacl: *mut ACL = ptr::null_mut();
let mut sd: PSECURITY_DESCRIPTOR = PSECURITY_DESCRIPTOR(ptr::null_mut());
let rc = unsafe {
GetNamedSecurityInfoW(
object_name,
SE_FILE_OBJECT,
DACL_SECURITY_INFORMATION,
None,
None,
Some(&mut existing_dacl),
None,
&mut sd,
)
};
if rc != ERROR_SUCCESS {
return Err(win32_err(path, "GetNamedSecurityInfoW", rc));
}
let mut new_dacl: *mut ACL = ptr::null_mut();
let rc = unsafe {
SetEntriesInAclW(
Some(&[ea]),
Some(existing_dacl as *const ACL),
&mut new_dacl,
)
};
if rc != ERROR_SUCCESS {
unsafe {
let _ = LocalFree(Some(HLOCAL(sd.0)));
}
return Err(win32_err(path, "SetEntriesInAclW", rc));
}
let rc = unsafe {
SetNamedSecurityInfoW(
object_name,
SE_FILE_OBJECT,
DACL_SECURITY_INFORMATION,
None,
None,
Some(new_dacl as *const ACL),
None,
)
};
unsafe {
if !new_dacl.is_null() {
let _ = LocalFree(Some(HLOCAL(new_dacl as *mut c_void)));
}
let _ = LocalFree(Some(HLOCAL(sd.0)));
}
if rc != ERROR_SUCCESS {
if rc.0 == 5 {
return Err(DaclError::WriteDacDenied {
path: path.to_path_buf(),
reason: format!("SetNamedSecurityInfoW: {rc:?}"),
});
}
return Err(win32_err(path, "SetNamedSecurityInfoW", rc));
}
Ok(())
}
fn token_sid(
token_information_class: TOKEN_INFORMATION_CLASS,
token_label: &str,
token_path: &Path,
sid_from_buffer: impl FnOnce(&[u8]) -> PSID,
) -> Result<OwnedSid, DaclError> {
use windows::Win32::System::Threading::OpenProcessToken;
unsafe {
let mut token = HANDLE::default();
OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token)
.map_err(|e| win32_err_str(token_path, &format!("OpenProcessToken: {e}")))?;
let _token = OwnedHandle(token);
let mut len = 0u32;
let probe = GetTokenInformation(token, token_information_class, None, 0, &mut len);
if probe.is_ok() || len == 0 {
return Err(win32_err_str(
token_path,
&format!("GetTokenInformation({token_label}) size probe: {probe:?}, len={len}"),
));
}
let mut buf = vec![0u8; len.max(1) as usize];
GetTokenInformation(
token,
token_information_class,
Some(buf.as_mut_ptr() as *mut c_void),
len,
&mut len,
)
.map_err(|e| {
win32_err_str(
token_path,
&format!("GetTokenInformation({token_label}): {e}"),
)
})?;
owned_sid_from_psid(sid_from_buffer(&buf), token_path, token_label)
}
}
fn owned_sid_from_psid(sid: PSID, path: &Path, context: &str) -> Result<OwnedSid, DaclError> {
let mut string_sid = PWSTR::null();
unsafe {
ConvertSidToStringSidW(sid, &mut string_sid)
.map_err(|e| win32_err_str(path, &format!("ConvertSidToStringSidW({context}): {e}")))?;
}
let sid_string = unsafe { string_sid.to_string() }
.map_err(|e| DaclError::InvalidSid(format!("{context} SID string not UTF-16: {e}")));
if !string_sid.is_null() {
unsafe {
let _ = LocalFree(Some(HLOCAL(string_sid.0 as *mut c_void)));
}
}
OwnedSid::parse(&sid_string?)
}
fn current_user_sid() -> Result<OwnedSid, DaclError> {
token_sid(
TokenUser,
"TokenUser",
Path::new("<process token>"),
|buf| {
unsafe { (*(buf.as_ptr() as *const TOKEN_USER)).User.Sid }
},
)
}
fn current_token_owner_sid() -> Result<OwnedSid, DaclError> {
token_sid(
TokenOwner,
"TokenOwner",
Path::new("<process token owner>"),
|buf| {
unsafe { (*(buf.as_ptr() as *const TOKEN_OWNER)).Owner }
},
)
}
fn self_owner_sids() -> Result<Vec<OwnedSid>, DaclError> {
let mut sids = vec![current_user_sid()?];
if let Ok(owner) = current_token_owner_sid() {
sids.push(owner);
}
Ok(sids)
}
pub fn owner_is_self(path: &Path) -> Result<bool, DaclError> {
let mine = self_owner_sids()?;
let path_w = wide(path);
let mut owner_psid: PSID = PSID(ptr::null_mut());
let mut sd: PSECURITY_DESCRIPTOR = PSECURITY_DESCRIPTOR(ptr::null_mut());
let rc = unsafe {
GetNamedSecurityInfoW(
PCWSTR(path_w.as_ptr()),
SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION,
Some(&mut owner_psid),
None,
None,
None,
&mut sd,
)
};
if rc != ERROR_SUCCESS {
return Err(win32_err(path, "GetNamedSecurityInfoW(owner)", rc));
}
let mut is_self = false;
if !owner_psid.0.is_null() {
for sid in &mine {
if unsafe { EqualSid(owner_psid, sid.as_psid()).is_ok() } {
is_self = true;
break;
}
}
}
unsafe {
let _ = LocalFree(Some(HLOCAL(sd.0)));
}
Ok(is_self)
}
pub fn set_owner_only_dacl(path: &Path, inheritable: bool) -> Result<(), DaclError> {
if !owner_is_self(path)? {
return Err(DaclError::ForeignOwner(path.to_path_buf()));
}
let user = current_user_sid()?;
let system = OwnedSid::parse("S-1-5-18")?;
let inheritance: u32 = if inheritable {
OBJECT_INHERIT_ACE.0 | CONTAINER_INHERIT_ACE.0
} else {
0
};
let mask = FILE_ALL_ACCESS.0;
let grant = |sid: &OwnedSid| EXPLICIT_ACCESS_W {
grfAccessPermissions: mask,
grfAccessMode: GRANT_ACCESS,
grfInheritance: ACE_FLAGS(inheritance),
Trustee: trustee_for(sid),
};
let access_entries = [grant(&user), grant(&system)];
let mut new_dacl: *mut ACL = ptr::null_mut();
let rc = unsafe { SetEntriesInAclW(Some(&access_entries), None, &mut new_dacl) };
if rc != ERROR_SUCCESS {
return Err(win32_err(path, "SetEntriesInAclW", rc));
}
let path_w = wide(path);
let info = OBJECT_SECURITY_INFORMATION(
DACL_SECURITY_INFORMATION.0 | PROTECTED_DACL_SECURITY_INFORMATION.0,
);
let rc = unsafe {
SetNamedSecurityInfoW(
PCWSTR(path_w.as_ptr()),
SE_FILE_OBJECT,
info,
None,
None,
Some(new_dacl as *const ACL),
None,
)
};
unsafe {
if !new_dacl.is_null() {
let _ = LocalFree(Some(HLOCAL(new_dacl as *mut c_void)));
}
}
if rc != ERROR_SUCCESS {
return Err(win32_err(path, "SetNamedSecurityInfoW", rc));
}
Ok(())
}
pub fn revoke_specific_aces_for_sid(
path: &Path,
sid_str: &str,
access_mask: u32,
ace_type: AceType,
inheritable: bool,
) -> Result<usize, DaclError> {
let expected_inherit_flags: u8 = if inheritable {
(OBJECT_INHERIT_ACE.0 | CONTAINER_INHERIT_ACE.0) as u8
} else {
0
};
let priors = scan_explicit_aces_for_sid(path, sid_str)?;
let mut keeps: Vec<PriorAce> = Vec::new();
let mut removed = 0usize;
for p in priors {
if p.access_mask == access_mask
&& p.ace_type == ace_type
&& p.inherit_flags == expected_inherit_flags
{
removed += 1;
} else {
keeps.push(p);
}
}
if removed == 0 {
return Ok(0);
}
replace_explicit_aces_for_sid(path, sid_str, &keeps)?;
Ok(removed)
}
fn restore_one(entry: &AppliedAce) -> Result<Option<String>, DaclError> {
let _guard = PathMutexGuard::acquire(&entry.canonical_path)?;
replace_explicit_aces_for_sid(&entry.canonical_path, &entry.sid_string, &entry.prior_state)?;
Ok(None)
}
pub fn scan_explicit_aces_for_sid(
canonical: &Path,
sid_str: &str,
) -> Result<Vec<PriorAce>, DaclError> {
let sid = OwnedSid::parse(sid_str)?;
let path_w = wide(canonical);
let object_name = PCWSTR(path_w.as_ptr());
let mut existing_dacl: *mut ACL = ptr::null_mut();
let mut sd: PSECURITY_DESCRIPTOR = PSECURITY_DESCRIPTOR(ptr::null_mut());
let rc = unsafe {
GetNamedSecurityInfoW(
object_name,
SE_FILE_OBJECT,
DACL_SECURITY_INFORMATION,
None,
None,
Some(&mut existing_dacl),
None,
&mut sd,
)
};
if rc != ERROR_SUCCESS {
return Err(win32_err(canonical, "GetNamedSecurityInfoW", rc));
}
if existing_dacl.is_null() {
unsafe {
let _ = LocalFree(Some(HLOCAL(sd.0)));
}
return Ok(Vec::new());
}
let mut info = ACL_SIZE_INFORMATION::default();
let info_sz = std::mem::size_of::<ACL_SIZE_INFORMATION>() as u32;
let scan_res = unsafe {
GetAclInformation(
existing_dacl,
&mut info as *mut _ as *mut c_void,
info_sz,
AclSizeInformation,
)
};
if let Err(e) = scan_res {
unsafe {
let _ = LocalFree(Some(HLOCAL(sd.0)));
}
return Err(win32_err_str(canonical, &format!("GetAclInformation: {e}")));
}
let mut prior: Vec<PriorAce> = Vec::new();
let inherited_bit = INHERITED_ACE.0 as u8;
for i in 0..info.AceCount {
let mut ace_ptr: *mut c_void = ptr::null_mut();
let gace = unsafe { GetAce(existing_dacl, i, &mut ace_ptr) };
if gace.is_err() {
continue;
}
let Some(ace_ptr) = NonNull::new(ace_ptr) else {
continue;
};
let header = unsafe { ace_ptr.cast::<ACE_HEADER>().as_ref() };
if (header.AceFlags & inherited_bit) != 0 {
continue;
}
let ace_type = match header.AceType {
0x00 => AceType::Allow, 0x01 => AceType::Deny, _ => continue, };
let mask_and_sid = unsafe { ace_ptr.cast::<ACCESS_ALLOWED_ACE>().as_ref() };
let ace_mask = mask_and_sid.Mask;
let ace_sid = PSID(&mask_and_sid.SidStart as *const _ as *mut c_void);
if unsafe { EqualSid(ace_sid, sid.as_psid()).is_ok() } {
prior.push(PriorAce {
ace_type,
access_mask: ace_mask,
inherit_flags: header.AceFlags & !inherited_bit,
});
}
}
let _ = std::mem::size_of::<ACCESS_DENIED_ACE>();
unsafe {
let _ = LocalFree(Some(HLOCAL(sd.0)));
}
Ok(prior)
}
const WELL_KNOWN_AC_SIDS: &[&str] = &["S-1-15-2-1", "S-1-15-2-2", "S-1-1-0"];
pub fn compute_appcontainer_effective_access(path: &Path) -> Result<u32, DaclError> {
let well_known = well_known_ac_sids();
let path_w = wide(path);
let object_name = PCWSTR(path_w.as_ptr());
let mut dacl: *mut ACL = ptr::null_mut();
let mut sd: PSECURITY_DESCRIPTOR = PSECURITY_DESCRIPTOR(ptr::null_mut());
let rc = unsafe {
GetNamedSecurityInfoW(
object_name,
SE_FILE_OBJECT,
DACL_SECURITY_INFORMATION,
None,
None,
Some(&mut dacl),
None,
&mut sd,
)
};
if rc != ERROR_SUCCESS {
return Err(win32_err(path, "GetNamedSecurityInfoW", rc));
}
if dacl.is_null() {
unsafe {
let _ = LocalFree(Some(HLOCAL(sd.0)));
}
return Ok(0);
}
let mut info = ACL_SIZE_INFORMATION::default();
let info_sz = std::mem::size_of::<ACL_SIZE_INFORMATION>() as u32;
let scan_res = unsafe {
GetAclInformation(
dacl,
&mut info as *mut _ as *mut c_void,
info_sz,
AclSizeInformation,
)
};
if let Err(e) = scan_res {
unsafe {
let _ = LocalFree(Some(HLOCAL(sd.0)));
}
return Err(win32_err_str(path, &format!("GetAclInformation: {e}")));
}
let mut allowed: u32 = 0;
let mut denied: u32 = 0;
for i in 0..info.AceCount {
let mut ace_ptr: *mut c_void = ptr::null_mut();
if unsafe { GetAce(dacl, i, &mut ace_ptr) }.is_err() {
continue;
}
let Some(ace_ptr) = NonNull::new(ace_ptr) else {
continue;
};
let header = unsafe { ace_ptr.cast::<ACE_HEADER>().as_ref() };
let ace_type = match header.AceType {
0x00 => AceType::Allow,
0x01 => AceType::Deny,
_ => continue, };
let mask_and_sid = unsafe { ace_ptr.cast::<ACCESS_ALLOWED_ACE>().as_ref() };
let ace_mask = mask_and_sid.Mask;
let ace_sid = PSID(&mask_and_sid.SidStart as *const _ as *mut c_void);
let matches = well_known
.iter()
.any(|s| unsafe { EqualSid(ace_sid, s.as_psid()).is_ok() });
if !matches {
continue;
}
match ace_type {
AceType::Deny => {
denied |= ace_mask & !allowed;
}
AceType::Allow => {
allowed |= ace_mask & !denied;
}
}
}
let _ = std::mem::size_of::<ACCESS_DENIED_ACE>();
unsafe {
let _ = LocalFree(Some(HLOCAL(sd.0)));
}
Ok(allowed)
}
pub fn null_device_appcontainer_grants() -> Option<bool> {
use windows::Win32::Foundation::GENERIC_READ;
use windows::Win32::Security::Authorization::{GetSecurityInfo, SE_KERNEL_OBJECT};
use windows::Win32::Storage::FileSystem::{
CreateFileW, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE,
OPEN_EXISTING,
};
const READ_CONTROL: u32 = 0x0002_0000;
let path: Vec<u16> = "\\\\.\\NUL\0".encode_utf16().collect();
let share = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
let handle = unsafe {
CreateFileW(
PCWSTR(path.as_ptr()),
GENERIC_READ.0 | READ_CONTROL,
share,
None,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
None,
)
};
let handle = match handle {
Ok(h) if !h.is_invalid() => h,
_ => return None,
};
let mut dacl: *mut ACL = ptr::null_mut();
let mut sd: PSECURITY_DESCRIPTOR = PSECURITY_DESCRIPTOR(ptr::null_mut());
let rc = unsafe {
GetSecurityInfo(
handle,
SE_KERNEL_OBJECT,
DACL_SECURITY_INFORMATION,
None,
None,
Some(&mut dacl),
None,
Some(&mut sd),
)
};
unsafe {
let _ = CloseHandle(handle);
}
if rc != ERROR_SUCCESS {
return None;
}
if dacl.is_null() {
unsafe {
let _ = LocalFree(Some(HLOCAL(sd.0)));
}
return Some(true);
}
let sids = match (OwnedSid::parse("S-1-15-2-1"), OwnedSid::parse("S-1-15-2-2")) {
(Ok(a), Ok(b)) => [a, b],
_ => {
unsafe {
let _ = LocalFree(Some(HLOCAL(sd.0)));
}
return None;
}
};
let mut info = ACL_SIZE_INFORMATION::default();
let info_sz = std::mem::size_of::<ACL_SIZE_INFORMATION>() as u32;
if unsafe {
GetAclInformation(
dacl,
&mut info as *mut _ as *mut c_void,
info_sz,
AclSizeInformation,
)
}
.is_err()
{
unsafe {
let _ = LocalFree(Some(HLOCAL(sd.0)));
}
return None;
}
let mut granted = [false; 2];
for i in 0..info.AceCount {
let mut ace_ptr: *mut c_void = ptr::null_mut();
if unsafe { GetAce(dacl, i, &mut ace_ptr) }.is_err() {
continue;
}
let Some(ace_ptr) = NonNull::new(ace_ptr) else {
continue;
};
let header = unsafe { ace_ptr.cast::<ACE_HEADER>().as_ref() };
if header.AceType != 0x00 {
continue;
}
let allowed = unsafe { ace_ptr.cast::<ACCESS_ALLOWED_ACE>().as_ref() };
let mask = allowed.Mask;
if mask == 0 {
continue;
}
let ace_sid = PSID(&allowed.SidStart as *const _ as *mut c_void);
for (idx, want) in sids.iter().enumerate() {
if unsafe { EqualSid(ace_sid, want.as_psid()).is_ok() } {
granted[idx] = true;
}
}
}
unsafe {
let _ = LocalFree(Some(HLOCAL(sd.0)));
}
Some(granted[0] && granted[1])
}
fn replace_explicit_aces_for_sid(
path: &Path,
sid_str: &str,
replay: &[PriorAce],
) -> Result<(), DaclError> {
let sid = OwnedSid::parse(sid_str)?;
let path_w = wide(path);
let object_name = PCWSTR(path_w.as_ptr());
let mut existing_dacl: *mut ACL = ptr::null_mut();
let mut sd: PSECURITY_DESCRIPTOR = PSECURITY_DESCRIPTOR(ptr::null_mut());
let rc = unsafe {
GetNamedSecurityInfoW(
object_name,
SE_FILE_OBJECT,
DACL_SECURITY_INFORMATION,
None,
None,
Some(&mut existing_dacl),
None,
&mut sd,
)
};
if rc != ERROR_SUCCESS {
return Err(win32_err(path, "GetNamedSecurityInfoW", rc));
}
let result = replace_explicit_aces_for_sid_inner(path, &sid, existing_dacl, replay);
unsafe {
let _ = LocalFree(Some(HLOCAL(sd.0)));
}
result.and_then(|new_acl_dwords| {
let new_acl_ptr = new_acl_dwords.as_ptr() as *const ACL;
let rc = unsafe {
SetNamedSecurityInfoW(
object_name,
SE_FILE_OBJECT,
DACL_SECURITY_INFORMATION,
None,
None,
Some(new_acl_ptr),
None,
)
};
if rc != ERROR_SUCCESS {
if rc.0 == 5 {
return Err(DaclError::WriteDacDenied {
path: path.to_path_buf(),
reason: format!("SetNamedSecurityInfoW: {rc:?}"),
});
}
return Err(win32_err(path, "SetNamedSecurityInfoW", rc));
}
Ok(())
})
}
fn canonical_bucket(ace_type: u8, inherited: bool) -> u8 {
if inherited {
3
} else {
match ace_type {
0x01 => 0,
0x00 => 1,
_ => 2,
}
}
}
fn replace_explicit_aces_for_sid_inner(
path: &Path,
sid: &OwnedSid,
existing_dacl: *mut ACL,
replay: &[PriorAce],
) -> Result<Vec<u32>, DaclError> {
enum Entry<'a> {
Kept {
ptr: *mut c_void,
size: u32,
bucket: u8,
order: u32,
},
Replay {
prior: &'a PriorAce,
bucket: u8,
order: u32,
},
}
let mut entries: Vec<Entry> = Vec::new();
let mut keeps_bytes: u32 = 0;
let mut next_order: u32 = 0;
if !existing_dacl.is_null() {
let mut info = ACL_SIZE_INFORMATION::default();
let info_sz = std::mem::size_of::<ACL_SIZE_INFORMATION>() as u32;
unsafe {
GetAclInformation(
existing_dacl,
&mut info as *mut _ as *mut c_void,
info_sz,
AclSizeInformation,
)
.map_err(|e| win32_err_str(path, &format!("GetAclInformation: {e}")))?;
}
let inherited_bit = INHERITED_ACE.0 as u8;
for i in 0..info.AceCount {
let mut ace_ptr: *mut c_void = ptr::null_mut();
if unsafe { GetAce(existing_dacl, i, &mut ace_ptr) }.is_err() {
continue;
}
let Some(ace_ptr) = NonNull::new(ace_ptr) else {
continue;
};
let header = unsafe { ace_ptr.cast::<ACE_HEADER>().as_ref() };
let inherited = (header.AceFlags & inherited_bit) != 0;
let mut drop_it = false;
if !inherited && (header.AceType == 0x00 || header.AceType == 0x01) {
let ace_struct = unsafe { ace_ptr.cast::<ACCESS_ALLOWED_ACE>().as_ref() };
let ace_sid = PSID(&ace_struct.SidStart as *const _ as *mut c_void);
if unsafe { EqualSid(ace_sid, sid.as_psid()).is_ok() } {
drop_it = true;
}
}
if !drop_it {
entries.push(Entry::Kept {
ptr: ace_ptr.as_ptr(),
size: header.AceSize as u32,
bucket: canonical_bucket(header.AceType, inherited),
order: next_order,
});
next_order += 1;
keeps_bytes += header.AceSize as u32;
}
}
}
for prior in replay {
let ace_type_byte = match prior.ace_type {
AceType::Allow => 0x00u8,
AceType::Deny => 0x01u8,
};
entries.push(Entry::Replay {
prior,
bucket: canonical_bucket(ace_type_byte, false),
order: next_order,
});
next_order += 1;
}
entries.sort_by_key(|e| match e {
Entry::Kept { bucket, order, .. } | Entry::Replay { bucket, order, .. } => {
(*bucket, *order)
}
});
let sid_len: u32 = unsafe { GetLengthSid(sid.as_psid()) };
let per_replay_size: u32 = 8 + sid_len;
let replay_bytes: u32 = per_replay_size.saturating_mul(replay.len() as u32);
let mut new_acl_size: u32 = std::mem::size_of::<ACL>() as u32 + keeps_bytes + replay_bytes;
new_acl_size = (new_acl_size + 3) & !3;
let min_acl_size = std::mem::size_of::<ACL>() as u32;
if new_acl_size < min_acl_size {
new_acl_size = min_acl_size;
}
let dwords = (new_acl_size as usize).div_ceil(4);
let mut new_acl_buf: Vec<u32> = vec![0u32; dwords];
let new_acl_ptr = new_acl_buf.as_mut_ptr() as *mut ACL;
unsafe {
InitializeAcl(new_acl_ptr, new_acl_size, ACL_REVISION)
.map_err(|e| win32_err_str(path, &format!("InitializeAcl: {e}")))?;
}
for entry in &entries {
match entry {
Entry::Kept { ptr, size, .. } => unsafe {
AddAce(new_acl_ptr, ACL_REVISION, u32::MAX, *ptr, *size)
.map_err(|e| win32_err_str(path, &format!("AddAce(keep): {e}")))?;
},
Entry::Replay { prior, .. } => {
let flags = ACE_FLAGS(prior.inherit_flags as u32);
let res = unsafe {
match prior.ace_type {
AceType::Allow => AddAccessAllowedAceEx(
new_acl_ptr,
ACL_REVISION,
flags,
prior.access_mask,
sid.as_psid(),
),
AceType::Deny => AddAccessDeniedAceEx(
new_acl_ptr,
ACL_REVISION,
flags,
prior.access_mask,
sid.as_psid(),
),
}
};
res.map_err(|e| {
win32_err_str(path, &format!("AddAccess{:?}AceEx: {e}", prior.ace_type))
})?;
}
}
}
Ok(new_acl_buf)
}
fn win32_err(path: &Path, op: &str, rc: WIN32_ERROR) -> DaclError {
DaclError::Win32 {
path: path.to_path_buf(),
reason: format!("{op}: {rc:?}"),
}
}
fn win32_err_str(path: &Path, msg: &str) -> DaclError {
DaclError::Win32 {
path: path.to_path_buf(),
reason: msg.to_string(),
}
}
struct OwnedHandle(HANDLE);
impl Drop for OwnedHandle {
fn drop(&mut self) {
if !self.0.is_invalid() {
unsafe {
let _ = CloseHandle(self.0);
}
}
}
}
fn process_alive_with_image(
pid: u32,
expected_image: &str,
expected_start_filetime: Option<u64>,
) -> bool {
if pid == 0 {
return false;
}
let handle = match unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) } {
Ok(h) if !h.is_invalid() => OwnedHandle(h),
_ => return false,
};
let mut buf = [0u16; 1024];
let mut sz: u32 = buf.len() as u32;
let ok = unsafe {
QueryFullProcessImageNameW(
handle.0,
PROCESS_NAME_FORMAT(0),
PWSTR(buf.as_mut_ptr()),
&mut sz,
)
};
if ok.is_err() || sz == 0 {
return false;
}
let full = String::from_utf16_lossy(&buf[..sz as usize]);
let basename = std::path::Path::new(&full)
.file_name()
.and_then(|s| s.to_str())
.unwrap_or("");
if !basename.eq_ignore_ascii_case(expected_image) {
return false;
}
let recorded = match expected_start_filetime {
Some(0) | None => return true,
Some(v) => v,
};
let mut creation = FILETIME::default();
let mut exit = FILETIME::default();
let mut kernel = FILETIME::default();
let mut user = FILETIME::default();
let gpt =
unsafe { GetProcessTimes(handle.0, &mut creation, &mut exit, &mut kernel, &mut user) };
if gpt.is_err() {
return false;
}
let live = ((creation.dwHighDateTime as u64) << 32) | (creation.dwLowDateTime as u64);
live == recorded
}
fn process_creation_filetime() -> Result<u64, DaclError> {
unsafe {
let h = GetCurrentProcess();
let mut creation = FILETIME::default();
let mut exit = FILETIME::default();
let mut kernel = FILETIME::default();
let mut user = FILETIME::default();
GetProcessTimes(h, &mut creation, &mut exit, &mut kernel, &mut user).map_err(|e| {
DaclError::Win32 {
path: PathBuf::new(),
reason: format!("GetProcessTimes(GetCurrentProcess): {e}"),
}
})?;
Ok(((creation.dwHighDateTime as u64) << 32) | (creation.dwLowDateTime as u64))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn owner_is_self_true_for_dir_we_create() {
let dir = std::env::temp_dir().join(format!(
"wxc-dacl-owner-test-{}-{}",
std::process::id(),
generate_run_id()
));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).expect("create test dir");
let owned = owner_is_self(&dir).expect("read owner");
assert!(
owned,
"a directory created by this process must be owned by us"
);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn owner_is_self_true_after_owner_only_stamp() {
let dir = std::env::temp_dir().join(format!(
"wxc-dacl-secure-test-{}-{}",
std::process::id(),
generate_run_id()
));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).expect("create test dir");
set_owner_only_dacl(&dir, true).expect("secure dir");
assert!(
owner_is_self(&dir).expect("read owner"),
"owner must be unchanged by stamping an owner-only DACL"
);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn state_file_roundtrip() {
let s = StateFile {
run_id: "pid-42-deadbeef".into(),
pid: 42,
image_name: "wxc-exec.exe".into(),
started_at_filetime: 132_000_000_000_000_000,
applied: vec![AppliedAce {
canonical_path: PathBuf::from(r"\\?\C:\tmp\foo"),
sid_string: "S-1-15-2-1-2-3-4-5-6-7".into(),
access_mask: 0x12_3456,
ace_type: AceType::Allow,
inheritable: true,
prior_state: vec![PriorAce {
ace_type: AceType::Allow,
access_mask: 0x01FF,
inherit_flags: (OBJECT_INHERIT_ACE.0 | CONTAINER_INHERIT_ACE.0) as u8,
}],
}],
};
let bytes = serde_json::to_vec(&s).unwrap();
let parsed: StateFile = serde_json::from_slice(&bytes).unwrap();
assert_eq!(parsed.run_id, s.run_id);
assert_eq!(parsed.pid, s.pid);
assert_eq!(parsed.started_at_filetime, s.started_at_filetime);
assert_eq!(parsed.applied.len(), 1);
assert_eq!(parsed.applied[0].access_mask, 0x12_3456);
assert_eq!(parsed.applied[0].ace_type, AceType::Allow);
assert_eq!(parsed.applied[0].prior_state.len(), 1);
assert_eq!(parsed.applied[0].prior_state[0].access_mask, 0x01FF);
}
#[test]
fn state_file_back_compat_no_prior_state_field() {
let json = br#"{
"run_id": "pid-1-old",
"pid": 1,
"image_name": "wxc-exec.exe",
"started_at_filetime": 132000000000000000,
"applied": [{
"canonical_path": "\\\\?\\C:\\tmp\\foo",
"sid_string": "S-1-1-0",
"access_mask": 1,
"ace_type": "Allow",
"inheritable": false,
"pre_existing": false
}]
}"#;
let parsed: StateFile = serde_json::from_slice(json).expect("legacy state must parse");
assert!(parsed.applied[0].prior_state.is_empty());
}
#[test]
fn process_creation_time_is_after_unix_epoch_and_not_in_the_future() {
let t = process_creation_filetime().expect("GetProcessTimes should succeed");
const UNIX_EPOCH_AS_FILETIME: u64 = 11_644_473_600 * 10_000_000;
assert!(
t > UNIX_EPOCH_AS_FILETIME,
"process_creation_filetime ({t}) should be > Unix epoch ({UNIX_EPOCH_AS_FILETIME})"
);
let now_ft = unsafe {
use windows::Win32::System::SystemInformation::GetSystemTimeAsFileTime;
let ft = GetSystemTimeAsFileTime();
((ft.dwHighDateTime as u64) << 32) | (ft.dwLowDateTime as u64)
};
const TEN_SECONDS_TICKS: u64 = 10 * 10_000_000;
assert!(
t <= now_ft.saturating_add(TEN_SECONDS_TICKS),
"process_creation_filetime ({t}) must not be after now ({now_ft})"
);
}
#[test]
fn ensure_local_canonical_prefix_accepts_local() {
assert!(ensure_local_canonical_prefix(Path::new(r"\\?\C:\tmp\foo")).is_ok());
assert!(ensure_local_canonical_prefix(Path::new(
r"\\.\Volume{12345678-1234-1234-1234-123456789abc}\foo"
))
.is_ok());
assert!(ensure_local_canonical_prefix(Path::new(r"\\.\C:\tmp\foo")).is_ok());
assert!(ensure_local_canonical_prefix(Path::new(r"C:\tmp\foo")).is_ok());
}
#[test]
fn ensure_local_canonical_prefix_rejects_unc_namespace() {
let err = ensure_local_canonical_prefix(Path::new(r"\\?\UNC\server\share\foo"));
assert!(matches!(err, Err(DaclError::NetworkPathRejected(_))));
let err = ensure_local_canonical_prefix(Path::new(r"\\?\unc\server\share\foo"));
assert!(matches!(err, Err(DaclError::NetworkPathRejected(_))));
}
#[test]
fn ensure_local_canonical_prefix_rejects_raw_unc() {
let err = ensure_local_canonical_prefix(Path::new(r"\\server\share\foo"));
assert!(matches!(err, Err(DaclError::NetworkPathRejected(_))));
}
#[test]
fn mutex_name_is_deterministic_and_local_prefix() {
let p = PathBuf::from(r"C:\tmp\foo");
let n1 = mutex_name_for(&p);
let n2 = mutex_name_for(&p);
assert_eq!(n1, n2);
assert!(n1.starts_with("Local\\Microsoft.MXC.Dacl."));
assert_eq!(n1.len(), "Local\\Microsoft.MXC.Dacl.".len() + 16);
}
#[test]
fn mutex_name_case_insensitive() {
let a = mutex_name_for(&PathBuf::from(r"C:\Tmp\Foo"));
let b = mutex_name_for(&PathBuf::from(r"c:\tmp\foo"));
assert_eq!(a, b);
}
#[test]
fn access_mask_layouts() {
let rw = FILE_GENERIC_READ.0 | FILE_GENERIC_WRITE.0 | FILE_GENERIC_EXECUTE.0 | DELETE.0;
let ro = FILE_GENERIC_READ.0 | FILE_GENERIC_EXECUTE.0;
assert_ne!(rw, 0);
assert_ne!(ro, 0);
assert!(rw & ro == ro, "rw should be a superset of ro");
assert!(rw & 0x20 == 0x20, "rw must grant FILE_TRAVERSE");
assert!(ro & 0x20 == 0x20, "ro must grant FILE_TRAVERSE");
assert_eq!(0x001F_01FF & 0xFF_FFFF, 0x001F_01FF);
}
#[test]
fn sid_parse_valid_and_invalid() {
let ok = OwnedSid::parse("S-1-1-0");
assert!(ok.is_ok(), "S-1-1-0 should parse: {:?}", ok.err());
drop(ok);
let err = OwnedSid::parse("not-a-sid");
assert!(matches!(err, Err(DaclError::InvalidSid(_))));
}
#[test]
fn sid_parse_rejects_empty_and_oversized() {
let empty = OwnedSid::parse("");
assert!(matches!(empty, Err(DaclError::InvalidSid(_))));
let huge = "S-1-".to_string() + &"1".repeat(MAX_SID_STRING_LEN);
let err = OwnedSid::parse(&huge);
assert!(matches!(err, Err(DaclError::InvalidSid(_))));
}
#[test]
fn image_name_compare_case_insensitive() {
let a = "wxc-exec.exe";
let b = "WXC-EXEC.EXE";
assert!(a.eq_ignore_ascii_case(b));
}
#[test]
fn run_id_format() {
let id = generate_run_id();
assert!(id.starts_with("pid-"));
let parts: Vec<&str> = id.split('-').collect();
assert_eq!(parts.len(), 3);
assert_eq!(parts[2].len(), 16);
assert!(parts[2].chars().all(|c| c.is_ascii_hexdigit()));
}
#[test]
fn recovery_ignores_active_pid() {
let pid = std::process::id();
let img = current_image_basename();
let start = process_creation_filetime().unwrap();
assert!(process_alive_with_image(pid, &img, Some(start)));
assert!(process_alive_with_image(pid, &img, None));
assert!(process_alive_with_image(pid, &img, Some(0)));
}
#[test]
fn recovery_detects_dead_pid() {
assert!(!process_alive_with_image(0, "anything.exe", None));
assert!(!process_alive_with_image(0x7FFF_FFFE, "wxc-exec.exe", None));
}
#[test]
fn recovery_detects_pid_reuse_via_creation_time() {
let pid = std::process::id();
let img = current_image_basename();
const Y2K_FILETIME: u64 = 125_911_584_000_000_000;
assert!(!process_alive_with_image(pid, &img, Some(Y2K_FILETIME)));
}
#[test]
fn recovery_detects_pid_reuse_off_by_one_tick() {
let pid = std::process::id();
let img = current_image_basename();
let real = process_creation_filetime().unwrap();
assert!(!process_alive_with_image(
pid,
&img,
Some(real.saturating_add(1))
));
assert!(!process_alive_with_image(
pid,
&img,
Some(real.saturating_sub(1))
));
}
use crate::mxc_common::test_env::ScopedStateDir;
#[test]
fn state_dir_honors_env_override() {
let _scope = ScopedStateDir::new();
let dir = state_dir().unwrap();
let env = std::env::var_os("MXC_DACL_STATE_DIR").unwrap();
assert_eq!(dir, PathBuf::from(env));
}
#[test]
fn apply_allow_then_restore_temp_dir() {
let _scope = ScopedStateDir::new();
let td = tempfile::tempdir().unwrap();
let mut m = DaclManager::new().unwrap();
m.grant_appcontainer_access("S-1-1-0", &[td.path().to_path_buf()], &[])
.unwrap();
m.restore().unwrap();
assert!(m.applied.is_empty());
}
#[test]
fn apply_deny_then_restore_temp_file() {
let _scope = ScopedStateDir::new();
let td = tempfile::tempdir().unwrap();
let f = td.path().join("file.txt");
std::fs::write(&f, b"x").unwrap();
let mut m = DaclManager::new().unwrap();
m.add_deny_aces("S-1-1-0", std::slice::from_ref(&f))
.unwrap();
m.restore().unwrap();
assert!(m.applied.is_empty());
}
fn collect_full_dacl_order(path: &Path) -> Vec<(u8, bool)> {
let path_w = wide(path);
let object_name = PCWSTR(path_w.as_ptr());
let mut dacl: *mut ACL = ptr::null_mut();
let mut sd: PSECURITY_DESCRIPTOR = PSECURITY_DESCRIPTOR(ptr::null_mut());
let rc = unsafe {
GetNamedSecurityInfoW(
object_name,
SE_FILE_OBJECT,
DACL_SECURITY_INFORMATION,
None,
None,
Some(&mut dacl),
None,
&mut sd,
)
};
assert_eq!(rc, ERROR_SUCCESS, "GetNamedSecurityInfoW failed: {rc:?}");
let mut out: Vec<(u8, bool)> = Vec::new();
if !dacl.is_null() {
let mut info = ACL_SIZE_INFORMATION::default();
let info_sz = std::mem::size_of::<ACL_SIZE_INFORMATION>() as u32;
unsafe {
GetAclInformation(
dacl,
&mut info as *mut _ as *mut c_void,
info_sz,
AclSizeInformation,
)
.expect("GetAclInformation");
}
let inherited_bit = INHERITED_ACE.0 as u8;
for i in 0..info.AceCount {
let mut ace_ptr: *mut c_void = ptr::null_mut();
if unsafe { GetAce(dacl, i, &mut ace_ptr) }.is_err() {
continue;
}
let Some(ace_ptr) = NonNull::new(ace_ptr) else {
continue;
};
let header = unsafe { ace_ptr.cast::<ACE_HEADER>().as_ref() };
let inherited = (header.AceFlags & inherited_bit) != 0;
out.push((header.AceType, inherited));
}
}
unsafe {
let _ = LocalFree(Some(HLOCAL(sd.0)));
}
out
}
fn assert_canonical_order(aces: &[(u8, bool)], label: &str) {
let mut saw_inherited = false;
let mut saw_explicit_allow = false;
for (i, (ty, inh)) in aces.iter().enumerate() {
if *inh {
saw_inherited = true;
continue;
}
assert!(
!saw_inherited,
"{label}: explicit ACE at index {i} appears AFTER an inherited ACE. order={aces:?}"
);
if *ty == 0x01 {
assert!(
!saw_explicit_allow,
"{label}: explicit DENY at index {i} appears AFTER an explicit ALLOW. order={aces:?}"
);
} else if *ty == 0x00 {
saw_explicit_allow = true;
}
}
}
#[test]
fn deny_round_trip_leaves_no_residue() {
let _scope = ScopedStateDir::new();
let td = tempfile::tempdir().unwrap();
let sid_str = "S-1-15-2-1";
let before = scan_explicit_aces_for_sid(td.path(), sid_str).expect("scan before");
assert_canonical_order(&collect_full_dacl_order(td.path()), "before apply");
let mut allow_mgr = DaclManager::new().unwrap();
allow_mgr
.grant_appcontainer_access(sid_str, std::slice::from_ref(&td.path().to_path_buf()), &[])
.unwrap();
assert_canonical_order(&collect_full_dacl_order(td.path()), "after ALLOW apply");
let mut deny_mgr = DaclManager::new().unwrap();
deny_mgr
.add_deny_aces(sid_str, std::slice::from_ref(&td.path().to_path_buf()))
.unwrap();
let mid_order = collect_full_dacl_order(td.path());
assert_canonical_order(&mid_order, "after DENY apply");
let mid = scan_explicit_aces_for_sid(td.path(), sid_str).expect("scan mid");
assert!(
mid.len() > before.len(),
"apply should have added explicit ACEs for {sid_str}: before={} mid={}",
before.len(),
mid.len()
);
deny_mgr.restore().unwrap();
assert!(deny_mgr.applied.is_empty());
assert_canonical_order(&collect_full_dacl_order(td.path()), "after DENY restore");
allow_mgr.restore().unwrap();
assert!(allow_mgr.applied.is_empty());
let after = scan_explicit_aces_for_sid(td.path(), sid_str).expect("scan after");
assert_eq!(
after.len(),
before.len(),
"restore left {} explicit ACEs for {sid_str} (expected {}). Residue: {after:?}",
after.len(),
before.len()
);
assert_canonical_order(&collect_full_dacl_order(td.path()), "after full restore");
}
#[test]
fn replace_explicit_aces_preserves_unrelated_and_canonicalizes() {
let _scope = ScopedStateDir::new();
let td = tempfile::tempdir().unwrap();
const N: u32 = 20;
let mut seed_managers: Vec<DaclManager> = Vec::new();
for i in 100..(100 + N) {
let sid = format!("S-1-15-2-{i}");
let mut m = DaclManager::new().unwrap();
m.grant_appcontainer_access(&sid, std::slice::from_ref(&td.path().to_path_buf()), &[])
.unwrap();
seed_managers.push(m);
}
let baseline: Vec<(String, usize)> = (100..(100 + N))
.map(|i| {
let sid = format!("S-1-15-2-{i}");
let c = scan_explicit_aces_for_sid(td.path(), &sid).unwrap().len();
(sid, c)
})
.collect();
for (sid, c) in &baseline {
assert_eq!(*c, 1, "seeded SID {sid} should have 1 explicit ACE");
}
let our_sid = "S-1-15-2-9999";
let mut deny_mgr = DaclManager::new().unwrap();
deny_mgr
.add_deny_aces(our_sid, std::slice::from_ref(&td.path().to_path_buf()))
.unwrap();
let mid_order = collect_full_dacl_order(td.path());
assert_canonical_order(&mid_order, "after N=20 keep + 1 deny");
for (sid, c) in &baseline {
let after = scan_explicit_aces_for_sid(td.path(), sid).unwrap().len();
assert_eq!(
after, *c,
"unrelated SID {sid} lost ACEs through rewrite: before={c} after={after}"
);
}
let our_mid = scan_explicit_aces_for_sid(td.path(), our_sid).unwrap();
assert!(
our_mid.iter().any(|p| p.ace_type == AceType::Deny),
"our DENY should be present in the rewritten DACL"
);
deny_mgr.restore().unwrap();
assert!(deny_mgr.applied.is_empty());
assert_canonical_order(&collect_full_dacl_order(td.path()), "after restore");
for (sid, c) in &baseline {
let after = scan_explicit_aces_for_sid(td.path(), sid).unwrap().len();
assert_eq!(after, *c, "restore disturbed seeded SID {sid}");
}
let our_after = scan_explicit_aces_for_sid(td.path(), our_sid).unwrap();
assert!(
our_after.is_empty(),
"restore left residue for our SID: {our_after:?}"
);
for mut m in seed_managers.into_iter().rev() {
m.restore().ok();
}
}
#[test]
fn inheritance_propagation() {
let _scope = ScopedStateDir::new();
let td = tempfile::tempdir().unwrap();
let sub = td.path().join("sub");
std::fs::create_dir(&sub).unwrap();
let f = sub.join("file.txt");
std::fs::write(&f, b"x").unwrap();
let mut m = DaclManager::new().unwrap();
m.grant_appcontainer_access("S-1-1-0", &[td.path().to_path_buf()], &[])
.unwrap();
m.restore().unwrap();
}
#[test]
fn apply_overlapping_then_restore_does_not_leak_rights() {
let _scope = ScopedStateDir::new();
let td = tempfile::tempdir().unwrap();
let target = td.path().to_path_buf();
let everyone = "S-1-1-0";
let mut outer = DaclManager::new().unwrap();
outer
.grant_appcontainer_access(everyone, std::slice::from_ref(&target), &[])
.unwrap();
let mut inner = DaclManager::new().unwrap();
inner
.add_deny_aces(everyone, std::slice::from_ref(&target))
.unwrap();
let captured = &inner.applied.last().unwrap().prior_state;
assert!(
captured.iter().any(|p| p.ace_type == AceType::Allow),
"inner.prior_state should contain outer's allow ACE: {captured:?}"
);
inner.restore().unwrap();
outer.restore().unwrap();
}
#[test]
fn crash_recovery_synthetic_dead_pid() {
let _scope = ScopedStateDir::new();
let td = tempfile::tempdir().unwrap();
let target = td.path().join("victim");
std::fs::create_dir(&target).unwrap();
{
let mut m = DaclManager::new().unwrap();
m.grant_appcontainer_access("S-1-1-0", std::slice::from_ref(&target), &[])
.unwrap();
let dir = state_dir().unwrap();
std::fs::create_dir_all(&dir).unwrap();
let synthetic = dir.join("pid-2147483646-orphan.json");
let s = StateFile {
run_id: "pid-2147483646-orphan".into(),
pid: 0x7FFF_FFFE,
image_name: "wxc-exec.exe".into(),
started_at_filetime: 0,
applied: m.applied.clone(),
};
write_state_file(&synthetic, &s).unwrap();
m.applied.clear();
}
let report = recover_orphaned_state().unwrap();
assert!(report.files_processed >= 1);
}
#[test]
fn set_owner_only_dacl_strips_inheritance_and_grants_owner() {
use windows::Win32::Storage::FileSystem::FILE_ALL_ACCESS;
let parent = tempfile::tempdir().unwrap();
apply_explicit_ace(
parent.path(),
"S-1-1-0", FILE_ALL_ACCESS.0,
AceType::Allow,
true,
)
.unwrap();
let child = parent.path().join("locked");
std::fs::create_dir(&child).unwrap();
let before = collect_full_dacl_order(&child);
assert!(
before.iter().any(|(_, inherited)| *inherited),
"child should start with at least one inherited ACE: {before:?}"
);
set_owner_only_dacl(&child, true).unwrap();
let after = collect_full_dacl_order(&child);
assert!(
!after.is_empty() && after.iter().all(|(_, inherited)| !*inherited),
"PROTECTED DACL must strip all inherited ACEs and keep explicit ones: {after:?}"
);
assert!(
scan_explicit_aces_for_sid(&child, "S-1-1-0")
.unwrap()
.is_empty(),
"owner-only lockdown must not grant Everyone"
);
}
#[test]
fn recovery_prunes_ace_whose_target_is_gone() {
use windows::Win32::Storage::FileSystem::FILE_ALL_ACCESS;
let _scope = ScopedStateDir::new();
let dir = state_dir().unwrap();
std::fs::create_dir_all(&dir).unwrap();
let missing = dir.join("does-not-exist-victim");
assert!(matches!(missing.try_exists(), Ok(false)));
let synthetic = dir.join("pid-2147483646-missing.json");
let s = StateFile {
run_id: "pid-2147483646-missing".into(),
pid: 0x7FFF_FFFE,
image_name: "wxc-exec.exe".into(),
started_at_filetime: 0,
applied: vec![AppliedAce {
canonical_path: missing,
sid_string: "S-1-1-0".into(),
access_mask: FILE_ALL_ACCESS.0,
ace_type: AceType::Allow,
inheritable: false,
prior_state: Vec::new(),
}],
};
write_state_file(&synthetic, &s).unwrap();
let report = recover_orphaned_state().unwrap();
assert!(
report.aces_pruned_missing >= 1,
"missing-target ACE should be pruned"
);
assert!(
report.errors.is_empty(),
"a pruned (missing-target) entry must not surface as an error: {:?}",
report.errors
);
assert!(
matches!(synthetic.try_exists(), Ok(false)),
"a fully-pruned state file should be removed"
);
}
#[test]
fn drop_calls_restore() {
let _scope = ScopedStateDir::new();
let td = tempfile::tempdir().unwrap();
{
let mut m = DaclManager::new().unwrap();
m.grant_appcontainer_access("S-1-1-0", &[td.path().to_path_buf()], &[])
.unwrap();
}
}
#[test]
fn nonexistent_path_errors_cleanly() {
let _scope = ScopedStateDir::new();
let mut m = DaclManager::new().unwrap();
let err = m.grant_appcontainer_access(
"S-1-1-0",
&[PathBuf::from(r"C:\__definitely_not_a_real_path__\xyzzy")],
&[],
);
assert!(matches!(err, Err(DaclError::PathNotFound(_))));
}
#[test]
fn network_path_rejected_e2e() {
let _scope = ScopedStateDir::new();
let mut m = DaclManager::new().unwrap();
let err = m.grant_appcontainer_access(
"S-1-1-0",
&[PathBuf::from(r"\\someserver\share\foo")],
&[],
);
match &err {
Err(DaclError::NetworkPathRejected(_))
| Err(DaclError::PathNotFound(_))
| Err(DaclError::Win32 { .. }) => {}
other => panic!(
"expected NetworkPathRejected | PathNotFound | Win32 for UNC path, got: {other:?}"
),
}
}
#[test]
fn effective_ac_access_empty_on_plain_temp_dir() {
let td = tempfile::tempdir().unwrap();
let access = compute_appcontainer_effective_access(td.path())
.expect("effective access should not error on a normal temp dir");
assert_eq!(
access, 0,
"fresh temp dir should have no AC-group grants, got mask 0x{access:08x}"
);
}
#[test]
fn effective_ac_access_picks_up_explicit_all_app_packages_grant() {
let _scope = ScopedStateDir::new();
let td = tempfile::tempdir().unwrap();
let mask = FILE_GENERIC_READ.0; {
let mut m = DaclManager::new().unwrap();
m.grant_appcontainer_access("S-1-15-2-1", &[], &[td.path().to_path_buf()])
.unwrap();
let observed = compute_appcontainer_effective_access(td.path())
.expect("effective access should not error after grant");
assert!(
observed & mask == mask,
"expected effective mask to cover at least 0x{mask:08x}, got 0x{observed:08x}"
);
}
let post = compute_appcontainer_effective_access(td.path())
.expect("effective access after restore");
assert_eq!(post, 0, "DaclManager Drop should have removed the ACE");
}
#[test]
fn effective_ac_access_ignores_unrelated_sid_grants() {
let _scope = ScopedStateDir::new();
let td = tempfile::tempdir().unwrap();
let mut m = DaclManager::new().unwrap();
m.grant_appcontainer_access("S-1-5-32-545", &[td.path().to_path_buf()], &[])
.unwrap();
let observed = compute_appcontainer_effective_access(td.path()).unwrap();
assert_eq!(
observed, 0,
"BUILTIN\\Users grant should not affect AC effective access, got 0x{observed:08x}"
);
}
}