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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Derive conservative request restrictions from caller-owned observations.

use std::collections::{HashMap, HashSet};

use crate::mxc_common::filesystem_canonical::{canonicalize_allowing_absent_tail, PathCanonical};
use crate::mxc_common::filesystem_probe::FilesystemProbe;
use crate::mxc_common::models::{
    CaptureDenialsMode, ContainerPolicy, ExecutionRequest, NetworkAction, ScriptResponse,
};
use crate::mxc_common::policy_failures::{PolicyFailureDetail as Detail, PolicyFailures};
use crate::process_container_common::base_container_helpers::{
    effective_capabilities, unrestricted_host_loopback_allowed,
};
use crate::process_container_common::network_policy_helpers::{
    capture_requests_internet_capability, ensure_capability,
};
use crate::process_container_common::secenv_policy::RestrictionHint;
use crate::process_container_common::secenv_policy::{PolicyResult, POLICY_RESULT_VERSION};

const MAX_FILESYSTEM_WORK: usize = 16 * 1024 * 1024;
const FILESYSTEM_WORK_LIMIT: &str =
    "filesystem restriction exceeds the cumulative safety-check work limit";

fn contradicts_earlier(hints: &[RestrictionHint], index: usize) -> bool {
    let hint = &hints[index];
    hints[..index]
        .iter()
        .any(|previous| match (previous, hint) {
            (
                RestrictionHint::RestrictPath { path: a, .. },
                RestrictionHint::RestrictPath { path: b, .. },
            ) => same_path(a, b) && previous != hint,
            (RestrictionHint::ReducePathCount { .. }, RestrictionHint::ReducePathCount { .. }) => {
                previous != hint
            }
            _ => false,
        })
}

fn restrict_request(
    original: &ExecutionRequest,
    failures: &PolicyFailures,
    capture_network_decisions: bool,
    resolve: &mut impl FnMut(&str) -> Result<PathCanonical, String>,
) -> Result<ExecutionRequest, String> {
    failures.validate()?;
    let mut merged = Vec::new();
    for result in &failures.results {
        if result.version != POLICY_RESULT_VERSION
            || result.minimum_reader_version != POLICY_RESULT_VERSION
        {
            return Err("unsupported native policy-result version".into());
        }
        let native = PolicyResult::from(result);
        let hints = native
            .restriction_hints()
            .ok_or("the observations contain an unsupported or non-actionable policy result")?;
        if (0..hints.len()).any(|index| contradicts_earlier(&hints, index)) {
            return Err("a native policy-result batch contains contradictory constraints".into());
        }
        combine_restriction_hints(&mut merged, &hints);
    }
    let mut resolutions: HashMap<String, PathCanonical> = HashMap::new();
    let mut resolve_once = |path: &str| {
        if let Some(resolved) = resolutions.get(path) {
            return Ok(resolved.clone());
        }
        let resolved = resolve(path)?;
        resolutions.insert(path.to_owned(), resolved.clone());
        Ok(resolved)
    };
    let mut work_remaining = MAX_FILESYSTEM_WORK;
    charge_filesystem_work(&original.policy, &merged, &mut work_remaining)?;
    validate_filesystem_paths(&original.policy, &merged, &mut resolve_once)?;
    let mut candidate = original.clone();
    for _ in 0..=merged.len() {
        let applicable = applicable_hints(&candidate, &merged, capture_network_decisions);
        if applicable.is_empty() {
            return Ok(candidate);
        }
        charge_filesystem_work(&candidate.policy, &applicable, &mut work_remaining)?;
        candidate = restrict_with_hints(
            &candidate,
            &applicable,
            capture_network_decisions,
            &mut resolve_once,
        )?;
    }
    Err("the policy restrictions did not converge".into())
}

pub(super) fn prepare_request(
    original: &ExecutionRequest,
    failures: &PolicyFailures,
    capture_network_decisions: bool,
) -> Result<ExecutionRequest, ScriptResponse> {
    let mut probe = FilesystemProbe::default();
    restrict_request(original, failures, capture_network_decisions, &mut |path| {
        probe.run(path, canonicalize_allowing_absent_tail)
    })
    .map_err(|reason| {
        let message = "Policy preparation cannot apply these observations safely.";
        ScriptResponse::rejected(message).with_error(
            crate::mxc_common::mxc_error::MxcError::policy_validation(message).with_details(
                serde_json::json!({
                    "policyFailures": failures,
                    "policyFeedbackError": { "code": "unsafeReplay", "reason": reason },
                }),
            ),
        )
    })
}

