microsandbox 0.6.9

`microsandbox` is the core library for the microsandbox project.
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
//! Linux host prerequisite checks for local sandbox execution.
//!
//! Local sandboxes need KVM through `/dev/kvm`. These checks diagnose the
//! common failure modes — missing CPU virtualization, an absent device node,
//! and a device the current user cannot open — and surface copy-pasteable
//! remediation commands. Nothing here mutates the host.

use std::ffi::CStr;
use std::fs::OpenOptions;
use std::os::unix::fs::MetadataExt;
use std::path::Path;

use super::host::{Check, Fix, FixCommand, Problem, Section};

//--------------------------------------------------------------------------------------------------
// Constants
//--------------------------------------------------------------------------------------------------

const KVM_DEVICE: &str = "/dev/kvm";

const KVM_AMD_AVIC_PARAMETER: &str = "/sys/module/kvm_amd/parameters/avic";
const KVM_INTEL_APICV_PARAMETER: &str = "/sys/module/kvm_intel/parameters/enable_apicv";

//--------------------------------------------------------------------------------------------------
// Types
//--------------------------------------------------------------------------------------------------

#[derive(Debug, Clone)]
struct DeviceGroup {
    name: Option<String>,
    gid: libc::gid_t,
    grants_read_write: bool,
}

#[derive(Debug, Clone)]
struct UserInfo {
    name: String,
    primary_gid: libc::gid_t,
}

//--------------------------------------------------------------------------------------------------
// Functions
//--------------------------------------------------------------------------------------------------

/// Diagnose Linux host virtualization prerequisites.
pub(super) fn host_section() -> (Section, Vec<Problem>) {
    let mut checks = Vec::new();
    let mut problems = Vec::new();

    let arch = std::env::consts::ARCH;
    checks.push(Check::info("Platform", &format!("Linux {arch}")));

    // x86 requires a VT-x / AMD-V flag in /proc/cpuinfo. On aarch64 the flag
    // isn't reported there — KVM availability is reflected by /dev/kvm itself —
    // so the cpuinfo probe would misfire; skip it and rely on the device check.
    if arch == "x86_64" {
        match cpu_virt_flag() {
            Some(flag) => checks.push(Check::pass("CPU virt", flag)),
            None => {
                checks.push(Check::fail("CPU virt", "not found"));
                problems.push(Problem::new(
                    "CPU virtualization is not available",
                    vec![
                        "no vmx (Intel) or svm (AMD) flag in /proc/cpuinfo".to_string(),
                        "enable virtualization (VT-x / AMD-V) in your BIOS or UEFI firmware"
                            .to_string(),
                        "inside a VM, enable nested virtualization on the host".to_string(),
                    ],
                ));
            }
        }
    }

    let kvm = Path::new(KVM_DEVICE);
    if !kvm.exists() {
        checks.push(Check::fail("KVM device", "missing"));
        let mut problem = Problem::new(
            format!("{KVM_DEVICE} is not present"),
            vec![
                "the KVM kernel module is not loaded".to_string(),
                "in containers or CI, the host must expose /dev/kvm to this environment"
                    .to_string(),
            ],
        );
        // Only the x86 vendor modules are safe to load by name. On aarch64 KVM
        // is typically built in, so there's nothing to modprobe — leave it
        // advisory rather than guess.
        if let Some(module) = kvm_module() {
            problem = problem.with_fix(Fix::new(
                format!("load the {module} kernel module"),
                vec![FixCommand::sudo(&["modprobe", module])],
            ));
        }
        problems.push(problem);
        return (section(checks), problems);
    }
    checks.push(Check::pass("KVM device", KVM_DEVICE));

    // Opening O_RDWR is the same access libkrun needs and is a side-effect-free
    // permission probe — we drop the handle immediately.
    match OpenOptions::new().read(true).write(true).open(kvm) {
        Ok(_) => checks.push(Check::pass("KVM access", "read/write")),
        Err(err) if err.kind() == std::io::ErrorKind::PermissionDenied => {
            checks.push(Check::fail("KVM access", "permission denied"));
            problems.push(kvm_permission_problem());
        }
        Err(err) => {
            checks.push(Check::fail("KVM access", "unavailable"));
            problems.push(Problem::new(
                format!("{KVM_DEVICE} could not be opened"),
                vec![format!("opening {KVM_DEVICE} failed: {err}")],
            ));
        }
    }

    // Hardware-assisted APIC virtualization is optional acceleration rather than a sandbox
    // correctness requirement. Report only the vendor-specific KVM policy that applies to this
    // host so non-x86 and unrelated x86 platforms do not get misleading rows.
    if arch == "x86_64"
        && let Some(check) = kvm_apic_acceleration_check()
    {
        checks.push(check);
    }

    (section(checks), problems)
}

