use std::ffi::c_void;
use std::ptr;
use std::sync::OnceLock;
use crate::mxc_common::api_set::is_api_set_implemented;
use crate::mxc_common::models::{FailurePhase, ScriptResponse};
use crate::mxc_common::mxc_error::{ApiFailure, MxcError};
use crate::mxc_common::policy_failures::{PolicyFailureResult, PolicyFailures};
use crate::mxc_common::string_util;
use windows::Win32::Foundation::{GetLastError, ERROR_INSUFFICIENT_BUFFER, HANDLE, HMODULE};
use windows::Win32::System::LibraryLoader::{
GetProcAddress, LoadLibraryExW, LOAD_LIBRARY_SEARCH_SYSTEM32,
};
use windows::Win32::System::Threading::{
DeleteProcThreadAttributeList, InitializeProcThreadAttributeList, UpdateProcThreadAttribute,
LPPROC_THREAD_ATTRIBUTE_LIST, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, STARTUPINFOEXW, STARTUPINFOW,
};
use windows_core::{HRESULT, PCSTR, PCWSTR};
use crate::learning_mode_windows::LearningModeError;
use crate::process_container_common::secenv_policy::{
PolicyResult, MAX_RESULT_BYTES, POLICY_RESULT_VERSION,
};
const PROCESSMODEL_DLL: &str = "processmodel.dll";
pub(crate) const SECURITY_ENVIRONMENT_API_SET: &core::ffi::CStr =
c"api-win-appmodel-processmodel~securityenvironment";
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(u64)]
pub enum SecurityEnvironmentSupport {
FileSystemDeny = 0x0000_0000_0000_0001,
FileSystemEnumerate = 0x0000_0000_0000_0004,
NetworkIngress = 0x0000_0000_0000_0008,
}
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub(crate) struct SecurityEnvironmentVersion {
pub(crate) major: u16,
pub(crate) minor: u16,
}
impl SecurityEnvironmentVersion {
pub(crate) const V1_0: Self = Self { major: 1, minor: 0 };
pub(crate) const V1_1: Self = Self { major: 1, minor: 1 };
}
impl SecurityEnvironmentSupport {
pub(crate) const fn required_version(self) -> SecurityEnvironmentVersion {
match self {
Self::FileSystemDeny => SecurityEnvironmentVersion::V1_0,
Self::FileSystemEnumerate | Self::NetworkIngress => SecurityEnvironmentVersion::V1_1,
}
}
}
pub const PROCESS_SECURITY_ENVIRONMENT_FLAG_NONE: u32 = 0;
const EXPERIMENTAL_PROCESS_SECURITY_ENVIRONMENT_FLAG_CAPTURE_POLICY_RESULT: u32 = 0x2;
const EXPERIMENTAL_PSE_SUPPORT_POLICY_RESULT: u64 = 0x10;
type PfnCreateProcessSecurityEnvironment = unsafe extern "system" fn(
sandbox_specification: *const c_void,
sandbox_specification_size: u32,
flags: u32,
process_security_environment: *mut HANDLE,
) -> HRESULT;
type PfnGetLastProcessSecurityEnvironmentPolicyResult = unsafe extern "system" fn(
requested_version: u32,
policy_result_size_bytes: *mut u32,
policy_result: *mut *mut u8,
) -> HRESULT;
type PfnQueryProcessSecurityEnvironmentSupport =
unsafe extern "system" fn(support_flags: *mut u64) -> HRESULT;
pub(crate) struct CreationError {
cause: LearningModeError,
diagnostic: Option<String>,
policy_result: Option<Box<PolicyFailureResult>>,
}
impl std::fmt::Debug for CreationError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("CreationError")
.field("cause", &self.cause)
.field("diagnostic", &self.diagnostic)
.field(
"policy_result",
&self.policy_result.as_ref().map(|_| "<redacted>"),
)
.finish()
}
}
impl From<LearningModeError> for CreationError {
fn from(cause: LearningModeError) -> Self {
Self {
cause,
diagnostic: None,
policy_result: None,
}
}
}
impl CreationError {
pub(crate) fn is_api_unavailable(&self) -> bool {
self.cause.is_api_unavailable()
}
pub(crate) fn message(&self, capture: bool) -> String {
crate::process_container_common::launch_diagnostics::security_environment_failure_message(
&self.cause,
capture,
)
}
pub(crate) fn response(&self, capture: bool) -> ScriptResponse {
let phase = if self.is_api_unavailable() {
FailurePhase::BackendUnavailable
} else {
FailurePhase::LaunchFailed
};
let mut error = MxcError::new(phase.error_code(), self.message(capture));
if let LearningModeError::HResultCall { function, code } = &self.cause {
error = error.with_api_failure(
ApiFailure::new(*function).with_native_code(format!("0x{:08X}", *code as u32)),
);
if *function == "CreateProcessSecurityEnvironment"
&& *code
== windows::Win32::Foundation::ERROR_ACCESS_DISABLED_BY_POLICY
.to_hresult()
.0
{
let mut failures = PolicyFailures::default();
if let Some(result) = &self.policy_result {
failures.append((**result).clone());
}
let mut details = serde_json::Map::new();
if !failures.results.is_empty() {
if let Err(reason) = failures.validate() {
details.insert(
"policyFeedbackError".into(),
serde_json::json!({
"code": "feedbackLimitExceeded",
"reason": reason,
}),
);
}
details.insert("policyFailures".into(), serde_json::json!(failures));
}
if let Some(diagnostic) = &self.diagnostic {
details.insert(
"policyResultUnavailable".into(),
serde_json::Value::String(diagnostic.clone()),
);
}
if !details.is_empty() {
error = error.with_details(serde_json::Value::Object(details));
}
}
}
ScriptResponse::failed(phase, &error.message).with_error(error)
}
}
impl std::fmt::Display for CreationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.cause.fmt(f)
}
}
impl std::error::Error for CreationError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.cause)
}
}
type PfnIsProcessSecurityEnvironmentVersionSupported =
unsafe extern "system" fn(major: u32, available: *mut u8, minor: *mut u32) -> HRESULT;
type PfnCloseProcessSecurityEnvironment =
unsafe extern "system" fn(process_security_environment: HANDLE);
pub struct ProcessSecurityEnvironment {
handle: HANDLE,
close: PfnCloseProcessSecurityEnvironment,
}
impl std::fmt::Debug for ProcessSecurityEnvironment {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ProcessSecurityEnvironment")
.field("handle", &self.handle)
.finish()
}
}
impl ProcessSecurityEnvironment {
#[must_use]
pub fn raw(&self) -> HANDLE {
self.handle
}
pub fn close(mut self) {
self.close_inner();
}
fn close_inner(&mut self) {
if self.handle.0.is_null() {
return;
}
unsafe { (self.close)(self.handle) };
self.handle = HANDLE(ptr::null_mut());
}
}
impl Drop for ProcessSecurityEnvironment {
fn drop(&mut self) {
self.close_inner();
}
}
const PROC_THREAD_ATTRIBUTE_SECURITY_ENVIRONMENT: usize = 35 | 0x0002_0000;
pub struct SecurityEnvironmentStartupInfo {
storage: Vec<usize>,
attribute_list: LPPROC_THREAD_ATTRIBUTE_LIST,
environment_value: Box<HANDLE>,
inherited_handles: Vec<HANDLE>,
startup_info: STARTUPINFOEXW,
}
impl SecurityEnvironmentStartupInfo {
pub fn new(
mut startup_info: STARTUPINFOW,
environment: HANDLE,
inherited_handles: &[HANDLE],
) -> Result<Self, LearningModeError> {
let attribute_count = 1 + u32::from(!inherited_handles.is_empty());
let mut byte_count = 0usize;
let sizing_result = unsafe {
InitializeProcThreadAttributeList(None, attribute_count, None, &mut byte_count)
};
let sizing_error = last_error();
if sizing_result.is_ok() || sizing_error != ERROR_INSUFFICIENT_BUFFER.0 || byte_count == 0 {
return Err(LearningModeError::ApiCall {
function: "InitializeProcThreadAttributeList(size)",
code: sizing_error,
});
}
let word_count = byte_count.div_ceil(std::mem::size_of::<usize>());
let mut storage = vec![0usize; word_count];
let attribute_list = LPPROC_THREAD_ATTRIBUTE_LIST(storage.as_mut_ptr().cast());
unsafe {
InitializeProcThreadAttributeList(
Some(attribute_list),
attribute_count,
None,
&mut byte_count,
)
}
.map_err(|_| LearningModeError::ApiCall {
function: "InitializeProcThreadAttributeList",
code: last_error(),
})?;
let environment_value = Box::new(environment);
let update_environment = || {
#[cfg(test)]
if policy_diagnostics_tests::injected_api().is_some() {
return Ok(());
}
unsafe {
UpdateProcThreadAttribute(
attribute_list,
0,
PROC_THREAD_ATTRIBUTE_SECURITY_ENVIRONMENT,
Some((&raw const *environment_value).cast()),
std::mem::size_of::<HANDLE>(),
None,
None,
)
}
};
if update_environment().is_err() {
let code = last_error();
unsafe { DeleteProcThreadAttributeList(attribute_list) };
return Err(LearningModeError::ApiCall {
function: "UpdateProcThreadAttribute(SecurityEnvironment)",
code,
});
}
let inherited_handles = inherited_handles.to_vec();
if !inherited_handles.is_empty()
&& unsafe {
UpdateProcThreadAttribute(
attribute_list,
0,
PROC_THREAD_ATTRIBUTE_HANDLE_LIST as usize,
Some(inherited_handles.as_ptr().cast()),
std::mem::size_of_val(inherited_handles.as_slice()),
None,
None,
)
}
.is_err()
{
let code = last_error();
unsafe { DeleteProcThreadAttributeList(attribute_list) };
return Err(LearningModeError::ApiCall {
function: "UpdateProcThreadAttribute(HANDLE_LIST)",
code,
});
}
startup_info.cb = u32::try_from(std::mem::size_of::<STARTUPINFOEXW>()).map_err(|_| {
LearningModeError::ApiCall {
function: "STARTUPINFOEXW size",
code: windows::Win32::Foundation::ERROR_INVALID_PARAMETER.0,
}
})?;
let startup_info = STARTUPINFOEXW {
StartupInfo: startup_info,
lpAttributeList: attribute_list,
};
Ok(Self {
storage,
attribute_list,
environment_value,
inherited_handles,
startup_info,
})
}
#[must_use]
pub fn startup_info(&self) -> &STARTUPINFOEXW {
&self.startup_info
}
#[cfg(test)]
pub(crate) fn environment_for_test(&self) -> HANDLE {
*self.environment_value
}
}
impl std::fmt::Debug for SecurityEnvironmentStartupInfo {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SecurityEnvironmentStartupInfo")
.field(
"attribute_bytes",
&(self.storage.len() * std::mem::size_of::<usize>()),
)
.field("environment", &self.environment_value)
.field("inherited_handles", &self.inherited_handles)
.finish()
}
}
impl Drop for SecurityEnvironmentStartupInfo {
fn drop(&mut self) {
if !self.attribute_list.is_invalid() {
unsafe { DeleteProcThreadAttributeList(self.attribute_list) };
self.attribute_list = LPPROC_THREAD_ATTRIBUTE_LIST::default();
}
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct SecurityEnvironmentExportReport {
pub create: Option<&'static str>,
pub query_support: Option<&'static str>,
pub close: Option<&'static str>,
}
impl SecurityEnvironmentExportReport {
#[must_use]
pub fn is_complete(&self) -> bool {
self.create.is_some() && self.query_support.is_some() && self.close.is_some()
}
}
const CREATE_NAMES: &[&core::ffi::CStr] = &[c"CreateProcessSecurityEnvironment"];
const POLICY_RESULT_NAME: &core::ffi::CStr =
c"Experimental_GetLastProcessSecurityEnvironmentPolicyResult";
const QUERY_SUPPORT_NAMES: &[&core::ffi::CStr] = &[c"QueryProcessSecurityEnvironmentSupport"];
const VERSION_SUPPORT_NAMES: &[&core::ffi::CStr] =
&[c"IsProcessSecurityEnvironmentVersionSupported"];
const CLOSE_NAMES: &[&core::ffi::CStr] = &[c"CloseProcessSecurityEnvironment"];
#[derive(Clone, Copy)]
pub struct SecurityEnvironmentApi {
create: PfnCreateProcessSecurityEnvironment,
get_last_policy_result: Option<PfnGetLastProcessSecurityEnvironmentPolicyResult>,
query_support: PfnQueryProcessSecurityEnvironmentSupport,
version_support: Option<PfnIsProcessSecurityEnvironmentVersionSupported>,
close: PfnCloseProcessSecurityEnvironment,
cacheable: bool,
}
impl std::fmt::Debug for SecurityEnvironmentApi {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SecurityEnvironmentApi")
.field("create", &(self.create as *const ()))
.field("query_support", &(self.query_support as *const ()))
.field(
"version_support",
&self.version_support.map(|function| function as *const ()),
)
.field("close", &(self.close as *const ()))
.field("cacheable", &self.cacheable)
.finish()
}
}
impl SecurityEnvironmentApi {
pub fn load() -> Result<Self, LearningModeError> {
#[cfg(test)]
if let Some(api) = policy_diagnostics_tests::injected_api() {
return Ok(api);
}
static CACHE: OnceLock<Result<SecurityEnvironmentApi, LearningModeError>> = OnceLock::new();
CACHE.get_or_init(Self::load_uncached).clone()
}
fn load_uncached() -> Result<Self, LearningModeError> {
if !is_api_set_implemented(SECURITY_ENVIRONMENT_API_SET) {
return Err(LearningModeError::ApiSetUnavailable {
api: "process security-environment",
api_set: SECURITY_ENVIRONMENT_API_SET
.to_str()
.expect("API-set contract names must be UTF-8"),
});
}
let dll = string_util::to_wide(PROCESSMODEL_DLL);
unsafe {
let hmodule = LoadLibraryExW(PCWSTR(dll.as_ptr()), None, LOAD_LIBRARY_SEARCH_SYSTEM32)
.map_err(|e| LearningModeError::DllLoad(e.to_string()))?;
let create_proc = resolve_any(hmodule, CREATE_NAMES)?;
let query_support_proc = resolve_any(hmodule, QUERY_SUPPORT_NAMES)?;
let version_support =
GetProcAddress(hmodule, PCSTR(VERSION_SUPPORT_NAMES[0].as_ptr().cast())).map(
|function| {
std::mem::transmute::<
unsafe extern "system" fn() -> isize,
PfnIsProcessSecurityEnvironmentVersionSupported,
>(function)
},
);
let close_proc = resolve_any(hmodule, CLOSE_NAMES)?;
Ok(Self {
create: std::mem::transmute::<
unsafe extern "system" fn() -> isize,
PfnCreateProcessSecurityEnvironment,
>(create_proc),
get_last_policy_result: GetProcAddress(
hmodule,
PCSTR(POLICY_RESULT_NAME.as_ptr().cast()),
)
.map(|function| {
std::mem::transmute::<
unsafe extern "system" fn() -> isize,
PfnGetLastProcessSecurityEnvironmentPolicyResult,
>(function)
}),
query_support: std::mem::transmute::<
unsafe extern "system" fn() -> isize,
PfnQueryProcessSecurityEnvironmentSupport,
>(query_support_proc),
version_support,
close: std::mem::transmute::<
unsafe extern "system" fn() -> isize,
PfnCloseProcessSecurityEnvironment,
>(close_proc),
cacheable: true,
})
}
}
#[cfg(test)]
pub(crate) fn from_raw_parts(
create: PfnCreateProcessSecurityEnvironment,
query_support: PfnQueryProcessSecurityEnvironmentSupport,
close: PfnCloseProcessSecurityEnvironment,
) -> Self {
Self {
create,
get_last_policy_result: None,
query_support,
version_support: None,
close,
cacheable: false,
}
}
#[cfg(test)]
pub(crate) fn from_raw_parts_cacheable(
create: PfnCreateProcessSecurityEnvironment,
query_support: PfnQueryProcessSecurityEnvironmentSupport,
close: PfnCloseProcessSecurityEnvironment,
) -> Self {
Self {
create,
get_last_policy_result: None,
query_support,
version_support: None,
close,
cacheable: true,
}
}
pub fn supports_version(&self, major: u32, minor: u32) -> Result<bool, LearningModeError> {
let Some(version_support) = self.version_support else {
return Ok(major == 1 && minor == 0);
};
query_supported_minor_version_with(major, version_support)
.map(|supported| supported.is_some_and(|supported| supported >= minor))
}
pub fn query_support(
&self,
capability: SecurityEnvironmentSupport,
) -> Result<bool, LearningModeError> {
self.support_flags()
.map(|support_flags| support_flags & capability as u64 != 0)
}
#[cfg(test)]
fn query_support_cached(
&self,
capability: SecurityEnvironmentSupport,
cache: &OnceLock<Result<u64, LearningModeError>>,
) -> Result<bool, LearningModeError> {
self.support_flags_cached(cache)
.map(|support_flags| support_flags & capability as u64 != 0)
}
fn support_flags(&self) -> Result<u64, LearningModeError> {
if self.cacheable {
static CACHE: OnceLock<Result<u64, LearningModeError>> = OnceLock::new();
self.support_flags_cached(&CACHE)
} else {
self.query_support_flags()
}
}
fn support_flags_cached(
&self,
cache: &OnceLock<Result<u64, LearningModeError>>,
) -> Result<u64, LearningModeError> {
cache.get_or_init(|| self.query_support_flags()).clone()
}
fn query_support_flags(&self) -> Result<u64, LearningModeError> {
let mut support_flags = 0u64;
let result = unsafe { (self.query_support)(&mut support_flags) };
if result.is_err() {
return Err(LearningModeError::HResultCall {
function: "QueryProcessSecurityEnvironmentSupport",
code: result.0,
});
}
Ok(support_flags)
}
pub(crate) fn create_with_diagnostics(
&self,
specification: &[u8],
flags: u32,
) -> Result<ProcessSecurityEnvironment, CreationError> {
let get_last_policy_result = match self.get_last_policy_result {
Some(get_result) => self.support_flags().map(|support| {
(support & EXPERIMENTAL_PSE_SUPPORT_POLICY_RESULT != 0).then_some(get_result)
}),
None => Ok(None),
};
let flags = if matches!(&get_last_policy_result, Ok(Some(_))) {
flags | EXPERIMENTAL_PROCESS_SECURITY_ENVIRONMENT_FLAG_CAPTURE_POLICY_RESULT
} else {
flags
};
self.create_internal(specification, flags, get_last_policy_result)
}
pub fn create(
&self,
sandbox_specification: &[u8],
flags: u32,
) -> Result<ProcessSecurityEnvironment, LearningModeError> {
self.create_internal(sandbox_specification, flags, Ok(None))
.map_err(|error| error.cause)
}
fn create_internal(
&self,
sandbox_specification: &[u8],
flags: u32,
get_last_policy_result: Result<
Option<PfnGetLastProcessSecurityEnvironmentPolicyResult>,
LearningModeError,
>,
) -> Result<ProcessSecurityEnvironment, CreationError> {
let mut env = HANDLE(ptr::null_mut());
let spec_len = u32::try_from(sandbox_specification.len()).map_err(|_| {
LearningModeError::HResultCall {
function: "CreateProcessSecurityEnvironment",
code: windows::Win32::Foundation::E_INVALIDARG.0,
}
})?;
let result = unsafe {
(self.create)(
sandbox_specification.as_ptr().cast(),
spec_len,
flags,
&mut env,
)
};
let environment = (!env.0.is_null()).then_some(ProcessSecurityEnvironment {
handle: env,
close: self.close,
});
if result.is_err() {
let mut error = CreationError::from(LearningModeError::HResultCall {
function: "CreateProcessSecurityEnvironment",
code: result.0,
});
if result == windows::Win32::Foundation::ERROR_ACCESS_DISABLED_BY_POLICY.to_hresult() {
match get_last_policy_result {
Ok(Some(get_result)) => {
let (result, diagnostic) = policy_failure_diagnostic(get_result);
error.policy_result = result.map(Box::new);
error.diagnostic = diagnostic;
}
Err(capture_error) => {
error.diagnostic = Some(format!(
"Creation-policy diagnostics unavailable: {capture_error}."
));
}
Ok(None) => {
error.diagnostic = Some(
"Creation-policy result reporting is unavailable on this host.".into(),
);
}
}
}
return Err(error);
}
environment.ok_or_else(|| {
CreationError::from(LearningModeError::HResultCall {
function: "CreateProcessSecurityEnvironment",
code: windows::Win32::Foundation::E_UNEXPECTED.0,
})
})
}
}
fn policy_failure_diagnostic(
get_result: PfnGetLastProcessSecurityEnvironmentPolicyResult,
) -> (Option<PolicyFailureResult>, Option<String>) {
let mut buffer = PolicyResultBuffer(ptr::null_mut());
let mut size = 0u32;
let status = unsafe { get_result(POLICY_RESULT_VERSION, &mut size, &mut buffer.0) };
if status.is_err() {
let error = LearningModeError::HResultCall {
function: "Experimental_GetLastProcessSecurityEnvironmentPolicyResult",
code: status.0,
};
let reason = if status == windows::Win32::Foundation::ERROR_NOT_FOUND.to_hresult() {
"Windows retained no policy result for this creation attempt. "
} else {
""
};
return (
None,
Some(format!(
"Creation-policy diagnostics unavailable: {reason}{error}."
)),
);
}
let decoded = buffer.bytes(size as usize).and_then(PolicyResult::decode);
match decoded {
Ok(result) => (Some(result.into()), None),
Err(error) => (
None,
Some(format!("Creation-policy diagnostics unavailable: {error}.")),
),
}
}
struct PolicyResultBuffer(*mut u8);
impl PolicyResultBuffer {
fn bytes(&self, size: usize) -> Result<&[u8], &'static str> {
if self.0.is_null() || size == 0 || size > MAX_RESULT_BYTES {
return Err("native result has a null buffer or invalid byte count");
}
Ok(unsafe { std::slice::from_raw_parts(self.0, size) })
}
}
impl Drop for PolicyResultBuffer {
fn drop(&mut self) {
if !self.0.is_null() {
unsafe { windows::Win32::System::Com::CoTaskMemFree(Some(self.0.cast())) };
#[cfg(test)]
policy_diagnostics_tests::policy_buffer_freed(self.0);
}
}
}
#[must_use]
pub(crate) fn query_support(capability: SecurityEnvironmentSupport) -> bool {
try_query_support(capability).unwrap_or(false)
}
pub(crate) fn try_query_support(
capability: SecurityEnvironmentSupport,
) -> Result<bool, LearningModeError> {
SecurityEnvironmentApi::load().and_then(|api| {
let version = capability.required_version();
if !api.supports_version(u32::from(version.major), u32::from(version.minor))? {
return Ok(false);
}
api.query_support(capability)
})
}
pub(crate) fn supports_version(
version: SecurityEnvironmentVersion,
) -> Result<bool, LearningModeError> {
SecurityEnvironmentApi::load()?
.supports_version(u32::from(version.major), u32::from(version.minor))
}
pub(crate) fn create(
sandbox_specification: &[u8],
flags: u32,
) -> Result<ProcessSecurityEnvironment, LearningModeError> {
SecurityEnvironmentApi::load()?.create(sandbox_specification, flags)
}
pub(crate) fn create_with_diagnostics(
specification: &[u8],
flags: u32,
) -> Result<ProcessSecurityEnvironment, CreationError> {
SecurityEnvironmentApi::load()?.create_with_diagnostics(specification, flags)
}
fn query_supported_minor_version_with(
major: u32,
version_support: PfnIsProcessSecurityEnvironmentVersionSupported,
) -> Result<Option<u32>, LearningModeError> {
let mut available = 0u8;
let mut minor = 0u32;
let result = unsafe { version_support(major, &mut available, &mut minor) };
if result.is_err() {
return Err(LearningModeError::HResultCall {
function: "IsProcessSecurityEnvironmentVersionSupported",
code: result.0,
});
}
Ok((available != 0).then_some(minor))
}
unsafe fn resolve_any(
hmodule: HMODULE,
names: &[&'static core::ffi::CStr],
) -> Result<unsafe extern "system" fn() -> isize, LearningModeError> {
let mut last_detail = String::new();
for name in names {
if let Some(proc) = unsafe { GetProcAddress(hmodule, PCSTR(name.as_ptr().cast())) } {
return Ok(proc);
}
last_detail = format!(
"GetProcAddress returned NULL (GetLastError = {})",
last_error()
);
}
Err(LearningModeError::ExportMissing {
api: "process security-environment",
export: names
.first()
.and_then(|n| n.to_str().ok())
.unwrap_or("<security-environment export>"),
detail: last_detail,
})
}
fn last_error() -> u32 {
unsafe { GetLastError().0 }
}
#[must_use]
pub fn probe_security_environment_exports() -> SecurityEnvironmentExportReport {
if !is_api_set_implemented(SECURITY_ENVIRONMENT_API_SET) {
return SecurityEnvironmentExportReport::default();
}
let dll = string_util::to_wide(PROCESSMODEL_DLL);
let hmodule =
match unsafe { LoadLibraryExW(PCWSTR(dll.as_ptr()), None, LOAD_LIBRARY_SEARCH_SYSTEM32) } {
Ok(h) => h,
Err(_) => return SecurityEnvironmentExportReport::default(),
};
unsafe {
SecurityEnvironmentExportReport {
create: first_present(hmodule, CREATE_NAMES),
query_support: first_present(hmodule, QUERY_SUPPORT_NAMES),
close: first_present(hmodule, CLOSE_NAMES),
}
}
}
unsafe fn first_present(
hmodule: HMODULE,
names: &[&'static core::ffi::CStr],
) -> Option<&'static str> {
for name in names {
if unsafe { GetProcAddress(hmodule, PCSTR(name.as_ptr().cast())) }.is_some() {
return name.to_str().ok();
}
}
None
}
#[must_use]
pub fn is_security_environment_api_available() -> bool {
probe_security_environment_exports().is_complete()
}
#[cfg(test)]
#[path = "secenv_policy_tests.rs"]
mod policy_diagnostics_tests;
#[cfg(test)]
pub(super) fn injected_capture_trace_sources(
) -> Option<crate::learning_mode_windows::LearningModeTraceSources> {
policy_diagnostics_tests::injected_capture_trace_sources()
}
#[cfg(test)]
pub(super) fn record_injected_creation_effect(effect: &'static str) {
policy_diagnostics_tests::record_injected_creation_effect(effect);
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicI32, AtomicU64, AtomicUsize, Ordering};
use std::sync::Mutex;
use windows::Win32::Foundation::{E_FAIL, S_OK};
static CLOSE_CALLS: AtomicUsize = AtomicUsize::new(0);
static QUERY_LOCK: Mutex<()> = Mutex::new(());
static QUERY_CALLS: AtomicUsize = AtomicUsize::new(0);
static QUERY_RESULT: AtomicI32 = AtomicI32::new(S_OK.0);
static QUERY_FLAGS: AtomicU64 = AtomicU64::new(0);
static VERSION_RESULT: AtomicI32 = AtomicI32::new(S_OK.0);
static VERSION_MINOR: AtomicUsize = AtomicUsize::new(1);
unsafe extern "system" fn fake_close(_: HANDLE) {
CLOSE_CALLS.fetch_add(1, Ordering::SeqCst);
}
unsafe extern "system" fn fake_create(
_: *const c_void,
_: u32,
_: u32,
_: *mut HANDLE,
) -> HRESULT {
S_OK
}
unsafe extern "system" fn fake_query(support_flags: *mut u64) -> HRESULT {
QUERY_CALLS.fetch_add(1, Ordering::SeqCst);
let result = HRESULT(QUERY_RESULT.load(Ordering::SeqCst));
if result.is_ok() {
unsafe { *support_flags = QUERY_FLAGS.load(Ordering::SeqCst) };
}
result
}
unsafe extern "system" fn fake_version(_: u32, available: *mut u8, minor: *mut u32) -> HRESULT {
let result = HRESULT(VERSION_RESULT.load(Ordering::SeqCst));
if result.is_ok() {
unsafe {
*available = 1;
*minor = VERSION_MINOR.load(Ordering::SeqCst) as u32;
}
}
result
}
fn reset_query_fakes() {
QUERY_CALLS.store(0, Ordering::SeqCst);
QUERY_RESULT.store(S_OK.0, Ordering::SeqCst);
QUERY_FLAGS.store(0, Ordering::SeqCst);
}
fn fake_uncached_api() -> SecurityEnvironmentApi {
SecurityEnvironmentApi::from_raw_parts(fake_create, fake_query, fake_close)
}
#[test]
fn probe_does_not_panic_and_agrees_with_load() {
let report = probe_security_environment_exports();
assert_eq!(report.is_complete(), SecurityEnvironmentApi::load().is_ok());
assert_eq!(
report.is_complete(),
is_security_environment_api_available()
);
}
#[test]
fn load_failure_is_graceful_when_api_absent() {
match SecurityEnvironmentApi::load() {
Ok(api) => {
let _ = format!("{api:?}");
}
Err(e) => assert!(
matches!(
e,
LearningModeError::ApiSetUnavailable { .. }
| LearningModeError::DllLoad(_)
| LearningModeError::ExportMissing { .. }
),
"unexpected error variant: {e}"
),
}
}
#[test]
fn flag_none_is_zero() {
assert_eq!(PROCESS_SECURITY_ENVIRONMENT_FLAG_NONE, 0);
}
#[test]
fn startup_info_attaches_security_environment_attribute() {
let startup_info = STARTUPINFOW {
cb: std::mem::size_of::<STARTUPINFOW>() as u32,
..Default::default()
};
let environment = HANDLE(std::ptr::dangling_mut::<c_void>());
match SecurityEnvironmentStartupInfo::new(startup_info, environment, &[]) {
Ok(extended) => {
assert_eq!(
extended.startup_info().StartupInfo.cb as usize,
std::mem::size_of::<STARTUPINFOEXW>()
);
assert!(!extended.startup_info().lpAttributeList.is_invalid());
}
Err(LearningModeError::ApiCall { code, .. })
if code == windows::Win32::Foundation::ERROR_NOT_SUPPORTED.0
|| code == windows::Win32::Foundation::ERROR_CALL_NOT_IMPLEMENTED.0 =>
{
}
Err(error) => panic!("unexpected attribute-list error: {error}"),
}
}
#[test]
fn explicit_close_is_exactly_once() {
CLOSE_CALLS.store(0, Ordering::SeqCst);
let environment = ProcessSecurityEnvironment {
handle: HANDLE(std::ptr::dangling_mut::<c_void>()),
close: fake_close,
};
environment.close();
assert_eq!(CLOSE_CALLS.load(Ordering::SeqCst), 1);
}
#[test]
fn export_report_all_present_is_complete() {
let report = SecurityEnvironmentExportReport {
create: Some("CreateProcessSecurityEnvironment"),
query_support: Some("QueryProcessSecurityEnvironmentSupport"),
close: Some("CloseProcessSecurityEnvironment"),
};
assert!(report.is_complete());
}
#[test]
fn export_report_each_missing_export_is_incomplete() {
let complete = SecurityEnvironmentExportReport {
create: Some("CreateProcessSecurityEnvironment"),
query_support: Some("QueryProcessSecurityEnvironmentSupport"),
close: Some("CloseProcessSecurityEnvironment"),
};
assert!(!SecurityEnvironmentExportReport {
create: None,
..complete
}
.is_complete());
assert!(!SecurityEnvironmentExportReport {
query_support: None,
..complete
}
.is_complete());
assert!(!SecurityEnvironmentExportReport {
close: None,
..complete
}
.is_complete());
assert!(!SecurityEnvironmentExportReport::default().is_complete());
}
#[test]
fn support_flags_are_reported_independently() {
let _guard = QUERY_LOCK.lock().unwrap();
let api = fake_uncached_api();
reset_query_fakes();
QUERY_FLAGS.store(
SecurityEnvironmentSupport::FileSystemDeny as u64,
Ordering::SeqCst,
);
assert!(api
.query_support(SecurityEnvironmentSupport::FileSystemDeny)
.unwrap());
assert!(!api
.query_support(SecurityEnvironmentSupport::FileSystemEnumerate)
.unwrap());
assert!(!api
.query_support(SecurityEnvironmentSupport::NetworkIngress)
.unwrap());
reset_query_fakes();
QUERY_FLAGS.store(
SecurityEnvironmentSupport::FileSystemEnumerate as u64,
Ordering::SeqCst,
);
assert!(!api
.query_support(SecurityEnvironmentSupport::FileSystemDeny)
.unwrap());
assert!(api
.query_support(SecurityEnvironmentSupport::FileSystemEnumerate)
.unwrap());
assert!(!api
.query_support(SecurityEnvironmentSupport::NetworkIngress)
.unwrap());
reset_query_fakes();
QUERY_FLAGS.store(
SecurityEnvironmentSupport::NetworkIngress as u64,
Ordering::SeqCst,
);
assert!(!api
.query_support(SecurityEnvironmentSupport::FileSystemDeny)
.unwrap());
assert!(!api
.query_support(SecurityEnvironmentSupport::FileSystemEnumerate)
.unwrap());
assert!(api
.query_support(SecurityEnvironmentSupport::NetworkIngress)
.unwrap());
}
#[test]
fn supported_minor_version_preserves_api_outcomes() {
VERSION_RESULT.store(S_OK.0, Ordering::SeqCst);
VERSION_MINOR.store(3, Ordering::SeqCst);
assert_eq!(
query_supported_minor_version_with(1, fake_version).unwrap(),
Some(3)
);
VERSION_RESULT.store(E_FAIL.0, Ordering::SeqCst);
let error = query_supported_minor_version_with(1, fake_version).unwrap_err();
assert!(matches!(
error,
LearningModeError::HResultCall {
function: "IsProcessSecurityEnvironmentVersionSupported",
code
} if code == E_FAIL.0
));
}
#[test]
fn missing_version_export_supports_only_the_baseline_contract() {
let api = fake_uncached_api();
assert!(api.supports_version(1, 0).unwrap());
assert!(!api.supports_version(1, 1).unwrap());
assert!(!api.supports_version(2, 0).unwrap());
}
#[test]
fn query_support_maps_failing_hresult() {
let _guard = QUERY_LOCK.lock().unwrap();
reset_query_fakes();
QUERY_RESULT.store(E_FAIL.0, Ordering::SeqCst);
let api = fake_uncached_api();
let error = api
.query_support(SecurityEnvironmentSupport::FileSystemDeny)
.unwrap_err();
assert!(matches!(
error,
LearningModeError::HResultCall {
function: "QueryProcessSecurityEnvironmentSupport",
code
} if code == E_FAIL.0
));
}
#[test]
fn non_cacheable_api_queries_every_call() {
let _guard = QUERY_LOCK.lock().unwrap();
reset_query_fakes();
QUERY_FLAGS.store(
SecurityEnvironmentSupport::FileSystemDeny as u64,
Ordering::SeqCst,
);
let api = fake_uncached_api();
assert!(api
.query_support(SecurityEnvironmentSupport::FileSystemDeny)
.unwrap());
assert!(api
.query_support(SecurityEnvironmentSupport::FileSystemDeny)
.unwrap());
assert_eq!(QUERY_CALLS.load(Ordering::SeqCst), 2);
}
#[test]
fn cacheable_api_memoizes_support_flags_across_capabilities() {
let _guard = QUERY_LOCK
.lock()
.unwrap_or_else(|poison| poison.into_inner());
reset_query_fakes();
QUERY_FLAGS.store(
SecurityEnvironmentSupport::FileSystemDeny as u64,
Ordering::SeqCst,
);
let api =
SecurityEnvironmentApi::from_raw_parts_cacheable(fake_create, fake_query, fake_close);
let cache = OnceLock::new();
assert!(api
.query_support_cached(SecurityEnvironmentSupport::FileSystemDeny, &cache)
.unwrap());
assert!(!api
.query_support_cached(SecurityEnvironmentSupport::FileSystemEnumerate, &cache)
.unwrap());
assert!(!api
.query_support_cached(SecurityEnvironmentSupport::NetworkIngress, &cache)
.unwrap());
assert_eq!(QUERY_CALLS.load(Ordering::SeqCst), 1);
}
}