boxlite 0.10.1

Embeddable virtual machine runtime for secure, isolated code execution
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
//! Integration tests for security enforcement from GHSA-g6ww-w5j2-r7x3:
//!
//! 1. Read-only virtiofs volumes enforced at hypervisor level
//! 2. Dangerous capabilities excluded (CAP_SYS_ADMIN etc.)
//! 3. TSI network isolation when network disabled
//! 4. Protected-link sysctls block unprivileged hardlink attacks
//!
//! Run with:
//!
//! ```sh
//! cargo test -p boxlite --test security_enforcement -- --nocapture
//! ```

mod common;

use boxlite::runtime::options::{BoxOptions, BoxliteOptions, NetworkSpec, RootfsSpec, VolumeSpec};
use boxlite::{BoxCommand, BoxliteRuntime, LiteBox};
use futures::StreamExt;
use tempfile::TempDir;

// ============================================================================
// HELPERS
// ============================================================================

async fn exec_stdout(bx: &LiteBox, cmd: BoxCommand) -> String {
    let mut execution = bx.exec(cmd).await.expect("exec failed");
    let mut stdout = String::new();
    if let Some(mut stream) = execution.stdout() {
        while let Some(chunk) = stream.next().await {
            stdout.push_str(&chunk);
        }
    }
    let result = execution.wait().await.expect("wait failed");
    assert_eq!(
        result.exit_code, 0,
        "command should exit 0, got stdout: {stdout}"
    );
    stdout
}

async fn exec_full(bx: &LiteBox, cmd: BoxCommand) -> (i32, String) {
    let mut execution = bx.exec(cmd).await.expect("exec failed");
    let mut stdout = String::new();
    if let Some(mut stream) = execution.stdout() {
        while let Some(chunk) = stream.next().await {
            stdout.push_str(&chunk);
        }
    }
    let result = execution.wait().await.expect("wait failed");
    (result.exit_code, stdout)
}

async fn exec_exit_code(bx: &LiteBox, cmd: BoxCommand) -> i32 {
    exec_full(bx, cmd).await.0
}

// ============================================================================
// TEST SUITE: single VM for virtiofs + capabilities + protected-links tests
// ============================================================================

#[tokio::test(flavor = "multi_thread")]
async fn virtiofs_readonly_and_capabilities() {
    let home = boxlite_test_utils::home::PerTestBoxHome::new();
    let runtime = BoxliteRuntime::new(BoxliteOptions {
        home_dir: home.path.clone(),
        image_registries: common::test_registries(),
    })
    .expect("create runtime");

    let ro_dir = TempDir::new_in("/tmp").unwrap();
    std::fs::write(ro_dir.path().join("secret.txt"), "classified\n").unwrap();

    let rw_dir = TempDir::new_in("/tmp").unwrap();

    let bx = runtime
        .create(
            BoxOptions {
                volumes: vec![
                    VolumeSpec {
                        managed_volume: None,
                        host_path: ro_dir.path().to_str().unwrap().into(),
                        guest_path: "/data/readonly".into(),
                        read_only: true,
                    },
                    VolumeSpec {
                        managed_volume: None,
                        host_path: rw_dir.path().to_str().unwrap().into(),
                        guest_path: "/data/writable".into(),
                        read_only: false,
                    },
                ],
                rootfs: RootfsSpec::Image("alpine:latest".into()),
                auto_delete: Some(0),
                ..Default::default()
            },
            None,
        )
        .await
        .expect("create box");
    bx.start().await.expect("start box");

    protected_links_block_unprivileged_hardlinks(&bx).await;
    readonly_volume_readable(&bx).await;
    readonly_volume_blocks_write(&bx).await;
    readonly_volume_blocks_remount(&bx).await;
    rw_volume_allows_write(&bx).await;
    sealed_root_leaves_container_rootfs_writable(&bx).await;
    capabilities_exclude_sys_admin(&bx).await;
    capabilities_match_docker_defaults(&bx).await;

    bx.stop().await.expect("stop box");
    let _ = runtime.shutdown(Some(common::TEST_SHUTDOWN_TIMEOUT)).await;
}