fn section(checks: Vec<Check>) -> Section {
    Section {
        title: "Host".to_string(),
        checks,
    }
}

/// Return the first virtualization flag found in `/proc/cpuinfo`, if any.
fn cpu_virt_flag() -> Option<&'static str> {
    let info = std::fs::read_to_string("/proc/cpuinfo").ok()?;
    cpu_virt_flag_from(&info)
}

fn cpu_virt_flag_from(info: &str) -> Option<&'static str> {
    for line in info.lines() {
        if line.starts_with("flags") {
            let flags = line.split(':').nth(1).unwrap_or("");
            if flags.split_whitespace().any(|f| f == "vmx") {
                return Some("vmx");
            }
            if flags.split_whitespace().any(|f| f == "svm") {
                return Some("svm");
            }
        }
    }
    None
}

/// Inspect the applicable x86 KVM interrupt-acceleration policy without changing host state.
fn kvm_apic_acceleration_check() -> Option<Check> {
    let cpuinfo = std::fs::read_to_string("/proc/cpuinfo").ok()?;

    match cpu_virt_flag_from(&cpuinfo) {
        Some("svm") => {
            let parameter = std::fs::read_to_string(KVM_AMD_AVIC_PARAMETER).ok();
            kvm_avic_check_from(&cpuinfo, parameter.as_deref())
        }
        Some("vmx") => {
            let parameter = std::fs::read_to_string(KVM_INTEL_APICV_PARAMETER).ok();
            kvm_apicv_check_from(&cpuinfo, parameter.as_deref())
        }
        _ => None,
    }
}

fn kvm_avic_check_from(cpuinfo: &str, parameter: Option<&str>) -> Option<Check> {
    // AVIC is advertised in AMD's CPU flags, so avoid showing an unsupported-host or unknown-state
    // row when the hardware capability or live module parameter cannot be established.
    if cpu_virt_flag_from(cpuinfo) != Some("svm") || !cpu_flag_present(cpuinfo, "avic") {
        return None;
    }

    let x2avic = cpu_flag_present(cpuinfo, "x2avic");

    match parse_module_bool(parameter?) {
        Some(true) if x2avic => Some(Check::pass("KVM AVIC", "enabled (x2AVIC available)")),
        Some(true) => Some(Check::pass("KVM AVIC", "enabled")),
        Some(false) if x2avic => Some(Check::warn("KVM AVIC", "disabled — x2AVIC available")),
        Some(false) => Some(Check::warn("KVM AVIC", "disabled — optional acceleration")),
        None => None,
    }
}

fn kvm_apicv_check_from(cpuinfo: &str, parameter: Option<&str>) -> Option<Check> {
    if cpu_virt_flag_from(cpuinfo) != Some("vmx") {
        return None;
    }

    // Intel does not expose an APICv capability flag in /proc/cpuinfo. The module parameter proves
    // only that KVM policy enables the acceleration; per-VM activation still requires runtime
    // tracing, so keep that distinction explicit in the value shown to operators.
    match parse_module_bool(parameter?) {
        Some(true) => Some(Check::pass("KVM APICv", "enabled by KVM policy")),
        Some(false) => Some(Check::warn("KVM APICv", "disabled by KVM policy")),
        None => None,
    }
}

fn cpu_flag_present(info: &str, expected: &str) -> bool {
    info.lines().any(|line| {
        line.starts_with("flags")
            && line
                .split_once(':')
                .is_some_and(|(_, flags)| flags.split_whitespace().any(|flag| flag == expected))
    })
}

fn parse_module_bool(value: &str) -> Option<bool> {
    match value.trim().to_ascii_lowercase().as_str() {
        "1" | "on" | "y" | "yes" => Some(true),
        "0" | "off" | "n" | "no" => Some(false),
        _ => None,
    }
}

