mxc-sdk 1.0.1

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.

//! Telemetry transport for the canonical Learning Mode verbose JSON artifact.

use std::io::Read;
use std::path::Path;

use crate::learning_mode_core::{
    capture_diagnostics::{
        parse_supported_verbose_document, CaptureVerboseLoggingDocument,
        CaptureVerboseLoggingProvider,
    },
    verbose_logging_sibling_path,
};
use crate::mxc_common::hashing::sha256_hex;
use crate::mxc_common::models::{ContainmentBackend, ScriptResponse};
use crate::mxc_common::telemetry::{self, VerboseEvent};

/// Leaves room for TraceLogging metadata beneath ETW's approximately 64 KiB
/// event limit.
const MAX_CONTENT_BYTES: usize = 48 * 1024;
/// The pretty-printed file is bounded separately from its compact form.
const MAX_INPUT_BYTES: u64 = 32 * 1024 * 1024;
#[derive(Debug)]
struct PreparedVerboseDocument {
    document_id: String,
    version: u32,
    document_bytes: u64,
    document_sha256: String,
    summary: String,
    chunks: Vec<String>,
}

/// Emit the verbose artifact referenced by a successful capture-denials result.
///
/// `Ok(())` also covers responses with no capture artifact. Telemetry failures
/// never alter the sandbox result; callers may surface the bounded error only
/// through local diagnostics.
pub fn emit_verbose_telemetry(
    active: bool,
    containment: &ContainmentBackend,
    requested_sandbox_kind: Option<&'static str>,
    response: &ScriptResponse,
) -> Result<(), String> {
    if !active {
        return Ok(());
    }
    let Some(prepared) = prepare_from_response(response)? else {
        return Ok(());
    };

    let backend = containment.wire_name();
    let sandbox_kind = requested_sandbox_kind.unwrap_or(backend);
    let chunk_count = u32::try_from(prepared.chunks.len())
        .map_err(|_| "verbose artifact produced too many telemetry chunks".to_string())?;
    for (index, content) in prepared.chunks.iter().enumerate() {
        let chunk_index = u32::try_from(index)
            .map_err(|_| "verbose artifact chunk index exceeded u32".to_string())?;
        match telemetry::emit_verbose(
            true,
            &VerboseEvent {
                backend,
                sandbox_kind,
                phase: "",
                correlation_vector: "",
                document_id: &prepared.document_id,
                document_version: prepared.version,
                chunk_index,
                chunk_count,
                document_bytes: prepared.document_bytes,
                document_sha256: &prepared.document_sha256,
                content,
                summary: &prepared.summary,
            },
        ) {
            Ok(true) => {}
            Ok(false) => break,
            Err(status) => {
                return Err(format!(
                    "ETW rejected a verbose telemetry chunk with status {status}"
                ));
            }
        }
    }
    Ok(())
}

fn prepare_from_response(
    response: &ScriptResponse,
) -> Result<Option<PreparedVerboseDocument>, String> {
    let Some(capture) = response
        .output_metadata
        .as_deref()
        .and_then(|metadata| metadata.capture_denials.as_ref())
    else {
        return Ok(None);
    };
    let path = verbose_logging_sibling_path(Path::new(&capture.output_path))
        .map_err(|_| "could not derive the verbose artifact path".to_string())?;
    prepare_document(&path).map(Some)
}

fn prepare_document(path: &Path) -> Result<PreparedVerboseDocument, String> {
    let file =
        std::fs::File::open(path).map_err(|_| "could not open the verbose artifact".to_string())?;
    let metadata = file
        .metadata()
        .map_err(|_| "could not inspect the verbose artifact".to_string())?;
    if metadata.len() > MAX_INPUT_BYTES {
        return Err("verbose artifact exceeds the telemetry input bound".to_string());
    }

    let capacity = usize::try_from(metadata.len())
        .map_err(|_| "verbose artifact size exceeds this platform".to_string())?;
    let mut bytes = Vec::with_capacity(capacity);
    file.take(MAX_INPUT_BYTES + 1)
        .read_to_end(&mut bytes)
        .map_err(|_| "could not read the verbose artifact".to_string())?;
    if bytes.len() as u64 > MAX_INPUT_BYTES {
        return Err("verbose artifact exceeds the telemetry input bound".to_string());
    }

    let document = parse_supported_verbose_document(&bytes)
        .map_err(|_| "verbose artifact is not valid supported typed JSON".to_string())?;
    let document = project_for_telemetry(document);

    let compact = serde_json::to_vec(&document)
        .map_err(|_| "could not compact the verbose artifact".to_string())?;
    let document_bytes = u64::try_from(compact.len())
        .map_err(|_| "verbose artifact byte count exceeded u64".to_string())?;
    let document_sha256 = sha256_hex(&compact);
    let summary = serde_json::to_string(&document.summary)
        .map_err(|_| "could not serialize the verbose artifact summary".to_string())?;
    let chunks = chunk_signatures(&document)?;
    let document_id = random_document_id()?;

    Ok(PreparedVerboseDocument {
        document_id,
        version: document.version,
        document_bytes,
        document_sha256,
        summary,
        chunks,
    })
}

