mxc-sdk 1.1.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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use base64::{engine::general_purpose::STANDARD, Engine as _};
use std::ffi::OsStr;
use std::os::windows::ffi::OsStrExt;
use widestring::{U16CString, U16Str};
use windows::Win32::Foundation::{LocalFree, HLOCAL};
use windows::Win32::Security::Authorization::ConvertSidToStringSidW;
use windows::Win32::Security::PSID;

/// Compare Windows path strings using ordinal case-insensitive semantics.
pub fn windows_paths_equal_ignore_case(a: &str, b: &str) -> bool {
    if a.is_ascii() && b.is_ascii() {
        return a.eq_ignore_ascii_case(b);
    }

    use std::borrow::Cow;
    use windows::Win32::Globalization::{CompareStringOrdinal, CSTR_EQUAL};

    const STACK_UNITS: usize = 512;
    fn encode<'a>(value: &str, stack: &'a mut [u16; STACK_UNITS]) -> Cow<'a, [u16]> {
        let units = value.encode_utf16().count();
        if units <= stack.len() {
            for (destination, unit) in stack.iter_mut().zip(value.encode_utf16()) {
                *destination = unit;
            }
            Cow::Borrowed(&stack[..units])
        } else {
            Cow::Owned(value.encode_utf16().collect())
        }
    }

    let mut a_stack = [0u16; STACK_UNITS];
    let mut b_stack = [0u16; STACK_UNITS];
    let a = encode(a, &mut a_stack);
    let b = encode(b, &mut b_stack);
    // SAFETY: Both slices remain valid UTF-16 buffers for the duration of the call.
    unsafe { CompareStringOrdinal(a.as_ref(), b.as_ref(), true) == CSTR_EQUAL }
}

/// Convert a UTF-8 string to a null-terminated UTF-16 wide string.
///
/// This truncates at the first embedded NUL. Do not use it for a security
/// identity or any other value whose prefix and full form must stay distinct.
/// Reject embedded NULs before calling it, or use [`os_str_to_wide`].
pub fn to_wide(s: &str) -> Vec<u16> {
    U16CString::from_str_truncate(s).into_vec_with_nul()
}

/// Error returned when an OS string contains an embedded NUL and therefore
/// cannot be passed as a single null-terminated Win32 string.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EmbeddedNulError;

impl std::fmt::Display for EmbeddedNulError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("OS string contains an embedded NUL")
    }
}

impl std::error::Error for EmbeddedNulError {}

/// Convert an OS string losslessly to null-terminated UTF-16.
///
/// Unlike [`to_wide`], this preserves Windows `OsStr` data that is not valid
/// Unicode. Embedded NULs are rejected rather than silently truncating the
/// value seen by Win32.
pub fn os_str_to_wide(value: &OsStr) -> Result<Vec<u16>, EmbeddedNulError> {
    let mut wide = value.encode_wide().collect::<Vec<u16>>();
    if wide.contains(&0) {
        return Err(EmbeddedNulError);
    }
    wide.push(0);
    Ok(wide)
}

/// Convert a UTF-16 slice to a UTF-8 String, stopping at the first null terminator if present.
pub fn from_wide(wide: &[u16]) -> String {
    let len = wide.iter().position(|&c| c == 0).unwrap_or(wide.len());
    U16Str::from_slice(&wide[..len]).to_string_lossy()
}

/// Convert a SID pointer to its string representation (e.g. "S-1-5-...").
/// Returns `None` if the pointer is null or the conversion fails.
///
/// # Safety
/// The caller must ensure `sid` points to a valid SID structure (or is null).
pub unsafe fn sid_to_string(sid: *mut std::ffi::c_void) -> Option<String> {
    if sid.is_null() {
        return None;
    }

    let mut string_sid = windows_core::PWSTR::null();
    let psid = PSID(sid);

    unsafe { ConvertSidToStringSidW(psid, &mut string_sid) }.ok()?;

    let result = unsafe { string_sid.to_string() }.ok();

    unsafe {
        let _ = LocalFree(Some(HLOCAL(string_sid.0 as *mut std::ffi::c_void)));
    }

    result
}