fn applicable_hints(
    request: &ExecutionRequest,
    hints: &[RestrictionHint],
    capture_network_decisions: bool,
) -> Vec<RestrictionHint> {
    hints
        .iter()
        .filter_map(|hint| match hint {
            RestrictionHint::RemoveCapability(capability) => {
                has_capability(request, capability, capture_network_decisions).then(|| hint.clone())
            }
            RestrictionHint::RestrictPath { path, maximum, .. } => {
                let requested = access_at(&request.policy, path);
                (requested > *maximum).then(|| RestrictionHint::RestrictPath {
                    path: path.clone(),
                    requested,
                    maximum: *maximum,
                })
            }
            RestrictionHint::ReducePathCount { maximum, .. } => {
                let requested = native_path_count(&request.policy);
                (requested > *maximum).then_some(RestrictionHint::ReducePathCount {
                    requested,
                    maximum: *maximum,
                })
            }
        })
        .collect()
}

/// Fold `hints` into `merged`, keeping the strictest maximum for each target.
fn combine_restriction_hints(merged: &mut Vec<RestrictionHint>, hints: &[RestrictionHint]) {
    for hint in hints {
        let previous = merged.iter().position(|previous| match (previous, hint) {
            (
                RestrictionHint::RemoveCapability(first),
                RestrictionHint::RemoveCapability(second),
            ) => capability_matches(first, second),
            (
                RestrictionHint::RestrictPath { path: first, .. },
                RestrictionHint::RestrictPath { path: second, .. },
            ) => same_path(first, second),
            (RestrictionHint::ReducePathCount { .. }, RestrictionHint::ReducePathCount { .. }) => {
                true
            }
            _ => false,
        });
        match previous {
            None => merged.push(hint.clone()),
            Some(index) => match (&mut merged[index], hint) {
                (
                    RestrictionHint::RestrictPath { maximum, .. },
                    RestrictionHint::RestrictPath { maximum: next, .. },
                )
                | (
                    RestrictionHint::ReducePathCount { maximum, .. },
                    RestrictionHint::ReducePathCount { maximum: next, .. },
                ) => {
                    *maximum = (*maximum).min(*next);
                }
                _ => {}
            },
        }
    }
}

fn restrict_with_hints(
    original: &ExecutionRequest,
    hints: &[RestrictionHint],
    capture_network_decisions: bool,
    resolve: &mut impl FnMut(&str) -> Result<PathCanonical, String>,
) -> Result<ExecutionRequest, String> {
    validate_filesystem_paths(&original.policy, hints, resolve)?;
    let mut candidate = original.clone();
    for (index, hint) in hints.iter().enumerate() {
        if contradicts_earlier(hints, index) {
            return Err("the native details contain contradictory constraints".into());
        }
        match hint {
            RestrictionHint::RemoveCapability(capability) => remove_capability(
                &mut candidate,
                original,
                capability,
                capture_network_decisions,
            )?,
            RestrictionHint::RestrictPath {
                path,
                requested,
                maximum,
            } => restrict_path(
                &mut candidate.policy,
                &original.policy,
                path,
                *requested,
                *maximum,
            )?,
            RestrictionHint::ReducePathCount { .. } => {}
        }
    }
    for hint in hints {
        match hint {
            RestrictionHint::RemoveCapability(capability) => {
                if has_capability(&candidate, capability, capture_network_decisions) {
                    return Err("a forbidden capability still has an effective source".into());
                }
            }
            RestrictionHint::ReducePathCount { requested, maximum } => {
                if native_path_count(&original.policy) != *requested {
                    return Err("the native path count disagrees with the submitted request".into());
                }
                for paths in [
                    &mut candidate.policy.readwrite_paths,
                    &mut candidate.policy.readonly_paths,
                    &mut candidate.policy.denied_paths,
                ] {
                    let mut seen = HashSet::new();
                    paths.retain(|path| seen.insert(path.clone()));
                }
                if native_path_count(&candidate.policy) > *maximum {
                    return Err(
                        "the path limit cannot be met by exact deduplication; MXC will not \
                         discard distinct grants or exceptions"
                            .into(),
                    );
                }
            }
            RestrictionHint::RestrictPath { .. } => {}
        }
    }
    if hints
        .iter()
        .any(|hint| matches!(hint, RestrictionHint::RestrictPath { .. }))
    {
        // Check the whole batch once; access changes only at grant boundaries.
        let points = original
            .policy
            .readwrite_paths
            .iter()
            .chain(&original.policy.readonly_paths)
            .chain(&original.policy.denied_paths)
            .chain(&candidate.policy.readwrite_paths)
            .chain(&candidate.policy.readonly_paths)
            .chain(&candidate.policy.denied_paths);
        if points
            .into_iter()
            .any(|path| access_at(&candidate.policy, path) > access_at(&original.policy, path))
        {
            return Err(
                "the proposed filesystem restriction could increase effective access".into(),
            );
        }
    }
    let before = effective_capabilities(original, capture_network_decisions);
    if effective_capabilities(&candidate, capture_network_decisions)
        .iter()
        .any(|capability| {
            !(before
                .iter()
                .any(|previous| capability_matches(previous, capability))
                || (capability_matches(capability, "learningModeLogging")
                    && before
                        .iter()
                        .any(|previous| capability_matches(previous, "permissiveLearningMode"))))
        })
    {
        return Err("the revised request would introduce a new effective capability".into());
    }

    Ok(candidate)
}