fn project_for_telemetry(
    mut document: CaptureVerboseLoggingDocument,
) -> CaptureVerboseLoggingDocument {
    let mut groups = std::collections::BTreeMap::new();
    for mut aggregate in document.signatures {
        aggregate.signature.provider_guid =
            canonical_provider_guid(aggregate.signature.provider).to_string();
        aggregate.signature.event_name = None;
        aggregate.signature.properties.clear();
        aggregate.signature.network_endpoint = None;
        let count = groups.entry(aggregate.signature).or_insert(0u64);
        *count = count.saturating_add(aggregate.count);
    }
    document.signatures = groups
        .into_iter()
        .map(|(signature, count)| {
            crate::learning_mode_core::capture_diagnostics::CaptureVerboseLoggingAggregate {
                signature,
                count,
            }
        })
        .collect();
    document
}

fn canonical_provider_guid(provider: CaptureVerboseLoggingProvider) -> &'static str {
    match provider {
        CaptureVerboseLoggingProvider::KernelGeneral => "{A68CA8B7-004F-D7B6-A698-07E2DE0F1F5D}",
        CaptureVerboseLoggingProvider::PrivacyAuditingPermissiveLearningMode => {
            "{811A1DDB-2E69-5F25-ADC0-4B186170E760}"
        }
        CaptureVerboseLoggingProvider::LearningModeNetworkDecision => {
            "{301EC03D-2951-5EFB-6D99-59C64628BBFC}"
        }
    }
}

fn chunk_signatures(document: &CaptureVerboseLoggingDocument) -> Result<Vec<String>, String> {
    let mut chunks = Vec::new();
    let mut current = String::from("[");
    let mut current_count = 0usize;

    for signature in &document.signatures {
        let item = serde_json::to_string(signature)
            .map_err(|_| "could not serialize a verbose signature".to_string())?;
        let separator_bytes = usize::from(current_count > 0);
        let candidate_bytes = current
            .len()
            .saturating_add(separator_bytes)
            .saturating_add(item.len())
            .saturating_add(1);

        if candidate_bytes > MAX_CONTENT_BYTES && current_count > 0 {
            current.push(']');
            chunks.push(current);
            current = String::from("[");
            current_count = 0;
        }

        if item.len().saturating_add(2) > MAX_CONTENT_BYTES {
            return Err("one verbose signature exceeds the telemetry event bound".to_string());
        }
        if current_count > 0 {
            current.push(',');
        }
        current.push_str(&item);
        current_count += 1;
    }

    current.push(']');
    chunks.push(current);
    Ok(chunks)
}