/// Decode a Base64-encoded string to raw bytes.
pub fn base64_decode(input: &str) -> Result<Vec<u8>, base64::DecodeError> {
    STANDARD.decode(input)
}

/// Encode raw bytes to a Base64 string.
pub fn base64_encode(input: &[u8]) -> String {
    STANDARD.encode(input)
}

/// RAII wrapper for a PWSTR allocated with `CoTaskMemAlloc`.
/// Automatically frees the memory with `CoTaskMemFree` on drop.
/// Used for error messages and other strings returned by COM/Win32 APIs.
pub struct CoTaskMemPWSTR {
    ptr: *mut u16,
}

impl CoTaskMemPWSTR {
    /// Create a new wrapper from a raw PWSTR pointer.
    /// Takes ownership — the pointer will be freed on drop.
    pub fn new(ptr: *mut u16) -> Self {
        Self { ptr }
    }

    /// Create a wrapper initialized to null.
    pub fn null() -> Self {
        Self {
            ptr: std::ptr::null_mut(),
        }
    }

    /// Get the raw pointer (for passing to SDK functions as an out-parameter).
    pub fn as_mut_ptr(&mut self) -> *mut *mut u16 {
        &mut self.ptr
    }

    /// Convert the pointed-to wide string into a Rust `String`.
    /// Returns an empty string if the pointer is null.
    pub fn to_string_lossy(&self) -> String {
        if self.ptr.is_null() {
            return String::new();
        }
        unsafe {
            let mut len = 0;
            while *self.ptr.add(len) != 0 {
                len += 1;
            }
            String::from_utf16_lossy(std::slice::from_raw_parts(self.ptr, len))
        }
    }

    /// Returns true if the pointer is null.
    pub fn is_null(&self) -> bool {
        self.ptr.is_null()
    }
}