fn native_path_count(policy: &ContainerPolicy) -> u64 {
    (policy.readwrite_paths.len() + policy.readonly_paths.len() + policy.denied_paths.len()) as u64
}

fn capability_matches(entry: &str, capability: &str) -> bool {
    entry
        .trim_matches([' ', '\t'])
        .eq_ignore_ascii_case(capability.trim_matches([' ', '\t']))
}

fn has_capability(request: &ExecutionRequest, capability: &str, network_capture: bool) -> bool {
    (capability.eq_ignore_ascii_case("networkLoopback")
        && unrestricted_host_loopback_allowed(&request.policy))
        || effective_capabilities(request, network_capture)
            .iter()
            .any(|entry| capability_matches(entry, capability))
}

fn remove_capability(
    candidate: &mut ExecutionRequest,
    original: &ExecutionRequest,
    capability: &str,
    network_capture: bool,
) -> Result<(), String> {
    if capability.is_empty()
        || capability.contains(',')
        || capability.chars().any(char::is_control)
        || !has_capability(original, capability, network_capture)
    {
        return Err("the forbidden capability does not match the submitted request".into());
    }
    let policy = &mut candidate.policy;
    policy
        .capabilities
        .retain(|entry| !capability_matches(entry, capability));
    if capability.eq_ignore_ascii_case("internetClient") {
        if let Some(egress) = &mut policy.network_egress {
            egress.default = NetworkAction::Deny;
            egress.allow.clear();
        }
        if capture_requests_internet_capability(policy, network_capture) {
            omit_capture(policy);
        }
    } else if capability.eq_ignore_ascii_case("privateNetworkClientServer") {
        if let Some(ingress) = &mut policy.network_ingress {
            ingress.default = NetworkAction::Deny;
        }
        disable_proxy(policy, network_capture);
    } else if capability.eq_ignore_ascii_case("networkLoopback") {
        if let Some(ingress) = &mut policy.network_ingress {
            ingress.host_loopback = NetworkAction::Deny;
        }
        if policy.network_proxy.is_enabled() && policy.allowed_proxy_peer.is_none() {
            disable_proxy(policy, network_capture);
        }
    } else if capability.eq_ignore_ascii_case("permissiveLearningMode") {
        if let Some(capture) = &mut policy.capture_denials {
            capture.mode = CaptureDenialsMode::Block;
            ensure_capability(&mut policy.capabilities, "learningModeLogging");
        }
    } else if capability.eq_ignore_ascii_case("learningModeLogging") {
        omit_capture(policy);
    }
    Ok(())
}

