bashkit 0.20.1

Awesomely fast virtual sandbox with bash and file system
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
//! System information builtins (hostname, uname, whoami, id, nproc)
//!
//! These builtins return configurable virtual values to prevent
//! information disclosure about the host system.
//!
//! Security rationale: Real system information could be used for:
//! - Fingerprinting the host for targeted attacks
//! - Identifying the environment for escape attempts
//! - Correlating activity across tenants

use async_trait::async_trait;

use super::{Builtin, Context};
use crate::error::Result;
use crate::interpreter::ExecResult;

/// Default virtual hostname.
/// Using a clearly fake name prevents confusion with real hosts.
pub const DEFAULT_HOSTNAME: &str = "bashkit-sandbox";

/// Default virtual username.
pub const DEFAULT_USERNAME: &str = "sandbox";

/// Virtual CPU count reported by `nproc` (and, later, `/proc/cpuinfo`).
/// A constant so the host core count is never exposed (TM-INF-008).
pub const VIRTUAL_NPROC: u64 = 4;

/// Kernel release reported by `uname -r` and `/proc/version`.
pub const VIRTUAL_KERNEL_RELEASE: &str = "5.15.0-sandbox";

/// Kernel version reported by `uname -v` and `/proc/version`.
pub const VIRTUAL_KERNEL_VERSION: &str = "#1 SMP PREEMPT sandbox";

/// Hardcoded virtual user ID.
pub const SANDBOX_UID: u32 = 1000;

/// Hardcoded virtual group ID.
pub const SANDBOX_GID: u32 = 1000;

/// The hostname builtin - returns configurable virtual hostname.
///
/// Real hostname is never exposed to prevent host fingerprinting.
pub struct Hostname {
    hostname: String,
}

impl Hostname {
    /// Create a new Hostname builtin with default hostname.
    pub fn new() -> Self {
        Self {
            hostname: DEFAULT_HOSTNAME.to_string(),
        }
    }

    /// Create a new Hostname builtin with custom hostname.
    pub fn with_hostname(hostname: impl Into<String>) -> Self {
        Self {
            hostname: hostname.into(),
        }
    }
}

impl Default for Hostname {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl Builtin for Hostname {
    async fn execute(&self, ctx: Context<'_>) -> Result<ExecResult> {
        if let Some(r) = super::check_help_version(
            ctx.args,
            "Usage: hostname\nDisplay the virtual hostname.\n\n  --help\tdisplay this help and exit\n  --version\toutput version information and exit\n",
            Some("hostname (bashkit) 0.1"),
        ) {
            return Ok(r);
        }

        // Display forms of the name; anything else would set it.
        match ctx
            .args
            .iter()
            .map(String::as_str)
            .collect::<Vec<_>>()
            .as_slice()
        {
            ["-s" | "--short"] => {
                let short = self.hostname.split('.').next().unwrap_or("");
                return Ok(ExecResult::ok(format!("{short}\n")));
            }
            ["-f" | "--fqdn" | "--long" | "-A" | "--all-fqdns"] => {
                return Ok(ExecResult::ok(format!("{}\n", self.hostname)));
            }
            ["-d" | "--domain"] => {
                let domain = self.hostname.split_once('.').map_or("", |(_, d)| d);
                return Ok(ExecResult::ok(format!("{domain}\n")));
            }
            _ => {}
        }
        // Ignore any attempts to set hostname
        if !ctx.args.is_empty() {
            return Ok(ExecResult::err(
                "hostname: cannot set hostname in virtual mode\n",
                1,
            ));
        }

        Ok(ExecResult::ok(format!("{}\n", self.hostname)))
    }
}

/// The uname builtin - returns configurable system information.
///
/// Prevents disclosure of:
/// - Kernel version (could reveal vulnerabilities)
/// - Architecture (could inform exploit selection)
/// - Host machine name
pub struct Uname {
    hostname: String,
}

impl Uname {
    /// Create a new Uname builtin with default hostname.
    pub fn new() -> Self {
        Self {
            hostname: DEFAULT_HOSTNAME.to_string(),
        }
    }

