use anyhow::{anyhow, Result};
use std::collections::{HashMap, HashSet};
#[cfg(target_os = "windows")]
use windows::core::PWSTR;
#[cfg(target_os = "windows")]
use windows::Win32::Foundation::{LocalFree, HLOCAL};
#[cfg(target_os = "windows")]
use windows::Win32::Security::Authorization::ConvertSidToStringSidW;
#[cfg(target_os = "windows")]
use windows::Win32::Security::{DeriveCapabilitySidsFromName, GetLengthSid, IsValidSid, PSID};
const ACE_TYPE_OFFSET: usize = 0;
const ACE_FLAGS_OFFSET: usize = 4;
const ACE_ACCESS_MASK_OFFSET: usize = 8;
const ACE_HEADER_SIZE: usize = 1 + 3 + 4 + 4;
const SID_SUB_AUTHORITY_COUNT_OFFSET: usize = 1;
const SID_FIXED_HEADER_SIZE: usize = 1 + 1 + 6; const SID_SUB_AUTHORITY_SIZE: usize = 4;
const ACE_TYPE_ACCESS_ALLOWED: u8 = 0x00;
const ACE_TYPE_ACCESS_ALLOWED_CALLBACK: u8 = 0x09;
const KNOWN_CAPABILITIES: &[&str] = &[
"internetClient",
"internetClientServer",
"privateNetworkClientServer",
"documentsLibrary",
"picturesLibrary",
"videosLibrary",
"musicLibrary",
"removableStorage",
"sharedUserCertificates",
"appointments",
"contacts",
"chat",
"phoneCall",
"voipCall",
"objects3D",
"userAccountInformation",
"backgroundMediaPlayback",
"codeGeneration",
"allowElevation",
"location",
"microphone",
"webcam",
"proximity",
"bluetooth",
"bluetooth.genericAttributeProfile",
"bluetooth.rfcomm",
"humaninterfacedevice",
"lowLevelDevices",
"pointOfService",
"radios",
"serialcommunication",
"usb",
"wiFiControl",
"gazeInput",
"optical",
"activity",
"graphicsCapture",
"graphicsCaptureProgrammatic",
"graphicsCaptureWithoutBorder",
"screenDuplication",
"appCaptureServices",
"appCaptureSettings",
"backgroundMediaRecording",
"backgroundSpatialPerception",
"backgroundVoIP",
"extendedBackgroundTaskTime",
"extendedExecutionBackgroundAudio",
"extendedExecutionCritical",
"extendedExecutionUnconstrained",
"accessoryManager",
"allAppMods",
"appBroadcastServices",
"appLicensing",
"audioDeviceConfiguration",
"cellularDeviceControl",
"cellularDeviceIdentity",
"cellularMessaging",
"confirmAppClose",
"customInstallActions",
"developmentModeNetwork",
"dualSimTiles",
"enterpriseCloudSSO",
"enterpriseDataPolicy",
"enterpriseDeviceLockdown",
"firstSignInSettings",
"gameBarServices",
"gameList",
"gameMonitor",
"globalMediaControl",
"inputForegroundObservation",
"inputInjectionBrokered",
"inputObservation",
"inputSuppression",
"interopServices",
"liveIdService",
"localSystemServices",
"locationHistory",
"locationSystem",
"modifiableApp",
"networkConnectionManagerProvisioning",
"networkDataPlanProvisioning",
"networkingVpnProvider",
"oemDeploymentInfo",
"oemPublicDirectory",
"packagePolicySystem",
"packageQuery",
"packageWriteRedirectionCompatibilityShim",
"previewInkWorkspace",
"previewPenWorkspace",
"previewStore",
"previewUiComposition",
"protectedApp",
"secondaryAuthenticationFactor",
"secureAssessment",
"shellExperience",
"shellExperienceComposer",
"slapiQueryLicenseValue",
"smbios",
"smsSend",
"startScreenManagement",
"storeLicenseManagement",
"systemManagement",
"targetedContent",
"teamEditionDeviceCredential",
"teamEditionExperience",
"teamEditionView",
"uiAccess",
"uiAutomation",
"unvirtualizedResources",
"walletSystem",
"xboxAccessoryManagement",
"appointmentsSystem",
"chatSystem",
"contactsSystem",
"email",
"emailSystem",
"phoneCallHistory",
"phoneCallHistorySystem",
"phoneLineTransportManagement",
"userDataAccountsProvider",
"userDataSystem",
"userSystemId",
"cortanaPermissions",
"cortanaSpeechAccessory",
];
#[cfg(target_os = "windows")]
fn to_wide_z(s: &str) -> Vec<u16> {
crate::mxc_common::string_util::to_wide(s)
}
#[cfg(target_os = "windows")]
unsafe fn sid_bytes_from_ptr(psid: PSID) -> Option<Vec<u8>> {
if psid.0.is_null() {
return None;
}
let len = GetLengthSid(psid);
if len == 0 {
return None;
}
let mut buf = vec![0u8; len as usize];
std::ptr::copy_nonoverlapping(psid.0 as *const u8, buf.as_mut_ptr(), len as usize);
Some(buf)
}
#[cfg(target_os = "windows")]
unsafe fn free_sid_array(arr: *mut PSID, count: u32) {
if arr.is_null() {
return;
}
for i in 0..count as isize {
let p = *arr.offset(i);
if !p.0.is_null() {
let _ = LocalFree(Some(HLOCAL(p.0)));
}
}
let _ = LocalFree(Some(HLOCAL(arr as *mut _)));
}
#[cfg(target_os = "windows")]
unsafe fn first_sid_bytes(arr: *const PSID, count: u32) -> Option<Vec<u8>> {
if arr.is_null() || count == 0 {
return None;
}
let first = unsafe { std::slice::from_raw_parts(arr, count as usize)[0] };
unsafe { sid_bytes_from_ptr(first) }
}
pub(crate) fn ascii_ci_cmp(a: &str, b: &str) -> std::cmp::Ordering {
let (ab, bb) = (a.as_bytes(), b.as_bytes());
for i in 0..ab.len().min(bb.len()) {
let (x, y) = (ab[i].to_ascii_lowercase(), bb[i].to_ascii_lowercase());
if x != y {
return x.cmp(&y);
}
}
ab.len().cmp(&bb.len())
}
pub fn sorted_capability_names<S>(caps: &HashSet<S>) -> Vec<&str>
where
S: std::borrow::Borrow<str> + Eq + std::hash::Hash,
{
let mut out: Vec<&str> = caps.iter().map(|s| s.borrow()).collect();
out.sort_by(|a, b| ascii_ci_cmp(a, b));
out
}
pub fn known_capability_count() -> usize {
KNOWN_CAPABILITIES.len()
}
#[cfg(target_os = "windows")]
pub fn build_capability_index() -> CapabilityIndex {
let mut index = CapabilityIndex::with_capacity(KNOWN_CAPABILITIES.len() * 2);
for &name in KNOWN_CAPABILITIES {
let wide = to_wide_z(name);
let mut group_sids: *mut PSID = std::ptr::null_mut();
let mut group_count: u32 = 0;
let mut cap_sids: *mut PSID = std::ptr::null_mut();
let mut cap_count: u32 = 0;
let ok = unsafe {
DeriveCapabilitySidsFromName(
PWSTR(wide.as_ptr() as *mut u16),
&mut group_sids as *mut _,
&mut group_count as *mut _,
&mut cap_sids as *mut _,
&mut cap_count as *mut _,
)
};
if ok.is_err() {
index.derive_failures += 1;
continue;
}
index.resolved_capabilities += 1;
if let Some(sid) = unsafe { first_sid_bytes(cap_sids, cap_count) } {
index.insert_package_sid(sid, name);
}
if let Some(sid) = unsafe { first_sid_bytes(group_sids, group_count) } {
index.insert_group_sid(sid, name);
}
unsafe {
free_sid_array(cap_sids, cap_count);
free_sid_array(group_sids, group_count);
}
}
index
}
#[cfg(not(target_os = "windows"))]
pub fn build_capability_index() -> CapabilityIndex {
CapabilityIndex::with_capacity(0)
}
pub fn discover_capabilities(verbose: bool) -> CapabilityIndex {
let index = build_capability_index();
if index.resolved_capabilities() == 0 {
eprintln!(
"warning: no AppContainer capability SIDs could be derived on this host \
({} of {} known names rejected); no capabilities will be detected.",
index.derive_failures(),
known_capability_count()
);
} else if index.derive_failures() > 0 && verbose {
println!(
"Note: {} of {} known capability names were rejected by this OS and will not be \
matched.",
index.derive_failures(),
known_capability_count()
);
}
index
}
#[cfg(any(target_os = "windows", test))]
fn encoded_sid_len(bytes: &[u8]) -> Option<usize> {
let sub_authority_count = *bytes.get(SID_SUB_AUTHORITY_COUNT_OFFSET)? as usize;
let len = SID_FIXED_HEADER_SIZE + SID_SUB_AUTHORITY_SIZE * sub_authority_count;
(bytes.len() >= len).then_some(len)
}
#[cfg(target_os = "windows")]
pub fn sid_to_string(sid_bytes: &[u8]) -> Option<String> {
encoded_sid_len(sid_bytes)?;
let psid = PSID(sid_bytes.as_ptr() as *mut _);
unsafe {
if !IsValidSid(psid).as_bool() {
return None;
}
let mut out = PWSTR::null();
if ConvertSidToStringSidW(psid, &mut out as *mut _).is_err() {
return None;
}
let mut len = 0usize;
while *out.0.add(len) != 0 {
len += 1;
}
let slice = std::slice::from_raw_parts(out.0, len);
let s = String::from_utf16_lossy(slice);
let _ = LocalFree(Some(HLOCAL(out.0 as *mut _)));
Some(s)
}
}
#[cfg(not(target_os = "windows"))]
pub fn sid_to_string(_sid_bytes: &[u8]) -> Option<String> {
None
}
pub struct CapabilityIndex {
by_sid: HashMap<Vec<u8>, (&'static str, bool)>,
resolved_capabilities: usize,
derive_failures: usize,
}
#[cfg(test)]
pub(crate) type TestCapabilityEntry<'a> = (&'static str, Option<&'a [u8]>, Option<&'a [u8]>);
impl CapabilityIndex {
fn with_capacity(sids: usize) -> Self {
Self {
by_sid: HashMap::with_capacity(sids),
resolved_capabilities: 0,
derive_failures: 0,
}
}
#[cfg(any(target_os = "windows", test))]
fn insert_package_sid(&mut self, sid: Vec<u8>, name: &'static str) {
self.by_sid.insert(sid, (name, false));
}
#[cfg(any(target_os = "windows", test))]
fn insert_group_sid(&mut self, sid: Vec<u8>, name: &'static str) {
self.by_sid.entry(sid).or_insert((name, true));
}
pub fn resolved_capabilities(&self) -> usize {
self.resolved_capabilities
}
pub fn derive_failures(&self) -> usize {
self.derive_failures
}
pub fn resolve(&self, sid_bytes: &[u8]) -> Option<(&'static str, bool)> {
self.by_sid.get(sid_bytes).copied()
}
#[cfg(all(test, target_os = "windows"))]
pub(crate) fn iter_sids(&self) -> impl Iterator<Item = (&[u8], &'static str, bool)> {
self.by_sid
.iter()
.map(|(sid, (name, is_group))| (sid.as_slice(), *name, *is_group))
}
#[cfg(test)]
pub(crate) fn for_test(entries: &[TestCapabilityEntry<'_>]) -> Self {
let mut index = Self::with_capacity(entries.len() * 2);
for &(name, package_sid, group_sid) in entries {
index.resolved_capabilities += 1;
if let Some(sid) = package_sid {
index.insert_package_sid(sid.to_vec(), name);
}
if let Some(sid) = group_sid {
index.insert_group_sid(sid.to_vec(), name);
}
}
index
}
}
#[derive(Default)]
pub struct AceWalkState {
scratch: Vec<u8>,
pub(crate) matches: HashSet<&'static str>,
zero_mask_capabilities: usize,
}
impl AceWalkState {
pub fn new() -> Self {
Self::default()
}
pub fn zero_mask_capabilities(&self) -> usize {
self.zero_mask_capabilities
}
}
#[cfg(test)]
pub(crate) fn parse_hex_string(hex_input: &str) -> Result<Vec<u8>> {
let mut out = Vec::new();
parse_hex_string_into(hex_input, &mut out)?;
Ok(out)
}
pub(crate) fn parse_hex_string_into(hex_input: &str, out: &mut Vec<u8>) -> Result<()> {
out.clear();
out.reserve(hex_input.len() / 2);
let mut nibble: Option<u8> = None;
for b in hex_input.as_bytes() {
let b = *b;
if b.is_ascii_whitespace() {
continue;
}
let v = match b {
b'0'..=b'9' => b - b'0',
b'a'..=b'f' => b - b'a' + 10,
b'A'..=b'F' => b - b'A' + 10,
_ => {
out.clear();
return Err(anyhow!("Hex string contains non-hex characters."));
}
};
match nibble.take() {
None => nibble = Some(v),
Some(hi) => out.push((hi << 4) | v),
}
}
if nibble.is_some() || out.is_empty() {
out.clear();
return Err(anyhow!(
"Hex string must be non-empty and have an even length."
));
}
Ok(())
}
struct AceSlice<'a> {
ace_type: u8,
ace_flags: u8,
access_mask: u32,
sub_authority_count: u8,
sid_bytes: &'a [u8],
next_cursor: usize,
}
fn read_ace_at_offset(buf: &[u8], cursor: usize) -> Result<AceSlice<'_>> {
let total = buf.len();
if total - cursor < ACE_HEADER_SIZE + SID_FIXED_HEADER_SIZE {
return Err(anyhow!(
"Truncated ACE header at byte offset {} (need at least {} more bytes).",
cursor,
ACE_HEADER_SIZE + SID_FIXED_HEADER_SIZE
));
}
let ace_type = buf[cursor + ACE_TYPE_OFFSET];
if ace_type == ACE_TYPE_ACCESS_ALLOWED_CALLBACK {
return Err(anyhow!(
"Unsupported callback ACE (type 0x{:02X}) at byte offset {}: its trailing OpaqueData \
has no length field in this header layout, so the rest of the blob cannot be framed.",
ACE_TYPE_ACCESS_ALLOWED_CALLBACK,
cursor
));
}
let ace_flags = buf[cursor + ACE_FLAGS_OFFSET];
let access_mask = u32::from_le_bytes([
buf[cursor + ACE_ACCESS_MASK_OFFSET],
buf[cursor + ACE_ACCESS_MASK_OFFSET + 1],
buf[cursor + ACE_ACCESS_MASK_OFFSET + 2],
buf[cursor + ACE_ACCESS_MASK_OFFSET + 3],
]);
let sid_offset = cursor + ACE_HEADER_SIZE;
let sub_authority_count = buf[sid_offset + SID_SUB_AUTHORITY_COUNT_OFFSET];
let sid_size = SID_FIXED_HEADER_SIZE + SID_SUB_AUTHORITY_SIZE * sub_authority_count as usize;
if total - sid_offset < sid_size {
return Err(anyhow!(
"Truncated SID at byte offset {} (need {} bytes, have {}).",
sid_offset,
sid_size,
total - sid_offset
));
}
Ok(AceSlice {
ace_type,
ace_flags,
access_mask,
sub_authority_count,
sid_bytes: &buf[sid_offset..sid_offset + sid_size],
next_cursor: sid_offset + sid_size,
})
}
fn walk_aces(
buf: &[u8],
index: &CapabilityIndex,
verbose: bool,
found: &mut HashSet<&'static str>,
zero_mask_capabilities: &mut usize,
) -> Result<()> {
let mut cursor = 0usize;
let mut ace_index = 0usize;
while cursor < buf.len() {
let ace = read_ace_at_offset(buf, cursor)?;
let is_allow_ace = ace.ace_type == ACE_TYPE_ACCESS_ALLOWED;
let grants_access = ace.access_mask != 0;
let resolution = index.resolve(ace.sid_bytes);
if is_allow_ace {
if let Some((name, _is_group)) = resolution {
if grants_access {
found.insert(name);
} else {
*zero_mask_capabilities += 1;
}
}
}
if verbose {
let resolved_str = match resolution {
Some((name, false)) => format!("capability \"{name}\""),
Some((name, true)) => format!("capability \"{name}\" (group SID)"),
None => "<no known capability/account matches this SID>".to_string(),
};
let sid_str =
sid_to_string(ace.sid_bytes).unwrap_or_else(|| "<invalid SID>".to_string());
println!(
"ACE {}: type=0x{:02X}, flags=0x{:02X}, mask=0x{:08X}, subAuthCount={}",
ace_index, ace.ace_type, ace.ace_flags, ace.access_mask, ace.sub_authority_count
);
println!(" SID: {sid_str}");
println!(" Resolved: {resolved_str}");
println!();
}
cursor = ace.next_cursor;
ace_index += 1;
}
Ok(())
}
pub fn extract_caps(hex_bytes: &str, verbose: bool) -> Result<HashSet<&'static str>> {
let index = build_capability_index();
let mut state = AceWalkState::new();
extract_caps_into(hex_bytes, &index, verbose, &mut state)?;
Ok(state.matches)
}
pub fn extract_caps_into(
hex_bytes: &str,
index: &CapabilityIndex,
verbose: bool,
state: &mut AceWalkState,
) -> Result<()> {
let AceWalkState {
scratch,
matches,
zero_mask_capabilities,
} = state;
parse_hex_string_into(hex_bytes, scratch)?;
walk_aces(scratch, index, verbose, matches, zero_mask_capabilities)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_hex_string_decodes_simple_bytes() {
let v = parse_hex_string("DEADBEEF").unwrap();
assert_eq!(v, vec![0xDE, 0xAD, 0xBE, 0xEF]);
}
#[test]
fn parse_hex_string_accepts_whitespace_and_lower() {
let v = parse_hex_string("de ad\nbe\tef").unwrap();
assert_eq!(v, vec![0xDE, 0xAD, 0xBE, 0xEF]);
}
#[test]
fn parse_hex_string_rejects_odd_length() {
assert!(parse_hex_string("ABC").is_err());
}
#[test]
fn parse_hex_string_rejects_empty() {
assert!(parse_hex_string("").is_err());
assert!(parse_hex_string(" \n").is_err());
}
#[test]
fn parse_hex_string_rejects_non_hex() {
assert!(parse_hex_string("DEADXYZZ").is_err());
}
fn well_world_sid() -> Vec<u8> {
vec![
1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, ]
}
fn build_ace(mask: u32, sid: &[u8]) -> Vec<u8> {
build_ace_typed(ACE_TYPE_ACCESS_ALLOWED, mask, sid)
}
const GRANT: u32 = 0x0012_0089;
#[test]
fn read_ace_at_offset_decodes_well_known_sid() {
let buf = build_ace(0xDEADBEEF, &well_world_sid());
let ace = read_ace_at_offset(&buf, 0).expect("should decode");
assert_eq!(ace.access_mask, 0xDEADBEEF);
assert_eq!(ace.sid_bytes, well_world_sid().as_slice());
assert_eq!(ace.next_cursor, buf.len());
}
#[test]
fn read_ace_at_offset_rejects_truncated_header() {
let buf = vec![0u8; 4];
assert!(read_ace_at_offset(&buf, 0).is_err());
}
#[test]
fn read_ace_at_offset_rejects_truncated_subauthorities() {
let mut sid = vec![1u8, 5, 0, 0, 0, 0, 0, 1]; sid.extend_from_slice(&[0, 0, 0, 0]); let buf = build_ace(0, &sid);
assert!(read_ace_at_offset(&buf, 0).is_err());
}
#[test]
fn encoded_sid_len_accepts_a_well_formed_sid() {
assert_eq!(encoded_sid_len(&well_world_sid()), Some(12));
}
#[test]
fn encoded_sid_len_rejects_slices_shorter_than_the_fixed_header() {
assert_eq!(encoded_sid_len(&[]), None);
assert_eq!(encoded_sid_len(&[1]), None);
assert_eq!(encoded_sid_len(&[1, 0, 0, 0, 0, 0, 0]), None);
}
#[test]
fn encoded_sid_len_rejects_subauthority_count_beyond_the_slice() {
let mut sid = vec![1u8, 5, 0, 0, 0, 0, 0, 1];
sid.extend_from_slice(&[0, 0, 0, 0]);
assert_eq!(encoded_sid_len(&sid), None);
let sid = vec![1u8, 255, 0, 0, 0, 0, 0, 1];
assert_eq!(encoded_sid_len(&sid), None);
}
#[test]
fn sid_to_string_rejects_undersized_slices_without_reading_out_of_bounds() {
assert_eq!(sid_to_string(&[]), None);
assert_eq!(sid_to_string(&[1]), None);
assert_eq!(sid_to_string(&[1, 0, 0, 0, 0, 0, 0]), None);
let mut truncated = vec![1u8, 5, 0, 0, 0, 0, 0, 1];
truncated.extend_from_slice(&[0, 0, 0, 0]);
assert_eq!(sid_to_string(&truncated), None);
}
#[test]
fn capability_index_resolves_app_package_and_group_sids() {
let sid = well_world_sid();
let idx = CapabilityIndex::for_test(&[("internetClient", Some(&sid), None)]);
assert_eq!(idx.resolve(&sid), Some(("internetClient", false)));
let group = vec![1u8, 1, 0, 0, 0, 0, 0, 5, 7, 0, 0, 0];
let idx = CapabilityIndex::for_test(&[("documentsLibrary", None, Some(&group))]);
assert_eq!(idx.resolve(&group), Some(("documentsLibrary", true)));
assert_eq!(idx.resolve(&sid), None);
}
#[test]
fn capability_index_prefers_the_package_sid_on_conflict() {
let sid = well_world_sid();
let idx = CapabilityIndex::for_test(&[
("internetClient", Some(&sid), None),
("documentsLibrary", None, Some(&sid)),
]);
assert_eq!(idx.resolve(&sid), Some(("internetClient", false)));
assert_eq!(idx.resolved_capabilities(), 2);
assert_eq!(idx.derive_failures(), 0);
}
fn build_ace_typed(ace_type: u8, mask: u32, sid: &[u8]) -> Vec<u8> {
let mut v = Vec::new();
v.push(ace_type);
v.extend_from_slice(&[0, 0, 0]); v.extend_from_slice(&[0, 0, 0, 0]); v.extend_from_slice(&mask.to_le_bytes());
v.extend_from_slice(sid);
v
}
fn walk_with_zero_mask(
buf: &[u8],
index: &CapabilityIndex,
) -> (Result<()>, HashSet<&'static str>, usize) {
let mut found = HashSet::new();
let mut zero_mask = 0usize;
let outcome = walk_aces(buf, index, false, &mut found, &mut zero_mask);
(outcome, found, zero_mask)
}
fn walk(buf: &[u8], index: &CapabilityIndex) -> Result<HashSet<&'static str>> {
let (outcome, found, _) = walk_with_zero_mask(buf, index);
outcome.map(|()| found)
}
fn extract(hex: &str, index: &CapabilityIndex) -> Result<HashSet<&'static str>> {
let mut state = AceWalkState::new();
extract_caps_into(hex, index, false, &mut state)?;
Ok(state.matches)
}
#[test]
fn ace_walk_collects_matched_caps() {
let sid = well_world_sid();
let idx = cap_index_for(&sid, "internetClient");
let mut buf = Vec::new();
buf.extend_from_slice(&build_ace(GRANT, &sid));
buf.extend_from_slice(&build_ace(GRANT, &sid));
let caps = walk(&buf, &idx).unwrap();
assert!(caps.contains("internetClient"));
assert_eq!(caps.len(), 1);
}
#[test]
fn ace_walk_skips_access_denied_ace() {
let sid = well_world_sid();
let idx = cap_index_for(&sid, "internetClient");
let buf = build_ace_typed(0x01, GRANT, &sid);
let caps = walk(&buf, &idx).unwrap();
assert!(caps.is_empty(), "deny ACE must not produce capability");
let buf = build_ace_typed(ACE_TYPE_ACCESS_ALLOWED_CALLBACK, GRANT, &sid);
let err = walk(&buf, &idx)
.expect_err("callback ACE framing is unresolvable and must be rejected");
assert!(
err.to_string().contains("callback ACE"),
"unexpected error: {err}"
);
}
#[test]
fn callback_ace_aborts_the_walk_so_later_aces_are_never_misframed() {
let sid = well_world_sid();
let idx = cap_index_for(&sid, "internetClient");
let mut buf = build_ace(GRANT, &sid);
buf.extend_from_slice(&build_ace_typed(
ACE_TYPE_ACCESS_ALLOWED_CALLBACK,
GRANT,
&sid,
));
let (outcome, found, _) = walk_with_zero_mask(&buf, &idx);
let err = outcome.expect_err("a callback ACE must abort the walk");
assert!(
err.to_string().contains("callback ACE"),
"unexpected error: {err}"
);
assert_eq!(
found.len(),
1,
"partial write expected; callers must discard this set on Err"
);
}
fn hex_for_bytes(bytes: &[u8]) -> String {
use std::fmt::Write;
let mut s = String::with_capacity(bytes.len() * 2);
for b in bytes {
let _ = write!(s, "{:02X}", b);
}
s
}
#[test]
fn extract_caps_into_decodes_hex_and_matches_capability() {
let sid = well_world_sid();
let idx = cap_index_for(&sid, "documentsLibrary");
let hex = hex_for_bytes(&build_ace(GRANT, &sid));
let caps = extract(&hex, &idx).unwrap();
assert!(caps.contains("documentsLibrary"));
assert_eq!(caps.len(), 1);
}
#[test]
fn extract_caps_into_preserves_existing_staged_entries() {
let sid = well_world_sid();
let idx = cap_index_for(&sid, "internetClient");
let mut buf = Vec::new();
buf.extend_from_slice(&build_ace(GRANT, &sid));
buf.extend_from_slice(&build_ace(GRANT, &sid));
let hex = hex_for_bytes(&buf);
let mut state = AceWalkState::new();
state.matches.insert("preexisting");
extract_caps_into(&hex, &idx, false, &mut state).unwrap();
assert!(state.matches.contains("preexisting"));
assert!(state.matches.contains("internetClient"));
}
#[test]
fn extract_caps_into_rejects_malformed_hex() {
let idx = CapabilityIndex::for_test(&[]);
assert!(extract("not-hex", &idx).is_err());
assert!(extract("ABC", &idx).is_err());
}
#[test]
fn extract_caps_into_returns_empty_for_no_match() {
let sid = well_world_sid();
let idx = CapabilityIndex::for_test(&[]);
let hex = hex_for_bytes(&build_ace(GRANT, &sid));
let caps = extract(&hex, &idx).unwrap();
assert!(caps.is_empty());
}
fn cap_index_for(sid: &[u8], name: &'static str) -> CapabilityIndex {
CapabilityIndex::for_test(&[(name, Some(sid), None)])
}
#[test]
fn zero_mask_allow_ace_does_not_grant_capability() {
let sid = well_world_sid();
let idx = cap_index_for(&sid, "internetClient");
let (outcome, caps, zero_mask) = walk_with_zero_mask(&build_ace(0, &sid), &idx);
outcome.unwrap();
assert!(
caps.is_empty(),
"zero-mask allow ACE must not produce a capability"
);
assert_eq!(zero_mask, 1);
}
#[test]
fn zero_mask_counter_is_per_walk_not_per_process() {
let sid = well_world_sid();
let idx = cap_index_for(&sid, "internetClient");
for _ in 0..2 {
let (outcome, _, zero_mask) = walk_with_zero_mask(&build_ace(0, &sid), &idx);
outcome.unwrap();
assert_eq!(zero_mask, 1, "each walk counts independently");
}
}
#[test]
fn valid_ace_followed_by_truncated_ace_is_an_error() {
let sid = well_world_sid();
let idx = cap_index_for(&sid, "internetClient");
let mut buf = build_ace(GRANT, &sid);
buf.extend_from_slice(&[0u8; 6]); assert!(walk(&buf, &idx).is_err());
}
#[test]
fn truncated_tail_writes_partially_so_callers_must_stage() {
let sid = well_world_sid();
let idx = cap_index_for(&sid, "internetClient");
let mut buf = build_ace(GRANT, &sid);
buf.extend_from_slice(&[0u8; 6]);
let (outcome, found, _) = walk_with_zero_mask(&buf, &idx);
assert!(
outcome.is_err(),
"truncated tail must still report an error"
);
assert!(
found.contains("internetClient"),
"walker writes as it goes; callers must stage and discard on Err"
);
}
#[test]
fn maximal_sub_authority_count_without_bytes_is_an_error() {
let mut sid = vec![1u8, 255, 0, 0, 0, 0, 0, 1];
sid.extend_from_slice(&[0, 0, 0, 0]);
let buf = build_ace(GRANT, &sid);
assert!(read_ace_at_offset(&buf, 0).is_err());
}
#[test]
fn ace_exactly_at_buffer_boundary_decodes() {
let sid = well_world_sid();
let idx = cap_index_for(&sid, "internetClient");
let buf = build_ace(GRANT, &sid);
let ace = read_ace_at_offset(&buf, 0).expect("exact-fit ACE should decode");
assert_eq!(ace.next_cursor, buf.len());
let caps = walk(&buf, &idx).unwrap();
assert!(caps.contains("internetClient"));
}
#[test]
fn single_trailing_byte_after_valid_ace_is_an_error() {
let sid = well_world_sid();
let idx = cap_index_for(&sid, "internetClient");
let mut buf = build_ace(GRANT, &sid);
buf.push(0xFF);
assert!(walk(&buf, &idx).is_err());
}
#[test]
fn malformed_hex_shapes_are_rejected_without_panic() {
let idx = CapabilityIndex::for_test(&[]);
for bad in ["ABC", "not-hex", "", " \n", "AB CD E"] {
let mut state = AceWalkState::new();
assert!(
extract_caps_into(bad, &idx, false, &mut state).is_err(),
"expected {bad:?} to be rejected"
);
assert!(
state.scratch.is_empty(),
"scratch must be left clean after a failed decode"
);
}
}
#[test]
fn scratch_buffer_is_reused_across_decodes() {
let sid = well_world_sid();
let idx = cap_index_for(&sid, "internetClient");
let hex = hex_for_bytes(&build_ace(GRANT, &sid));
let mut state = AceWalkState::new();
extract_caps_into(&hex, &idx, false, &mut state).unwrap();
let after_first = state.scratch.len();
extract_caps_into(&hex, &idx, false, &mut state).unwrap();
assert_eq!(
state.scratch.len(),
after_first,
"reused scratch must not accumulate across decodes"
);
assert_eq!(state.matches.len(), 1);
}
#[test]
fn sorted_capability_names_orders_case_insensitively() {
let caps: HashSet<String> = ["Zebra", "apple", "Banana"]
.iter()
.map(|s| s.to_string())
.collect();
assert_eq!(
sorted_capability_names(&caps),
vec!["apple", "Banana", "Zebra"]
);
}
#[test]
fn sorted_capability_names_handles_empty_set() {
let caps: HashSet<String> = HashSet::new();
assert!(sorted_capability_names(&caps).is_empty());
}
#[test]
#[ignore = "needs a real captured EventID=14 ACE blob; see TODO above"]
fn golden_fixture_needed_real_ace_blob_decodes() {
unimplemented!("paste a captured ACE blob and its expected capabilities");
}
}
#[cfg(all(test, target_os = "windows"))]
mod windows_ffi_tests {
use super::*;
#[test]
fn build_capability_index_derives_real_sids() {
let index = build_capability_index();
assert_eq!(
index.resolved_capabilities() + index.derive_failures(),
KNOWN_CAPABILITIES.len(),
"every known capability must be either derived or counted as a failure"
);
if index.resolved_capabilities() == 0 {
assert_eq!(index.derive_failures(), KNOWN_CAPABILITIES.len());
return;
}
for (sid, name, _is_group) in index.iter_sids() {
assert!(!name.is_empty());
assert!(
sid_to_string(sid).is_some(),
"derived SID for {name} did not round-trip through ConvertSidToStringSid"
);
}
}
#[test]
fn real_derived_sid_resolves_through_the_index() {
let index = build_capability_index();
let Some((sid, name)) = index.iter_sids().next().map(|(s, n, _)| (s.to_vec(), n)) else {
return;
};
let mut ace = vec![ACE_TYPE_ACCESS_ALLOWED, 0, 0, 0];
ace.extend_from_slice(&[0, 0, 0, 0]);
ace.extend_from_slice(&0x0012_0089u32.to_le_bytes());
ace.extend_from_slice(&sid);
let mut found = HashSet::new();
let mut zero_mask = 0usize;
walk_aces(&ace, &index, false, &mut found, &mut zero_mask).unwrap();
assert!(
found.contains(name),
"walker did not recover {name} from a real derived SID"
);
}
#[test]
fn repeated_index_builds_are_stable_and_do_not_leak_handles() {
let a = build_capability_index();
let b = build_capability_index();
assert_eq!(a.resolved_capabilities(), b.resolved_capabilities());
assert_eq!(a.derive_failures(), b.derive_failures());
let mut a_pairs: Vec<(Vec<u8>, &str, bool)> =
a.iter_sids().map(|(s, n, g)| (s.to_vec(), n, g)).collect();
let mut b_pairs: Vec<(Vec<u8>, &str, bool)> =
b.iter_sids().map(|(s, n, g)| (s.to_vec(), n, g)).collect();
a_pairs.sort();
b_pairs.sort();
assert_eq!(a_pairs, b_pairs);
}
}