fn omit_capture(policy: &mut ContainerPolicy) {
    policy.capture_denials = None;
    policy.capabilities.retain(|capability| {
        !capability_matches(capability, "permissiveLearningMode")
            && !capability_matches(capability, "learningModeLogging")
    });
}

fn disable_proxy(policy: &mut ContainerPolicy, network_capture: bool) {
    if !policy.network_proxy.is_enabled() {
        return;
    }
    // Proxy mode omits the direct policy tables. Do not activate allowances
    // that were ineffective in the submitted proxy form.
    if let Some(egress) = &mut policy.network_egress {
        egress.default = NetworkAction::Deny;
        egress.allow.clear();
    }
    if let Some(ingress) = &mut policy.network_ingress {
        ingress.default = NetworkAction::Deny;
        ingress.host_loopback = NetworkAction::Deny;
    }
    policy.network_proxy = Default::default();
    policy.runtime_network_proxy_specified = false;
    policy.allowed_proxy_peer = None;
    if capture_requests_internet_capability(policy, network_capture) {
        // Leaving proxy mode must not synthesize a new direct-egress capability.
        omit_capture(policy);
    }
}

fn literal_path(path: &str) -> Result<String, String> {
    let bytes = path.as_bytes();
    let drive =
        bytes.len() >= 3 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' && bytes[2] == b'\\';
    let unc = path.starts_with("\\\\") && !path.starts_with("\\\\?") && !path.starts_with("\\\\.");
    if (!drive && !unc) || path.contains(['/', '*', '?']) || path.chars().any(char::is_control) {
        return Err("filesystem restriction requires an absolute literal DOS or UNC path".into());
    }
    let normalized = path.trim_end_matches('\\');
    let normalized = if drive && normalized.len() == 2 {
        &path[..3]
    } else {
        normalized
    };
    let tail = normalized
        .get(if drive { 3.. } else { 2.. })
        .ok_or("filesystem restriction cannot reinterpret non-canonical path components")?;
    if (!tail.is_empty()
        && tail.split('\\').any(|part| {
            part.is_empty()
                || part == "."
                || part == ".."
                || part.ends_with(['.', ' '])
                || part.contains(':')
        }))
        || (unc && tail.split('\\').count() < 2)
    {
        return Err(
            "filesystem restriction cannot reinterpret non-canonical path components".into(),
        );
    }
    Ok(normalized.to_owned())
}

fn contains(parent: &str, child: &str) -> bool {
    child.eq_ignore_ascii_case(parent)
        || (child
            .get(..parent.len())
            .is_some_and(|prefix| prefix.eq_ignore_ascii_case(parent))
            && child.as_bytes().get(parent.len()) == Some(&b'\\'))
}

fn same_path(first: &str, second: &str) -> bool {
    first
        .trim_end_matches('\\')
        .eq_ignore_ascii_case(second.trim_end_matches('\\'))
}

fn access_at(policy: &ContainerPolicy, point: &str) -> u64 {
    let mut best = None;
    let mut access = Detail::ACCESS_NONE;
    for (paths, value) in [
        (&policy.readwrite_paths, Detail::ACCESS_READ_WRITE),
        (&policy.readonly_paths, Detail::ACCESS_READ_ONLY),
        (&policy.denied_paths, Detail::ACCESS_NONE),
    ] {
        for path in paths {
            let path = path.trim_end_matches('\\');
            if contains(path, point) && best.is_none_or(|length| path.len() >= length) {
                let same_depth = best == Some(path.len());
                best = Some(path.len());
                access = if same_depth && value != Detail::ACCESS_NONE {
                    access.max(value)
                } else {
                    value
                };
            }
        }
    }
    access
}

fn charge_filesystem_work(
    policy: &ContainerPolicy,
    hints: &[RestrictionHint],
    remaining: &mut usize,
) -> Result<(), String> {
    let witnesses = hints
        .iter()
        .filter(|hint| matches!(hint, RestrictionHint::RestrictPath { .. }))
        .count();
    if witnesses == 0 {
        return Ok(());
    }
    let paths = policy.readwrite_paths.len()
        + policy.readonly_paths.len()
        + policy.denied_paths.len()
        + policy.enumerate_paths.len()
        + witnesses;
    // Each pass has pairwise grant work; bound all passes, not just each probe.
    let cost = paths.checked_mul(paths).ok_or(FILESYSTEM_WORK_LIMIT)?;
    *remaining = remaining.checked_sub(cost).ok_or(FILESYSTEM_WORK_LIMIT)?;
    Ok(())
}

