use crate::learning_mode_core::{
AccessType, ResourceType, VerboseLoggingOutcomeReason, VerboseLoggingProvider,
};
use crate::mxc_common::hashing::sha256_hex;
use windows::core::GUID;
pub(crate) const KERNEL_GENERAL_PROVIDER: GUID = GUID {
data1: 0xa68c_a8b7,
data2: 0x004f,
data3: 0xd7b6,
data4: [0xa6, 0x98, 0x07, 0xe2, 0xde, 0x0f, 0x1f, 0x5d],
};
pub(crate) const PRIVACY_LEARNING_MODE_PROVIDER: GUID = GUID {
data1: 0x811a_1ddb,
data2: 0x2e69,
data3: 0x5f25,
data4: [0xad, 0xc0, 0x4b, 0x18, 0x61, 0x70, 0xe7, 0x60],
};
pub(crate) const NETWORK_DECISION_PROVIDER: GUID =
GUID::from_u128(0x301ec03d_2951_5efb_6d99_59c64628bbfc);
pub(crate) const NETWORK_DECISION_EVENT_ID: u16 = 1;
pub(crate) const ACCESS_CHECK_EVENT_ID: u16 = 14;
pub(crate) const LEARNING_MODE_VIOLATION_EVENT_ID: u16 = 27;
pub(crate) const CAPABILITY_DENIAL_EVENT_ID: u16 = 28;
pub(crate) const PRIVACY_ACCESS_CHECK_EVENT_ID: u16 = 4907;
const COM_ACTIVATION_OBJECT_TYPE: &str = "ComActivationForClass";
const COM_CALL_OBJECT_TYPE: &str = "ComCallOnInterface";
#[derive(Debug, Clone)]
pub struct DecodedEventParts {
pub provider: GUID,
pub event_id: u16,
pub event_name: Option<String>,
pub props: Vec<(String, String)>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RawDenial {
pub pid: u32,
pub resource_type: ResourceType,
pub object_name: String,
pub access_type: AccessType,
pub filetime: u64,
pub event_id: u16,
pub provider: Option<VerboseLoggingProvider>,
pub verbose_logging_properties: Vec<(String, String)>,
}
pub fn extract_denial(
parts: &DecodedEventParts,
pid: u32,
filetime: u64,
) -> Result<RawDenial, VerboseLoggingOutcomeReason> {
let provider = verbose_logging_provider_for_guid(parts.provider)
.ok_or(VerboseLoggingOutcomeReason::UnsupportedEventSchema)?;
if !is_learning_mode_event(parts.provider, parts.event_id) {
return Err(VerboseLoggingOutcomeReason::UnsupportedEventSchema);
}
match parts.event_id {
ACCESS_CHECK_EVENT_ID | PRIVACY_ACCESS_CHECK_EVENT_ID => {
build_denial_from_access_check(parts, pid, filetime, provider)
}
LEARNING_MODE_VIOLATION_EVENT_ID => {
build_denial_from_learning_mode(parts, pid, filetime, provider)
}
CAPABILITY_DENIAL_EVENT_ID if is_ui_violation_schema(parts) => {
build_denial_from_learning_mode(parts, pid, filetime, provider)
}
CAPABILITY_DENIAL_EVENT_ID => build_denial_from_capability(parts, pid, filetime, provider),
_ => Err(VerboseLoggingOutcomeReason::UnsupportedEventSchema),
}
}
pub(crate) fn verbose_logging_classification(
parts: &DecodedEventParts,
) -> (Option<AccessType>, Option<ResourceType>) {
if parts.provider == super::network_extractors::NETWORK_DECISION_PROVIDER {
return super::network_extractors::verbose_logging_classification(parts);
}
match parts.event_id {
ACCESS_CHECK_EVENT_ID | PRIVACY_ACCESS_CHECK_EVENT_ID => {
let Some(object_type) = find_prop(&parts.props, "ObjectType") else {
return (None, None);
};
match object_type.trim_matches('"') {
"File" => (
Some(
find_prop(&parts.props, "AccessMask")
.and_then(|value| parse_u32(value))
.map(|mask| access_type_from_mask(mask, false))
.unwrap_or(AccessType::Unknown),
),
Some(ResourceType::File),
),
"Key" => (
Some(
find_prop(&parts.props, "AccessMask")
.and_then(|value| parse_u32(value))
.map(|mask| access_type_from_mask(mask, true))
.unwrap_or(AccessType::Unknown),
),
Some(ResourceType::Other),
),
"Section" | "SymbolicLink" | "Timer" => (
Some(
find_prop(&parts.props, "AccessMask")
.and_then(|value| parse_u32(value))
.map(|mask| {
named_object_access_type(object_type.trim_matches('"'), mask)
})
.unwrap_or(AccessType::Unknown),
),
Some(ResourceType::Other),
),
object_type if com_outcome_reason(object_type).is_some() => {
(None, Some(ResourceType::Other))
}
"" => (Some(AccessType::Unknown), Some(ResourceType::Capability)),
_ => (None, None),
}
}
LEARNING_MODE_VIOLATION_EVENT_ID => (Some(AccessType::Unknown), Some(ResourceType::Ui)),
CAPABILITY_DENIAL_EVENT_ID if is_ui_violation_schema(parts) => {
(Some(AccessType::Unknown), Some(ResourceType::Ui))
}
CAPABILITY_DENIAL_EVENT_ID => (Some(AccessType::Unknown), Some(ResourceType::Capability)),
_ => (None, None),
}
}
pub(crate) fn is_learning_mode_event(provider: GUID, event_id: u16) -> bool {
if provider == KERNEL_GENERAL_PROVIDER {
matches!(
event_id,
ACCESS_CHECK_EVENT_ID | LEARNING_MODE_VIOLATION_EVENT_ID | CAPABILITY_DENIAL_EVENT_ID
)
} else if provider == PRIVACY_LEARNING_MODE_PROVIDER {
matches!(
event_id,
ACCESS_CHECK_EVENT_ID
| LEARNING_MODE_VIOLATION_EVENT_ID
| PRIVACY_ACCESS_CHECK_EVENT_ID
)
} else if provider == NETWORK_DECISION_PROVIDER {
event_id == NETWORK_DECISION_EVENT_ID
} else {
false
}
}
pub(crate) fn is_process_scoped_event(provider: GUID, event_id: u16) -> bool {
provider != NETWORK_DECISION_PROVIDER && is_learning_mode_event(provider, event_id)
}
pub(crate) fn effective_event_pid(parts: &DecodedEventParts, header_pid: u32) -> Option<u32> {
if parts.provider == NETWORK_DECISION_PROVIDER {
Some(0)
} else if parts.event_id == CAPABILITY_DENIAL_EVENT_ID {
effective_capability_event_pid(
find_prop(&parts.props, "ProcessId").map(std::string::String::as_str),
)
} else {
Some(header_pid)
}
}
fn is_ui_violation_schema(parts: &DecodedEventParts) -> bool {
parts.event_id == CAPABILITY_DENIAL_EVENT_ID
&& find_prop(&parts.props, "Detail").is_some()
&& find_prop(&parts.props, "Category").is_some()
}
pub(crate) fn effective_capability_event_pid(process_id: Option<&str>) -> Option<u32> {
process_id.and_then(parse_u32)
}
pub(crate) fn verbose_logging_provider_for_guid(provider: GUID) -> Option<VerboseLoggingProvider> {
if provider == KERNEL_GENERAL_PROVIDER {
Some(VerboseLoggingProvider::KernelGeneral)
} else if provider == PRIVACY_LEARNING_MODE_PROVIDER {
Some(VerboseLoggingProvider::PrivacyAuditingPermissiveLearningMode)
} else {
None
}
}
pub(crate) fn verbose_logging_provider_guid(provider: VerboseLoggingProvider) -> String {
match provider {
VerboseLoggingProvider::KernelGeneral => {
format_guid_braced_uppercase(KERNEL_GENERAL_PROVIDER)
}
VerboseLoggingProvider::PrivacyAuditingPermissiveLearningMode => {
format_guid_braced_uppercase(PRIVACY_LEARNING_MODE_PROVIDER)
}
}
}
pub(crate) fn format_guid_braced_uppercase(guid: GUID) -> String {
format!(
"{{{:08X}-{:04X}-{:04X}-{:02X}{:02X}-{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}}}",
guid.data1,
guid.data2,
guid.data3,
guid.data4[0],
guid.data4[1],
guid.data4[2],
guid.data4[3],
guid.data4[4],
guid.data4[5],
guid.data4[6],
guid.data4[7],
)
}
pub(crate) const REDACTED_USER: &str = "<redacted-user>";
pub(crate) const REDACTED_PATH: &str = "<REDACTED>";
pub(crate) const MAX_SIGNATURE_PROPERTIES: usize = 24;
pub(crate) const MAX_SIGNATURE_VALUE_LEN: usize = 256;
const SHA256_HEX_LEN: usize = 64;
const BOUNDED_VALUE_MARKER_LEN: usize = "...<sha256=".len() + SHA256_HEX_LEN + ">...".len();
const _: () = assert!(MAX_SIGNATURE_VALUE_LEN > BOUNDED_VALUE_MARKER_LEN);
const TIMESTAMP_PROPERTY_NAMES: &[&str] = &[
"time",
"timestamp",
"filetime",
"systemtime",
"eventtime",
"timecreated",
"creationtime",
"createtime",
"starttime",
"endtime",
"exittime",
"lastwritetime",
];
const RETAINED_IDENTIFIER_SUFFIXES: &[&str] = &["sid", "guid", "identifier", "id"];
const IDENTITY_PROPERTY_NAMES: &[&str] = &["user", "account", "owner", "upn"];
const IDENTITY_PROPERTY_SUFFIXES: &[&str] = &[
"username",
"accountname",
"ownername",
"principalname",
"account",
"upn",
];
#[derive(Clone, Copy)]
struct NormalizedPropertyName<'a>(&'a str);
impl<'a> NormalizedPropertyName<'a> {
fn bytes(self) -> impl DoubleEndedIterator<Item = u8> + Clone + 'a {
self.0
.bytes()
.filter(|byte| !matches!(byte, b'_' | b'-'))
.map(|byte| byte.to_ascii_lowercase())
}
fn equals(self, expected: &str) -> bool {
self.bytes().eq(expected.bytes())
}
fn ends_with(self, suffix: &str) -> bool {
let mut bytes = self.bytes().rev();
suffix
.bytes()
.rev()
.all(|expected| bytes.next() == Some(expected))
}
}
fn is_timestamp_like_property(name: &str) -> bool {
let normalized = NormalizedPropertyName(name);
TIMESTAMP_PROPERTY_NAMES
.iter()
.copied()
.any(|expected| normalized.equals(expected))
|| normalized.ends_with("timestamp")
|| normalized.ends_with("filetime")
}
fn is_identity_property(name: &str) -> bool {
let normalized = NormalizedPropertyName(name);
if RETAINED_IDENTIFIER_SUFFIXES
.iter()
.copied()
.any(|suffix| normalized.equals(suffix) || normalized.ends_with(suffix))
{
return false;
}
IDENTITY_PROPERTY_NAMES
.iter()
.copied()
.any(|expected| normalized.equals(expected))
|| IDENTITY_PROPERTY_SUFFIXES
.iter()
.copied()
.any(|suffix| normalized.ends_with(suffix))
}
fn looks_like_file_path_property(name: &str, value: &str, object_type: Option<&str>) -> bool {
let normalized = NormalizedPropertyName(name);
if normalized.equals("applicationid") {
return true;
}
if normalized.ends_with("path")
|| normalized.ends_with("filename")
|| normalized.ends_with("filenamestring")
{
return true;
}
if normalized.equals("objectname") || normalized.equals("resource") {
if object_type.is_some_and(|object_type| com_outcome_reason(object_type).is_some()) {
return !is_guid_identifier(value);
}
if object_type.is_some_and(|object_type| object_type.eq_ignore_ascii_case("File")) {
return true;
}
}
contains_file_path(value)
}
fn contains_file_path(value: &str) -> bool {
value.match_indices(['\\', ':']).any(|(offset, marker)| {
if value[offset..].starts_with(r"\\\\") {
return false;
}
let offset = if marker == ":" {
offset.saturating_sub(1)
} else {
offset
};
let Some(candidate) = value.get(offset..) else {
return false;
};
if offset > 0
&& candidate.get(1..4) == Some("://")
&& (value.as_bytes()[offset - 1].is_ascii_alphanumeric()
|| matches!(value.as_bytes()[offset - 1], b'+' | b'-' | b'.'))
{
return false;
}
crate::learning_mode_windows::path_norm::is_user_visible_absolute(candidate)
|| looks_like_dos_device_filesystem_path(candidate)
|| looks_like_nt_filesystem_path(candidate)
})
}
fn looks_like_dos_device_filesystem_path(value: &str) -> bool {
let rest = [r"\??\", r"\\?\", r"\\.\"]
.into_iter()
.find_map(|prefix| strip_prefix_ignore_ascii_case(value, prefix));
let Some(rest) = rest else {
return false;
};
if looks_like_drive_absolute_path(rest)
|| strip_prefix_ignore_ascii_case(rest, r"UNC\").is_some()
{
return true;
}
let Some(volume) = strip_prefix_ignore_ascii_case(rest, "Volume{") else {
return false;
};
volume
.split_once('\\')
.is_some_and(|(guid, _)| guid.ends_with('}'))
}
fn looks_like_drive_absolute_path(value: &str) -> bool {
let bytes = value.as_bytes();
bytes.len() >= 3
&& bytes[0].is_ascii_alphabetic()
&& bytes[1] == b':'
&& matches!(bytes[2], b'\\' | b'/')
}
fn looks_like_nt_filesystem_path(value: &str) -> bool {
let Some(rest) = strip_prefix_ignore_ascii_case(value, r"\Device\") else {
return false;
};
let Some((device, _path)) = rest.split_once('\\') else {
return false;
};
if device.eq_ignore_ascii_case("Mup") || ends_with_ignore_ascii_case(device, "Redirector") {
return true;
}
let Some(volume_number) = strip_prefix_ignore_ascii_case(device, "HarddiskVolume") else {
return false;
};
!volume_number.is_empty() && volume_number.bytes().all(|byte| byte.is_ascii_digit())
}
fn strip_prefix_ignore_ascii_case<'a>(value: &'a str, prefix: &str) -> Option<&'a str> {
value
.get(..prefix.len())
.is_some_and(|candidate| candidate.eq_ignore_ascii_case(prefix))
.then(|| &value[prefix.len()..])
}
fn ends_with_ignore_ascii_case(value: &str, suffix: &str) -> bool {
value
.get(value.len().saturating_sub(suffix.len())..)
.is_some_and(|candidate| candidate.eq_ignore_ascii_case(suffix))
}
pub(crate) fn bound_properties(mut properties: Vec<(String, String)>) -> Vec<(String, String)> {
properties.truncate(MAX_SIGNATURE_PROPERTIES);
for (_, value) in &mut properties {
let char_count = value.chars().count();
if char_count > MAX_SIGNATURE_VALUE_LEN {
*value = bound_property_value(value, char_count);
}
}
properties
}
fn bound_property_value(value: &str, char_count: usize) -> String {
let digest = sha256_hex(value.as_bytes());
let marker = format!("...<sha256={digest}>...");
debug_assert_eq!(marker.len(), BOUNDED_VALUE_MARKER_LEN);
let context_len = MAX_SIGNATURE_VALUE_LEN - BOUNDED_VALUE_MARKER_LEN;
let prefix_len = context_len.div_ceil(2);
let suffix_len = context_len / 2;
let prefix = value.chars().take(prefix_len).collect::<String>();
let suffix = value
.chars()
.skip(char_count - suffix_len)
.collect::<String>();
format!("{prefix}{marker}{suffix}")
}
pub(crate) fn sanitize_properties(props: &[(String, String)]) -> Vec<(String, String)> {
let usernames = props
.iter()
.filter(|(name, _)| is_identity_property(name))
.flat_map(|(_, value)| username_match_candidates(value.trim_matches('"')))
.collect::<Vec<_>>();
let object_type = props
.iter()
.find(|(name, _)| name.eq_ignore_ascii_case("ObjectType"))
.map(|(_, value)| value.trim_matches('"'));
let mut sanitized = std::collections::BTreeMap::new();
for (name, raw_value) in props {
if is_timestamp_like_property(name) || contains_file_path(name) {
continue;
}
let value = raw_value.trim_matches('"');
let sanitized_value = if is_identity_property(name) {
REDACTED_USER.to_string()
} else if looks_like_file_path_property(name, value, object_type) {
REDACTED_PATH.to_string()
} else {
redact_known_username_components(value, &usernames)
};
sanitized.insert(name.clone(), sanitized_value);
}
fn username_match_candidates(identity: &str) -> Vec<String> {
let mut candidates = Vec::new();
let account = identity
.rsplit_once('\\')
.map_or(identity, |(_, account)| account);
for candidate in [
identity,
account,
account.split_once('@').map_or(account, |(name, _)| name),
] {
if !candidate.is_empty()
&& !candidates
.iter()
.any(|existing: &String| windows_paths_equal_ignore_case(existing, candidate))
{
candidates.push(candidate.to_string());
}
}
candidates
}
fn redact_known_username_components(value: &str, usernames: &[String]) -> String {
value
.split_inclusive(['\\', '/'])
.map(|component| {
let (segment, separator) = if component.ends_with('\\') || component.ends_with('/')
{
component.split_at(component.len() - 1)
} else {
(component, "")
};
if usernames
.iter()
.any(|username| windows_paths_equal_ignore_case(segment, username))
{
format!("{REDACTED_USER}{separator}")
} else {
component.to_string()
}
})
.collect()
}
bound_properties(sanitized.into_iter().collect())
}
pub(crate) fn sanitize_event_name(name: Option<&str>) -> Option<String> {
let name = name?;
sanitize_properties(&[("EventName".into(), name.into())])
.into_iter()
.next()
.map(|(_, value)| value)
}
pub fn build_denial_from_access_check(
parts: &DecodedEventParts,
pid: u32,
filetime: u64,
provider: VerboseLoggingProvider,
) -> Result<RawDenial, VerboseLoggingOutcomeReason> {
let object_type = find_prop(&parts.props, "ObjectType")
.ok_or(VerboseLoggingOutcomeReason::MissingObjectType)?;
let object_type_str = object_type.trim_matches('"');
let com_reason = com_outcome_reason(object_type_str);
let resource_type = match object_type_str {
"File" => ResourceType::File,
"Key" => ResourceType::Other,
"Section" | "SymbolicLink" | "Timer" => ResourceType::Other,
"" => ResourceType::Capability,
_ if com_reason.is_some() => ResourceType::Other,
_ => return Err(VerboseLoggingOutcomeReason::UnsupportedObjectType),
};
let object_name = find_prop(&parts.props, "ObjectName")
.map(|v| v.trim_matches('"').to_string())
.filter(|name| !name.is_empty());
let object_name = match (resource_type, object_name) {
(ResourceType::Capability, None) => {
return Err(VerboseLoggingOutcomeReason::UnresolvedCapability)
}
(_, None) => return Err(VerboseLoggingOutcomeReason::MissingObjectName),
(_, Some(name)) => name,
};
if let Some(reason) = com_reason {
if !is_guid_identifier(&object_name) {
return Err(VerboseLoggingOutcomeReason::EventPayloadMalformed);
}
return Err(reason);
}
if resource_type == ResourceType::File {
let app_path = find_prop(&parts.props, "AppPath")
.or_else(|| find_prop(&parts.props, "ApplicationPath"))
.map(|value| value.trim_matches('"'));
if app_path.is_some_and(|app_path| is_self_access(&object_name, app_path)) {
return Err(VerboseLoggingOutcomeReason::NotActionable);
}
}
let access_type = if resource_type == ResourceType::Capability {
AccessType::Unknown
} else {
find_prop(&parts.props, "AccessMask")
.and_then(|v| parse_u32(v))
.map(|mask| match object_type_str {
"Key" => access_type_from_mask(mask, true),
"File" => access_type_from_mask(mask, false),
_ => named_object_access_type(object_type_str, mask),
})
.unwrap_or(AccessType::Unknown)
};
if (object_type_str == "Key" && access_type != AccessType::Read)
|| matches!(object_type_str, "Section" | "SymbolicLink" | "Timer")
{
return Err(VerboseLoggingOutcomeReason::NotActionable);
}
Ok(RawDenial {
pid,
resource_type,
object_name,
access_type,
filetime,
event_id: parts.event_id,
provider: Some(provider),
verbose_logging_properties: sanitize_properties(&parts.props),
})
}
fn is_self_access(object_name: &str, app_path: &str) -> bool {
let object_name = strip_dos_namespace_prefix(object_name);
let app_path = strip_dos_namespace_prefix(app_path);
match (path_namespace(object_name), path_namespace(app_path)) {
(Some(object_namespace), Some(app_namespace)) if object_namespace == app_namespace => {
windows_paths_equal_ignore_case(object_name, app_path)
}
(Some(PathNamespace::Dos), Some(PathNamespace::DeviceVolume)) => {
crate::learning_mode_windows::path_norm::device_path_matches_dos(app_path, object_name)
}
(Some(PathNamespace::DeviceVolume), Some(PathNamespace::Dos)) => {
crate::learning_mode_windows::path_norm::device_path_matches_dos(object_name, app_path)
}
_ => false,
}
}
fn windows_paths_equal_ignore_case(a: &str, b: &str) -> bool {
crate::mxc_common::string_util::windows_paths_equal_ignore_case(a, b)
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum PathNamespace {
Dos,
DeviceVolume,
}
fn path_namespace(path: &str) -> Option<PathNamespace> {
let bytes = path.as_bytes();
if bytes.len() >= 3 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' && bytes[2] == b'\\' {
return Some(PathNamespace::Dos);
}
const VOLUME_PREFIX: &str = r"\Device\HarddiskVolume";
path.get(..VOLUME_PREFIX.len())
.is_some_and(|prefix| prefix.eq_ignore_ascii_case(VOLUME_PREFIX))
.then_some(PathNamespace::DeviceVolume)
}
fn strip_dos_namespace_prefix(path: &str) -> &str {
for prefix in [r"\??\", r"\\?\", r"\\.\"] {
if let Some(path) = path.strip_prefix(prefix) {
return path;
}
}
path
}
pub fn build_denial_from_learning_mode(
parts: &DecodedEventParts,
pid: u32,
filetime: u64,
provider: VerboseLoggingProvider,
) -> Result<RawDenial, VerboseLoggingOutcomeReason> {
let category = find_prop(&parts.props, "Category")
.and_then(|value| parse_u32(value))
.ok_or(VerboseLoggingOutcomeReason::MissingObjectType)?;
let detail = match find_prop(&parts.props, "Detail") {
Some(value) => parse_u32(value).ok_or(VerboseLoggingOutcomeReason::MissingObjectName)?,
None if category == crate::learning_mode_windows::ui::CONVERT_TO_GUI => 0,
None => return Err(VerboseLoggingOutcomeReason::MissingObjectName),
};
let object_name = crate::learning_mode_windows::ui::resource_name(category, detail)
.ok_or(VerboseLoggingOutcomeReason::NotActionable)?;
Ok(RawDenial {
pid,
resource_type: ResourceType::Ui,
object_name,
access_type: AccessType::Unknown,
filetime,
event_id: parts.event_id,
provider: Some(provider),
verbose_logging_properties: sanitize_properties(&parts.props),
})
}
pub fn build_denial_from_capability(
parts: &DecodedEventParts,
pid: u32,
filetime: u64,
provider: VerboseLoggingProvider,
) -> Result<RawDenial, VerboseLoggingOutcomeReason> {
let denied = find_prop(&parts.props, "Denied")
.is_some_and(|value| value.trim_matches('"').eq_ignore_ascii_case("true"));
if !denied {
return Err(VerboseLoggingOutcomeReason::NotActionable);
}
let pid = find_prop(&parts.props, "ProcessId")
.and_then(|v| parse_u32(v))
.unwrap_or(pid);
let object_name = find_prop(&parts.props, "CapabilityName")
.or_else(|| find_prop(&parts.props, "Capability"))
.map(|v| v.trim_matches('"').to_string())
.or_else(|| {
find_prop(&parts.props, "PackageSid")
.or_else(|| find_prop(&parts.props, "CapabilitySid"))
.or_else(|| find_prop(&parts.props, "Sid"))
.map(|v| {
crate::learning_mode_windows::capability_names::resolve(v.trim_matches('"'))
})
})
.filter(|name| {
!name.is_empty()
&& name != "<unsupported>"
&& name != "<invalid SID>"
&& name != "<malformed-sid>"
})
.ok_or(VerboseLoggingOutcomeReason::UnresolvedCapability)?;
Ok(RawDenial {
pid,
resource_type: ResourceType::Capability,
object_name,
access_type: AccessType::Unknown,
filetime,
event_id: parts.event_id,
provider: Some(provider),
verbose_logging_properties: sanitize_properties(&parts.props),
})
}
fn parse_u32(raw: &str) -> Option<u32> {
let s = raw.trim().trim_matches('"').trim();
if let Some(hex) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
return u32::from_str_radix(hex, 16).ok();
}
s.parse::<u32>()
.ok()
.or_else(|| u32::from_str_radix(s, 16).ok())
}
fn access_type_from_mask(mask: u32, is_registry: bool) -> AccessType {
const DELETE: u32 = 0x0001_0000;
const WRITE_DAC: u32 = 0x0004_0000;
const WRITE_OWNER: u32 = 0x0008_0000;
const GENERIC_READ: u32 = 0x8000_0000;
const GENERIC_WRITE: u32 = 0x4000_0000;
const GENERIC_EXECUTE: u32 = 0x2000_0000;
const GENERIC_ALL: u32 = 0x1000_0000;
let standard_write = DELETE | WRITE_DAC | WRITE_OWNER;
let (read_bits, write_bits, execute_bits) = if is_registry {
const KEY_QUERY_VALUE: u32 = 0x0001;
const KEY_SET_VALUE: u32 = 0x0002;
const KEY_CREATE_SUB_KEY: u32 = 0x0004;
const KEY_ENUMERATE_SUB_KEYS: u32 = 0x0008;
const KEY_NOTIFY: u32 = 0x0010;
const KEY_CREATE_LINK: u32 = 0x0020;
(
KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS | KEY_NOTIFY | GENERIC_READ | GENERIC_EXECUTE,
KEY_SET_VALUE
| KEY_CREATE_SUB_KEY
| KEY_CREATE_LINK
| standard_write
| GENERIC_WRITE
| GENERIC_ALL,
0,
)
} else {
const FILE_READ_DATA: u32 = 0x0001; const FILE_WRITE_DATA: u32 = 0x0002; const FILE_APPEND_DATA: u32 = 0x0004; const FILE_READ_EA: u32 = 0x0008;
const FILE_WRITE_EA: u32 = 0x0010;
const FILE_EXECUTE: u32 = 0x0020; const FILE_DELETE_CHILD: u32 = 0x0040;
const FILE_READ_ATTRIBUTES: u32 = 0x0080;
const FILE_WRITE_ATTRIBUTES: u32 = 0x0100;
(
FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES | GENERIC_READ,
FILE_WRITE_DATA
| FILE_APPEND_DATA
| FILE_WRITE_EA
| FILE_DELETE_CHILD
| FILE_WRITE_ATTRIBUTES
| standard_write
| GENERIC_WRITE
| GENERIC_ALL,
FILE_EXECUTE | GENERIC_EXECUTE,
)
};
if mask & write_bits != 0 {
AccessType::Write
} else if mask & execute_bits != 0 {
AccessType::Execute
} else if mask & read_bits != 0 {
AccessType::Read
} else {
AccessType::Unknown
}
}
fn named_object_access_type(object_type: &str, mask: u32) -> AccessType {
let (read_bits, write_bits, execute_bits) = match object_type {
"Section" => (0x0001 | 0x0004, 0x0002 | 0x0010, 0x0008 | 0x0020),
"SymbolicLink" => (0x0001, 0x0002, 0),
"Timer" => (0x0001, 0x0002, 0),
_ => return AccessType::Unknown,
};
const DELETE: u32 = 0x0001_0000;
const WRITE_DAC: u32 = 0x0004_0000;
const WRITE_OWNER: u32 = 0x0008_0000;
const GENERIC_READ: u32 = 0x8000_0000;
const GENERIC_WRITE: u32 = 0x4000_0000;
const GENERIC_EXECUTE: u32 = 0x2000_0000;
const GENERIC_ALL: u32 = 0x1000_0000;
if mask & (write_bits | DELETE | WRITE_DAC | WRITE_OWNER | GENERIC_WRITE | GENERIC_ALL) != 0 {
AccessType::Write
} else if mask & (execute_bits | GENERIC_EXECUTE) != 0 {
AccessType::Execute
} else if mask & (read_bits | GENERIC_READ) != 0 {
AccessType::Read
} else {
AccessType::Unknown
}
}
fn find_prop<'a>(props: &'a [(String, String)], name: &str) -> Option<&'a String> {
props.iter().find(|(k, _)| k == name).map(|(_, v)| v)
}
fn com_outcome_reason(object_type: &str) -> Option<VerboseLoggingOutcomeReason> {
match object_type {
COM_ACTIVATION_OBJECT_TYPE => Some(VerboseLoggingOutcomeReason::ComActivation),
COM_CALL_OBJECT_TYPE => Some(VerboseLoggingOutcomeReason::ComInterfaceCall),
_ => None,
}
}
fn is_guid_identifier(value: &str) -> bool {
let value = value
.strip_prefix('{')
.and_then(|value| value.strip_suffix('}'))
.unwrap_or(value);
GUID::try_from(value).is_ok()
}
#[cfg(test)]
mod tests {
use super::*;
const FIXED_FILETIME: u64 = 132_847_890_123_456_789;
fn parts(event_id: u16, kv: &[(&str, &str)]) -> DecodedEventParts {
let provider = if event_id == 4907 {
PRIVACY_LEARNING_MODE_PROVIDER
} else {
KERNEL_GENERAL_PROVIDER
};
parts_with_provider(provider, event_id, kv)
}
fn parts_with_provider(
provider: GUID,
event_id: u16,
kv: &[(&str, &str)],
) -> DecodedEventParts {
DecodedEventParts {
provider,
event_id,
event_name: None,
props: kv
.iter()
.map(|(k, v)| ((*k).to_string(), (*v).to_string()))
.collect(),
}
}
#[test]
fn access_check_file_denial_read_mask() {
let p = parts(
14,
&[
("Mode", "\"Normal\""),
("ObjectType", "\"File\""),
(
"ObjectName",
"\"\\Device\\HarddiskVolume3\\Users\\x\\f.txt\"",
),
("AccessMask", "0x120089"),
],
);
let ev = extract_denial(&p, 7777, FIXED_FILETIME).expect("should extract");
assert_eq!(ev.event_id, 14);
assert_eq!(ev.pid, 7777);
assert_eq!(ev.resource_type, ResourceType::File);
assert_eq!(ev.object_name, r"\Device\HarddiskVolume3\Users\x\f.txt");
assert_eq!(ev.access_type, AccessType::Read);
assert_eq!(ev.filetime, FIXED_FILETIME);
}
#[test]
fn access_check_event_4907_still_routed() {
let p = parts(
4907,
&[
("ObjectType", "\"File\""),
("ObjectName", "\"c:\\x\""),
("AccessMask", "0x1"),
],
);
let ev = extract_denial(&p, 1, FIXED_FILETIME).expect("should extract");
assert_eq!(ev.resource_type, ResourceType::File);
assert_eq!(ev.access_type, AccessType::Read);
}
#[test]
fn access_check_write_mask_classified_write() {
let p = parts(
14,
&[
("ObjectType", "\"File\""),
("ObjectName", "\"c:\\x\""),
("AccessMask", "0x10001"),
],
);
let ev = extract_denial(&p, 1, FIXED_FILETIME).unwrap();
assert_eq!(ev.access_type, AccessType::Write);
}
#[test]
fn access_check_drops_workload_self_access() {
let drive_map = crate::learning_mode_windows::path_norm::rebuild_drive_map_for_tests();
let (drive, device) = drive_map
.first()
.expect("Windows test host has a drive map");
let object_name = format!(r#""\??\{drive}\Tools\App.EXE""#);
for app_path in [
format!(r#""{device}\Tools\app.exe""#),
format!(r#""{drive}\Tools\app.exe""#),
] {
let p = parts(
14,
&[
("ObjectType", "\"File\""),
("ObjectName", &object_name),
("AppPath", &app_path),
("AccessMask", "0x1"),
],
);
assert_eq!(
extract_denial(&p, 1, FIXED_FILETIME).unwrap_err(),
VerboseLoggingOutcomeReason::NotActionable
);
}
}
#[test]
fn access_check_preserves_mixed_namespace_path_on_another_volume() {
let drive_map = crate::learning_mode_windows::path_norm::rebuild_drive_map_for_tests();
let (drive, device) = drive_map
.first()
.expect("Windows test host has a drive map");
let other_drive = if drive.eq_ignore_ascii_case("C:") {
"D:"
} else {
"C:"
};
let object_name = format!(r#""{other_drive}\Tools\app.exe""#);
let app_path = format!(r#""{device}\Tools\app.exe""#);
let p = parts(
14,
&[
("ObjectType", "\"File\""),
("ObjectName", &object_name),
("AppPath", &app_path),
("AccessMask", "0x1"),
],
);
assert!(extract_denial(&p, 1, FIXED_FILETIME).is_ok());
}
#[test]
fn access_check_preserves_unmapped_device_path() {
let p = parts(
14,
&[
("ObjectType", "\"File\""),
("ObjectName", r#""C:\Tools\app.exe""#),
(
"AppPath",
r#""\Device\HarddiskVolume4294967295\Tools\app.exe""#,
),
("AccessMask", "0x1"),
],
);
assert!(extract_denial(&p, 1, FIXED_FILETIME).is_ok());
}
#[test]
fn windows_path_comparison_uses_unicode_ordinal_case_folding() {
assert!(windows_paths_equal_ignore_case(
r"C:\TÄST\app.exe",
r"c:\täst\APP.EXE"
));
}
#[test]
fn access_check_preserves_same_suffix_on_different_dos_drives() {
let p = parts(
14,
&[
("ObjectType", "\"File\""),
("ObjectName", r#""C:\Tools\app.exe""#),
("AppPath", r#""D:\Tools\app.exe""#),
("AccessMask", "0x1"),
],
);
assert!(extract_denial(&p, 1, FIXED_FILETIME).is_ok());
}
#[test]
fn access_check_preserves_same_suffix_on_different_device_volumes() {
let p = parts(
14,
&[
("ObjectType", "\"File\""),
("ObjectName", r#""\Device\HarddiskVolume3\Tools\app.exe""#),
("AppPath", r#""\Device\HarddiskVolume4\Tools\app.exe""#),
("AccessMask", "0x1"),
],
);
assert!(extract_denial(&p, 1, FIXED_FILETIME).is_ok());
}
#[test]
fn access_check_keeps_same_name_at_different_path() {
let p = parts(
14,
&[
("ObjectType", "\"File\""),
("ObjectName", r#""C:\app.exe""#),
("AppPath", r#""\Device\HarddiskVolume3\Tools\app.exe""#),
("AccessMask", "0x1"),
],
);
assert!(extract_denial(&p, 1, FIXED_FILETIME).is_ok());
}
#[test]
fn access_check_key_denial_uses_registry_vocabulary() {
let p = parts(
14,
&[
("ObjectType", "\"Key\""),
("ObjectName", "\"\\REGISTRY\\USER\\.DEFAULT\\Console\""),
("AccessMask", "0x20019"),
],
);
let ev = extract_denial(&p, 1, FIXED_FILETIME).expect("should extract");
assert_eq!(ev.resource_type, ResourceType::Other);
assert_eq!(ev.access_type, AccessType::Read);
}
#[test]
fn access_check_key_write_is_not_actionable() {
let p = parts(
14,
&[
("ObjectType", "\"Key\""),
("ObjectName", "\"\\REGISTRY\\USER\\.DEFAULT\\Console\""),
("AccessMask", "0x2"),
],
);
assert_eq!(
extract_denial(&p, 1, FIXED_FILETIME).unwrap_err(),
VerboseLoggingOutcomeReason::NotActionable
);
assert_eq!(
verbose_logging_classification(&p),
(Some(AccessType::Write), Some(ResourceType::Other))
);
}
#[test]
fn access_check_key_unknown_access_is_not_actionable() {
for access_mask in [None, Some("not-a-mask"), Some("0x0")] {
let mut properties = vec![
("ObjectType", "\"Key\""),
("ObjectName", "\"\\REGISTRY\\USER\\.DEFAULT\\Console\""),
];
if let Some(access_mask) = access_mask {
properties.push(("AccessMask", access_mask));
}
let p = parts(14, &properties);
assert_eq!(
extract_denial(&p, 1, FIXED_FILETIME).unwrap_err(),
VerboseLoggingOutcomeReason::NotActionable
);
assert_eq!(
verbose_logging_classification(&p),
(Some(AccessType::Unknown), Some(ResourceType::Other))
);
}
}
#[test]
fn access_check_empty_capability_identifier_is_dropped() {
let p = parts(
14,
&[
("Mode", "\"Permissive\""),
("ObjectType", "\"\""),
("ObjectName", "\"\""),
("AccessMask", "0x1"),
],
);
assert_eq!(
extract_denial(&p, 5900, FIXED_FILETIME).unwrap_err(),
VerboseLoggingOutcomeReason::UnresolvedCapability
);
}
#[test]
fn access_check_empty_file_and_registry_identifiers_are_dropped() {
for object_type in ["File", "Key"] {
let p = parts(
14,
&[
("ObjectType", object_type),
("ObjectName", "\"\""),
("AccessMask", "0x1"),
],
);
assert_eq!(
extract_denial(&p, 5900, FIXED_FILETIME).unwrap_err(),
VerboseLoggingOutcomeReason::MissingObjectName
);
}
}
#[test]
fn access_check_missing_mask_defaults_to_unknown() {
let p = parts(
4907,
&[("ObjectType", "\"File\""), ("ObjectName", "\"c:\\x\"")],
);
let ev = extract_denial(&p, 1, FIXED_FILETIME).unwrap();
assert_eq!(ev.access_type, AccessType::Unknown);
}
#[test]
fn access_check_observed_named_object_types_are_not_actionable() {
for (object_type, object_name, mask, expected_access) in [
(
"Section",
r"\Sessions\1\BaseNamedObjects\shared-section",
"0x6",
AccessType::Write,
),
("SymbolicLink", r"\??\C:", "0x1", AccessType::Read),
(
"Timer",
r"\Sessions\1\BaseNamedObjects\deadline",
"0x1",
AccessType::Read,
),
] {
let p = parts(
14,
&[
("ObjectType", object_type),
("ObjectName", object_name),
("AccessMask", mask),
],
);
assert_eq!(
extract_denial(&p, 1, FIXED_FILETIME).unwrap_err(),
VerboseLoggingOutcomeReason::NotActionable
);
assert_eq!(
verbose_logging_classification(&p),
(Some(expected_access), Some(ResourceType::Other))
);
}
}
#[test]
fn access_check_com_denials_use_distinct_verbose_reasons() {
for (object_type, object_name, mode, expected_reason) in [
(
COM_ACTIVATION_OBJECT_TYPE,
"{A47979D2-C419-11D9-A5B4-001185AD2B89}",
"\"Normal\"",
VerboseLoggingOutcomeReason::ComActivation,
),
(
COM_CALL_OBJECT_TYPE,
"{00000132-0000-0000-C000-000000000046}",
"\"Permissive\"",
VerboseLoggingOutcomeReason::ComInterfaceCall,
),
] {
let p = parts(
14,
&[
("Mode", mode),
("ObjectType", object_type),
("ObjectName", object_name),
("AccessMask", "0xffffffff"),
],
);
assert_eq!(extract_denial(&p, 42, FIXED_FILETIME), Err(expected_reason));
assert_eq!(
verbose_logging_classification(&p),
(None, Some(ResourceType::Other))
);
}
}
#[test]
fn access_check_com_denials_require_guid_identifier() {
for (object_name, expected) in [
(None, VerboseLoggingOutcomeReason::MissingObjectName),
(Some("\"\""), VerboseLoggingOutcomeReason::MissingObjectName),
(
Some("\"not-a-guid\""),
VerboseLoggingOutcomeReason::EventPayloadMalformed,
),
(
Some("\"{00000132-0000-0000-C000-000000000046\""),
VerboseLoggingOutcomeReason::EventPayloadMalformed,
),
(
Some("\"00000132-0000-0000-C000-000000000046}\""),
VerboseLoggingOutcomeReason::EventPayloadMalformed,
),
(
Some("\"00000132-0000-0000-C000-000000000046\""),
VerboseLoggingOutcomeReason::ComInterfaceCall,
),
] {
let mut properties = vec![("ObjectType", COM_CALL_OBJECT_TYPE)];
if let Some(object_name) = object_name {
properties.push(("ObjectName", object_name));
}
let p = parts(14, &properties);
assert_eq!(extract_denial(&p, 42, FIXED_FILETIME), Err(expected));
assert_eq!(
verbose_logging_classification(&p),
(None, Some(ResourceType::Other))
);
}
}
#[test]
fn access_check_rpc_interface_remains_unsupported() {
let p = parts(
14,
&[
("ObjectType", "\"RPC Interface\""),
("ObjectName", "\"f6beaff7-1e19-4fbb-9f8f-b89e2018337c\""),
],
);
assert_eq!(
extract_denial(&p, 1, FIXED_FILETIME),
Err(VerboseLoggingOutcomeReason::UnsupportedObjectType)
);
assert_eq!(verbose_logging_classification(&p), (None, None));
}
#[test]
fn access_check_unrecognized_object_type_is_dropped() {
let p = parts(
14,
&[("ObjectType", "\"Process\""), ("ObjectName", "\"target\"")],
);
assert_eq!(
extract_denial(&p, 1, FIXED_FILETIME).unwrap_err(),
VerboseLoggingOutcomeReason::UnsupportedObjectType
);
}
#[test]
fn access_check_absent_object_type_dropped() {
let p = parts(14, &[("ObjectName", "\"x\"")]);
assert_eq!(
extract_denial(&p, 1, FIXED_FILETIME).unwrap_err(),
VerboseLoggingOutcomeReason::MissingObjectType
);
}
#[test]
fn learning_mode_violation_extracted_as_ui() {
let p = parts(
27,
&[
("ProcessName", "\"caller.exe\""),
("Category", "2"),
("Detail", "4"),
],
);
let ev = extract_denial(&p, 9999, FIXED_FILETIME).expect("should extract");
assert_eq!(ev.event_id, 27);
assert_eq!(ev.resource_type, ResourceType::Ui);
assert_eq!(ev.access_type, AccessType::Unknown);
assert_eq!(ev.object_name, "WriteClipboard");
}
#[test]
fn learning_mode_violation_accepts_hex_category_and_detail() {
let p = parts(
27,
&[
("ProcessName", "\"caller.exe\""),
("Category", "0x2"),
("Detail", "0x200"),
],
);
let ev = extract_denial(&p, 9999, FIXED_FILETIME).expect("should extract");
assert_eq!(ev.object_name, "Injection");
}
#[test]
fn learning_mode_violation_maps_every_ui_limit() {
let expected = [
(0x0001, "Handles"),
(0x0002, "ReadClipboard"),
(0x0004, "WriteClipboard"),
(0x0008, "SystemParameters"),
(0x0010, "DisplaySettings"),
(0x0020, "GlobalAtoms"),
(0x0040, "Desktop"),
(0x0080, "ExitWindows"),
(0x0100, "IME"),
(0x0200, "Injection"),
];
for (detail, name) in expected {
let detail = detail.to_string();
let p = parts(27, &[("Category", "2"), ("Detail", detail.as_str())]);
let ev = extract_denial(&p, 9999, FIXED_FILETIME).expect("should extract");
assert_eq!(ev.object_name, name);
}
}
#[test]
fn learning_mode_violation_is_supported_from_permissive_provider() {
let p = parts_with_provider(
PRIVACY_LEARNING_MODE_PROVIDER,
27,
&[("Category", "1"), ("Detail", "0")],
);
let ev = extract_denial(&p, 9999, FIXED_FILETIME).expect("should extract");
assert_eq!(ev.object_name, "ConvertToGui");
}
#[test]
fn convert_to_gui_does_not_require_detail() {
let p = parts(27, &[("Category", "1")]);
let ev = extract_denial(&p, 9999, FIXED_FILETIME).expect("should extract");
assert_eq!(ev.object_name, "ConvertToGui");
}
#[test]
fn learning_mode_violation_rejects_invalid_required_numbers() {
let invalid_category = parts(27, &[("Category", "not-a-number"), ("Detail", "4")]);
assert_eq!(
extract_denial(&invalid_category, 9999, FIXED_FILETIME).unwrap_err(),
VerboseLoggingOutcomeReason::MissingObjectType
);
let invalid_detail = parts(27, &[("Category", "2"), ("Detail", "not-a-number")]);
assert_eq!(
extract_denial(&invalid_detail, 9999, FIXED_FILETIME).unwrap_err(),
VerboseLoggingOutcomeReason::MissingObjectName
);
}
#[test]
fn learning_mode_category_none_is_dropped() {
let p = parts(27, &[("Category", "0"), ("Detail", "0")]);
assert_eq!(
extract_denial(&p, 9999, FIXED_FILETIME).unwrap_err(),
VerboseLoggingOutcomeReason::NotActionable
);
}
#[test]
fn capability_denial_event_28_extracted() {
let p = parts(
28,
&[
("ProcessName", "\"conhost.exe\""),
("ProcessId", "0x1acc"),
("Category", "1"),
("Denied", "true"),
("PackageSid", "S-1-15-3-1"),
],
);
let ev = extract_denial(&p, 42, FIXED_FILETIME).expect("should extract");
assert_eq!(ev.resource_type, ResourceType::Capability);
assert_eq!(ev.access_type, AccessType::Unknown);
assert_eq!(ev.pid, 0x1acc);
assert_eq!(ev.object_name, "internetClient");
assert_eq!(ev.provider, Some(VerboseLoggingProvider::KernelGeneral));
}
#[test]
fn event_28_ui_violation_is_not_misclassified_as_capability() {
let p = parts(
28,
&[
("ProcessName", "\"powershell.exe\""),
("ProcessId", "0x1594"),
("SequenceNumber", "302"),
("Category", "2"),
("Detail", "1"),
("Denied", "false"),
("UserSid", "S-1-5-21-1-2-3-1000"),
("PackageSid", "S-1-15-2-1-2-3-4-5-6-7"),
],
);
let denial = extract_denial(&p, 0x1594, FIXED_FILETIME).unwrap();
assert_eq!(denial.resource_type, ResourceType::Ui);
assert_eq!(denial.object_name, "Handles");
assert_eq!(denial.pid, 0x1594);
assert_eq!(
verbose_logging_classification(&p),
(Some(AccessType::Unknown), Some(ResourceType::Ui))
);
}
#[test]
fn capability_denial_resolves_well_known_sid_to_name() {
let p = parts(
28,
&[
("ProcessId", "0x10"),
("PackageSid", "\"S-1-15-3-1\""),
("Denied", "true"),
],
);
let ev = extract_denial(&p, 1, FIXED_FILETIME).unwrap();
assert_eq!(ev.resource_type, ResourceType::Capability);
assert_eq!(ev.object_name, "internetClient");
}
#[test]
fn capability_denial_custom_sid_falls_back_to_sid_string() {
let sid = "S-1-15-3-1024-1065365936-1281604716-3511738428-1654721687";
let sid_quoted = format!("\"{sid}\"");
let p = parts(
28,
&[
("ProcessId", "0x10"),
("PackageSid", sid_quoted.as_str()),
("Denied", "true"),
],
);
let ev = extract_denial(&p, 1, FIXED_FILETIME).unwrap();
assert_eq!(ev.object_name, sid);
}
#[test]
fn capability_denial_not_denied_is_dropped() {
let p = parts(28, &[("ProcessId", "0x10"), ("Denied", "false")]);
assert_eq!(
extract_denial(&p, 1, FIXED_FILETIME).unwrap_err(),
VerboseLoggingOutcomeReason::NotActionable
);
}
#[test]
fn capability_denial_without_denied_field_is_dropped() {
let p = parts(28, &[("PackageSid", "S-1-15-3-1")]);
assert_eq!(
extract_denial(&p, 1, FIXED_FILETIME).unwrap_err(),
VerboseLoggingOutcomeReason::NotActionable
);
}
#[test]
fn capability_denial_without_identifier_is_unresolved() {
let p = parts(28, &[("ProcessId", "0x10"), ("Denied", "true")]);
assert_eq!(
extract_denial(&p, 1, FIXED_FILETIME).unwrap_err(),
VerboseLoggingOutcomeReason::UnresolvedCapability
);
}
#[test]
fn unrelated_provider_event_id_is_dropped() {
let p = parts_with_provider(
GUID::from_u128(0x12345678_1234_1234_1234_1234567890ab),
27,
&[("Category", "2"), ("Detail", "4")],
);
assert_eq!(
extract_denial(&p, 1, FIXED_FILETIME).unwrap_err(),
VerboseLoggingOutcomeReason::UnsupportedEventSchema
);
assert!(verbose_logging_provider_for_guid(GUID::from_u128(
0x12345678_1234_1234_1234_1234567890ab
))
.is_none());
}
#[test]
fn capability_denial_uses_supplied_effective_pid() {
let p = parts(28, &[("Denied", "true"), ("PackageSid", "S-1-15-3-1")]);
let ev = extract_denial(&p, 555, FIXED_FILETIME).unwrap();
assert_eq!(ev.pid, 555);
}
#[test]
fn capability_event_requires_payload_pid_for_scoping() {
let missing = parts(28, &[("Denied", "true")]);
let malformed = parts(28, &[("ProcessId", "\"broker\"")]);
let valid = parts(28, &[("ProcessId", "42")]);
assert_eq!(effective_event_pid(&missing, 555), None);
assert_eq!(effective_event_pid(&malformed, 555), None);
assert_eq!(effective_event_pid(&valid, 555), Some(42));
}
#[test]
fn unrelated_event_ignored() {
let p = parts(9999, &[("Foo", "\"bar\"")]);
assert_eq!(
extract_denial(&p, 1, FIXED_FILETIME).unwrap_err(),
VerboseLoggingOutcomeReason::UnsupportedEventSchema
);
}
#[test]
fn known_provider_guid_maps_to_symbolic_pii_free_category() {
assert_eq!(
verbose_logging_provider_for_guid(KERNEL_GENERAL_PROVIDER),
Some(VerboseLoggingProvider::KernelGeneral)
);
assert_eq!(
verbose_logging_provider_for_guid(PRIVACY_LEARNING_MODE_PROVIDER),
Some(VerboseLoggingProvider::PrivacyAuditingPermissiveLearningMode)
);
assert_eq!(verbose_logging_provider_for_guid(GUID::from_u128(0)), None);
}
#[test]
fn verbose_logging_provider_guid_has_stable_spelling() {
let kernel_guid = verbose_logging_provider_guid(VerboseLoggingProvider::KernelGeneral);
let privacy_guid = verbose_logging_provider_guid(
VerboseLoggingProvider::PrivacyAuditingPermissiveLearningMode,
);
assert_ne!(kernel_guid, privacy_guid);
assert_eq!(
kernel_guid,
format_guid_braced_uppercase(KERNEL_GENERAL_PROVIDER)
);
assert_eq!(
privacy_guid,
format_guid_braced_uppercase(PRIVACY_LEARNING_MODE_PROVIDER)
);
assert!(kernel_guid.starts_with('{') && kernel_guid.ends_with('}'));
}
#[test]
fn file_path_detection_preserves_non_file_identifiers() {
assert!(looks_like_file_path_property(
"ObjectName",
r"C:\Users\jsmith\secret.txt",
None
));
assert!(looks_like_file_path_property(
"FilePath",
r"\Device\HarddiskVolume3\secret.txt",
Some("Section")
));
assert!(looks_like_file_path_property(
"ObjectName",
r"C:\Users\alice\secret.txt",
Some("Section")
));
for path in [
r"\Device\HarddiskVolume3\Users\alice\secret.txt",
r"\device\mup\server\share\Users\alice\secret.txt",
r"\Device\LanmanRedirector\;Z:0000000000001234\server\share\secret.txt",
r"\??\C:\Users\alice\secret.txt",
r"\??\UNC\server\share\Users\alice\secret.txt",
] {
assert!(looks_like_file_path_property(
"ObjectName",
path,
Some("Section")
));
}
assert!(!looks_like_file_path_property(
"ObjectName",
r"\BaseNamedObjects\shared-cache",
Some("Section")
));
assert!(!looks_like_file_path_property(
"ObjectName",
r"\REGISTRY\USER\S-1-5-21-1-2-3-1000\Software\Test",
Some("Key")
));
assert!(!looks_like_file_path_property(
"resource",
"internetClient",
None
));
assert!(!looks_like_file_path_property(
"ObjectName",
r"\Device\MountPointManager",
Some("Section")
));
for identifier in [
r"\??\FDC#GENERIC_FLOPPY_DRIVE",
r"\\.\PhysicalDrive0",
"https://example.com/resource",
"custom+a://example.com/resource",
r"\Device\NamedPipe\mxc",
] {
assert!(!looks_like_file_path_property(
"ObjectName",
identifier,
Some("SymbolicLink")
));
}
}
#[test]
fn path_content_scan_handles_candidate_boundaries() {
for (value, expected) in [
("", false),
(":", false),
("::", false),
("\u{03bb}:/not-a-drive", false),
("\u{03bb}:C:/private.txt", true),
("https://example.com:443/resource", false),
("custom+a://example.com/resource", false),
(r"\\server\pipe\mxc", false),
(r"\Device\NamedPipe\mxc", false),
(r"\BaseNamedObjects\cache", false),
(r"C:\", true),
("C:/", true),
(r"prefix \\server\share\file.txt", true),
(r"prefix \\?\Volume{1234}\file.txt", true),
] {
assert_eq!(contains_file_path(value), expected, "{value}");
}
let prefix = "ordinary text ".repeat(4096);
assert!(!contains_file_path(&prefix));
assert!(contains_file_path(&format!("{prefix}C:\\private.txt")));
assert!(!contains_file_path(&format!(
"{}server\\pipe\\mxc",
"\\".repeat(32 * 1024)
)));
assert!(!contains_file_path(&r"\??\Volume{".repeat(4096)));
}
#[test]
fn sanitize_properties_drops_timestamp_like_properties() {
let props = vec![
("ObjectName".to_string(), "\"C:\\a.txt\"".to_string()),
("Timestamp".to_string(), "132847890123456789".to_string()),
(
"LastWriteTime".to_string(),
"132847890123456789".to_string(),
),
("RuntimePolicy".to_string(), "\"retain\"".to_string()),
("Timeout".to_string(), "\"30\"".to_string()),
];
let out = sanitize_properties(&props);
assert!(out
.iter()
.all(|(name, _)| name != "Timestamp" && name != "LastWriteTime"));
assert!(out.iter().any(|(name, _)| name == "ObjectName"));
assert!(out.iter().any(|(name, _)| name == "RuntimePolicy"));
assert!(out.iter().any(|(name, _)| name == "Timeout"));
}
#[test]
fn sanitize_properties_redacts_standalone_identity_properties() {
let props = vec![
("UserName".to_string(), "\"jsmith\"".to_string()),
(
"AccountName".to_string(),
"\"DOMAIN\\\\jsmith\"".to_string(),
),
("PackageSid".to_string(), "\"S-1-15-3-1\"".to_string()),
("UserSid".to_string(), "\"S-1-5-21-123\"".to_string()),
("AccountId".to_string(), "\"42\"".to_string()),
];
let out = sanitize_properties(&props);
let value_for = |name: &str| out.iter().find(|(k, _)| k == name).map(|(_, v)| v.as_str());
assert_eq!(value_for("UserName"), Some(REDACTED_USER));
assert_eq!(value_for("AccountName"), Some(REDACTED_USER));
assert_eq!(value_for("PackageSid"), Some("S-1-15-3-1"));
assert_eq!(value_for("UserSid"), Some("S-1-5-21-123"));
assert_eq!(value_for("AccountId"), Some("42"));
}
#[test]
fn sanitize_properties_redacts_the_entire_file_path() {
let props = vec![
(
"ObjectName".to_string(),
"\"C:\\Users\\jsmith\\secret.txt\"".to_string(),
),
(
"AppPath".to_string(),
"\"C:\\Users\\jsmith\\app.exe\"".to_string(),
),
(
"ApplicationPath".to_string(),
"\"D:\\Profiles\\alice\\tool.exe\"".to_string(),
),
];
let out = sanitize_properties(&props);
assert_eq!(
out,
vec![
("AppPath".to_string(), REDACTED_PATH.to_string()),
("ApplicationPath".to_string(), REDACTED_PATH.to_string()),
("ObjectName".to_string(), REDACTED_PATH.to_string()),
]
);
}
#[test]
fn sanitize_properties_redacts_arbitrary_file_path() {
let props = vec![
("UserName".to_string(), "\"jsmith\"".to_string()),
(
"ObjectName".to_string(),
"\"D:\\profiles\\jsmith\\secret.txt\"".to_string(),
),
];
let out = sanitize_properties(&props);
let value_for = |name: &str| out.iter().find(|(k, _)| k == name).map(|(_, v)| v.as_str());
assert_eq!(value_for("UserName"), Some(REDACTED_USER));
assert_eq!(value_for("ObjectName"), Some(REDACTED_PATH));
}
#[test]
fn sanitize_properties_omits_sensitive_property_names() {
let props = [
(r"C:\Users\alice\secret.txt".into(), "42".into()),
(r"lookup \\server\share\private.txt".into(), "43".into()),
(r"\Device\HarddiskVolume3\private.txt".into(), "44".into()),
("SafeIdentifier".into(), "42".into()),
];
assert_eq!(
sanitize_properties(&props),
[("SafeIdentifier".into(), "42".into())]
);
}
#[test]
fn event_names_are_sanitized_and_bounded() {
assert_eq!(sanitize_event_name(None), None);
assert_eq!(
sanitize_event_name(Some("AccessCheck")).as_deref(),
Some("AccessCheck")
);
assert_eq!(
sanitize_event_name(Some(r"C:\Users\alice\secret.txt")).as_deref(),
Some(REDACTED_PATH)
);
let first = sanitize_event_name(Some(&format!("{}First", "a".repeat(400)))).unwrap();
let second = sanitize_event_name(Some(&format!("{}Second", "a".repeat(400)))).unwrap();
assert_ne!(first, second);
assert!(first.chars().count() <= MAX_SIGNATURE_VALUE_LEN);
assert!(second.chars().count() <= MAX_SIGNATURE_VALUE_LEN);
}
#[test]
fn sanitize_properties_redacts_embedded_file_paths() {
let long_value = format!("{}C:\\Users\\alice\\secret.txt", "prefix ".repeat(100));
for (name, value) in [
("CommandLine", r"cmd.exe /c type C:\Users\alice\secret.txt"),
(
"CommandLine",
r#"--input="C:\Program Files\private\data.txt""#,
),
("CommandLine", r"open \\server\share\private.txt"),
("CommandLine", r"open \??\C:\Users\alice\secret.txt"),
("CommandLine", r"open \\?\Volume{1234}\private.txt"),
(
"CommandLine",
r"open \Device\HarddiskVolume3\Users\alice\secret.txt",
),
("CommandLine", "message: C:/Users/alice/secret.txt"),
("CommandLine", "\u{03bb}: C:\\Users\\alice\\secret.txt"),
("CommandLine", long_value.as_str()),
(
"FutureLocations",
r#"["C:\Users\alice\secret.txt", "D:\private.txt"]"#,
),
(
"FutureLocations",
r#"["safe", "\\server\share\private.txt"]"#,
),
(
"FutureLocations",
r#"["safe", "\Device\HarddiskVolume3\private.txt"]"#,
),
("FutureLocations", r#"["C:\\Users\\alice\\secret.txt"]"#),
("FutureLocation", r"C:\Users\private\file.txt"),
("LogFileNameString", "ReloggedFile.ETL"),
("UnrecognizedField", r"\\server\share\private.txt"),
] {
assert_eq!(
sanitize_properties(&[(name.into(), value.into())]),
[(name.into(), REDACTED_PATH.into())],
"{value}",
);
}
}
#[test]
fn sanitize_properties_redacts_absolute_path_despite_non_file_object_type() {
for path in [
r"C:\Users\alice\secret.txt",
r"\Device\HarddiskVolume3\Users\alice\secret.txt",
r"\Device\Mup\server\share\Users\alice\secret.txt",
] {
let props = vec![
("ObjectType".to_string(), "\"Section\"".to_string()),
("ObjectName".to_string(), format!("\"{path}\"")),
];
let out = sanitize_properties(&props);
let value_for =
|name: &str| out.iter().find(|(k, _)| k == name).map(|(_, v)| v.as_str());
assert_eq!(value_for("ObjectName"), Some(REDACTED_PATH));
assert_eq!(value_for("ObjectType"), Some("Section"));
}
}
#[test]
fn sanitize_properties_still_redacts_username_in_non_file_identifier() {
let props = vec![
("ObjectType".to_string(), "\"Section\"".to_string()),
("UserName".to_string(), "\"jsmith\"".to_string()),
(
"ObjectName".to_string(),
"\"\\BaseNamedObjects\\jsmith\\cache\"".to_string(),
),
];
let out = sanitize_properties(&props);
let value_for = |name: &str| out.iter().find(|(k, _)| k == name).map(|(_, v)| v.as_str());
assert_eq!(
value_for("ObjectName"),
Some(r"\BaseNamedObjects\<redacted-user>\cache")
);
}
#[test]
fn sanitize_properties_redacts_path_with_qualified_username() {
for (property_name, identity) in [
("UserName", r"CONTOSO\jsmith"),
("UserPrincipalName", "jsmith@example.com"),
] {
let props = vec![
(property_name.to_string(), format!("\"{identity}\"")),
(
"ObjectName".to_string(),
"\"D:\\profiles\\jsmith\\secret.txt\"".to_string(),
),
];
let out = sanitize_properties(&props);
let value_for = |name: &str| {
out.iter()
.find(|(key, _)| key == name)
.map(|(_, value)| value)
};
assert_eq!(
value_for("ObjectName").map(String::as_str),
Some(REDACTED_PATH)
);
assert_eq!(
value_for(property_name).map(String::as_str),
Some(REDACTED_USER)
);
}
}
#[test]
fn sanitize_properties_redacts_standard_account_identity_fields() {
for (property_name, identity) in [
("PrincipalName", "jsmith@example.com"),
("TargetAccount", r"CONTOSO\jsmith"),
("SubjectAccount", "jsmith"),
] {
let props = vec![
(property_name.to_string(), format!("\"{identity}\"")),
(
"ObjectName".to_string(),
"\"D:\\profiles\\jsmith\\secret.txt\"".to_string(),
),
];
let out = sanitize_properties(&props);
let value_for = |name: &str| {
out.iter()
.find(|(key, _)| key == name)
.map(|(_, value)| value)
};
assert_eq!(
value_for(property_name).map(String::as_str),
Some(REDACTED_USER)
);
assert_eq!(
value_for("ObjectName").map(String::as_str),
Some(REDACTED_PATH)
);
}
}
#[test]
fn identity_detection_does_not_match_embedded_name_fragments() {
let props = vec![
(
"AccountNamePolicy".to_string(),
"\"retain-this-value\"".to_string(),
),
(
"ConsiderationUserName".to_string(),
"\"redact-this-value\"".to_string(),
),
];
let out = sanitize_properties(&props);
let value_for = |name: &str| {
out.iter()
.find(|(key, _)| key == name)
.map(|(_, value)| value.as_str())
};
assert_eq!(value_for("AccountNamePolicy"), Some("retain-this-value"));
assert_eq!(value_for("ConsiderationUserName"), Some(REDACTED_USER));
}
#[test]
fn sanitize_properties_redacts_unicode_username_case_variants() {
let props = vec![
("UserName".to_string(), "\"JÖRG\"".to_string()),
(
"ObjectName".to_string(),
"\"D:\\profiles\\jörg\\secret.txt\"".to_string(),
),
];
let out = sanitize_properties(&props);
assert_eq!(
out.iter()
.find(|(name, _)| name == "ObjectName")
.map(|(_, value)| value.as_str()),
Some(REDACTED_PATH)
);
}
#[test]
fn sanitize_properties_is_deterministically_sorted_by_name() {
let props = vec![
("Zeta".to_string(), "\"z\"".to_string()),
("Alpha".to_string(), "\"a\"".to_string()),
];
let out = sanitize_properties(&props);
assert_eq!(
out,
vec![
("Alpha".to_string(), "a".to_string()),
("Zeta".to_string(), "z".to_string()),
]
);
}
#[test]
fn sanitize_properties_redacts_network_application_id() {
let application_id = r"\Device\HarddiskVolume3\app.exe";
let out = sanitize_properties(&[("ApplicationId".to_string(), application_id.to_string())]);
assert_eq!(
out,
vec![("ApplicationId".to_string(), REDACTED_PATH.to_string())]
);
assert!(out.iter().all(|(_, value)| value != application_id));
}
#[test]
fn sanitize_properties_never_carries_a_decoder_error_message() {
let props: Vec<(String, String)> = Vec::new();
assert!(sanitize_properties(&props).is_empty());
}
#[test]
fn bound_properties_preserves_redaction_within_count_and_value_limits() {
let long_value = format!(
r"C:\Users\{}\{}",
"jsmith",
"x".repeat(MAX_SIGNATURE_VALUE_LEN * 2)
);
let mut props = vec![("ObjectName".to_string(), long_value)];
for i in 0..(MAX_SIGNATURE_PROPERTIES + 10) {
props.push((format!("Extra{i:03}"), "v".to_string()));
}
let sanitized: Vec<(String, String)> = props
.into_iter()
.map(|(name, value)| {
let value = if looks_like_file_path_property(&name, &value, None) {
REDACTED_PATH.to_string()
} else {
value
};
(name, value)
})
.collect();
let out = bound_properties(sanitized);
assert_eq!(out.len(), MAX_SIGNATURE_PROPERTIES);
let object_name = out
.iter()
.find(|(name, _)| name == "ObjectName")
.expect("ObjectName retained (sorted first)");
assert!(
object_name.1.contains(REDACTED_PATH),
"redaction must survive bounding: {}",
object_name.1
);
assert!(!object_name.1.contains("<sha256="));
assert_eq!(object_name.1, REDACTED_PATH);
}
#[test]
fn bound_properties_keeps_long_shared_prefixes_distinct() {
let common = "x".repeat(MAX_SIGNATURE_VALUE_LEN * 2);
let first = bound_properties(vec![(
"ObjectName".to_string(),
format!("{common}\\first.db"),
)]);
let second = bound_properties(vec![(
"ObjectName".to_string(),
format!("{common}\\second.db"),
)]);
assert_ne!(first, second);
assert!(first[0].1.ends_with(r"\first.db"));
assert!(second[0].1.ends_with(r"\second.db"));
assert_eq!(first[0].1.chars().count(), MAX_SIGNATURE_VALUE_LEN);
assert_eq!(second[0].1.chars().count(), MAX_SIGNATURE_VALUE_LEN);
}
#[test]
fn sanitize_properties_redacts_before_bounding_and_hashing() {
let tail = "x".repeat(MAX_SIGNATURE_VALUE_LEN * 2);
let alice = sanitize_properties(&[
("UserName".to_string(), "\"alice\"".to_string()),
(
"ObjectName".to_string(),
format!("\"C:\\Users\\alice\\{tail}\""),
),
]);
let bob = sanitize_properties(&[
("UserName".to_string(), "\"bob\"".to_string()),
(
"ObjectName".to_string(),
format!("\"C:\\Users\\bob\\{tail}\""),
),
]);
assert_eq!(alice, bob);
assert!(alice
.iter()
.all(|(_, value)| { !value.contains("alice") && !value.contains("bob") }));
}
#[test]
fn bound_properties_preserves_unicode_boundaries_and_short_values() {
let short = "unchanged".to_string();
let bounded_short = bound_properties(vec![("ObjectName".to_string(), short.clone())]);
assert_eq!(bounded_short[0].1, short);
let exact = "x".repeat(MAX_SIGNATURE_VALUE_LEN);
let bounded_exact = bound_properties(vec![("ObjectName".to_string(), exact.clone())]);
assert_eq!(bounded_exact[0].1, exact);
let long = format!("{}尾", "é".repeat(MAX_SIGNATURE_VALUE_LEN * 2));
let bounded_long = bound_properties(vec![("ObjectName".to_string(), long)]);
assert_eq!(bounded_long[0].1.chars().count(), MAX_SIGNATURE_VALUE_LEN);
assert!(bounded_long[0].1.ends_with('尾'));
}
#[test]
fn parse_u32_reads_hex_prefixed() {
assert_eq!(parse_u32("0x120089"), Some(0x0012_0089));
assert_eq!(parse_u32("0X1"), Some(1));
assert_eq!(parse_u32("0x1acc"), Some(0x1acc));
assert_eq!(parse_u32(" \"0x2\" "), Some(2));
}
#[test]
fn parse_u32_reads_bare_forms_and_rejects_garbage() {
assert_eq!(parse_u32("32"), Some(32));
assert_eq!(parse_u32("ff"), Some(0xff));
assert_eq!(parse_u32(""), None);
assert_eq!(parse_u32("<no data>"), None);
assert_eq!(parse_u32("0x100000000"), None);
}
#[test]
fn file_mask_read_write_execute_priority() {
assert_eq!(access_type_from_mask(0x0001, false), AccessType::Read); assert_eq!(access_type_from_mask(0x0012_0089, false), AccessType::Read); assert_eq!(access_type_from_mask(0x0020, false), AccessType::Execute); assert_eq!(
access_type_from_mask(0x2000_0000, false),
AccessType::Execute
); assert_eq!(access_type_from_mask(0x0002, false), AccessType::Write); assert_eq!(access_type_from_mask(0x0040, false), AccessType::Write); assert_eq!(access_type_from_mask(0x0001_0000, false), AccessType::Write); assert_eq!(access_type_from_mask(0x4000_0000, false), AccessType::Write); assert_eq!(access_type_from_mask(0x1000_0000, false), AccessType::Write); assert_eq!(
access_type_from_mask(0x0001 | 0x0020 | 0x0002, false),
AccessType::Write
);
assert_eq!(
access_type_from_mask(0x0001 | 0x0020, false),
AccessType::Execute
);
}
#[test]
fn file_mask_no_recognised_right_is_unknown() {
assert_eq!(
access_type_from_mask(0x0002_0000, false),
AccessType::Unknown
);
assert_eq!(
access_type_from_mask(0x0010_0000, false),
AccessType::Unknown
);
assert_eq!(
access_type_from_mask(0x0200_0000, false),
AccessType::Unknown
);
assert_eq!(access_type_from_mask(0, false), AccessType::Unknown);
}
#[test]
fn key_mask_uses_registry_vocabulary() {
assert_eq!(access_type_from_mask(0x0001, true), AccessType::Read); assert_eq!(access_type_from_mask(0x0010, true), AccessType::Read); assert_eq!(access_type_from_mask(0x2000_0000, true), AccessType::Read); assert_eq!(access_type_from_mask(0x0002, true), AccessType::Write); assert_eq!(access_type_from_mask(0x0020, true), AccessType::Write); assert_ne!(access_type_from_mask(0x0020, true), AccessType::Execute);
assert_eq!(
access_type_from_mask(0x0002_0000, true),
AccessType::Unknown
);
}
}