fn random_document_id() -> Result<String, String> {
    let mut bytes = [0u8; 16];
    getrandom::getrandom(&mut bytes)
        .map_err(|_| "could not generate a verbose telemetry document id".to_string())?;
    Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::learning_mode_core::capture_diagnostics::{
        write_capture_verbose_logging_document, CaptureVerboseLoggingAggregate,
        CaptureVerboseLoggingDocumentSummary, CaptureVerboseLoggingOutcomeReason,
        CaptureVerboseLoggingSignature, NetworkEndpoint, CAPTURE_VERBOSE_LOGGING_VERSION,
    };
    use crate::mxc_common::models::{CaptureDenialsOutput, SandboxOutputMetadata};

    fn aggregate_with_reason(
        event_id: u16,
        value: &str,
        reason: CaptureVerboseLoggingOutcomeReason,
    ) -> CaptureVerboseLoggingAggregate {
        CaptureVerboseLoggingAggregate {
            signature: CaptureVerboseLoggingSignature {
                provider: CaptureVerboseLoggingProvider::KernelGeneral,
                provider_guid: "{a68ca8b7-004f-d7b6-a698-07e2de0f1f5d}".to_string(),
                event_id,
                event_name: None,
                reason,
                pid: 42,
                access_type: None,
                resource_type: None,
                network_decision_reason: None,
                configuration_recommendation: None,
                network_endpoint: None,
                properties: vec![("Value".to_string(), value.to_string())],
            },
            count: 1,
        }
    }

    fn aggregate(event_id: u16, value: &str) -> CaptureVerboseLoggingAggregate {
        aggregate_with_reason(
            event_id,
            value,
            CaptureVerboseLoggingOutcomeReason::UnsupportedEventSchema,
        )
    }

    fn document(signatures: Vec<CaptureVerboseLoggingAggregate>) -> CaptureVerboseLoggingDocument {
        CaptureVerboseLoggingDocument {
            version: CAPTURE_VERBOSE_LOGGING_VERSION,
            signatures,
            summary: CaptureVerboseLoggingDocumentSummary {
                total_occurrences: 1,
                overflow_occurrences: 0,
                actionable_overflow_occurrences: 0,
                aggregate_groups_truncated: false,
                processed_events_truncated: false,
                actionable_limit_reached: false,
            },
        }
    }

    #[test]
    fn every_chunk_is_an_independently_parseable_json_array() {
        let doc = document(vec![aggregate(1, "one"), aggregate(2, "two")]);
        let chunks = chunk_signatures(&doc).unwrap();
        let rebuilt = chunks
            .iter()
            .flat_map(|chunk| {
                serde_json::from_str::<Vec<CaptureVerboseLoggingAggregate>>(chunk).unwrap()
            })
            .collect::<Vec<_>>();
        assert_eq!(rebuilt, doc.signatures);
    }

    #[test]
    fn empty_document_emits_one_empty_array() {
        assert_eq!(chunk_signatures(&document(Vec::new())).unwrap(), ["[]"]);
    }

    #[test]
    fn chunks_only_between_complete_aggregates() {
        let large = "x".repeat(MAX_CONTENT_BYTES / 2);
        let doc = document(vec![aggregate(1, &large), aggregate(2, &large)]);
        let chunks = chunk_signatures(&doc).unwrap();
        assert_eq!(chunks.len(), 2);
        for chunk in chunks {
            let parsed: Vec<CaptureVerboseLoggingAggregate> = serde_json::from_str(&chunk).unwrap();
            assert_eq!(parsed.len(), 1);
        }
    }

    #[test]
    fn rejects_unsupported_document_version() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("denials.verbose.json");
        let mut doc = document(Vec::new());
        doc.version += 1;
        std::fs::write(&path, serde_json::to_vec(&doc).unwrap()).unwrap();
        assert!(prepare_document(&path)
            .unwrap_err()
            .contains("valid supported typed JSON"));
    }

    #[test]
    fn prepared_chunks_reconstruct_the_telemetry_projection() {
        let directory = tempfile::tempdir().unwrap();
        let denials_path = directory.path().join("denials.json");
        let verbose_path = verbose_logging_sibling_path(&denials_path).unwrap();
        let doc = document(vec![
            aggregate(1, "customer-secret-one"),
            aggregate(2, "customer-secret-two"),
        ]);
        let mut pretty = Vec::new();
        write_capture_verbose_logging_document(&mut pretty, &doc).unwrap();
        std::fs::write(&verbose_path, pretty).unwrap();

        let response = ScriptResponse {
            output_metadata: Some(Box::new(SandboxOutputMetadata {
                capture_denials: Some(CaptureDenialsOutput {
                    kind: CaptureDenialsOutput::KIND.to_string(),
                    output_path: denials_path.to_string_lossy().into_owned(),
                    exit_code: 0,
                    total_denials: 0,
                    denied_resources_truncated: false,
                    etl_path: None,
                }),
                capture_denials_error: None,
            })),
            ..Default::default()
        };
        let prepared = prepare_from_response(&response).unwrap().unwrap();
        let signatures = prepared
            .chunks
            .iter()
            .flat_map(|chunk| {
                serde_json::from_str::<Vec<CaptureVerboseLoggingAggregate>>(chunk).unwrap()
            })
            .collect();
        let summary = serde_json::from_str(&prepared.summary).unwrap();
        let reconstructed = CaptureVerboseLoggingDocument {
            version: prepared.version,
            signatures,
            summary,
        };
        let compact = serde_json::to_vec(&reconstructed).unwrap();

        assert_eq!(compact.len() as u64, prepared.document_bytes);
        assert_eq!(sha256_hex(&compact), prepared.document_sha256);
        assert_eq!(reconstructed, project_for_telemetry(doc));
        assert!(reconstructed.signatures.iter().all(|aggregate| aggregate
            .signature
            .properties
            .is_empty()
            && aggregate.signature.event_name.is_none()
            && aggregate.signature.network_endpoint.is_none()));
        assert!(reconstructed.signatures.iter().all(|aggregate| {
            aggregate.signature.provider_guid
                == canonical_provider_guid(aggregate.signature.provider)
        }));
    }

    #[test]
    fn telemetry_preserves_com_reason_but_strips_clsid() {
        let mut document = document(vec![aggregate_with_reason(
            14,
            "{A47979D2-C419-11D9-A5B4-001185AD2B89}",
            CaptureVerboseLoggingOutcomeReason::ComActivation,
        )]);
        document.signatures[0].signature.resource_type =
            Some(crate::learning_mode_core::ResourceType::Other);

        document = project_for_telemetry(document);

        let signature = &document.signatures[0].signature;
        assert_eq!(
            signature.reason,
            CaptureVerboseLoggingOutcomeReason::ComActivation
        );
        assert_eq!(
            signature.resource_type,
            Some(crate::learning_mode_core::ResourceType::Other)
        );
        assert!(signature.access_type.is_none());
        assert!(signature.properties.is_empty());
    }

    #[test]
    fn malformed_artifact_never_falls_back_to_raw_bytes() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("denials.verbose.json");
        std::fs::write(&path, br#"{"secret":"do-not-send"}"#).unwrap();
        let error = prepare_document(&path).unwrap_err();
        assert_eq!(error, "verbose artifact is not valid supported typed JSON");
        assert!(!error.contains("do-not-send"));
    }

    #[test]
    fn telemetry_projection_drops_injected_strings() {
        let injected = "customer-secret";
        let mut doc = document(vec![aggregate(1, injected)]);
        doc.signatures[0].signature.provider_guid = injected.to_string();
        doc.signatures[0].signature.event_name = Some(injected.to_string());
        doc.signatures[0].signature.properties = vec![(injected.to_string(), injected.to_string())];
        doc.signatures[0].signature.network_endpoint = Some(NetworkEndpoint {
            protocol: "tcp".to_string(),
            remote_address: injected.to_string(),
            remote_port: Some(443),
        });

        let projected = project_for_telemetry(doc);
        let serialized = serde_json::to_string(&projected).unwrap();

        assert!(!serialized.contains(injected));
        assert_eq!(
            projected.signatures[0].signature.provider_guid,
            canonical_provider_guid(CaptureVerboseLoggingProvider::KernelGeneral)
        );
        assert!(projected.signatures[0].signature.event_name.is_none());
        assert!(projected.signatures[0].signature.properties.is_empty());
        assert!(projected.signatures[0].signature.network_endpoint.is_none());
    }

    #[test]
    fn telemetry_projection_regroups_after_removing_sensitive_fields() {
        let mut first = aggregate(999, "first-secret");
        first.signature.provider_guid = "first-provider".to_string();
        first.signature.event_name = Some("first-event".to_string());
        first.count = 3;
        let mut second = first.clone();
        second.signature.provider_guid = "second-provider".to_string();
        second.signature.event_name = Some("second-event".to_string());
        second.signature.properties[0].1 = "second-secret".to_string();
        second.count = 4;
        let mut input = document(vec![first, second]);
        input.summary.total_occurrences = 7;

        let projected = project_for_telemetry(input);

        assert_eq!(projected.signatures.len(), 1);
        assert_eq!(projected.signatures[0].count, 7);
        assert_eq!(
            projected.signatures[0].signature.provider_guid,
            canonical_provider_guid(CaptureVerboseLoggingProvider::KernelGeneral)
        );
        assert!(projected.signatures[0].signature.event_name.is_none());
        assert!(projected.signatures[0].signature.properties.is_empty());
        assert_eq!(projected.summary.total_occurrences, 7);
    }

    #[test]
    fn network_provider_uses_the_canonical_guid() {
        assert_eq!(
            canonical_provider_guid(CaptureVerboseLoggingProvider::LearningModeNetworkDecision),
            "{301EC03D-2951-5EFB-6D99-59C64628BBFC}"
        );
    }
}