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}
341
342const INJECTION_ENV_KEYS: &[&str] = &[
343    "LD_PRELOAD",
344    "LD_AUDIT",
345    "BASH_ENV",
346    "ENV",
347    "IFS",
348    "PATH",
349    "GIT_EXTERNAL_DIFF",
350    "GIT_PROXY_COMMAND",
351    "PROMPT_COMMAND",
352];
353
354const INJECTION_ENV_KEY_PREFIXES: &[&str] = &["DYLD_", "GIT_CONFIG"];
355
356pub(super) fn is_injection_env_key(key: &str) -> bool {
357    INJECTION_ENV_KEYS.contains(&key)
358        || INJECTION_ENV_KEY_PREFIXES
359            .iter()
360            .any(|prefix| key.starts_with(prefix))
361}
362
363/// Parses a strictly plain, expansion-free, redirect-free command sequence
364/// joined only by `;`, `|`, `||`, or `&&` (used by the narrow SP3-A shell
365/// read-only lane). Fails closed when the `bash-ast` feature is disabled.
366pub(super) fn parse_plain_shell_command_sequence(script: &str) -> Option<Vec<Vec<String>>> {
367    #[cfg(feature = "bash-ast")]
368    {
369        super::bash_ast::parse_plain_shell_command_sequence(script)
370    }
371    #[cfg(not(feature = "bash-ast"))]
372    {
373        let _ = script;
374        None
375    }
376}
377
378/// Parses a bash script into an AST security summary. Returns `None` on syntax
379/// errors or when `bash-ast` is disabled so callers fail closed.
380pub(super) fn parse_bash_security_analysis(script: &str) -> Option<BashSecurityAnalysis> {
381    #[cfg(feature = "bash-ast")]
382    {
383        super::bash_ast::parse_bash_security_analysis(script)
384    }
385    #[cfg(not(feature = "bash-ast"))]
386    {
387        let _ = script;
388        None
389    }
390}
391
392/// Detects dangerous `env` invocations (`env -S`, `env LD_PRELOAD=...`, etc.)
393/// even behind wrapper chains such as `timeout 5 env ...`.
394pub(super) fn command_words_have_env_injection(words: &[String]) -> bool {
395    let mut index = 0;
396    while let Some(head) = words.get(index) {
397        let name = executable_name(head);
398        if name == "env" {
399            let mut options_done = false;
400            for arg in &words[index + 1..] {
401                if !options_done && arg == "--" {
402                    options_done = true;
403                    continue;
404                }
405                if !options_done && arg.starts_with('-') {
406                    // `-S` / `--split-string` rewrites argv and can smuggle commands.
407                    if arg == "-S"
408                        || arg.starts_with("-S")
409                        || arg == "--split-string"
410                        || arg.starts_with("--split-string=")
411                        || (!arg.starts_with("--") && arg.contains('S'))
412                    {
413                        return true;
414                    }
415                    continue;
416                }
417                if let Some((key, _)) = arg.split_once('=') {
418                    if is_injection_env_key(key) {
419                        return true;
420                    }
421                    continue;
422                }
423                break;
424            }
425            return false;
426        }
427        if matches!(
428            head.as_str(),
429            "!" | "time" | "exec" | "command" | "builtin" | "nohup"
430        ) {
431            index += 1;
432            continue;
433        }
434        if name == "timeout" {
435            index += 1;
436            while let Some(arg) = words.get(index) {
437                if matches!(arg.as_str(), "-k" | "--kill-after" | "-s" | "--signal") {
438                    index += 2;
439                    continue;
440                }
441                if arg.starts_with('-') {
442                    index += 1;
443                    continue;
444                }
445                index += 1;
446                break;
447            }
448            continue;
449        }
450        break;
451    }
452    false
453}
454
455pub(super) fn executable_name(argument: &str) -> String {
456    let base = argument
457        .rsplit(['/', '\\'])
458        .next()
459        .unwrap_or(argument)
460        .to_ascii_lowercase();
461    for suffix in [".exe", ".cmd", ".bat", ".com"] {
462        if let Some(stripped) = base.strip_suffix(suffix)
463            && !stripped.is_empty()
464        {
465            return stripped.to_owned();
466        }
467    }
468    base
469}
470
471pub(super) fn executable_token_is(argument: &str, expected: &str) -> bool {
472    #[cfg(windows)]
473    {
474        argument.eq_ignore_ascii_case(expected)
475            || argument
476                .strip_suffix(".exe")
477                .or_else(|| argument.strip_suffix(".EXE"))
478                .is_some_and(|stripped| stripped.eq_ignore_ascii_case(expected))
479    }
480    #[cfg(not(windows))]
481    {
482        argument == expected
483    }
484}