use std::ffi::{OsStr, OsString};
use std::fmt::Write as _;
use std::path::Path;
#[cfg(windows)]
mod windows;
#[cfg(windows)]
pub use windows::{descriptor, icacls, protect, read};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RawAce {
pub allows: bool,
pub flags: u8,
pub mask: u32,
pub sid: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Descriptor {
pub owner: String,
pub protected: bool,
pub aces: Option<Vec<RawAce>>,
}
pub fn sddl_of(descriptor: &Descriptor) -> String {
let mut sddl = format!("O:{}D:", descriptor.owner);
let Some(aces) = &descriptor.aces else {
sddl.push_str("NO_ACCESS_CONTROL");
return sddl;
};
if descriptor.protected {
sddl.push('P');
}
for ace in aces {
let kind = if ace.allows { "A" } else { "D" };
let flags: String = [(1, "OI"), (2, "CI"), (4, "NP"), (8, "IO"), (16, "ID")]
.iter()
.filter(|(bit, _)| ace.flags & bit != 0)
.map(|(_, name)| *name)
.collect();
let _ = write!(sddl, "({kind};{flags};0x{:x};;;{})", ace.mask, ace.sid);
}
sddl
}
pub const SYSTEM: &str = "S-1-5-18";
const WRITE_MASK: u32 =
0x2 | 0x4 | 0x10 | 0x40 | 0x100 | 0x1_0000 | 0x4_0000 | 0x8_0000 | 0x4000_0000 | 0x1000_0000;
const READ_MASK: u32 = 0x1 | 0x8000_0000 | 0x1000_0000;
const ADMINISTRATORS: &str = "S-1-5-32-544";
const OWNER_STANDINS: &[&str] = &["S-1-3-0", "S-1-3-4"];
const LOCAL_ACCOUNTS: &[(&str, &str)] = &[("LA", "500"), ("LG", "501")];
const ALIASES: &[(&str, &str)] = &[
("SY", SYSTEM),
("BA", "S-1-5-32-544"),
("BU", "S-1-5-32-545"),
("BG", "S-1-5-32-546"),
("PU", "S-1-5-32-547"),
("WD", "S-1-1-0"),
("AU", "S-1-5-11"),
("IU", "S-1-5-4"),
("NU", "S-1-5-2"),
("AN", "S-1-5-7"),
("RC", "S-1-5-12"),
("LS", "S-1-5-19"),
("NS", "S-1-5-20"),
("CO", "S-1-3-0"),
("CG", "S-1-3-1"),
("OW", "S-1-3-4"),
("AC", "S-1-15-2-1"),
];
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Judged {
pub protected: bool,
pub foreign_owner: Option<String>,
pub writers: Vec<String>,
pub readers: Vec<String>,
}
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Plan {
pub remove: Vec<String>,
pub remove_denies: Vec<String>,
}
fn is_sid(text: &str) -> bool {
text.strip_prefix("S-1-").is_some_and(|rest| {
!rest.is_empty() && rest.bytes().all(|b| b.is_ascii_digit() || b == b'-')
})
}
pub fn grant_args(dir: &OsStr, me: &str) -> Vec<OsString> {
let mut args = vec![dir.to_owned()];
args.extend(
[
"/inheritance:r".to_owned(),
"/grant:r".to_owned(),
format!("*{me}:(OI)(CI)F"),
format!("*{SYSTEM}:(OI)(CI)F"),
"/q".to_owned(),
]
.map(OsString::from),
);
args
}
pub fn remove_args(dir: &OsStr, sid: &str, denies_only: bool) -> Vec<OsString> {
let remove = if denies_only { "/remove:d" } else { "/remove" };
vec![
dir.to_owned(),
remove.into(),
format!("*{sid}").into(),
"/q".into(),
]
}
pub fn fix_commands(icacls: &Path, dir: &Path, me: &str, plan: &Plan) -> Vec<String> {
let dir = dir.as_os_str();
let removals = plan
.remove
.iter()
.map(|sid| remove_args(dir, sid, false))
.chain(
plan.remove_denies
.iter()
.map(|sid| remove_args(dir, sid, true)),
);
std::iter::once(grant_args(dir, me))
.chain(removals)
.map(|args| {
std::iter::once(icacls.as_os_str().to_owned())
.chain(args)
.map(|a| quoted(&a.to_string_lossy()))
.collect::<Vec<_>>()
.join(" ")
})
.collect()
}
fn quoted(text: &str) -> String {
if text.contains([' ', '(', ')']) {
format!("\"{text}\"")
} else {
text.to_owned()
}
}
fn owner(sddl: &str) -> Option<&str> {
let rest = sddl.strip_prefix("O:")?;
let end = ["G:", "D:", "S:"]
.iter()
.filter_map(|tag| rest.find(tag))
.min()
.unwrap_or(rest.len());
Some(&rest[..end])
}
fn dacl(sddl: &str) -> Option<&str> {
let at = sddl.find("D:")?;
let dacl = &sddl[at + 2..];
let dacl = &dacl[..dacl.find("S:").unwrap_or(dacl.len())];
(!dacl.starts_with("NO_ACCESS_CONTROL")).then_some(dacl)
}
fn aces(dacl: &str) -> impl Iterator<Item = (bool, &str, &str, &str)> {
dacl.split('(').skip(1).filter_map(|ace| {
let fields: Vec<&str> = ace.trim_end_matches(')').split(';').collect();
let [kind, flags, rights, _, _, sid, ..] = fields.as_slice() else {
return None;
};
Some((
matches!(*kind, "A" | "OA" | "XA" | "ZA"),
*flags,
*rights,
*sid,
))
})
}
pub fn judge(sddl: &str, me: &str) -> Judged {
let foreign_owner = match owner(sddl) {
Some(owner) if sid_of(owner, me).is_some_and(|sid| owner_trusted(&sid, me)) => None,
Some(owner) => Some(name_of(owner)),
None => Some("an account that could not be read".to_owned()),
};
let Some(dacl) = dacl(sddl) else {
return Judged {
foreign_owner,
writers: vec!["everyone (no access list)".to_owned()],
..Judged::default()
};
};
let flags = &dacl[..dacl.find('(').unwrap_or(dacl.len())];
let mut judged = Judged {
protected: flags.contains('P'),
foreign_owner,
..Judged::default()
};
for (allows, _, rights, sid) in aces(dacl) {
let full = sid_of(sid, me);
let own = full
.as_deref()
.is_some_and(|f| is_own(f, me) || OWNER_STANDINS.contains(&f));
if !allows || own {
continue;
}
let mask = rights_mask(rights);
let name = name_of(sid);
if mask & WRITE_MASK != 0 {
judged.writers.push(name);
} else if mask & READ_MASK != 0 {
judged.readers.push(name);
}
}
judged
}
pub fn plan(sddl: &str, me: &str) -> Result<Plan, String> {
let mut plan = Plan::default();
for (allows, flags, _, sid) in dacl(sddl).into_iter().flat_map(aces) {
if flags.as_bytes().chunks(2).any(|flag| flag == b"ID") {
continue;
}
let sid = sid_of(sid, me).ok_or_else(|| sid.to_owned())?;
let list = match (is_own(&sid, me), allows) {
(true, true) => continue,
(true, false) => &mut plan.remove_denies,
(false, _) => &mut plan.remove,
};
if !list.contains(&sid) {
list.push(sid);
}
}
Ok(plan)
}
pub fn verify(sddl: &str, me: &str) -> Result<(), String> {
let judged = judge(sddl, me);
let mut stayed: Vec<String> = Vec::new();
if let Some(owner) = &judged.foreign_owner {
stayed.push(format!("the owner {owner}"));
}
if !judged.protected {
stayed.push("entries inherited from the folder above".to_owned());
}
stayed.extend(
judged
.writers
.iter()
.map(|w| format!("{w}, who may change it")),
);
stayed.extend(
judged
.readers
.iter()
.map(|r| format!("{r}, who may read it")),
);
match plan(sddl, me) {
Ok(plan) => {
stayed.extend(plan.remove.iter().map(|sid| format!("an entry for {sid}")));
stayed.extend(
plan.remove_denies
.iter()
.map(|sid| format!("a deny entry for {sid}")),
);
}
Err(alias) => stayed.push(format!("an entry for `{alias}`")),
}
stayed.dedup();
if stayed.is_empty() {
Ok(())
} else {
Err(stayed.join("; "))
}
}
fn sid_of(sid: &str, me: &str) -> Option<String> {
if is_sid(sid) {
return Some(sid.to_owned());
}
if let Some((_, rid)) = LOCAL_ACCOUNTS.iter().find(|(alias, _)| *alias == sid) {
let (domain, own_rid) = me.rsplit_once('-')?;
if own_rid == *rid {
return Some(me.to_owned());
}
return me
.starts_with("S-1-5-21-")
.then(|| format!("{domain}-{rid}"));
}
ALIASES
.iter()
.find(|(alias, _)| *alias == sid)
.map(|(_, full)| (*full).to_owned())
}
fn is_own(sid: &str, me: &str) -> bool {
sid.eq_ignore_ascii_case(me) || sid == SYSTEM
}
fn owner_trusted(sid: &str, me: &str) -> bool {
is_own(sid, me) || sid == ADMINISTRATORS
}
fn name_of(sid: &str) -> String {
match sid {
"WD" | "S-1-1-0" => "Everyone",
"AU" | "S-1-5-11" => "Authenticated Users",
"BU" | "S-1-5-32-545" => "Users",
"BA" | ADMINISTRATORS => "Administrators",
"IU" | "S-1-5-4" => "interactive users",
"AN" | "S-1-5-7" => "anonymous logons",
"AC" | "S-1-15-2-1" => "all app containers",
"LA" => "the built-in Administrator",
"LG" => "the built-in Guest",
other => other,
}
.to_owned()
}
fn rights_mask(rights: &str) -> u32 {
if let Some(hex) = rights
.strip_prefix("0x")
.or_else(|| rights.strip_prefix("0X"))
{
return u32::from_str_radix(hex, 16).unwrap_or(u32::MAX);
}
rights
.as_bytes()
.chunks(2)
.map(|code| match code {
b"GA" => 0x1000_0000,
b"GR" => 0x8000_0000,
b"GW" => 0x4000_0000,
b"GX" => 0x2000_0000,
b"FA" => 0x001F_01FF,
b"FR" => 0x0012_0089,
b"FW" => 0x0012_0116,
b"FX" => 0x0012_00A0,
b"RC" => 0x2_0000,
b"SD" => 0x1_0000,
b"WD" => 0x4_0000,
b"WO" => 0x8_0000,
b"CC" => 0x1,
b"DC" => 0x2,
b"LC" => 0x4,
b"SW" => 0x8,
b"RP" => 0x10,
b"WP" => 0x20,
b"DT" => 0x40,
b"LO" => 0x80,
b"CR" => 0x100,
_ => u32::MAX,
})
.fold(0, |mask, bits| mask | bits)
}
#[cfg(test)]
mod tests;