fn validate_filesystem_paths(
    policy: &ContainerPolicy,
    hints: &[RestrictionHint],
    resolve: &mut impl FnMut(&str) -> Result<PathCanonical, String>,
) -> Result<(), String> {
    if !hints
        .iter()
        .any(|hint| matches!(hint, RestrictionHint::RestrictPath { .. }))
    {
        return Ok(());
    }
    let mut budget = MAX_FILESYSTEM_WORK;
    charge_filesystem_work(policy, hints, &mut budget)?;
    let mut checked = HashSet::new();
    for path in policy
        .readwrite_paths
        .iter()
        .chain(&policy.readonly_paths)
        .chain(&policy.denied_paths)
        .map(String::as_str)
        .chain(hints.iter().filter_map(|hint| match hint {
            RestrictionHint::RestrictPath { path, .. } => Some(path.as_str()),
            _ => None,
        }))
    {
        if !checked.insert(path) {
            continue;
        }
        let spelling = literal_path(path)?;
        let resolved = match resolve(path)? {
            PathCanonical::Canonical(path) => literal_path(&path)?,
            _ => {
                return Err(
                    "filesystem restriction cannot resolve every relevant path safely".into(),
                )
            }
        };
        if !spelling.eq_ignore_ascii_case(&resolved) {
            return Err(
                "filesystem restriction will not guess the provenance of an aliased path".into(),
            );
        }
    }
    Ok(())
}

fn restrict_path(
    policy: &mut ContainerPolicy,
    original: &ContainerPolicy,
    path: &str,
    requested: u64,
    maximum: u64,
) -> Result<(), String> {
    if maximum > Detail::ACCESS_READ_ONLY
        || requested > Detail::ACCESS_READ_WRITE
        || maximum >= requested
    {
        return Err("the filesystem constraint is not a supported narrowing instruction".into());
    }
    let point = literal_path(path)?;
    if access_at(original, &point) != requested {
        return Err("the native filesystem witness disagrees with the submitted request".into());
    }
    if access_at(policy, &point) <= maximum {
        return Ok(());
    }
    let readonly_grants: Vec<_> = if maximum == Detail::ACCESS_READ_ONLY {
        policy
            .readwrite_paths
            .iter()
            .filter(|path| same_path(path, &point))
            .cloned()
            .collect()
    } else {
        Vec::new()
    };
    if maximum == Detail::ACCESS_READ_ONLY && readonly_grants.is_empty() {
        return Err(
            "read-only restriction requires an existing matching read-write grant; MXC will not \
             introduce a new grant name or downgrade an unrelated ancestor"
                .into(),
        );
    }
    if original.readwrite_paths.iter().any(|path| {
        let path = path.trim_end_matches('\\');
        path.len() == 2 || (path.starts_with("\\\\") && path[2..].split('\\').count() == 2)
    }) {
        return Err(
            "volume/share-root write grants have no supported automatic restriction".into(),
        );
    }

    policy
        .readwrite_paths
        .retain(|path| !same_path(path, &point));
    if maximum == Detail::ACCESS_NONE {
        policy
            .readonly_paths
            .retain(|path| !same_path(path, &point));
        if !policy
            .denied_paths
            .iter()
            .any(|path| same_path(path, &point))
        {
            policy.denied_paths.push(point.clone());
        }
        // Match contract normalization without changing unrelated enumeration.
        if let Some(denied) = policy
            .denied_paths
            .iter()
            .find(|path| same_path(path, &point))
        {
            policy.enumerate_paths.retain(|path| path != denied);
        }
    } else {
        for grant in readonly_grants {
            if !policy.readonly_paths.contains(&grant) {
                policy.readonly_paths.push(grant);
            }
        }
    }
    if access_at(policy, &point) > maximum {
        return Err("the proposed filesystem restriction could increase effective access".into());
    }
    Ok(())
}

#[cfg(test)]
#[path = "policy_restriction_tests.rs"]
mod tests;