/// Build the `/dev/kvm` permission failure, with a fix tailored to whether the
/// user already belongs to the device's owning group.
///
/// The fix always prefers the narrowest safe mutation: `setfacl` grants the
/// running user access for this boot, and `usermod -aG` is offered only when the
/// device is owned by the standard `kvm` group with group read/write bits.
/// We can only build commands once we know the effective username, so a missing
/// username degrades to advisory hints.
fn kvm_permission_problem() -> Problem {
    let device_group = device_group(KVM_DEVICE);
    let user = current_user();
    let process_member = device_group
        .as_ref()
        .map(|group| process_has_group(group.gid))
        .unwrap_or(false);
    let persistent_member = match (&user, &device_group) {
        (Some(user), Some(group)) => persistent_user_in_group(user, group.gid),
        _ => false,
    };

    let cause = match &device_group {
        Some(group) if persistent_member && !process_member => {
            let label = group_label(group);
            format!("you are in the '{label}' group, but this login session predates the change")
        }
        Some(group) if process_member => {
            let label = group_label(group);
            format!(
                "your process belongs to the '{label}' group, but {KVM_DEVICE} still rejects read/write access"
            )
        }
        Some(group) if group.grants_read_write => {
            let label = group_label(group);
            format!("{KVM_DEVICE} is owned by group '{label}', which your user is not in")
        }
        Some(group) => {
            let label = group_label(group);
            format!(
                "{KVM_DEVICE} is owned by group '{label}', but group permissions do not grant read/write access"
            )
        }
        None => format!("your user lacks read/write access to {KVM_DEVICE}"),
    };

    let mut problem = Problem::new(
        format!("{KVM_DEVICE} is not accessible by your user"),
        vec![cause],
    );

    let Some(user) = user else {
        return problem;
    };
    let acl = format!("u:{}:rw", user.name);

    if persistent_member || process_member || !can_offer_group_fix(device_group.as_ref()) {
        // When persistent membership is already present, the direct ACL grants
        // this login session access immediately. For non-standard device groups
        // it is also the only safe automatic mutation; adding users to arbitrary
        // groups can accidentally grant unrelated host privileges.
        problem = problem.with_fix(Fix::new(
            format!(
                "grant {} access to {KVM_DEVICE} for the current session",
                user.name
            ),
            vec![FixCommand::sudo(&[
                "setfacl",
                "-m",
                acl.as_str(),
                KVM_DEVICE,
            ])],
        ));
    } else {
        let group = device_group
            .as_ref()
            .and_then(|group| group.name.as_deref())
            .expect("safe KVM group fixes require a named device group");
        problem = problem.with_fix(
            Fix::new(
                format!(
                    "add {} to the '{group}' group and grant access now",
                    user.name
                ),
                vec![
                    FixCommand::sudo(&["usermod", "-aG", group, user.name.as_str()]),
                    FixCommand::sudo(&["setfacl", "-m", acl.as_str(), KVM_DEVICE]),
                ],
            )
            .requires_relogin(),
        );
    }

    problem
}

/// The x86 vendor KVM module to load, derived from the CPU virtualization flag.
fn kvm_module() -> Option<&'static str> {
    match cpu_virt_flag() {
        Some("vmx") => Some("kvm_intel"),
        Some("svm") => Some("kvm_amd"),
        _ => None,
    }
}

/// Resolve the current effective user's login name and primary group.
fn current_user() -> Option<UserInfo> {
    // SAFETY: getpwuid returns a pointer into a shared static buffer; the doctor
    // command is single-threaded, and we copy the name out immediately.
    unsafe {
        let entry = libc::getpwuid(libc::geteuid());
        if entry.is_null() {
            return None;
        }
        Some(UserInfo {
            name: CStr::from_ptr((*entry).pw_name)
                .to_string_lossy()
                .into_owned(),
            primary_gid: (*entry).pw_gid,
        })
    }
}

/// Resolve the owning group and group permission bits of a device path.
fn device_group(path: &str) -> Option<DeviceGroup> {
    let metadata = std::fs::metadata(path).ok()?;
    let gid = metadata.gid();
    Some(DeviceGroup {
        name: group_name(gid),
        gid,
        grants_read_write: metadata.mode() & 0o060 == 0o060,
    })
}

/// Resolve a gid to its group name.
fn group_name(gid: libc::gid_t) -> Option<String> {
    // SAFETY: getgrgid returns a pointer into a shared static buffer. The doctor
    // command is single-threaded, and we copy the name out immediately before
    // any further libc call can overwrite the buffer.
    unsafe {
        let entry = libc::getgrgid(gid);
        if entry.is_null() {
            return None;
        }
        Some(
            CStr::from_ptr((*entry).gr_name)
                .to_string_lossy()
                .into_owned(),
        )
    }
}

/// Whether the current process belongs to the given group.
fn process_has_group(gid: libc::gid_t) -> bool {
    if unsafe { libc::getegid() } == gid {
        return true;
    }

    // SAFETY: the first call queries the count; the second fills the buffer.
    let count = unsafe { libc::getgroups(0, std::ptr::null_mut()) };
    if count <= 0 {
        return false;
    }

    let mut gids = vec![0 as libc::gid_t; count as usize];
    let filled = unsafe { libc::getgroups(count, gids.as_mut_ptr()) };
    if filled < 0 {
        return false;
    }
    gids.truncate(filled as usize);

    gids.into_iter().any(|g| g == gid)
}