/// Protected-link sysctls must be active before the first unprivileged workload.
async fn protected_links_block_unprivileged_hardlinks(bx: &LiteBox) {
    let security_state = exec_stdout(
        bx,
        BoxCommand::new("sh")
            .args([
                "-c",
                "id -u; cat /proc/sys/fs/protected_hardlinks; \
                 cat /proc/sys/fs/protected_symlinks; grep '^CapEff:' /proc/self/status",
            ])
            .user("1000:1000"),
    )
    .await;

    let mut lines = security_state.lines();
    assert_eq!(
        lines.next(),
        Some("1000"),
        "security probe must run as the unprivileged uid"
    );
    assert_eq!(
        lines.next(),
        Some("1"),
        "fs.protected_hardlinks must be enabled before workloads start"
    );
    assert_eq!(
        lines.next(),
        Some("1"),
        "fs.protected_symlinks must be enabled before workloads start"
    );

    let cap_eff_line = lines.next().expect("security probe should report CapEff");
    let cap_eff_hex = cap_eff_line
        .strip_prefix("CapEff:")
        .expect("security probe should emit a CapEff line")
        .trim();
    let cap_eff = u64::from_str_radix(cap_eff_hex, 16).expect("CapEff should be hexadecimal");

    // CAP_FOWNER = bit 3. If it leaked across exec, it would bypass protected_hardlinks.
    let cap_fowner = 1u64 << 3;
    assert_eq!(
        cap_eff & cap_fowner,
        0,
        "unprivileged workload must not retain CAP_FOWNER, CapEff=0x{cap_eff:x}"
    );

    exec_stdout(
        bx,
        BoxCommand::new("sh").args([
            "-c",
            "set -eu; base=/tmp/boxlite-protected-links; \
             mkdir \"$base\" \"$base/attacker\"; \
             printf 'classified\\n' > \"$base/source\"; \
             chmod 0444 \"$base/source\"; chown 0:0 \"$base/source\"; \
             chown 1000:1000 \"$base/attacker\"",
        ]),
    )
    .await;

    let (exit, output) = exec_full(
        bx,
        BoxCommand::new("sh")
            .args([
                "-c",
                "ln /tmp/boxlite-protected-links/source \
                 /tmp/boxlite-protected-links/attacker/link 2>&1",
            ])
            .user("1000:1000"),
    )
    .await;
    assert_ne!(
        exit, 0,
        "unprivileged user must not hardlink a root-owned, non-writable file"
    );
    assert!(
        output
            .to_ascii_lowercase()
            .contains("operation not permitted"),
        "hardlink denial should report EPERM, got: {output}"
    );

    let link_count = exec_stdout(
        bx,
        BoxCommand::new("stat").args(["-c", "%h", "/tmp/boxlite-protected-links/source"]),
    )
    .await;
    assert_eq!(
        link_count.trim(),
        "1",
        "failed hardlink attempt must not change the source link count"
    );
}

/// Read-only virtiofs volume can be read.
async fn readonly_volume_readable(bx: &LiteBox) {
    let content = exec_stdout(bx, BoxCommand::new("cat").arg("/data/readonly/secret.txt")).await;
    assert_eq!(content.trim(), "classified");
}

/// Write to read-only virtiofs volume fails at hypervisor level.
async fn readonly_volume_blocks_write(bx: &LiteBox) {
    let exit = exec_exit_code(
        bx,
        BoxCommand::new("sh").args(["-c", "echo pwned > /data/readonly/hack.txt 2>&1"]),
    )
    .await;
    assert_ne!(exit, 0, "writing to read-only volume should fail");

    let check = exec_exit_code(
        bx,
        BoxCommand::new("test").args(["-f", "/data/readonly/hack.txt"]),
    )
    .await;
    assert_ne!(check, 0, "file should not exist on read-only volume");
}

/// Guest without CAP_SYS_ADMIN cannot remount read-only volume as read-write.
async fn readonly_volume_blocks_remount(bx: &LiteBox) {
    let (exit, output) = exec_full(
        bx,
        BoxCommand::new("sh").args(["-c", "mount -o remount,rw /data/readonly 2>&1"]),
    )
    .await;
    assert_ne!(exit, 0, "remount rw should fail without CAP_SYS_ADMIN");
    assert!(
        output.contains("ermission denied")
            || output.contains("peration not permitted")
            || output.contains("not permitted")
            || output.contains("EPERM")
            || output.contains("Read-only"),
        "error should indicate permission/readonly denial, got: {output}"
    );
}

/// The guest rootfs is read-only by construction; the container rootfs
/// (writes outside the tmpfs mounts) must stay writable.
async fn sealed_root_leaves_container_rootfs_writable(bx: &LiteBox) {
    let exit = exec_exit_code(
        bx,
        BoxCommand::new("sh").args(["-c", "echo ok > /usr/boxlite-seal-probe 2>&1"]),
    )
    .await;
    assert_eq!(exit, 0, "container rootfs should stay writable");

    let content = exec_stdout(bx, BoxCommand::new("cat").arg("/usr/boxlite-seal-probe")).await;
    assert_eq!(content.trim(), "ok");
}

/// Sanity check: writable volume does accept writes.
async fn rw_volume_allows_write(bx: &LiteBox) {
    let exit = exec_exit_code(
        bx,
        BoxCommand::new("sh").args(["-c", "echo ok > /data/writable/test.txt"]),
    )
    .await;
    assert_eq!(exit, 0, "writing to writable volume should succeed");

    let content = exec_stdout(bx, BoxCommand::new("cat").arg("/data/writable/test.txt")).await;
    assert_eq!(content.trim(), "ok");
}

