mxc-sdk 1.2.0

Importable library for starting MXC sandboxes in-process, with streaming stdio.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Makes IsolationSession API calls from a thread of their own.
//!
//! The backend makes every call into the in-proc API through [`call`], so all
//! of them are made from one apartment whatever the caller's thread is in: the
//! thread never initializes COM, so it runs in the process's multi-threaded
//! apartment, which an [`MtaReference`] keeps alive for the call. It makes the
//! call under the [`Impersonation`] it is given, takes on the calling thread's
//! diagnostic sink, and a panic on it resumes on the calling thread.
//!
//! The backend waits for every async call's result through [`wait_for`].

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";

/// The impersonation token [`call`] makes calls under: that of the thread
/// [`Impersonation::of_this_thread`] ran on.
#[derive(Clone)]
pub(super) struct Impersonation {
    /// `None` when that thread was not impersonating: calls are then made as the
    /// process.
    token: Option<Arc<SendOwnedHandle>>,
}

impl Impersonation {
    /// Refused when this thread is impersonating with a token this process
    /// cannot duplicate at `SecurityImpersonation` level.
    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),
        })
    }
}

/// Runs `f` on a thread of its own, under `impersonation`, and returns its
/// result.
///
/// Fails without running `f` when it cannot run there.
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 {
                    // SAFETY: `token` is a live impersonation token; `None`
                    // targets the current thread.
                    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))
}

/// Waits for the result of the async API call that returned `started`.
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;

    /// A single-threaded apartment on the test thread while it lives.
    struct Sta;

    impl Sta {
        fn enter() -> Self {
            // SAFETY: balanced by `CoUninitialize` in `drop`.
            let hr = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };
            assert!(hr.is_ok(), "CoInitializeEx failed: {hr:?}");
            Self
        }
    }

    impl Drop for Sta {
        fn drop(&mut self) {
            // SAFETY: balances `enter`.
            unsafe { CoUninitialize() };
        }
    }

    /// The test thread impersonating while it lives.
    struct Impersonating;

    impl Impersonating {
        fn process_token(level: SECURITY_IMPERSONATION_LEVEL) -> Self {
            // SAFETY: impersonation of the process token on this thread, ended
            // in `drop`.
            unsafe { ImpersonateSelf(level) }.expect("ImpersonateSelf failed");
            Self
        }

        fn token(token: &OwnedHandle) -> Self {
            // SAFETY: `token` is a live impersonation token; `None` targets the
            // current thread. Ended in `drop`.
            unsafe { SetThreadToken(None, Some(token.get())) }.expect("SetThreadToken failed");
            Self
        }
    }

    impl Drop for Impersonating {
        fn drop(&mut self) {
            // SAFETY: ends the impersonation the constructor began.
            let _ = unsafe { RevertToSelf() };
        }
    }

    /// An impersonation copy of the process token, restricted so that a thread
    /// holding it can be told apart from one running as the process.
    fn restricted_token() -> OwnedHandle {
        let mut process_token = HANDLE::default();
        // SAFETY: the out-parameter is a valid, writable local.
        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;
        // SAFETY: `everyone` is writable for `size` bytes.
        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();
        // SAFETY: `process_token` is live, `restricting` points at a valid SID
        // for the call, and the out-parameter is a valid, writable local.
        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();
        // SAFETY: `restricted` is live; the out-parameter is a valid, writable
        // local.
        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();
        // SAFETY: both out-parameters are valid, writable locals.
        unsafe { CoGetApartmentType(&mut apartment, &mut qualifier) }
            .expect("CoGetApartmentType failed");
        (apartment, qualifier)
    }

    /// Whether this thread's impersonation token is restricted, and its level;
    /// `None` when the thread is not impersonating.
    fn thread_token() -> Option<(bool, SECURITY_IMPERSONATION_LEVEL)> {
        let mut token = HANDLE::default();
        // SAFETY: the out-parameter is a valid, writable local.
        unsafe { OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, true, &mut token) }.ok()?;
        let token = OwnedHandle::new(token);

        // SAFETY: `token` is live.
        let restricted = unsafe { IsTokenRestricted(token.get()) }.is_ok();
        let mut level = SECURITY_IMPERSONATION_LEVEL::default();
        let mut size = 0;
        // SAFETY: `level` is writable for the length passed, and `size` is a
        // valid, writable local.
        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);
    }

    /// An identification-level token is one that cannot be carried onto the
    /// call's thread.
    #[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"));
    }
}