bashkit 0.1.18

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
//! System information builtins (hostname, uname, whoami, id)
//!
//! 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";

/// 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);
        }

        // 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;

        for arg in ctx.args {
            match arg.as_str() {
                "-a" | "--all" => show_all = true,
                "-s" | "--kernel-name" => show_kernel = true,
                "-n" | "--nodename" => show_nodename = true,
                "-r" | "--kernel-release" => show_release = true,
                "-v" | "--kernel-version" => show_version = true,
                "-m" | "--machine" => show_machine = true,
                "-o" | "--operating-system" => show_os = true,
                _ => {}
            }
        }

        // 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("5.15.0-sandbox".to_string());
        }
        if show_all || show_version {
            parts.push("#1 SMP PREEMPT sandbox".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);
        }

        // 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
        )))
    }
}

#[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");
    }
}