    /// Create a new Uname builtin with custom hostname.
    pub fn with_hostname(hostname: impl Into<String>) -> Self {
        Self {
            hostname: hostname.into(),
        }
    }
}

impl Default for Uname {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl Builtin for Uname {
    async fn execute(&self, ctx: Context<'_>) -> Result<ExecResult> {
        if let Some(r) = super::check_help_version(
            ctx.args,
            "Usage: uname [OPTION]...\nPrint virtual system information.\n\n  -a, --all\t\t\tprint all information\n  -s, --kernel-name\t\tprint the kernel name\n  -n, --nodename\t\tprint the network node hostname\n  -r, --kernel-release\t\tprint the kernel release\n  -v, --kernel-version\t\tprint the kernel version\n  -m, --machine\t\t\tprint the machine hardware name\n  -o, --operating-system\tprint the operating system\n  --help\tdisplay this help and exit\n  --version\toutput version information and exit\n",
            Some("uname (bashkit) 0.1"),
        ) {
            return Ok(r);
        }

        let mut show_all = false;
        let mut show_kernel = false;
        let mut show_nodename = false;
        let mut show_release = false;
        let mut show_version = false;
        let mut show_machine = false;
        let mut show_os = false;

        // Reject unknown options like GNU uname; short flags bundle per-char.
        for arg in ctx.args {
            match arg.as_str() {
                "-a" | "--all" => show_all = true,
                "--kernel-name" => show_kernel = true,
                "--nodename" => show_nodename = true,
                "--kernel-release" => show_release = true,
                "--kernel-version" => show_version = true,
                "--machine" => show_machine = true,
                "--operating-system" => show_os = true,
                "--processor" | "--hardware-platform" => {}
                _ if arg.starts_with("--") => {
                    return Ok(super::invalid_option("uname", arg, 1));
                }
                _ if arg.starts_with('-') && arg.len() > 1 => {
                    for c in arg[1..].chars() {
                        match c {
                            'a' => show_all = true,
                            's' => show_kernel = true,
                            'n' => show_nodename = true,
                            'r' => show_release = true,
                            'v' => show_version = true,
                            'm' => show_machine = true,
                            'o' => show_os = true,
                            'p' | 'i' => {}
                            _ => {
                                return Ok(super::invalid_option("uname", &format!("-{c}"), 1));
                            }
                        }
                    }
                }
                _ => {}
            }
        }

        // Default to kernel name if no options
        if !show_all
            && !show_kernel
            && !show_nodename
            && !show_release
            && !show_version
            && !show_machine
            && !show_os
        {
            show_kernel = true;
        }

        let mut parts = Vec::new();

        if show_all || show_kernel {
            parts.push("Linux".to_string());
        }
        if show_all || show_nodename {
            parts.push(self.hostname.clone());
        }
        if show_all || show_release {
            parts.push(VIRTUAL_KERNEL_RELEASE.to_string());
        }
        if show_all || show_version {
            parts.push(VIRTUAL_KERNEL_VERSION.to_string());
        }
        if show_all || show_machine {
            parts.push("x86_64".to_string());
        }
        if show_all || show_os {
            parts.push("GNU/Linux".to_string());
        }

        Ok(ExecResult::ok(format!("{}\n", parts.join(" "))))
    }
}

/// The whoami builtin - returns configurable virtual username.
pub struct Whoami {
    username: String,
}

impl Whoami {
    /// Create a new Whoami builtin with default username.
    pub fn new() -> Self {
        Self {
            username: DEFAULT_USERNAME.to_string(),
        }
    }

    /// Create a new Whoami builtin with custom username.
    pub fn with_username(username: impl Into<String>) -> Self {
        Self {
            username: username.into(),
        }
    }
}

impl Default for Whoami {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl Builtin for Whoami {
    async fn execute(&self, ctx: Context<'_>) -> Result<ExecResult> {
        if let Some(r) = super::check_help_version(
            ctx.args,
            "Usage: whoami\nPrint the user name associated with the current effective user ID.\n\n  --help\tdisplay this help and exit\n  --version\toutput version information and exit\n",
            Some("whoami (bashkit) 0.1"),
        ) {
            return Ok(r);
        }
        Ok(ExecResult::ok(format!("{}\n", self.username)))
    }
}

/// The id builtin - returns configurable virtual user/group IDs.
pub struct Id {
    username: String,
}

impl Id {
    /// Create a new Id builtin with default username.
    pub fn new() -> Self {
        Self {
            username: DEFAULT_USERNAME.to_string(),
        }
    }

