use std::sync::Arc;
use crate::mxc_common::logger::Logger;
use crate::mxc_common::process_util::{duplicate_thread_token, SendOwnedHandle};
use crate::mxc_common::telemetry::session;
use windows::Win32::System::Threading::SetThreadToken;
use windows_core::RuntimeType;
use windows_future::IAsyncOperation;
use super::error::{identity_refusal, lifecycle_err, transport_err, IsolationSessionError};
use super::manager::MtaReference;
const THREAD_NAME: &str = "isolation-session-call";
#[derive(Clone)]
pub(super) struct Impersonation {
token: Option<Arc<SendOwnedHandle>>,
}
impl Impersonation {
pub(super) fn of_this_thread() -> Result<Self, IsolationSessionError> {
let token = duplicate_thread_token().map_err(identity_refusal)?;
Ok(Self {
token: token.map(Arc::new),
})
}
}
pub(super) fn call<T: Send>(
impersonation: &Impersonation,
f: impl FnOnce() -> Result<T, IsolationSessionError> + Send,
) -> Result<T, IsolationSessionError> {
let _mta = MtaReference::acquire()?;
let sink = Logger::inherit_thread_diagnostic_sink();
let sink = sink.has_diagnostic_sink().then_some(sink);
let telemetry_context = session::capture();
let joined = std::thread::scope(|scope| {
std::thread::Builder::new()
.name(THREAD_NAME.to_string())
.spawn_scoped(scope, move || {
let _session = session::resume(telemetry_context);
if let Some(token) = &impersonation.token {
unsafe { SetThreadToken(None, Some(token.get())) }.map_err(|e| {
lifecycle_err(format!(
"could not impersonate on the thread for the IsolationSession \
call: {e}"
))
})?;
}
let _sink = sink.as_ref().map(Logger::install_thread_diagnostic_sink);
f()
})
.map(|thread| thread.join())
})
.map_err(|e| {
lifecycle_err(format!(
"could not create a thread for the IsolationSession call: {e}"
))
})?;
joined.unwrap_or_else(|panic| std::panic::resume_unwind(panic))
}
pub(super) fn wait_for<T: RuntimeType>(
operation: &str,
started: windows_core::Result<IAsyncOperation<T>>,
) -> Result<T, IsolationSessionError> {
started
.map_err(|e| transport_err(operation, "call failed", &e))?
.join()
.map_err(|e| transport_err(operation, "wait failed", &e))
}
#[cfg(test)]
mod tests {
use crate::mxc_common::logger::Mode;
use crate::mxc_common::process_util::OwnedHandle;
use windows::Win32::Foundation::HANDLE;
use windows::Win32::Security::{
CreateRestrictedToken, CreateWellKnownSid, DuplicateTokenEx, GetTokenInformation,
ImpersonateSelf, IsTokenRestricted, RevertToSelf, SecurityIdentification,
SecurityImpersonation, TokenImpersonation, TokenImpersonationLevel, WinWorldSid,
CREATE_RESTRICTED_TOKEN_FLAGS, PSID, SECURITY_IMPERSONATION_LEVEL, SECURITY_MAX_SID_SIZE,
SID_AND_ATTRIBUTES, TOKEN_DUPLICATE, TOKEN_IMPERSONATE, TOKEN_QUERY,
};
use windows::Win32::System::Com::{
CoGetApartmentType, CoInitializeEx, CoUninitialize, APTTYPE, APTTYPEQUALIFIER,
APTTYPEQUALIFIER_IMPLICIT_MTA, APTTYPE_MAINSTA, APTTYPE_MTA, APTTYPE_STA,
COINIT_APARTMENTTHREADED,
};
use windows::Win32::System::Threading::{
GetCurrentProcess, GetCurrentThread, OpenProcessToken, OpenThreadToken,
};
use super::*;
use crate::isolation_session_common::error::LifecycleFailure;
struct Sta;
impl Sta {
fn enter() -> Self {
let hr = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };
assert!(hr.is_ok(), "CoInitializeEx failed: {hr:?}");
Self
}
}
impl Drop for Sta {
fn drop(&mut self) {
unsafe { CoUninitialize() };
}
}
struct Impersonating;
impl Impersonating {
fn process_token(level: SECURITY_IMPERSONATION_LEVEL) -> Self {
unsafe { ImpersonateSelf(level) }.expect("ImpersonateSelf failed");
Self
}
fn token(token: &OwnedHandle) -> Self {
unsafe { SetThreadToken(None, Some(token.get())) }.expect("SetThreadToken failed");
Self
}
}
impl Drop for Impersonating {
fn drop(&mut self) {
let _ = unsafe { RevertToSelf() };
}
}
fn restricted_token() -> OwnedHandle {
let mut process_token = HANDLE::default();
unsafe {
OpenProcessToken(
GetCurrentProcess(),
TOKEN_DUPLICATE | TOKEN_QUERY,
&mut process_token,
)
}
.expect("OpenProcessToken failed");
let process_token = OwnedHandle::new(process_token);
let mut everyone = [0u8; SECURITY_MAX_SID_SIZE as usize];
let mut size = everyone.len() as u32;
unsafe {
CreateWellKnownSid(
WinWorldSid,
None,
Some(PSID(everyone.as_mut_ptr().cast())),
&mut size,
)
}
.expect("CreateWellKnownSid failed");
let restricting = [SID_AND_ATTRIBUTES {
Sid: PSID(everyone.as_mut_ptr().cast()),
Attributes: 0,
}];
let mut restricted = HANDLE::default();
unsafe {
CreateRestrictedToken(
process_token.get(),
CREATE_RESTRICTED_TOKEN_FLAGS(0),
None,
None,
Some(&restricting),
&mut restricted,
)
}
.expect("CreateRestrictedToken failed");
let restricted = OwnedHandle::new(restricted);
let mut impersonation = HANDLE::default();
unsafe {
DuplicateTokenEx(
restricted.get(),
TOKEN_QUERY | TOKEN_IMPERSONATE,
None,
SecurityImpersonation,
TokenImpersonation,
&mut impersonation,
)
}
.expect("DuplicateTokenEx failed");
OwnedHandle::new(impersonation)
}
fn apartment() -> (APTTYPE, APTTYPEQUALIFIER) {
let mut apartment = APTTYPE::default();
let mut qualifier = APTTYPEQUALIFIER::default();
unsafe { CoGetApartmentType(&mut apartment, &mut qualifier) }
.expect("CoGetApartmentType failed");
(apartment, qualifier)
}
fn thread_token() -> Option<(bool, SECURITY_IMPERSONATION_LEVEL)> {
let mut token = HANDLE::default();
unsafe { OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, true, &mut token) }.ok()?;
let token = OwnedHandle::new(token);
let restricted = unsafe { IsTokenRestricted(token.get()) }.is_ok();
let mut level = SECURITY_IMPERSONATION_LEVEL::default();
let mut size = 0;
unsafe {
GetTokenInformation(
token.get(),
TokenImpersonationLevel,
Some(std::ptr::from_mut(&mut level).cast()),
std::mem::size_of::<SECURITY_IMPERSONATION_LEVEL>() as u32,
&mut size,
)
}
.expect("GetTokenInformation failed");
Some((restricted, level))
}
fn sees_a_sink() -> bool {
Logger::inherit_thread_diagnostic_sink().has_diagnostic_sink()
}
#[test]
fn piped_exec_workers_preserve_telemetry_authorization_and_attribution() {
use std::os::windows::io::AsRawHandle;
use crate::mxc_common::exec_stream::ExecSandboxProcess;
use crate::mxc_common::sandbox_process::SandboxProcess;
use crate::mxc_common::state_aware_backend::{null_pipe_handle, ExecHandle, ExecOutcome};
use crate::mxc_common::telemetry::{self, events::test_sink, LearningMode, ProcessEvent};
let store = tempfile::tempdir().unwrap();
let environment = telemetry::test_support::TelemetryTestEnv::new(store.path());
environment.set_policy_value(3);
telemetry::consent::set_consent(true, "test").unwrap();
let _lock = test_sink::TEST_LOCK.lock().unwrap();
let mut logger = Logger::new(Mode::Buffer);
let _other_request = session::start_with_learning_mode(
true,
"",
None,
LearningMode::Enforcement,
&mut logger,
);
assert!(crate::mxc_telemetry::init("test", "dev"));
for (active, vector) in [(true, ""), (false, ""), (true, "invalid")] {
let _invocation = session::start_with_learning_mode(
active,
vector,
Some(crate::mxc_contract::ContractVersion::V1_1_0Alpha),
LearningMode::Learning,
&mut logger,
);
let expected_id = session::current();
let expected_mode = session::learning_mode();
let expected_critical = session::critical_events();
let impersonation = Impersonation::of_this_thread().unwrap();
let (stdout_read, stdout_write) = std::io::pipe().unwrap();
let handle = ExecHandle {
stdout: HANDLE(stdout_read.as_raw_handle()),
stderr: null_pipe_handle(),
stdin: null_pipe_handle(),
stdin_closer: None,
waiter: Box::new(move || {
call(&impersonation, || {
assert_eq!(session::current(), expected_id);
assert_eq!(session::learning_mode(), expected_mode);
assert_eq!(session::critical_events(), expected_critical);
assert_eq!(session::invocation_disabled(), !active);
test_sink::install();
telemetry::log_process_event("synthetic", 42, ProcessEvent::Exited(7));
let events = test_sink::take_requirements();
test_sink::clear();
let collected =
active && crate::mxc_telemetry::REQUIRED_COLLECTION_ELIGIBLE;
assert_eq!(events.len(), usize::from(collected));
if collected {
assert_eq!(
events[0].session_id,
expected_id
.map(|id| id.to_string())
.unwrap_or_else(|| "unknown".to_string())
);
assert_eq!(events[0].name, "MXC.ProcessExited");
}
Ok(())
})
.map_err(super::super::error::map_lifecycle_error)?;
Ok(ExecOutcome::Exited(7))
}),
terminator: Box::new(|| Ok(())),
};
let mut process = ExecSandboxProcess::from_exec_handle(handle).unwrap();
drop(stdout_write);
assert_eq!(process.wait().unwrap(), 7);
assert_eq!(session::current(), expected_id);
assert_eq!(session::invocation_disabled(), !active);
}
crate::mxc_telemetry::shutdown();
}
#[test]
fn calls_from_a_single_threaded_apartment_run_in_the_multi_threaded_one() {
let _sta = Sta::enter();
let caller = apartment();
assert!(
caller.0 == APTTYPE_STA || caller.0 == APTTYPE_MAINSTA,
"{caller:?}"
);
let implicit_mta = (APTTYPE_MTA, APTTYPEQUALIFIER_IMPLICIT_MTA);
let impersonation = Impersonation::of_this_thread().unwrap();
assert_eq!(
call(&impersonation, || Ok(apartment())).unwrap(),
implicit_mta
);
assert_eq!(
apartment(),
caller,
"the caller's apartment must be untouched"
);
}
#[test]
fn a_call_runs_under_the_captured_token_at_impersonation_level() {
let token = restricted_token();
let _impersonating = Impersonating::token(&token);
let caller = thread_token();
assert_eq!(caller, Some((true, SecurityImpersonation)));
let impersonation = Impersonation::of_this_thread().unwrap();
assert_eq!(call(&impersonation, || Ok(thread_token())).unwrap(), caller);
assert_eq!(
thread_token(),
caller,
"the caller's token must be untouched"
);
}
#[test]
fn a_call_runs_under_the_captured_token_not_the_calling_threads() {
let impersonation = std::thread::spawn(|| {
let token = restricted_token();
let _impersonating = Impersonating::token(&token);
Impersonation::of_this_thread().unwrap()
})
.join()
.unwrap_or_else(|panic| std::panic::resume_unwind(panic));
std::thread::spawn(move || {
let _sta = Sta::enter();
let _impersonating = Impersonating::process_token(SecurityIdentification);
assert!(
Impersonation::of_this_thread().is_err(),
"this thread's own token must be one that cannot be captured"
);
let caller = (apartment(), thread_token());
assert_eq!(
call(&impersonation, || Ok((apartment(), thread_token()))).unwrap(),
(
(APTTYPE_MTA, APTTYPEQUALIFIER_IMPLICIT_MTA),
Some((true, SecurityImpersonation))
)
);
assert_eq!(
(apartment(), thread_token()),
caller,
"the calling thread must be untouched"
);
})
.join()
.unwrap_or_else(|panic| std::panic::resume_unwind(panic));
}
#[test]
fn a_caller_that_is_not_impersonating_passes_no_token() {
assert_eq!(thread_token(), None);
let impersonation = Impersonation::of_this_thread().unwrap();
assert_eq!(call(&impersonation, || Ok(thread_token())).unwrap(), None);
}
#[test]
fn an_uncarriable_token_is_refused() {
let _impersonating = Impersonating::process_token(SecurityIdentification);
let refused = Impersonation::of_this_thread().map(|_| ());
assert!(
matches!(
refused,
Err(IsolationSessionError::Lifecycle(
LifecycleFailure::Refused { .. }
))
),
"{refused:?}"
);
}
#[test]
fn a_sink_installed_on_the_caller_is_the_one_the_call_writes_to() {
let path = std::env::temp_dir().join(format!(
"isolation-session-owned-thread-{}.log",
std::process::id()
));
let mut logger = Logger::new(Mode::Buffer);
logger
.enable_file_sink(&path)
.expect("enable_file_sink failed");
let installed = logger.install_thread_diagnostic_sink();
let write = |marker: &str| {
Logger::inherit_thread_diagnostic_sink().log_diagnostic_line(marker);
};
let impersonation = Impersonation::of_this_thread().unwrap();
call(&impersonation, || {
write("call-marker");
Ok(())
})
.unwrap();
drop(installed);
drop(logger);
let written = std::fs::read_to_string(&path).expect("reading the sink's file failed");
let _ = std::fs::remove_file(&path);
assert!(written.contains("call-marker"), "{written}");
}
#[test]
fn a_caller_with_no_sink_passes_none() {
assert!(!sees_a_sink());
let impersonation = Impersonation::of_this_thread().unwrap();
assert!(!call(&impersonation, || Ok(sees_a_sink())).unwrap());
}
#[test]
fn a_panic_during_the_call_resumes_on_the_caller() {
let caught = std::panic::catch_unwind(|| {
let impersonation = Impersonation::of_this_thread().unwrap();
call(&impersonation, || -> Result<(), IsolationSessionError> {
panic!("inside the call")
})
});
let payload = caught.expect_err("the panic must reach the caller");
assert_eq!(payload.downcast_ref::<&str>(), Some(&"inside the call"));
}
}