impl Drop for CoTaskMemPWSTR {
    fn drop(&mut self) {
        if !self.ptr.is_null() {
            unsafe {
                windows::Win32::System::Com::CoTaskMemFree(Some(
                    self.ptr as *const std::ffi::c_void,
                ));
            }
            self.ptr = std::ptr::null_mut();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::ffi::OsString;
    use std::os::windows::ffi::OsStringExt;

    // ========== Base64 Encode ==========

    #[test]
    fn base64_encode_empty() {
        assert_eq!(base64_encode(b""), "");
    }

    #[test]
    fn base64_encode_simple_string() {
        assert_eq!(base64_encode(b"Hello World"), "SGVsbG8gV29ybGQ=");
    }

    #[test]
    fn base64_encode_json_string() {
        let input = r#"{"script":{"code":"print('test')"}}"#;
        assert_eq!(
            base64_encode(input.as_bytes()),
            "eyJzY3JpcHQiOnsiY29kZSI6InByaW50KCd0ZXN0JykifX0="
        );
    }

    #[test]
    fn base64_encode_special_characters() {
        let encoded = base64_encode(b"Line1\nLine2\tTabbed");
        assert!(!encoded.is_empty());
        assert!(!encoded.contains('\n'));
        assert!(!encoded.contains('\r'));
    }

    #[test]
    fn base64_encode_binary_data() {
        assert_eq!(base64_encode(&[0x00, 0x01, 0x02, 0xFF]), "AAEC/w==");
    }

    // ========== Base64 Decode ==========

    #[test]
    fn base64_decode_empty() {
        assert_eq!(base64_decode("").unwrap(), b"");
    }

    #[test]
    fn base64_decode_valid() {
        assert_eq!(base64_decode("SGVsbG8gV29ybGQ=").unwrap(), b"Hello World");
    }

    #[test]
    fn base64_decode_json_string() {
        let decoded = base64_decode("eyJzY3JpcHQiOnsiY29kZSI6InByaW50KCd0ZXN0JykifX0=").unwrap();
        assert_eq!(
            String::from_utf8(decoded).unwrap(),
            r#"{"script":{"code":"print('test')"}}"#
        );
    }

    #[test]
    fn base64_decode_invalid() {
        assert!(base64_decode("Invalid!!!Base64").is_err());
    }

    #[test]
    fn base64_decode_binary_data() {
        let decoded = base64_decode("AAEC/w==").unwrap();
        assert_eq!(decoded.len(), 4);
        assert_eq!(decoded, vec![0x00, 0x01, 0x02, 0xFF]);
    }

    // ========== Base64 Round-Trip ==========

    #[test]
    fn base64_roundtrip_simple_string() {
        let original = b"Hello World";
        let decoded = base64_decode(&base64_encode(original)).unwrap();
        assert_eq!(decoded, original);
    }

    #[test]
    fn base64_roundtrip_json_config() {
        let original = br#"{"script":{"code":"print('Hello')"}}"#;
        let decoded = base64_decode(&base64_encode(original)).unwrap();
        assert_eq!(decoded, original);
    }

    #[test]
    fn base64_roundtrip_special_characters() {
        let original = b"Test\nWith\tSpecial \"Characters\" and 'quotes'";
        let decoded = base64_decode(&base64_encode(original)).unwrap();
        assert_eq!(decoded, original);
    }

    #[test]
    fn base64_roundtrip_empty() {
        let decoded = base64_decode(&base64_encode(b"")).unwrap();
        assert_eq!(decoded, b"");
    }

    #[test]
    fn base64_roundtrip_large_string() {
        let original = vec![b'A'; 10_000];
        let decoded = base64_decode(&base64_encode(&original)).unwrap();
        assert_eq!(decoded, original);
    }

    // ========== to_wide / from_wide ==========

    #[test]
    fn to_wide_empty_string() {
        let wide = to_wide("");
        // Should be just the null terminator
        assert_eq!(wide, vec![0u16]);
    }

    #[test]
    fn to_wide_simple_ascii() {
        let wide = to_wide("Hello World");
        let expected: Vec<u16> = "Hello World"
            .encode_utf16()
            .chain(std::iter::once(0))
            .collect();
        assert_eq!(wide, expected);
    }

    #[test]
    fn to_wide_extended_ascii() {
        let wide = to_wide("Café");
        let expected: Vec<u16> = "Café".encode_utf16().chain(std::iter::once(0)).collect();
        assert_eq!(wide, expected);
        // 'é' is U+00E9
        assert_eq!(wide[3], 0x00E9);
    }

    #[test]
    fn to_wide_chinese_characters() {
        let wide = to_wide("Hello 世界");
        // 世 = U+4E16, 界 = U+754C
        let no_null = &wide[..wide.len() - 1];
        let expected: Vec<u16> = "Hello 世界".encode_utf16().collect();
        assert_eq!(no_null, &expected[..]);
    }

    #[test]
    fn to_wide_emoji() {
        let wide = to_wide("Test 😀");
        // 😀 = U+1F600, encoded as surrogate pair in UTF-16
        assert!(!wide.is_empty());
        let s = from_wide(&wide);
        assert_eq!(s, "Test 😀");
    }

    #[test]
    fn to_wide_mixed_characters() {
        let wide = to_wide("ASCII é 中 😀");
        let s = from_wide(&wide);
        assert_eq!(s, "ASCII é 中 😀");
    }

    #[test]
    fn to_wide_special_characters() {
        let wide = to_wide("Line1\nLine2\tTabbed");
        let s = from_wide(&wide);
        assert_eq!(s, "Line1\nLine2\tTabbed");
    }

    #[test]
    fn os_str_to_wide_preserves_non_unicode_units() {
        let units = [b'a' as u16, 0xD800, b'b' as u16];
        let value = OsString::from_wide(&units);

        let wide = os_str_to_wide(&value).expect("non-Unicode units are preserved");

        assert_eq!(wide, [units[0], units[1], units[2], 0]);
    }

    #[test]
    fn os_str_to_wide_rejects_embedded_nul() {
        let value = OsString::from_wide(&[b'a' as u16, 0, b'b' as u16]);

        assert_eq!(os_str_to_wide(&value), Err(EmbeddedNulError));
    }

    #[test]
    fn windows_path_comparison_handles_ascii_and_unicode_case() {
        assert!(windows_paths_equal_ignore_case(
            r"C:\Tools\App.exe",
            r"c:\tools\app.EXE"
        ));
        assert!(windows_paths_equal_ignore_case(
            r"C:\TÄST\app.exe",
            r"c:\täst\APP.EXE"
        ));
        assert!(windows_paths_equal_ignore_case(
            &format!(r"C:\{}\APP.EXE", "Ä".repeat(600)),
            &format!(r"c:\{}\app.exe", "ä".repeat(600))
        ));
    }

    #[test]
    fn from_wide_empty_string() {
        let wide: Vec<u16> = vec![0u16];
        assert_eq!(from_wide(&wide), "");
    }

    #[test]
    fn from_wide_simple_ascii() {
        let wide: Vec<u16> = "Hello World"
            .encode_utf16()
            .chain(std::iter::once(0))
            .collect();
        assert_eq!(from_wide(&wide), "Hello World");
    }

    #[test]
    fn from_wide_unicode_characters() {
        // "Hello 世界"
        let wide: Vec<u16> = "Hello 世界"
            .encode_utf16()
            .chain(std::iter::once(0))
            .collect();
        assert_eq!(from_wide(&wide), "Hello 世界");
    }

    #[test]
    fn from_wide_emoji() {
        let wide: Vec<u16> = "Test 😀".encode_utf16().chain(std::iter::once(0)).collect();
        assert_eq!(from_wide(&wide), "Test 😀");
    }

    #[test]
    fn from_wide_no_null_terminator() {
        // from_wide should handle slices without null terminator
        let wide: Vec<u16> = "Hello".encode_utf16().collect();
        assert_eq!(from_wide(&wide), "Hello");
    }

    #[test]
    fn from_wide_extended_ascii() {
        let wide: Vec<u16> = "Café".encode_utf16().chain(std::iter::once(0)).collect();
        assert_eq!(from_wide(&wide), "Café");
    }

    #[test]
    fn from_wide_large_string() {
        let original = "A".repeat(10_000);
        let wide: Vec<u16> = original.encode_utf16().chain(std::iter::once(0)).collect();
        assert_eq!(from_wide(&wide), original);
    }

    // ========== Wide Round-Trip ==========

    #[test]
    fn wide_roundtrip_simple() {
        let original = "Hello World";
        assert_eq!(from_wide(&to_wide(original)), original);
    }

    #[test]
    fn wide_roundtrip_unicode() {
        let original = "Hello 世界";
        assert_eq!(from_wide(&to_wide(original)), original);
    }

    #[test]
    fn wide_roundtrip_emoji() {
        let original = "Test 😀 👍";
        assert_eq!(from_wide(&to_wide(original)), original);
    }

    #[test]
    fn wide_roundtrip_special_characters() {
        let original = "Test\nWith\tSpecial \"Characters\" and 'quotes'";
        assert_eq!(from_wide(&to_wide(original)), original);
    }

    #[test]
    fn wide_roundtrip_empty() {
        assert_eq!(from_wide(&to_wide("")), "");
    }

    #[test]
    fn wide_roundtrip_mixed_characters() {
        let original = "ASCII é 中 😀 test";
        assert_eq!(from_wide(&to_wide(original)), original);
    }

    #[test]
    fn wide_roundtrip_large_unicode() {
        let original = "中".repeat(1000);
        assert_eq!(from_wide(&to_wide(&original)), original);
    }

    // ========== sid_to_string ==========

    #[test]
    fn sid_to_string_null_returns_none() {
        let result = unsafe { sid_to_string(std::ptr::null_mut()) };
        assert_eq!(result, None);
    }
}