Skip to main content

merry_runtime/process/classification/
windows_shell.rs

1//! Windows shell detection, invocation, and PowerShell security analysis.
2//!
3//! On Windows, Merry prefers PowerShell (`pwsh`, then `powershell.exe`) over
4//! Git Bash because MSYS2 path conversion mangles `/flag` arguments passed to
5//! native Windows toolchains (`MSBuild /t:Build`, `cl.exe /nologo`). Users can
6//! override auto-detection via `MERRY_SHELL=pwsh|powershell|bash|cmd`.
7
8#[cfg(windows)]
9use std::{env, sync::OnceLock};
10#[cfg(any(windows, test))]
11use std::{
12    ffi::OsStr,
13    path::{Path, PathBuf},
14};
15
16/// Detected Windows shell backend and its command-invocation shape.
17#[cfg(any(windows, test))]
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub(crate) enum WindowsShell {
20    /// PowerShell 7+ (`pwsh`).
21    Pwsh,
22    /// Windows PowerShell 5.1 (`powershell.exe`).
23    PowerShell,
24    /// Git for Windows Bash (`...\Git\bin\bash.exe`).
25    GitBash(PathBuf),
26    /// Windows Command Prompt (`cmd.exe`).
27    Cmd,
28}
29
30#[cfg(any(windows, test))]
31impl WindowsShell {
32    /// Short human- and prompt-facing shell name.
33    #[cfg(windows)]
34    #[must_use]
35    pub(crate) const fn name(&self) -> &'static str {
36        match self {
37            Self::Pwsh => "pwsh",
38            Self::PowerShell => "powershell",
39            Self::GitBash(_) => "bash",
40            Self::Cmd => "cmd.exe",
41        }
42    }
43
44    /// Whether this shell supports `&&` for error-propagating command chaining.
45    ///
46    /// `pwsh` (PowerShell 7+) and Git Bash support `&&`; Windows PowerShell 5.1
47    /// does not and requires `;`.
48    #[cfg(windows)]
49    #[must_use]
50    pub(crate) const fn supports_chain_operator(&self) -> bool {
51        matches!(self, Self::Pwsh | Self::GitBash(_))
52    }
53
54    /// Whether Unix coreutils (`grep`, `find`, `sed`, `head`, `tail`) are
55    /// expected to be usable directly inside this shell.
56    #[cfg(windows)]
57    #[must_use]
58    pub(crate) const fn has_unix_utilities(&self) -> bool {
59        matches!(self, Self::GitBash(_))
60    }
61
62    /// Builds the process argv that executes `command` in this Windows shell.
63    #[must_use]
64    pub(crate) fn command_argv(&self, command: &str) -> Vec<String> {
65        match self {
66            Self::Pwsh => vec![
67                "pwsh".to_owned(),
68                "-NoProfile".to_owned(),
69                "-NonInteractive".to_owned(),
70                "-Command".to_owned(),
71                command.to_owned(),
72            ],
73            Self::PowerShell => vec![
74                "powershell.exe".to_owned(),
75                "-NoProfile".to_owned(),
76                "-NonInteractive".to_owned(),
77                "-Command".to_owned(),
78                command.to_owned(),
79            ],
80            Self::GitBash(path) => vec![
81                path.to_string_lossy().into_owned(),
82                "-c".to_owned(),
83                command.to_owned(),
84            ],
85            Self::Cmd => vec!["cmd.exe".to_owned(), "/C".to_owned(), command.to_owned()],
86        }
87    }
88}
89
90/// Detects the active Windows shell once per process.
91#[cfg(windows)]
92#[must_use]
93pub(crate) fn detect_windows_shell() -> &'static WindowsShell {
94    static CACHED: OnceLock<WindowsShell> = OnceLock::new();
95    CACHED.get_or_init(|| {
96        let override_env = env::var("MERRY_SHELL").ok();
97        let path_env = env::var_os("PATH");
98        let pathext = env::var_os("PATHEXT");
99        let git_bash_candidates = default_git_bash_candidates();
100        detect_windows_shell_with(
101            override_env.as_deref(),
102            path_env.as_deref(),
103            pathext.as_deref(),
104            &git_bash_candidates,
105            Path::is_file,
106        )
107    })
108}
109
110#[cfg(windows)]
111fn default_git_bash_candidates() -> Vec<PathBuf> {
112    let mut candidates = Vec::new();
113    for (var, suffix) in [
114        ("PROGRAMFILES", r"Git\bin\bash.exe"),
115        ("PROGRAMFILES(X86)", r"Git\bin\bash.exe"),
116        ("LOCALAPPDATA", r"Programs\Git\bin\bash.exe"),
117    ] {
118        if let Some(root) = env::var_os(var) {
119            candidates.push(PathBuf::from(root).join(suffix));
120        }
121    }
122    candidates
123}
124
125/// Pure, deterministic Windows shell detection cascade for production and tests.
126#[cfg(any(windows, test))]
127pub(crate) fn detect_windows_shell_with(
128    merry_shell_override: Option<&str>,
129    path_env: Option<&OsStr>,
130    pathext: Option<&OsStr>,
131    git_bash_candidates: &[PathBuf],
132    mut is_file: impl FnMut(&Path) -> bool,
133) -> WindowsShell {
134    let find_git_bash = |is_file: &mut dyn FnMut(&Path) -> bool| -> Option<PathBuf> {
135        for candidate in git_bash_candidates {
136            if is_file(candidate) {
137                return Some(candidate.clone());
138            }
139        }
140        let path_env = path_env?;
141        merry_core::host_paths::find_executable_in_path_for(
142            path_env,
143            &["bash"],
144            pathext,
145            true,
146            |candidate| {
147                candidate
148                    .to_string_lossy()
149                    .to_ascii_lowercase()
150                    .contains("git")
151                    && is_file(candidate)
152            },
153        )
154    };
155
156    if let Some(value) = merry_shell_override {
157        match value.trim().to_ascii_lowercase().as_str() {
158            "pwsh" => return WindowsShell::Pwsh,
159            "powershell" | "powershell.exe" => return WindowsShell::PowerShell,
160            "bash" | "gitbash" | "git-bash" => {
161                if let Some(path) = find_git_bash(&mut is_file) {
162                    return WindowsShell::GitBash(path);
163                }
164            }
165            "cmd" | "cmd.exe" => return WindowsShell::Cmd,
166            _ => {}
167        }
168    }
169
170    if let Some(path_env) = path_env
171        && merry_core::host_paths::find_executable_in_path_for(
172            path_env,
173            &["pwsh"],
174            pathext,
175            true,
176            &mut is_file,
177        )
178        .is_some()
179    {
180        return WindowsShell::Pwsh;
181    }
182
183    let system_powershell = Path::new(r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe");
184    if is_file(system_powershell)
185        || path_env.is_some_and(|path_env| {
186            merry_core::host_paths::find_executable_in_path_for(
187                path_env,
188                &["powershell"],
189                pathext,
190                true,
191                &mut is_file,
192            )
193            .is_some()
194        })
195    {
196        return WindowsShell::PowerShell;
197    }
198
199    if let Some(path) = find_git_bash(&mut is_file) {
200        return WindowsShell::GitBash(path);
201    }
202
203    WindowsShell::PowerShell
204}
205
206/// Returns the short name of the active host shell (`"bash"` on Unix;
207/// `"pwsh"`, `"powershell"`, `"bash"`, or `"cmd.exe"` on Windows).
208#[must_use]
209pub fn host_shell_name() -> &'static str {
210    #[cfg(windows)]
211    {
212        detect_windows_shell().name()
213    }
214    #[cfg(not(windows))]
215    {
216        "bash"
217    }
218}
219
220/// Returns whether Unix text/search utilities (`grep`, `find`, `sed`, `head`,
221/// `tail`) are expected to be available in the active host shell.
222#[must_use]
223pub fn host_shell_has_unix_utilities() -> bool {
224    #[cfg(windows)]
225    {
226        detect_windows_shell().has_unix_utilities()
227    }
228    #[cfg(not(windows))]
229    {
230        true
231    }
232}
233
234/// Returns the error-propagating command chain separator for the active host
235/// shell (`"&&"` on Unix, `pwsh`, and Git Bash; `";"` on Windows PowerShell
236/// 5.1 and `cmd.exe`).
237#[must_use]
238pub fn host_shell_chain_separator() -> &'static str {
239    #[cfg(windows)]
240    {
241        if detect_windows_shell().supports_chain_operator() {
242            "&&"
243        } else {
244            ";"
245        }
246    }
247    #[cfg(not(windows))]
248    {
249        "&&"
250    }
251}
252
253/// Security summary of one parsed PowerShell command script.
254#[cfg(any(windows, test))]
255pub(crate) struct PowerShellSecurityAnalysis {
256    /// Commands split by `;`, `|`, `&&`, `||`, or newlines, in source order.
257    pub(crate) commands: Vec<Vec<String>>,
258    /// True if the script mutates execution-affecting environment variables
259    /// (`$env:PATH`, `$env:PATHEXT`, `$env:GIT_CONFIG*`, etc.) or invokes
260    /// PowerShell dynamic execution (`iex`, `-EncodedCommand`, `&`, `.`).
261    pub(crate) env_or_eval_injection: bool,
262    /// True if the script contains subexpression/variable expansion (`$(...)`)
263    /// or redirections that could hide host paths.
264    pub(crate) has_command_substitution: bool,
265    /// True if the script invokes a destructive PowerShell delete cmdlet/alias
266    /// (`Remove-Item`, `ri`, `del`, `erase`, `rd`, `rmdir`) with recursive or
267    /// broad targets.
268    pub(crate) has_destructive_delete: bool,
269    /// Non-comment command words for host-path review checks.
270    pub(crate) path_check_tokens: Vec<String>,
271}
272
273/// Parses a plain, expansion-free PowerShell command sequence joined by `;`,
274/// `|`, `&&`, or `||` for the read-only shell lane.
275#[cfg(any(windows, test))]
276pub(crate) fn parse_plain_powershell_command_sequence(script: &str) -> Option<Vec<Vec<String>>> {
277    let analysis = analyze_powershell_script(script)?;
278    if analysis.env_or_eval_injection
279        || analysis.has_command_substitution
280        || analysis.has_destructive_delete
281        || analysis.commands.is_empty()
282    {
283        return None;
284    }
285    // Reject redirections or shell expansions in the strict read-only lane.
286    for command in &analysis.commands {
287        for word in command {
288            if word.chars().any(|ch| {
289                matches!(
290                    ch,
291                    '$' | '`' | '>' | '<' | '(' | ')' | '{' | '}' | '*' | '?'
292                )
293            }) {
294                return None;
295            }
296        }
297    }
298    Some(analysis.commands)
299}
300
301/// Performs a fail-closed lexical/structural security analysis of a PowerShell
302/// script. Returns `None` on unclosed quotes or block comments so callers fail
303/// closed.
304#[cfg(any(windows, test))]
305pub(crate) fn analyze_powershell_script(script: &str) -> Option<PowerShellSecurityAnalysis> {
306    let mut commands: Vec<Vec<String>> = Vec::new();
307    let mut current_cmd: Vec<String> = Vec::new();
308    let mut current_word = String::new();
309    let mut has_word = false;
310    let mut in_single = false;
311    let mut in_double = false;
312    let mut env_or_eval_injection = false;
313    let mut has_command_substitution = false;
314    let mut path_check_tokens = Vec::new();
315
316    let chars: Vec<char> = script.chars().collect();
317    let mut i = 0;
318
319    let flush_word = |current_word: &mut String,
320                      has_word: &mut bool,
321                      current_cmd: &mut Vec<String>,
322                      path_check_tokens: &mut Vec<String>| {
323        if *has_word {
324            let word = std::mem::take(current_word);
325            if !word.is_empty() {
326                path_check_tokens.push(word.clone());
327                current_cmd.push(word);
328            }
329            *has_word = false;
330        }
331    };
332
333    let flush_cmd = |current_cmd: &mut Vec<String>, commands: &mut Vec<Vec<String>>| {
334        if !current_cmd.is_empty() {
335            commands.push(std::mem::take(current_cmd));
336        }
337    };
338
339    while i < chars.len() {
340        let ch = chars[i];
341        let next = chars.get(i + 1).copied();
342
343        if in_single {
344            if ch == '\'' {
345                if next == Some('\'') {
346                    current_word.push('\'');
347                    i += 2;
348                    continue;
349                }
350                in_single = false;
351                i += 1;
352                continue;
353            }
354            current_word.push(ch);
355            has_word = true;
356            i += 1;
357            continue;
358        }
359
360        if in_double {
361            if ch == '`' {
362                let escaped = next?;
363                current_word.push(escaped);
364                has_word = true;
365                i += 2;
366                continue;
367            }
368            if ch == '$' && next == Some('(') {
369                has_command_substitution = true;
370            }
371            if ch == '"' {
372                in_double = false;
373                i += 1;
374                continue;
375            }
376            current_word.push(ch);
377            has_word = true;
378            i += 1;
379            continue;
380        }
381
382        // Unquoted context
383        if ch == '<' && next == Some('#') {
384            // PowerShell block comment `<# ... #>`
385            i += 2;
386            let mut closed = false;
387            while i + 1 < chars.len() {
388                if chars[i] == '#' && chars[i + 1] == '>' {
389                    i += 2;
390                    closed = true;
391                    break;
392                }
393                i += 1;
394            }
395            if !closed {
396                return None;
397            }
398            continue;
399        }
400
401        if ch == '#' && !has_word {
402            // Line comment until newline.
403            while i < chars.len() && chars[i] != '\n' {
404                i += 1;
405            }
406            continue;
407        }
408
409        if ch == '\'' {
410            in_single = true;
411            has_word = true;
412            i += 1;
413            continue;
414        }
415
416        if ch == '"' {
417            in_double = true;
418            has_word = true;
419            i += 1;
420            continue;
421        }
422
423        if ch == '`' {
424            // Unquoted backtick escapes in PowerShell are a common obfuscation
425            // vector (`I`EX, `r`m); fail closed as dynamic/eval injection.
426            env_or_eval_injection = true;
427            let escaped = next?;
428            if escaped != '\n' && escaped != '\r' {
429                current_word.push(escaped);
430                has_word = true;
431            }
432            i += 2;
433            continue;
434        }
435
436        if ch == '$' && next == Some('(') {
437            has_command_substitution = true;
438            current_word.push(ch);
439            has_word = true;
440            i += 1;
441            continue;
442        }
443
444        // Command separators: `;`, `\n`, `\r`, `|`, `||`, `&&`
445        if matches!(ch, ';' | '\n' | '\r') {
446            flush_word(
447                &mut current_word,
448                &mut has_word,
449                &mut current_cmd,
450                &mut path_check_tokens,
451            );
452            flush_cmd(&mut current_cmd, &mut commands);
453            i += 1;
454            continue;
455        }
456
457        if ch == '|' {
458            flush_word(
459                &mut current_word,
460                &mut has_word,
461                &mut current_cmd,
462                &mut path_check_tokens,
463            );
464            flush_cmd(&mut current_cmd, &mut commands);
465            i += if next == Some('|') { 2 } else { 1 };
466            continue;
467        }
468
469        if ch == '&' && next == Some('&') {
470            flush_word(
471                &mut current_word,
472                &mut has_word,
473                &mut current_cmd,
474                &mut path_check_tokens,
475            );
476            flush_cmd(&mut current_cmd, &mut commands);
477            i += 2;
478            continue;
479        }
480
481        if ch.is_whitespace() {
482            flush_word(
483                &mut current_word,
484                &mut has_word,
485                &mut current_cmd,
486                &mut path_check_tokens,
487            );
488            i += 1;
489            continue;
490        }
491
492        current_word.push(ch);
493        has_word = true;
494        i += 1;
495    }
496
497    if in_single || in_double {
498        return None;
499    }
500
501    flush_word(
502        &mut current_word,
503        &mut has_word,
504        &mut current_cmd,
505        &mut path_check_tokens,
506    );
507    flush_cmd(&mut current_cmd, &mut commands);
508
509    let mut has_destructive_delete = false;
510    for cmd in &commands {
511        if powershell_command_has_env_or_eval_injection(cmd) {
512            env_or_eval_injection = true;
513        }
514        if powershell_command_is_destructive_delete(cmd) {
515            has_destructive_delete = true;
516        }
517    }
518
519    Some(PowerShellSecurityAnalysis {
520        commands,
521        env_or_eval_injection,
522        has_command_substitution,
523        has_destructive_delete,
524        path_check_tokens,
525    })
526}
527
528#[cfg(any(windows, test))]
529fn powershell_command_has_env_or_eval_injection(words: &[String]) -> bool {
530    let Some(head_raw) = words.first() else {
531        return false;
532    };
533    let head = head_raw.to_ascii_lowercase();
534    let normalized = super::shell::executable_name(head_raw);
535
536    // Call operator `&` and dot-sourcing `.` execute arbitrary commands/scripts.
537    if matches!(head.as_str(), "&" | ".") {
538        return true;
539    }
540
541    // Direct `$env:KEY = ...` or `$env:KEY=...` assignment.
542    if let Some(rest) = head.strip_prefix("$env:") {
543        let key = rest.split('=').next().unwrap_or(rest);
544        let assigns =
545            rest.contains('=') || words.get(1).is_some_and(|w| w == "=" || w.starts_with('='));
546        if assigns && is_windows_injection_env_key(key) {
547            return true;
548        }
549    }
550
551    // PowerShell dynamic execution & process launch cmdlets/aliases.
552    if matches!(
553        normalized.as_str(),
554        "invoke-expression"
555            | "iex"
556            | "invoke-command"
557            | "icm"
558            | "start-process"
559            | "saps"
560            | "start"
561            | "wsl"
562            | "runas"
563    ) {
564        return true;
565    }
566
567    // `Set-Item Env:PATH ...` / `New-Item Env:PATH ...`
568    if matches!(head.as_str(), "set-item" | "si" | "new-item" | "ni")
569        && words.iter().skip(1).any(|arg| {
570            let lower = arg.to_ascii_lowercase();
571            lower
572                .strip_prefix("env:\\")
573                .or_else(|| lower.strip_prefix("env:"))
574                .is_some_and(is_windows_injection_env_key)
575        })
576    {
577        return true;
578    }
579
580    // Encoded PowerShell flags anywhere in the invocation.
581    if words.iter().skip(1).any(|arg| {
582        let lower = arg.to_ascii_lowercase();
583        matches!(
584            lower.as_str(),
585            "-enc" | "-ec" | "-e" | "-encodedcommand" | "/enc"
586        ) || lower.starts_with("-encoded")
587    }) {
588        return true;
589    }
590
591    false
592}
593
594#[cfg(any(windows, test))]
595fn is_windows_injection_env_key(key: &str) -> bool {
596    let upper = key.to_ascii_uppercase();
597    matches!(
598        upper.as_str(),
599        "PATH"
600            | "PATHEXT"
601            | "COMSPEC"
602            | "PSMODULEPATH"
603            | "LD_PRELOAD"
604            | "LD_AUDIT"
605            | "BASH_ENV"
606            | "ENV"
607            | "IFS"
608            | "GIT_EXTERNAL_DIFF"
609            | "GIT_PROXY_COMMAND"
610            | "PROMPT_COMMAND"
611    ) || upper.starts_with("DYLD_")
612        || upper.starts_with("GIT_CONFIG")
613}
614
615#[cfg(any(windows, test))]
616fn powershell_command_is_destructive_delete(words: &[String]) -> bool {
617    let Some(head) = words.first() else {
618        return false;
619    };
620    let normalized = super::shell::executable_name(head);
621    if !matches!(
622        normalized.as_str(),
623        "remove-item" | "ri" | "del" | "erase" | "rd" | "rmdir"
624    ) {
625        return false;
626    }
627    let mut operands = Vec::new();
628    for arg in words.iter().skip(1) {
629        let lower = arg.to_ascii_lowercase();
630        if lower.starts_with('-') || lower.starts_with('/') {
631            if matches!(
632                lower.as_str(),
633                "-recurse" | "-r" | "-rec" | "-rf" | "/s" | "/q"
634            ) || (lower.starts_with("-rec") && "-recurse".starts_with(&lower))
635            {
636                return true;
637            }
638            continue;
639        }
640        operands.push(arg.as_str());
641    }
642    operands.is_empty()
643        || operands.iter().any(|op| {
644            op.is_empty()
645                || matches!(*op, "." | ".." | "/" | "\\" | "*" | "~")
646                || op.ends_with("/*")
647                || op.ends_with("\\*")
648                || op
649                    .chars()
650                    .any(|ch| matches!(ch, '*' | '?' | '[' | '{' | '$' | '`'))
651        })
652}
653
654#[cfg(test)]
655mod tests {
656    use super::*;
657    use std::{env, ffi::OsString};
658
659    #[test]
660    fn windows_shell_cascade_prefers_pwsh_then_powershell_then_git_bash() {
661        let tools_dir = Path::new("/tools");
662        let pwsh_exe = tools_dir.join("pwsh.exe");
663        let path_env = env::join_paths([tools_dir]).expect("join paths");
664        let pathext = OsString::from(".EXE;.CMD");
665        let git_bash = vec![PathBuf::from(r"C:\Program Files\Git\bin\bash.exe")];
666
667        assert_eq!(
668            detect_windows_shell_with(None, Some(&path_env), Some(&pathext), &git_bash, |p| p
669                == pwsh_exe
670                || p == git_bash[0],),
671            WindowsShell::Pwsh
672        );
673
674        assert_eq!(
675            detect_windows_shell_with(None, Some(&path_env), Some(&pathext), &git_bash, |p| p
676                == Path::new(r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe")
677                || p == git_bash[0],),
678            WindowsShell::PowerShell
679        );
680
681        assert_eq!(
682            detect_windows_shell_with(None, Some(&path_env), Some(&pathext), &git_bash, |p| p
683                == git_bash[0],),
684            WindowsShell::GitBash(git_bash[0].clone())
685        );
686
687        assert_eq!(
688            detect_windows_shell_with(
689                Some("bash"),
690                Some(&path_env),
691                Some(&pathext),
692                &git_bash,
693                |p| p == pwsh_exe || p == git_bash[0],
694            ),
695            WindowsShell::GitBash(git_bash[0].clone())
696        );
697
698        assert_eq!(
699            WindowsShell::Pwsh.command_argv("cargo test"),
700            vec![
701                "pwsh",
702                "-NoProfile",
703                "-NonInteractive",
704                "-Command",
705                "cargo test"
706            ]
707        );
708        assert_eq!(
709            WindowsShell::PowerShell.command_argv("cargo test"),
710            vec![
711                "powershell.exe",
712                "-NoProfile",
713                "-NonInteractive",
714                "-Command",
715                "cargo test"
716            ]
717        );
718        assert_eq!(
719            WindowsShell::Cmd.command_argv("dir"),
720            vec!["cmd.exe", "/C", "dir"]
721        );
722    }
723
724    #[test]
725    fn powershell_analysis_accepts_plain_commands_and_flags_dangerous_ones() {
726        let safe = analyze_powershell_script(r"rg foo src\main.rs | Select-String bar")
727            .expect("safe script parses");
728        assert!(!safe.env_or_eval_injection);
729        assert!(!safe.has_command_substitution);
730        assert!(!safe.has_destructive_delete);
731        assert_eq!(safe.commands.len(), 2);
732        assert!(safe.path_check_tokens.iter().any(|t| t == r"src\main.rs"));
733
734        let iex = analyze_powershell_script("Invoke-Expression $payload").expect("parses");
735        assert!(iex.env_or_eval_injection);
736
737        let env_hijack =
738            analyze_powershell_script(r"$env:PATH = 'C:\evil;' + $env:PATH; cargo test")
739                .expect("parses");
740        assert!(env_hijack.env_or_eval_injection);
741
742        let delete_tree =
743            analyze_powershell_script(r"Remove-Item -Recurse -Force target").expect("parses");
744        assert!(delete_tree.has_destructive_delete);
745
746        let subexpr =
747            analyze_powershell_script("echo \"$(Get-Content C:\\secret.txt)\"").expect("parses");
748        assert!(subexpr.has_command_substitution);
749
750        assert!(analyze_powershell_script("echo 'unclosed").is_none());
751        let plain =
752            parse_plain_powershell_command_sequence(r"Get-Content src\lib.rs | Select-String foo")
753                .expect("plain sequence");
754        assert_eq!(plain.len(), 2);
755    }
756}