/// Whether the user's account is persistently a member of the target group.
fn persistent_user_in_group(user: &UserInfo, gid: libc::gid_t) -> bool {
    user.primary_gid == gid || group_has_member(gid, &user.name)
}

/// Whether a group database entry lists a user as a member.
fn group_has_member(gid: libc::gid_t, user: &str) -> bool {
    // SAFETY: getgrgid returns a pointer into a shared static buffer. We only
    // read the null-terminated member list during this call and copy names into
    // Rust strings before comparing.
    unsafe {
        let entry = libc::getgrgid(gid);
        if entry.is_null() {
            return false;
        }

        let mut member = (*entry).gr_mem;
        while !member.is_null() && !(*member).is_null() {
            if CStr::from_ptr(*member).to_string_lossy() == user {
                return true;
            }
            member = member.add(1);
        }
    }

    false
}

/// Whether it is safe to persist access by adding the user to the device group.
fn can_offer_group_fix(group: Option<&DeviceGroup>) -> bool {
    matches!(
        group,
        Some(DeviceGroup {
            name: Some(name),
            grants_read_write: true,
            ..
        }) if name == "kvm"
    )
}

fn group_label(group: &DeviceGroup) -> String {
    group
        .name
        .clone()
        .unwrap_or_else(|| format!("gid {}", group.gid))
}

//--------------------------------------------------------------------------------------------------
// Tests
//--------------------------------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn cpu_flags_are_read_from_the_flags_field() {
        let cpuinfo = "processor: 0\nflags: fpu svm avic x2avic\n";

        assert_eq!(cpu_virt_flag_from(cpuinfo), Some("svm"));
        assert!(cpu_flag_present(cpuinfo, "avic"));
        assert!(cpu_flag_present(cpuinfo, "x2avic"));
        assert!(!cpu_flag_present(cpuinfo, "vmx"));
    }

    #[test]
    fn module_boolean_parser_accepts_sysfs_shapes() {
        assert_eq!(parse_module_bool("Y\n"), Some(true));
        assert_eq!(parse_module_bool("1"), Some(true));
        assert_eq!(parse_module_bool("N\n"), Some(false));
        assert_eq!(parse_module_bool("0"), Some(false));
        assert_eq!(parse_module_bool("auto"), None);
    }

    #[test]
    fn avic_check_distinguishes_enabled_disabled_and_irrelevant_hosts() {
        let amd = "processor: 0\nflags: fpu svm avic x2avic\n";
        let amd_without_avic = "processor: 0\nflags: fpu svm\n";
        let intel = "processor: 0\nflags: fpu vmx\n";

        let enabled = kvm_avic_check_from(amd, Some("Y\n")).unwrap();
        assert_eq!(enabled.state, super::super::host::CheckState::Pass);
        assert_eq!(enabled.value, "enabled (x2AVIC available)");

        let disabled = kvm_avic_check_from(amd, Some("N\n")).unwrap();
        assert_eq!(disabled.state, super::super::host::CheckState::Warn);
        assert_eq!(disabled.value, "disabled — x2AVIC available");

        assert!(kvm_avic_check_from(intel, None).is_none());
        assert!(kvm_avic_check_from(amd_without_avic, Some("Y\n")).is_none());
        assert!(kvm_avic_check_from(amd, None).is_none());
        assert!(kvm_avic_check_from(amd, Some("unknown")).is_none());
    }

    #[test]
    fn apicv_check_reports_intel_kvm_policy_only_when_known() {
        let intel = "processor: 0\nflags: fpu vmx\n";
        let amd = "processor: 0\nflags: fpu svm avic x2avic\n";

        let enabled = kvm_apicv_check_from(intel, Some("Y\n")).unwrap();
        assert_eq!(enabled.state, super::super::host::CheckState::Pass);
        assert_eq!(enabled.value, "enabled by KVM policy");

        let disabled = kvm_apicv_check_from(intel, Some("N\n")).unwrap();
        assert_eq!(disabled.state, super::super::host::CheckState::Warn);
        assert_eq!(disabled.value, "disabled by KVM policy");

        assert!(kvm_apicv_check_from(amd, Some("Y\n")).is_none());
        assert!(kvm_apicv_check_from(intel, None).is_none());
        assert!(kvm_apicv_check_from(intel, Some("unknown")).is_none());
    }
}