/// CAP_SYS_ADMIN must NOT be in the effective capability set.
async fn capabilities_exclude_sys_admin(bx: &LiteBox) {
    let status = exec_stdout(
        bx,
        BoxCommand::new("sh").args(["-c", "grep '^CapEff:' /proc/1/status"]),
    )
    .await;

    let hex_str = status.trim().strip_prefix("CapEff:\t").unwrap_or("");
    let cap_bits = u64::from_str_radix(hex_str.trim(), 16).unwrap_or(0);

    // CAP_SYS_ADMIN = bit 21
    let cap_sys_admin = 1u64 << 21;
    assert_eq!(
        cap_bits & cap_sys_admin,
        0,
        "CAP_SYS_ADMIN (bit 21) must not be set, CapEff=0x{:x}",
        cap_bits
    );

    // CAP_NET_ADMIN = bit 12
    let cap_net_admin = 1u64 << 12;
    assert_eq!(
        cap_bits & cap_net_admin,
        0,
        "CAP_NET_ADMIN (bit 12) must not be set, CapEff=0x{:x}",
        cap_bits
    );
}

/// Verify the capability set matches Docker defaults (14 capabilities).
async fn capabilities_match_docker_defaults(bx: &LiteBox) {
    let status = exec_stdout(
        bx,
        BoxCommand::new("sh").args(["-c", "grep '^CapEff:' /proc/1/status"]),
    )
    .await;

    let hex_str = status.trim().strip_prefix("CapEff:\t").unwrap_or("");
    let cap_bits = u64::from_str_radix(hex_str.trim(), 16).unwrap_or(0);

    let expected_docker_caps: u64 = (1 << 0)  // CAP_CHOWN
        | (1 << 1)  // CAP_DAC_OVERRIDE
        | (1 << 3)  // CAP_FOWNER
        | (1 << 4)  // CAP_FSETID
        | (1 << 5)  // CAP_KILL
        | (1 << 6)  // CAP_SETGID
        | (1 << 7)  // CAP_SETUID
        | (1 << 8)  // CAP_SETPCAP
        | (1 << 10) // CAP_NET_BIND_SERVICE
        | (1 << 13) // CAP_NET_RAW
        | (1 << 18) // CAP_SYS_CHROOT
        | (1 << 27) // CAP_MKNOD
        | (1 << 29) // CAP_AUDIT_WRITE
        | (1 << 31); // CAP_SETFCAP

    assert_eq!(
        cap_bits,
        expected_docker_caps,
        "CapEff should match Docker defaults.\n  got:    0x{:016x}\n  expect: 0x{:016x}\n  diff:   0x{:016x}",
        cap_bits,
        expected_docker_caps,
        cap_bits ^ expected_docker_caps,
    );
}

// ============================================================================
// TEST: TSI isolation when network is disabled
// ============================================================================

#[tokio::test(flavor = "multi_thread")]
async fn disabled_network_blocks_tsi_socket_forwarding() {
    let home = boxlite_test_utils::home::PerTestBoxHome::new();
    let runtime = BoxliteRuntime::new(BoxliteOptions {
        home_dir: home.path.clone(),
        image_registries: common::test_registries(),
    })
    .expect("create runtime");

    let bx = runtime
        .create(
            BoxOptions {
                network: NetworkSpec::Disabled,
                rootfs: RootfsSpec::Image("alpine:latest".into()),
                auto_delete: Some(0),
                ..Default::default()
            },
            None,
        )
        .await
        .expect("create box");
    bx.start().await.expect("start box");

    tsi_inet_blocked(&bx).await;
    tsi_unix_blocked(&bx).await;
    grpc_vsock_still_works(&bx).await;

    bx.stop().await.expect("stop box");
    let _ = runtime.shutdown(Some(common::TEST_SHUTDOWN_TIMEOUT)).await;
}

/// AF_INET sockets should not be forwarded through TSI when network is disabled.
async fn tsi_inet_blocked(bx: &LiteBox) {
    let (_, output) = exec_full(
        bx,
        BoxCommand::new("sh").args([
            "-c",
            "wget -q -O /dev/null --timeout=3 http://1.1.1.1/ 2>&1; echo EXIT:$?",
        ]),
    )
    .await;

    let exit_line = output
        .lines()
        .find(|l| l.starts_with("EXIT:"))
        .unwrap_or("EXIT:unknown");
    assert_ne!(
        exit_line, "EXIT:0",
        "TCP to external IP should fail with TSI disabled, got: {output}"
    );
}

/// AF_UNIX sockets should not be transparently forwarded through TSI.
async fn tsi_unix_blocked(bx: &LiteBox) {
    let exit = exec_exit_code(
        bx,
        BoxCommand::new("sh").args(["-c", "test -S /var/run/docker.sock 2>/dev/null"]),
    )
    .await;
    assert_ne!(
        exit, 0,
        "host Unix sockets should not be visible in guest with TSI disabled"
    );
}

/// Host-guest gRPC channel (vsock IPC) must still work even with TSI disabled.
async fn grpc_vsock_still_works(bx: &LiteBox) {
    let out = exec_stdout(bx, BoxCommand::new("echo").arg("vsock-ok")).await;
    assert_eq!(out.trim(), "vsock-ok");
}