Skip to main content

merry_runtime/process/classification/
shell.rs

1//! Narrow shell-wrapper recognition, tree-sitter-bash AST normalization, and
2//! Windows PowerShell detection/analysis; policy stays in the classifier.
3
4use crate::process::contracts::ProcessActionIntent;
5
6#[cfg(windows)]
7use super::windows_shell;
8
9/// Shell grammar family represented by one recognized shell wrapper argv.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub(crate) enum ShellKind {
12    /// POSIX/Bash-compatible shell (`bash`, `sh`, `zsh`, Git Bash).
13    Bash,
14    /// PowerShell (`pwsh`, `powershell`, `powershell.exe`).
15    #[cfg(windows)]
16    PowerShell,
17    /// Windows Command Prompt (`cmd`, `cmd.exe`).
18    #[cfg(windows)]
19    Cmd,
20}
21
22/// Exact shell-wrapper input plus payload-free metadata helpers.
23///
24/// This value recognizes only the validated wrapper shape used by the current
25/// shell read-only lane. It does not authorize execution by itself.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub(crate) struct ShellProcessInput<'a> {
28    pub(super) kind: ShellKind,
29    pub(super) shell: &'a str,
30    pub(super) flag: &'a str,
31    pub(super) script: &'a str,
32}
33
34impl<'a> ShellProcessInput<'a> {
35    pub(crate) const fn kind(self) -> ShellKind {
36        self.kind
37    }
38
39    pub(crate) const fn shell(self) -> &'a str {
40        self.shell
41    }
42
43    pub(crate) const fn flag(self) -> &'a str {
44        self.flag
45    }
46
47    pub(crate) const fn script(self) -> &'a str {
48        self.script
49    }
50
51    pub(crate) const fn script_bytes(self) -> usize {
52        self.script.len()
53    }
54
55    pub(crate) fn script_fingerprint(self) -> String {
56        stable_process_input_fingerprint(self.script.as_bytes())
57    }
58}
59
60pub(crate) fn shell_process_input(intent: &ProcessActionIntent) -> Option<ShellProcessInput<'_>> {
61    shell_process_input_from_argv(intent.argv())
62}
63
64/// Converts one model-facing shell command into the platform process argv
65/// consumed by runtime policy and process runners.
66pub(crate) fn shell_command_argv(command: &str) -> Vec<String> {
67    #[cfg(windows)]
68    {
69        windows_shell::detect_windows_shell().command_argv(command)
70    }
71
72    #[cfg(not(windows))]
73    {
74        vec!["bash".to_owned(), "-lc".to_owned(), command.to_owned()]
75    }
76}
77
78/// Returns the command script represented by a platform shell argv wrapper.
79pub(crate) fn shell_command_from_argv(argv: &[String]) -> Option<&str> {
80    #[cfg(windows)]
81    {
82        match argv {
83            [shell, no_profile, non_interactive, flag, command]
84                if matches!(executable_name(shell).as_str(), "powershell" | "pwsh")
85                    && no_profile.eq_ignore_ascii_case("-NoProfile")
86                    && non_interactive.eq_ignore_ascii_case("-NonInteractive")
87                    && flag.eq_ignore_ascii_case("-Command") =>
88            {
89                Some(command)
90            }
91            [shell, no_profile, flag, command]
92                if matches!(executable_name(shell).as_str(), "powershell" | "pwsh")
93                    && no_profile.eq_ignore_ascii_case("-NoProfile")
94                    && flag.eq_ignore_ascii_case("-Command") =>
95            {
96                Some(command)
97            }
98            [shell, flag, command]
99                if executable_name(shell) == "bash" && matches!(flag.as_str(), "-c" | "-lc") =>
100            {
101                Some(command)
102            }
103            [shell, flag, command]
104                if executable_name(shell) == "cmd" && flag.eq_ignore_ascii_case("/C") =>
105            {
106                Some(command)
107            }
108            _ => None,
109        }
110    }
111
112    #[cfg(not(windows))]
113    {
114        match argv {
115            [shell, flag, command] if shell == "bash" && matches!(flag.as_str(), "-c" | "-lc") => {
116                Some(command)
117            }
118            _ => None,
119        }
120    }
121}
122
123/// Converts an argv vector into one shell command string for a model-facing
124/// command field. Existing platform shell wrappers are unwrapped so their
125/// script is preserved; direct argv items are quoted for the host shell.
126#[must_use]
127pub fn shell_command_for_argv(argv: &[String]) -> String {
128    if let Some(command) = shell_command_from_argv(argv) {
129        return command.to_owned();
130    }
131
132    argv.iter()
133        .map(|argument| shell_quote_argument(argument))
134        .collect::<Vec<_>>()
135        .join(" ")
136}
137
138#[cfg(not(windows))]
139pub(super) fn shell_quote_argument(argument: &str) -> String {
140    if !argument.is_empty() && argument.bytes().all(is_safe_shell_word_byte) {
141        return argument.to_owned();
142    }
143    format!("'{}'", argument.replace('\'', "'\\''"))
144}
145
146#[cfg(windows)]
147pub(super) fn shell_quote_argument(argument: &str) -> String {
148    if !argument.is_empty() && argument.bytes().all(is_safe_shell_word_byte) {
149        return argument.to_owned();
150    }
151    format!("'{}'", argument.replace('\'', "''"))
152}
153
154pub(super) fn is_safe_shell_word_byte(byte: u8) -> bool {
155    byte.is_ascii_alphanumeric()
156        || matches!(
157            byte,
158            b'_' | b'-' | b'.' | b'/' | b':' | b'=' | b'@' | b'%' | b'+'
159        )
160}
161
162pub(super) fn shell_process_input_from_argv(argv: &[String]) -> Option<ShellProcessInput<'_>> {
163    #[cfg(windows)]
164    {
165        match argv {
166            [shell, no_profile, non_interactive, flag, script]
167                if is_supported_plain_shell_token(shell)
168                    && no_profile.eq_ignore_ascii_case("-NoProfile")
169                    && non_interactive.eq_ignore_ascii_case("-NonInteractive")
170                    && flag.eq_ignore_ascii_case("-Command") =>
171            {
172                Some(ShellProcessInput {
173                    kind: ShellKind::PowerShell,
174                    shell,
175                    flag,
176                    script,
177                })
178            }
179            [shell, no_profile, flag, script]
180                if is_supported_plain_shell_token(shell)
181                    && no_profile.eq_ignore_ascii_case("-NoProfile")
182                    && flag.eq_ignore_ascii_case("-Command") =>
183            {
184                Some(ShellProcessInput {
185                    kind: ShellKind::PowerShell,
186                    shell,
187                    flag,
188                    script,
189                })
190            }
191            [shell, flag, script]
192                if is_supported_plain_bash_token(shell)
193                    && matches!(flag.as_str(), "-c" | "-lc") =>
194            {
195                Some(ShellProcessInput {
196                    kind: ShellKind::Bash,
197                    shell,
198                    flag,
199                    script,
200                })
201            }
202            _ => None,
203        }
204    }
205
206    #[cfg(not(windows))]
207    {
208        let [shell, flag, script] = argv else {
209            return None;
210        };
211        if !is_supported_plain_shell_token(shell) || !matches!(flag.as_str(), "-c" | "-lc") {
212            return None;
213        }
214        Some(ShellProcessInput {
215            kind: ShellKind::Bash,
216            shell,
217            flag,
218            script,
219        })
220    }
221}
222
223pub(super) fn is_supported_plain_shell_token(shell: &str) -> bool {
224    #[cfg(windows)]
225    {
226        !shell.contains(['/', '\\'])
227            && matches!(executable_name(shell).as_str(), "powershell" | "pwsh")
228    }
229
230    #[cfg(not(windows))]
231    matches!(shell, "bash" | "sh" | "zsh")
232}
233
234#[cfg(windows)]
235fn is_supported_plain_bash_token(shell: &str) -> bool {
236    if !shell.contains(['/', '\\']) {
237        return matches!(executable_name(shell).as_str(), "bash" | "sh" | "zsh");
238    }
239    matches!(
240        windows_shell::detect_windows_shell(),
241        windows_shell::WindowsShell::GitBash(path)
242            if path.to_string_lossy().eq_ignore_ascii_case(shell)
243    )
244}
245
246pub(crate) fn stable_process_input_fingerprint(bytes: &[u8]) -> String {
247    const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
248    const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
249
250    let hash = bytes.iter().fold(FNV_OFFSET_BASIS, |hash, byte| {
251        (hash ^ u64::from(*byte)).wrapping_mul(FNV_PRIME)
252    });
253    format!("fnv1a64:{hash:016x}")
254}
255
256pub(super) fn shell_like_process_input_from_argv(argv: &[String]) -> Option<ShellProcessInput<'_>> {
257    #[cfg(windows)]
258    {
259        match argv {
260            [shell, no_profile, non_interactive, flag, script]
261                if matches!(executable_name(shell).as_str(), "powershell" | "pwsh")
262                    && no_profile.eq_ignore_ascii_case("-NoProfile")
263                    && non_interactive.eq_ignore_ascii_case("-NonInteractive")
264                    && flag.eq_ignore_ascii_case("-Command") =>
265            {
266                Some(ShellProcessInput {
267                    kind: ShellKind::PowerShell,
268                    shell,
269                    flag,
270                    script,
271                })
272            }
273            [shell, no_profile, flag, script]
274                if matches!(executable_name(shell).as_str(), "powershell" | "pwsh")
275                    && no_profile.eq_ignore_ascii_case("-NoProfile")
276                    && flag.eq_ignore_ascii_case("-Command") =>
277            {
278                Some(ShellProcessInput {
279                    kind: ShellKind::PowerShell,
280                    shell,
281                    flag,
282                    script,
283                })
284            }
285            [shell, flag, script]
286                if matches!(executable_name(shell).as_str(), "bash" | "sh" | "zsh")
287                    && matches!(flag.as_str(), "-c" | "-lc") =>
288            {
289                Some(ShellProcessInput {
290                    kind: ShellKind::Bash,
291                    shell,
292                    flag,
293                    script,
294                })
295            }
296            [shell, flag, script]
297                if executable_name(shell) == "cmd" && flag.eq_ignore_ascii_case("/C") =>
298            {
299                Some(ShellProcessInput {
300                    kind: ShellKind::Cmd,
301                    shell,
302                    flag,
303                    script,
304                })
305            }
306            _ => None,
307        }
308    }
309
310    #[cfg(not(windows))]
311    {
312        let [shell, flag, script] = argv else {
313            return None;
314        };
315        if !is_supported_shell_executable_name(shell) || !matches!(flag.as_str(), "-c" | "-lc") {
316            return None;
317        }
318        Some(ShellProcessInput {
319            kind: ShellKind::Bash,
320            shell,
321            flag,
322            script,
323        })
324    }
325}
326
327#[cfg(not(windows))]
328pub(super) fn is_supported_shell_executable_name(shell: &str) -> bool {
329    matches!(executable_name(shell).as_str(), "bash" | "sh" | "zsh")
330}
331
332/// AST-derived security summary of one parsed bash script.
333pub(super) struct BashSecurityAnalysis {
334    /// Every command node found anywhere in the AST (including inside control
335    /// flow, subshells, and `$(...)`/backtick substitutions), in source order.
336    pub(super) commands: Vec<Vec<String>>,
337    /// True if any inline assignment, `export`/`declare`, or `env` invocation
338    /// sets an execution-injecting environment variable or uses `env -S`.
339    pub(super) env_injection: bool,
340    /// True if the AST contains command or process substitution (`$(...)`,
341    /// `` `...` ``, `<(...)`, `>(...)`).
342    pub(super) has_command_substitution: bool,
343    /// Non-comment command words and redirect destinations for host-path checks.
344    pub(super) path_check_tokens: Vec<String>,
345}
346
347const INJECTION_ENV_KEYS: &[&str] = &[
348    "LD_PRELOAD",
349    "LD_AUDIT",
350    "BASH_ENV",
351    "ENV",
352    "IFS",
353    "PATH",
354    "GIT_EXTERNAL_DIFF",
355    "GIT_PROXY_COMMAND",
356    "PROMPT_COMMAND",
357];
358
359const INJECTION_ENV_KEY_PREFIXES: &[&str] = &["DYLD_", "GIT_CONFIG"];
360
361pub(super) fn is_injection_env_key(key: &str) -> bool {
362    INJECTION_ENV_KEYS.contains(&key)
363        || INJECTION_ENV_KEY_PREFIXES
364            .iter()
365            .any(|prefix| key.starts_with(prefix))
366}
367
368/// Parses a strictly plain, expansion-free, redirect-free command sequence
369/// joined only by `;`, `|`, `||`, or `&&` (used by the narrow SP3-A shell
370/// read-only lane). Fails closed when the `bash-ast` feature is disabled.
371pub(super) fn parse_plain_shell_command_sequence(script: &str) -> Option<Vec<Vec<String>>> {
372    #[cfg(feature = "bash-ast")]
373    {
374        super::bash_ast::parse_plain_shell_command_sequence(script)
375    }
376    #[cfg(not(feature = "bash-ast"))]
377    {
378        let _ = script;
379        None
380    }
381}
382
383/// Parses a bash script into an AST security summary. Returns `None` on syntax
384/// errors or when `bash-ast` is disabled so callers fail closed.
385pub(super) fn parse_bash_security_analysis(script: &str) -> Option<BashSecurityAnalysis> {
386    #[cfg(feature = "bash-ast")]
387    {
388        super::bash_ast::parse_bash_security_analysis(script)
389    }
390    #[cfg(not(feature = "bash-ast"))]
391    {
392        let _ = script;
393        None
394    }
395}
396
397/// Detects dangerous `env` invocations (`env -S`, `env LD_PRELOAD=...`, etc.)
398/// even behind wrapper chains such as `timeout 5 env ...`.
399pub(super) fn command_words_have_env_injection(words: &[String]) -> bool {
400    let mut index = 0;
401    while let Some(head) = words.get(index) {
402        let name = executable_name(head);
403        if name == "env" {
404            let mut options_done = false;
405            for arg in &words[index + 1..] {
406                if !options_done && arg == "--" {
407                    options_done = true;
408                    continue;
409                }
410                if !options_done && arg.starts_with('-') {
411                    // `-S` / `--split-string` rewrites argv and can smuggle commands.
412                    if arg == "-S"
413                        || arg.starts_with("-S")
414                        || arg == "--split-string"
415                        || arg.starts_with("--split-string=")
416                        || (!arg.starts_with("--") && arg.contains('S'))
417                    {
418                        return true;
419                    }
420                    continue;
421                }
422                if let Some((key, _)) = arg.split_once('=') {
423                    if is_injection_env_key(key) {
424                        return true;
425                    }
426                    continue;
427                }
428                break;
429            }
430            return false;
431        }
432        if matches!(
433            head.as_str(),
434            "!" | "time" | "exec" | "command" | "builtin" | "nohup"
435        ) {
436            index += 1;
437            continue;
438        }
439        if name == "timeout" {
440            index += 1;
441            while let Some(arg) = words.get(index) {
442                if matches!(arg.as_str(), "-k" | "--kill-after" | "-s" | "--signal") {
443                    index += 2;
444                    continue;
445                }
446                if arg.starts_with('-') {
447                    index += 1;
448                    continue;
449                }
450                index += 1;
451                break;
452            }
453            continue;
454        }
455        break;
456    }
457    false
458}
459
460pub(super) fn executable_name(argument: &str) -> String {
461    let base = argument
462        .rsplit(['/', '\\'])
463        .next()
464        .unwrap_or(argument)
465        .to_ascii_lowercase();
466    for suffix in [".exe", ".cmd", ".bat", ".com"] {
467        if let Some(stripped) = base.strip_suffix(suffix)
468            && !stripped.is_empty()
469        {
470            return stripped.to_owned();
471        }
472    }
473    base
474}
475
476pub(super) fn executable_token_is(argument: &str, expected: &str) -> bool {
477    #[cfg(windows)]
478    {
479        argument.eq_ignore_ascii_case(expected)
480            || argument
481                .strip_suffix(".exe")
482                .or_else(|| argument.strip_suffix(".EXE"))
483                .is_some_and(|stripped| stripped.eq_ignore_ascii_case(expected))
484    }
485    #[cfg(not(windows))]
486    {
487        argument == expected
488    }
489}