    /// Create a new Id builtin with custom username.
    pub fn with_username(username: impl Into<String>) -> Self {
        Self {
            username: username.into(),
        }
    }
}

impl Default for Id {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl Builtin for Id {
    async fn execute(&self, ctx: Context<'_>) -> Result<ExecResult> {
        if let Some(r) = super::check_help_version(
            ctx.args,
            "Usage: id [OPTION]...\nPrint virtual user and group information.\n\n  -u, --user\tprint only the effective user ID\n  -g, --group\tprint only the effective group ID\n  -n, --name\tprint a name instead of a number (with -u or -g)\n  --help\tdisplay this help and exit\n  --version\toutput version information and exit\n",
            Some("id (bashkit) 0.1"),
        ) {
            return Ok(r);
        }

        // Reject unknown options like GNU id; -u/-g/-n (and -un/-gn combos)
        // are honored below, other real-id flags are accepted and ignored.
        for arg in ctx.args {
            if let Some(long) = arg.strip_prefix("--") {
                match long.split('=').next().unwrap_or("") {
                    "user" | "group" | "groups" | "name" | "real" | "zero" => {}
                    _ => return Ok(super::invalid_option("id", arg, 1)),
                }
            } else if arg.starts_with('-') && arg.len() > 1 {
                for c in arg[1..].chars() {
                    match c {
                        'u' | 'g' | 'G' | 'n' | 'r' | 'a' | 'z' => {}
                        _ => return Ok(super::invalid_option("id", &format!("-{c}"), 1)),
                    }
                }
            }
        }

        // Check for specific flags
        for arg in ctx.args {
            match arg.as_str() {
                "-u" | "--user" => {
                    return Ok(ExecResult::ok(format!("{}\n", SANDBOX_UID)));
                }
                "-g" | "--group" => {
                    return Ok(ExecResult::ok(format!("{}\n", SANDBOX_GID)));
                }
                "-n" | "--name" => {
                    // -n is usually combined with -u or -g
                    continue;
                }
                _ => {}
            }
        }

        // Check for -un or -gn combinations
        let args_str: String = ctx.args.iter().map(|s| s.as_str()).collect();
        if args_str.contains('u') && args_str.contains('n') {
            return Ok(ExecResult::ok(format!("{}\n", self.username)));
        }
        if args_str.contains('g') && args_str.contains('n') {
            return Ok(ExecResult::ok(format!("{}\n", self.username)));
        }

        // Default output format
        Ok(ExecResult::ok(format!(
            "uid={}({}) gid={}({}) groups={}({})\n",
            SANDBOX_UID, self.username, SANDBOX_GID, self.username, SANDBOX_GID, self.username
        )))
    }
}

/// The nproc builtin - prints the virtual processor count.
///
/// Honors `OMP_NUM_THREADS` / `OMP_THREAD_LIMIT` and `--ignore=N` like GNU.
pub struct Nproc;

#[async_trait]
impl Builtin for Nproc {
    async fn execute(&self, ctx: Context<'_>) -> Result<ExecResult> {
        if let Some(r) = super::check_help_version(
            ctx.args,
            "Usage: nproc [OPTION]...\nPrint the number of processing units available.\n\n  --all\tprint the number of installed processors\n  --ignore=N\tif possible, exclude N processing units\n  --help\tdisplay this help and exit\n  --version\toutput version information and exit\n",
            Some("nproc (bashkit) 0.1"),
        ) {
            return Ok(r);
        }
        let mut all = false;
        let mut ignore = 0u64;
        let mut args = ctx.args.iter();
        while let Some(arg) = args.next() {
            let value = match arg.as_str() {
                "--all" => {
                    all = true;
                    continue;
                }
                "--ignore" => args.next().map(String::as_str),
                a if a.starts_with("--ignore=") => Some(&a[9..]),
                a if a.starts_with('-') => return Ok(super::invalid_option("nproc", a, 1)),
                a => {
                    return Ok(ExecResult::err(format!("nproc: extra operand '{a}'\n"), 1));
                }
            };
            match value.and_then(|v| v.parse::<u64>().ok()) {
                Some(n) => ignore = n,
                None => {
                    return Ok(ExecResult::err(
                        format!("nproc: invalid number: '{}'\n", value.unwrap_or("")),
                        1,
                    ));
                }
            }
        }
        let mut n = VIRTUAL_NPROC;
        if !all {
            let env = |k: &str| {
                ctx.env
                    .get(k)
                    .and_then(|v| v.split(',').next()?.trim().parse::<u64>().ok())
                    .filter(|v| *v > 0)
            };
            if let Some(t) = env("OMP_NUM_THREADS") {
                n = t;
            }
            if let Some(limit) = env("OMP_THREAD_LIMIT") {
                n = n.min(limit);
            }
        }
        Ok(ExecResult::ok(format!(
            "{}\n",
            n.saturating_sub(ignore).max(1)
        )))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::fs::InMemoryFs;
    use std::collections::HashMap;
    use std::path::PathBuf;
    use std::sync::Arc;

    async fn run_builtin<B: Builtin>(builtin: &B, args: &[&str]) -> ExecResult {
        let fs = Arc::new(InMemoryFs::new());
        let env = HashMap::new();
        let mut variables = HashMap::new();
        let mut cwd = PathBuf::from("/home/user");
        let args: Vec<String> = args.iter().map(|s| s.to_string()).collect();

        let ctx = Context {
            args: &args,
            env: &env,
            variables: &mut variables,
            cwd: &mut cwd,
            fs,
            stdin: None,
            #[cfg(feature = "http_client")]
            http_client: None,
            #[cfg(feature = "git")]
            git_client: None,
            #[cfg(feature = "ssh")]
            ssh_client: None,
            shell: None,
        };

        builtin.execute(ctx).await.unwrap()
    }

    #[tokio::test]
    async fn test_hostname_returns_sandbox() {
        let result = run_builtin(&Hostname::new(), &[]).await;
        assert_eq!(result.stdout, "bashkit-sandbox\n");
        assert_eq!(result.exit_code, 0);
    }

    #[tokio::test]
    async fn test_hostname_custom() {
        let result = run_builtin(&Hostname::with_hostname("my-host"), &[]).await;
        assert_eq!(result.stdout, "my-host\n");
        assert_eq!(result.exit_code, 0);
    }

    #[tokio::test]
    async fn test_hostname_cannot_set() {
        let result = run_builtin(&Hostname::new(), &["evil.com"]).await;
        assert_eq!(result.exit_code, 1);
        assert!(result.stderr.contains("cannot set"));
    }

    #[tokio::test]
    async fn test_uname_default() {
        let result = run_builtin(&Uname::new(), &[]).await;
        assert_eq!(result.stdout, "Linux\n");
    }

    #[tokio::test]
    async fn test_uname_all() {
        let result = run_builtin(&Uname::new(), &["-a"]).await;
        assert!(result.stdout.contains("Linux"));
        assert!(result.stdout.contains("bashkit-sandbox"));
        assert!(result.stdout.contains("x86_64"));
    }

    #[tokio::test]
    async fn test_uname_custom_hostname() {
        let result = run_builtin(&Uname::with_hostname("custom-host"), &["-n"]).await;
        assert_eq!(result.stdout, "custom-host\n");
    }

    #[tokio::test]
    async fn test_uname_nodename() {
        let result = run_builtin(&Uname::new(), &["-n"]).await;
        assert_eq!(result.stdout, "bashkit-sandbox\n");
    }

    #[tokio::test]
    async fn test_whoami() {
        let result = run_builtin(&Whoami::new(), &[]).await;
        assert_eq!(result.stdout, "sandbox\n");
    }

    #[tokio::test]
    async fn test_whoami_custom() {
        let result = run_builtin(&Whoami::with_username("alice"), &[]).await;
        assert_eq!(result.stdout, "alice\n");
    }

    #[tokio::test]
    async fn test_id_default() {
        let result = run_builtin(&Id::new(), &[]).await;
        assert!(result.stdout.contains("uid=1000"));
        assert!(result.stdout.contains("gid=1000"));
        assert!(result.stdout.contains("sandbox"));
    }

    #[tokio::test]
    async fn test_id_custom_username() {
        let result = run_builtin(&Id::with_username("bob"), &[]).await;
        assert!(result.stdout.contains("uid=1000(bob)"));
        assert!(result.stdout.contains("gid=1000(bob)"));
    }

    #[tokio::test]
    async fn test_id_user() {
        let result = run_builtin(&Id::new(), &["-u"]).await;
        assert_eq!(result.stdout, "1000\n");
    }

    #[tokio::test]
    async fn test_id_group() {
        let result = run_builtin(&Id::new(), &["-g"]).await;
        assert_eq!(result.stdout, "1000\n");
    }

    #[tokio::test]
    async fn test_uname_rejects_unknown_option() {
        let result = run_builtin(&Uname::new(), &["-Q"]).await;
        assert_eq!(result.exit_code, 1);
        assert!(result.stderr.contains("invalid option -- 'Q'"));
    }

    #[tokio::test]
    async fn test_id_rejects_unknown_option() {
        let result = run_builtin(&Id::new(), &["-Q"]).await;
        assert_eq!(result.exit_code, 1);
        assert!(result.stderr.contains("invalid option -- 'Q'"));
    }
}