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;
5use tree_sitter::{Node, Parser, Tree};
6use tree_sitter_bash::LANGUAGE as BASH_LANGUAGE;
7
8#[cfg(windows)]
9use super::windows_shell;
10
11/// Shell grammar family represented by one recognized shell wrapper argv.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub(crate) enum ShellKind {
14    /// POSIX/Bash-compatible shell (`bash`, `sh`, `zsh`, Git Bash).
15    Bash,
16    /// PowerShell (`pwsh`, `powershell`, `powershell.exe`).
17    #[cfg(windows)]
18    PowerShell,
19    /// Windows Command Prompt (`cmd`, `cmd.exe`).
20    #[cfg(windows)]
21    Cmd,
22}
23
24/// Exact shell-wrapper input plus payload-free metadata helpers.
25///
26/// This value recognizes only the validated wrapper shape used by the current
27/// shell read-only lane. It does not authorize execution by itself.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub(crate) struct ShellProcessInput<'a> {
30    pub(super) kind: ShellKind,
31    pub(super) shell: &'a str,
32    pub(super) flag: &'a str,
33    pub(super) script: &'a str,
34}
35
36impl<'a> ShellProcessInput<'a> {
37    pub(crate) const fn kind(self) -> ShellKind {
38        self.kind
39    }
40
41    pub(crate) const fn shell(self) -> &'a str {
42        self.shell
43    }
44
45    pub(crate) const fn flag(self) -> &'a str {
46        self.flag
47    }
48
49    pub(crate) const fn script(self) -> &'a str {
50        self.script
51    }
52
53    pub(crate) const fn script_bytes(self) -> usize {
54        self.script.len()
55    }
56
57    pub(crate) fn script_fingerprint(self) -> String {
58        stable_process_input_fingerprint(self.script.as_bytes())
59    }
60}
61
62pub(crate) fn shell_process_input(intent: &ProcessActionIntent) -> Option<ShellProcessInput<'_>> {
63    shell_process_input_from_argv(intent.argv())
64}
65
66/// Converts one model-facing shell command into the platform process argv
67/// consumed by runtime policy and process runners.
68pub(crate) fn shell_command_argv(command: &str) -> Vec<String> {
69    #[cfg(windows)]
70    {
71        windows_shell::detect_windows_shell().command_argv(command)
72    }
73
74    #[cfg(not(windows))]
75    {
76        vec!["bash".to_owned(), "-lc".to_owned(), command.to_owned()]
77    }
78}
79
80/// Returns the command script represented by a platform shell argv wrapper.
81pub(crate) fn shell_command_from_argv(argv: &[String]) -> Option<&str> {
82    #[cfg(windows)]
83    {
84        match argv {
85            [shell, no_profile, non_interactive, flag, command]
86                if matches!(executable_name(shell).as_str(), "powershell" | "pwsh")
87                    && no_profile.eq_ignore_ascii_case("-NoProfile")
88                    && non_interactive.eq_ignore_ascii_case("-NonInteractive")
89                    && flag.eq_ignore_ascii_case("-Command") =>
90            {
91                Some(command)
92            }
93            [shell, no_profile, flag, command]
94                if matches!(executable_name(shell).as_str(), "powershell" | "pwsh")
95                    && no_profile.eq_ignore_ascii_case("-NoProfile")
96                    && flag.eq_ignore_ascii_case("-Command") =>
97            {
98                Some(command)
99            }
100            [shell, flag, command]
101                if executable_name(shell) == "bash" && matches!(flag.as_str(), "-c" | "-lc") =>
102            {
103                Some(command)
104            }
105            [shell, flag, command]
106                if executable_name(shell) == "cmd" && flag.eq_ignore_ascii_case("/C") =>
107            {
108                Some(command)
109            }
110            _ => None,
111        }
112    }
113
114    #[cfg(not(windows))]
115    {
116        match argv {
117            [shell, flag, command] if shell == "bash" && matches!(flag.as_str(), "-c" | "-lc") => {
118                Some(command)
119            }
120            _ => None,
121        }
122    }
123}
124
125/// Converts an argv vector into one shell command string for a model-facing
126/// command field. Existing platform shell wrappers are unwrapped so their
127/// script is preserved; direct argv items are quoted for the host shell.
128#[must_use]
129pub fn shell_command_for_argv(argv: &[String]) -> String {
130    if let Some(command) = shell_command_from_argv(argv) {
131        return command.to_owned();
132    }
133
134    argv.iter()
135        .map(|argument| shell_quote_argument(argument))
136        .collect::<Vec<_>>()
137        .join(" ")
138}
139
140#[cfg(not(windows))]
141pub(super) fn shell_quote_argument(argument: &str) -> String {
142    if !argument.is_empty() && argument.bytes().all(is_safe_shell_word_byte) {
143        return argument.to_owned();
144    }
145    format!("'{}'", argument.replace('\'', "'\\''"))
146}
147
148#[cfg(windows)]
149pub(super) fn shell_quote_argument(argument: &str) -> String {
150    if !argument.is_empty() && argument.bytes().all(is_safe_shell_word_byte) {
151        return argument.to_owned();
152    }
153    format!("'{}'", argument.replace('\'', "''"))
154}
155
156pub(super) fn is_safe_shell_word_byte(byte: u8) -> bool {
157    byte.is_ascii_alphanumeric()
158        || matches!(
159            byte,
160            b'_' | b'-' | b'.' | b'/' | b':' | b'=' | b'@' | b'%' | b'+'
161        )
162}
163
164pub(super) fn shell_process_input_from_argv(argv: &[String]) -> Option<ShellProcessInput<'_>> {
165    #[cfg(windows)]
166    {
167        match argv {
168            [shell, no_profile, non_interactive, flag, script]
169                if is_supported_plain_shell_token(shell)
170                    && no_profile.eq_ignore_ascii_case("-NoProfile")
171                    && non_interactive.eq_ignore_ascii_case("-NonInteractive")
172                    && flag.eq_ignore_ascii_case("-Command") =>
173            {
174                Some(ShellProcessInput {
175                    kind: ShellKind::PowerShell,
176                    shell,
177                    flag,
178                    script,
179                })
180            }
181            [shell, no_profile, flag, script]
182                if is_supported_plain_shell_token(shell)
183                    && no_profile.eq_ignore_ascii_case("-NoProfile")
184                    && flag.eq_ignore_ascii_case("-Command") =>
185            {
186                Some(ShellProcessInput {
187                    kind: ShellKind::PowerShell,
188                    shell,
189                    flag,
190                    script,
191                })
192            }
193            [shell, flag, script]
194                if is_supported_plain_bash_token(shell)
195                    && matches!(flag.as_str(), "-c" | "-lc") =>
196            {
197                Some(ShellProcessInput {
198                    kind: ShellKind::Bash,
199                    shell,
200                    flag,
201                    script,
202                })
203            }
204            _ => None,
205        }
206    }
207
208    #[cfg(not(windows))]
209    {
210        let [shell, flag, script] = argv else {
211            return None;
212        };
213        if !is_supported_plain_shell_token(shell) || !matches!(flag.as_str(), "-c" | "-lc") {
214            return None;
215        }
216        Some(ShellProcessInput {
217            kind: ShellKind::Bash,
218            shell,
219            flag,
220            script,
221        })
222    }
223}
224
225pub(super) fn is_supported_plain_shell_token(shell: &str) -> bool {
226    #[cfg(windows)]
227    {
228        !shell.contains(['/', '\\'])
229            && matches!(executable_name(shell).as_str(), "powershell" | "pwsh")
230    }
231
232    #[cfg(not(windows))]
233    matches!(shell, "bash" | "sh" | "zsh")
234}
235
236#[cfg(windows)]
237fn is_supported_plain_bash_token(shell: &str) -> bool {
238    if !shell.contains(['/', '\\']) {
239        return matches!(executable_name(shell).as_str(), "bash" | "sh" | "zsh");
240    }
241    matches!(
242        windows_shell::detect_windows_shell(),
243        windows_shell::WindowsShell::GitBash(path)
244            if path.to_string_lossy().eq_ignore_ascii_case(shell)
245    )
246}
247
248pub(crate) fn stable_process_input_fingerprint(bytes: &[u8]) -> String {
249    const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
250    const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
251
252    let hash = bytes.iter().fold(FNV_OFFSET_BASIS, |hash, byte| {
253        (hash ^ u64::from(*byte)).wrapping_mul(FNV_PRIME)
254    });
255    format!("fnv1a64:{hash:016x}")
256}
257
258pub(super) fn shell_like_process_input_from_argv(argv: &[String]) -> Option<ShellProcessInput<'_>> {
259    #[cfg(windows)]
260    {
261        match argv {
262            [shell, no_profile, non_interactive, flag, script]
263                if matches!(executable_name(shell).as_str(), "powershell" | "pwsh")
264                    && no_profile.eq_ignore_ascii_case("-NoProfile")
265                    && non_interactive.eq_ignore_ascii_case("-NonInteractive")
266                    && flag.eq_ignore_ascii_case("-Command") =>
267            {
268                Some(ShellProcessInput {
269                    kind: ShellKind::PowerShell,
270                    shell,
271                    flag,
272                    script,
273                })
274            }
275            [shell, no_profile, flag, script]
276                if matches!(executable_name(shell).as_str(), "powershell" | "pwsh")
277                    && no_profile.eq_ignore_ascii_case("-NoProfile")
278                    && flag.eq_ignore_ascii_case("-Command") =>
279            {
280                Some(ShellProcessInput {
281                    kind: ShellKind::PowerShell,
282                    shell,
283                    flag,
284                    script,
285                })
286            }
287            [shell, flag, script]
288                if matches!(executable_name(shell).as_str(), "bash" | "sh" | "zsh")
289                    && matches!(flag.as_str(), "-c" | "-lc") =>
290            {
291                Some(ShellProcessInput {
292                    kind: ShellKind::Bash,
293                    shell,
294                    flag,
295                    script,
296                })
297            }
298            [shell, flag, script]
299                if executable_name(shell) == "cmd" && flag.eq_ignore_ascii_case("/C") =>
300            {
301                Some(ShellProcessInput {
302                    kind: ShellKind::Cmd,
303                    shell,
304                    flag,
305                    script,
306                })
307            }
308            _ => None,
309        }
310    }
311
312    #[cfg(not(windows))]
313    {
314        let [shell, flag, script] = argv else {
315            return None;
316        };
317        if !is_supported_shell_executable_name(shell) || !matches!(flag.as_str(), "-c" | "-lc") {
318            return None;
319        }
320        Some(ShellProcessInput {
321            kind: ShellKind::Bash,
322            shell,
323            flag,
324            script,
325        })
326    }
327}
328
329#[cfg(not(windows))]
330pub(super) fn is_supported_shell_executable_name(shell: &str) -> bool {
331    matches!(executable_name(shell).as_str(), "bash" | "sh" | "zsh")
332}
333
334/// AST-derived security summary of one parsed bash script.
335pub(super) struct BashSecurityAnalysis {
336    /// Every command node found anywhere in the AST (including inside control
337    /// flow, subshells, and `$(...)`/backtick substitutions), in source order.
338    pub(super) commands: Vec<Vec<String>>,
339    /// True if any inline assignment, `export`/`declare`, or `env` invocation
340    /// sets an execution-injecting environment variable or uses `env -S`.
341    pub(super) env_injection: bool,
342    /// True if the AST contains command or process substitution (`$(...)`,
343    /// `` `...` ``, `<(...)`, `>(...)`).
344    pub(super) has_command_substitution: bool,
345    /// Non-comment command words and redirect destinations for host-path checks.
346    pub(super) path_check_tokens: Vec<String>,
347}
348
349const INJECTION_ENV_KEYS: &[&str] = &[
350    "LD_PRELOAD",
351    "LD_AUDIT",
352    "BASH_ENV",
353    "ENV",
354    "IFS",
355    "PATH",
356    "GIT_EXTERNAL_DIFF",
357    "GIT_PROXY_COMMAND",
358    "PROMPT_COMMAND",
359];
360
361const INJECTION_ENV_KEY_PREFIXES: &[&str] = &["DYLD_", "GIT_CONFIG"];
362
363pub(super) fn is_injection_env_key(key: &str) -> bool {
364    INJECTION_ENV_KEYS.contains(&key)
365        || INJECTION_ENV_KEY_PREFIXES
366            .iter()
367            .any(|prefix| key.starts_with(prefix))
368}
369
370fn try_parse_bash(script: &str) -> Option<Tree> {
371    let mut parser = Parser::new();
372    parser.set_language(&BASH_LANGUAGE.into()).ok()?;
373    parser.parse(script, None)
374}
375
376/// Parses a strictly plain, expansion-free, redirect-free command sequence
377/// joined only by `;`, `|`, `||`, or `&&` (used by the narrow SP3-A shell
378/// read-only lane).
379pub(super) fn parse_plain_shell_command_sequence(script: &str) -> Option<Vec<Vec<String>>> {
380    let tree = try_parse_bash(script)?;
381    let root = tree.root_node();
382    if root.has_error() {
383        return None;
384    }
385
386    const ALLOWED_KINDS: &[&str] = &[
387        "program",
388        "list",
389        "pipeline",
390        "command",
391        "command_name",
392        "word",
393        "string",
394        "string_content",
395        "raw_string",
396        "number",
397        "concatenation",
398    ];
399    const ALLOWED_PUNCT: &[&str] = &["&&", "||", ";", "|", "\"", "'"];
400
401    let mut stack = vec![root];
402    let mut command_nodes = Vec::new();
403    while let Some(node) = stack.pop() {
404        let kind = node.kind();
405        if node.is_named() {
406            if !ALLOWED_KINDS.contains(&kind) {
407                return None;
408            }
409            if kind == "command" {
410                command_nodes.push(node);
411            }
412        } else if !(ALLOWED_PUNCT.contains(&kind) || kind.trim().is_empty()) {
413            return None;
414        }
415        let mut cursor = node.walk();
416        for child in node.children(&mut cursor) {
417            stack.push(child);
418        }
419    }
420
421    if command_nodes.is_empty() {
422        return None;
423    }
424    command_nodes.sort_by_key(Node::start_byte);
425
426    let mut commands = Vec::with_capacity(command_nodes.len());
427    for command_node in command_nodes {
428        let mut words = Vec::new();
429        let mut cursor = command_node.walk();
430        for child in command_node.children(&mut cursor) {
431            if !child.is_named() {
432                continue;
433            }
434            let word = decode_strict_plain_word(child, script)?;
435            if word.is_empty() {
436                return None;
437            }
438            words.push(word);
439        }
440        if words.is_empty() {
441            return None;
442        }
443        commands.push(words);
444    }
445    Some(commands)
446}
447
448fn decode_strict_plain_word(node: Node<'_>, src: &str) -> Option<String> {
449    match node.kind() {
450        "command_name" => {
451            let child = node.named_child(0)?;
452            decode_strict_plain_word(child, src)
453        }
454        "word" | "number" => {
455            let text = node.utf8_text(src.as_bytes()).ok()?;
456            if text.chars().any(shell_word_character_is_disallowed) {
457                return None;
458            }
459            Some(text.to_owned())
460        }
461        "raw_string" => {
462            let text = node.utf8_text(src.as_bytes()).ok()?;
463            text.strip_prefix('\'')
464                .and_then(|rest| rest.strip_suffix('\''))
465                .map(str::to_owned)
466        }
467        "string" => {
468            let mut out = String::new();
469            let mut cursor = node.walk();
470            for child in node.children(&mut cursor) {
471                if !child.is_named() {
472                    continue;
473                }
474                if child.kind() != "string_content" {
475                    return None;
476                }
477                let text = child.utf8_text(src.as_bytes()).ok()?;
478                if text.chars().any(|ch| matches!(ch, '$' | '`' | '\\' | '!')) {
479                    return None;
480                }
481                out.push_str(text);
482            }
483            Some(out)
484        }
485        "concatenation" => {
486            let mut out = String::new();
487            let mut cursor = node.walk();
488            for child in node.children(&mut cursor) {
489                if child.is_named() {
490                    out.push_str(&decode_strict_plain_word(child, src)?);
491                }
492            }
493            Some(out)
494        }
495        _ => None,
496    }
497}
498
499fn shell_word_character_is_disallowed(character: char) -> bool {
500    matches!(
501        character,
502        '$' | '`'
503            | '\\'
504            | '<'
505            | '>'
506            | '('
507            | ')'
508            | '{'
509            | '}'
510            | '['
511            | ']'
512            | '*'
513            | '?'
514            | '~'
515            | '#'
516            | '!'
517    )
518}
519
520/// Parses a bash script into an AST security summary. Returns `None` on syntax
521/// errors (such as unclosed quotes) so callers fail closed.
522pub(super) fn parse_bash_security_analysis(script: &str) -> Option<BashSecurityAnalysis> {
523    let tree = try_parse_bash(script)?;
524    let root = tree.root_node();
525    if root.has_error() {
526        return None;
527    }
528
529    let mut stack = vec![root];
530    let mut command_nodes = Vec::new();
531    let mut env_injection = false;
532    let mut has_command_substitution = false;
533    let mut path_check_tokens = Vec::new();
534
535    while let Some(node) = stack.pop() {
536        match node.kind() {
537            "command" => command_nodes.push(node),
538            "command_substitution" | "process_substitution" => {
539                has_command_substitution = true;
540            }
541            "variable_assignment" => {
542                if let Some(key) = variable_assignment_key(node, script)
543                    && is_injection_env_key(key)
544                {
545                    env_injection = true;
546                }
547                if let Some(value_node) = node.child_by_field_name("value")
548                    && let Ok(text) = value_node.utf8_text(script.as_bytes())
549                {
550                    path_check_tokens.push(text.to_owned());
551                }
552            }
553            "file_redirect" => {
554                if let Some(dest) = node.child_by_field_name("destination") {
555                    path_check_tokens.push(decode_security_word(dest, script));
556                }
557            }
558            _ => {}
559        }
560        let mut cursor = node.walk();
561        for child in node.children(&mut cursor) {
562            stack.push(child);
563        }
564    }
565
566    command_nodes.sort_by_key(Node::start_byte);
567
568    let mut commands = Vec::with_capacity(command_nodes.len());
569    for command_node in command_nodes {
570        let mut words = Vec::new();
571        let mut cursor = command_node.walk();
572        for child in command_node.children(&mut cursor) {
573            if !child.is_named() {
574                continue;
575            }
576            if matches!(
577                child.kind(),
578                "variable_assignment" | "file_redirect" | "heredoc_redirect" | "comment"
579            ) {
580                continue;
581            }
582            let decoded = decode_security_word(child, script);
583            if !decoded.is_empty() {
584                path_check_tokens.push(decoded.clone());
585                words.push(decoded);
586            }
587        }
588        if !words.is_empty() {
589            if command_words_have_env_injection(&words) {
590                env_injection = true;
591            }
592            commands.push(words);
593        }
594    }
595
596    Some(BashSecurityAnalysis {
597        commands,
598        env_injection,
599        has_command_substitution,
600        path_check_tokens,
601    })
602}
603
604fn variable_assignment_key<'a>(node: Node<'_>, src: &'a str) -> Option<&'a str> {
605    if let Some(name_node) = node.child_by_field_name("name")
606        && let Ok(text) = name_node.utf8_text(src.as_bytes())
607    {
608        return Some(text);
609    }
610    node.utf8_text(src.as_bytes())
611        .ok()
612        .and_then(|text| text.split('=').next())
613}
614
615/// Detects dangerous `env` invocations (`env -S`, `env LD_PRELOAD=...`, etc.)
616/// even behind wrapper chains such as `timeout 5 env ...`.
617pub(super) fn command_words_have_env_injection(words: &[String]) -> bool {
618    let mut index = 0;
619    while let Some(head) = words.get(index) {
620        let name = executable_name(head);
621        if name == "env" {
622            let mut options_done = false;
623            for arg in &words[index + 1..] {
624                if !options_done && arg == "--" {
625                    options_done = true;
626                    continue;
627                }
628                if !options_done && arg.starts_with('-') {
629                    // `-S` / `--split-string` rewrites argv and can smuggle commands.
630                    if arg == "-S"
631                        || arg.starts_with("-S")
632                        || arg == "--split-string"
633                        || arg.starts_with("--split-string=")
634                        || (!arg.starts_with("--") && arg.contains('S'))
635                    {
636                        return true;
637                    }
638                    continue;
639                }
640                if let Some((key, _)) = arg.split_once('=') {
641                    if is_injection_env_key(key) {
642                        return true;
643                    }
644                    continue;
645                }
646                break;
647            }
648            return false;
649        }
650        if matches!(
651            head.as_str(),
652            "!" | "time" | "exec" | "command" | "builtin" | "nohup"
653        ) {
654            index += 1;
655            continue;
656        }
657        if name == "timeout" {
658            index += 1;
659            while let Some(arg) = words.get(index) {
660                if matches!(arg.as_str(), "-k" | "--kill-after" | "-s" | "--signal") {
661                    index += 2;
662                    continue;
663                }
664                if arg.starts_with('-') {
665                    index += 1;
666                    continue;
667                }
668                index += 1;
669                break;
670            }
671            continue;
672        }
673        break;
674    }
675    false
676}
677
678/// Decodes a command word for security analysis. Expansion-free quotes are
679/// unwrapped so `env "LD_PRELOAD=..."` or `"rm"` cannot hide behind quoting;
680/// dynamic nodes keep their raw source text so `$VAR`/`$(...)` remain visible.
681fn decode_security_word(node: Node<'_>, src: &str) -> String {
682    match node.kind() {
683        "command_name" => node
684            .named_child(0)
685            .map(|child| decode_security_word(child, src))
686            .unwrap_or_default(),
687        "raw_string" => node
688            .utf8_text(src.as_bytes())
689            .ok()
690            .and_then(|text| {
691                text.strip_prefix('\'')
692                    .and_then(|rest| rest.strip_suffix('\''))
693            })
694            .unwrap_or_default()
695            .to_owned(),
696        "string" => {
697            let mut out = String::new();
698            let mut cursor = node.walk();
699            for child in node.children(&mut cursor) {
700                if !child.is_named() {
701                    continue;
702                }
703                if child.kind() == "string_content" {
704                    if let Ok(text) = child.utf8_text(src.as_bytes()) {
705                        out.push_str(text);
706                    }
707                } else if let Ok(text) = child.utf8_text(src.as_bytes()) {
708                    out.push_str(text);
709                }
710            }
711            out
712        }
713        "concatenation" => {
714            let mut out = String::new();
715            let mut cursor = node.walk();
716            for child in node.children(&mut cursor) {
717                if child.is_named() {
718                    out.push_str(&decode_security_word(child, src));
719                }
720            }
721            out
722        }
723        _ => node.utf8_text(src.as_bytes()).unwrap_or("").to_owned(),
724    }
725}
726
727pub(super) fn executable_name(argument: &str) -> String {
728    let base = argument
729        .rsplit(['/', '\\'])
730        .next()
731        .unwrap_or(argument)
732        .to_ascii_lowercase();
733    for suffix in [".exe", ".cmd", ".bat", ".com"] {
734        if let Some(stripped) = base.strip_suffix(suffix)
735            && !stripped.is_empty()
736        {
737            return stripped.to_owned();
738        }
739    }
740    base
741}
742
743pub(super) fn executable_token_is(argument: &str, expected: &str) -> bool {
744    #[cfg(windows)]
745    {
746        argument.eq_ignore_ascii_case(expected)
747            || argument
748                .strip_suffix(".exe")
749                .or_else(|| argument.strip_suffix(".EXE"))
750                .is_some_and(|stripped| stripped.eq_ignore_ascii_case(expected))
751    }
752    #[cfg(not(windows))]
753    {
754        argument == expected
755    }
756}