merry_runtime/process/classification/
windows_shell.rs1#[cfg(windows)]
9use std::{env, sync::OnceLock};
10#[cfg(any(windows, test))]
11use std::{
12 ffi::OsStr,
13 path::{Path, PathBuf},
14};
15
16#[cfg(any(windows, test))]
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub(crate) enum WindowsShell {
20 Pwsh,
22 PowerShell,
24 GitBash(PathBuf),
26 Cmd,
28}
29
30#[cfg(any(windows, test))]
31impl WindowsShell {
32 #[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 #[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 #[cfg(windows)]
57 #[must_use]
58 pub(crate) const fn has_unix_utilities(&self) -> bool {
59 matches!(self, Self::GitBash(_))
60 }
61
62 #[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#[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#[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#[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#[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#[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#[cfg(any(windows, test))]
255pub(crate) struct PowerShellSecurityAnalysis {
256 pub(crate) commands: Vec<Vec<String>>,
258 pub(crate) env_or_eval_injection: bool,
262 pub(crate) has_command_substitution: bool,
265 pub(crate) has_destructive_delete: bool,
269}
270
271#[cfg(any(windows, test))]
274pub(crate) fn parse_plain_powershell_command_sequence(script: &str) -> Option<Vec<Vec<String>>> {
275 let analysis = analyze_powershell_script(script)?;
276 if analysis.env_or_eval_injection
277 || analysis.has_command_substitution
278 || analysis.has_destructive_delete
279 || analysis.commands.is_empty()
280 {
281 return None;
282 }
283 for command in &analysis.commands {
285 for word in command {
286 if word.chars().any(|ch| {
287 matches!(
288 ch,
289 '$' | '`' | '>' | '<' | '(' | ')' | '{' | '}' | '*' | '?'
290 )
291 }) {
292 return None;
293 }
294 }
295 }
296 Some(analysis.commands)
297}
298
299#[cfg(any(windows, test))]
303pub(crate) fn analyze_powershell_script(script: &str) -> Option<PowerShellSecurityAnalysis> {
304 let mut commands: Vec<Vec<String>> = Vec::new();
305 let mut current_cmd: Vec<String> = Vec::new();
306 let mut current_word = String::new();
307 let mut has_word = false;
308 let mut in_single = false;
309 let mut in_double = false;
310 let mut env_or_eval_injection = false;
311 let mut has_command_substitution = false;
312
313 let chars: Vec<char> = script.chars().collect();
314 let mut i = 0;
315
316 let flush_word =
317 |current_word: &mut String, has_word: &mut bool, current_cmd: &mut Vec<String>| {
318 if *has_word {
319 let word = std::mem::take(current_word);
320 if !word.is_empty() {
321 current_cmd.push(word);
322 }
323 *has_word = false;
324 }
325 };
326
327 let flush_cmd = |current_cmd: &mut Vec<String>, commands: &mut Vec<Vec<String>>| {
328 if !current_cmd.is_empty() {
329 commands.push(std::mem::take(current_cmd));
330 }
331 };
332
333 while i < chars.len() {
334 let ch = chars[i];
335 let next = chars.get(i + 1).copied();
336
337 if in_single {
338 if ch == '\'' {
339 if next == Some('\'') {
340 current_word.push('\'');
341 i += 2;
342 continue;
343 }
344 in_single = false;
345 i += 1;
346 continue;
347 }
348 current_word.push(ch);
349 has_word = true;
350 i += 1;
351 continue;
352 }
353
354 if in_double {
355 if ch == '`' {
356 let escaped = next?;
357 current_word.push(escaped);
358 has_word = true;
359 i += 2;
360 continue;
361 }
362 if ch == '$' && next == Some('(') {
363 has_command_substitution = true;
364 }
365 if ch == '"' {
366 in_double = false;
367 i += 1;
368 continue;
369 }
370 current_word.push(ch);
371 has_word = true;
372 i += 1;
373 continue;
374 }
375
376 if ch == '<' && next == Some('#') {
378 i += 2;
380 let mut closed = false;
381 while i + 1 < chars.len() {
382 if chars[i] == '#' && chars[i + 1] == '>' {
383 i += 2;
384 closed = true;
385 break;
386 }
387 i += 1;
388 }
389 if !closed {
390 return None;
391 }
392 continue;
393 }
394
395 if ch == '#' && !has_word {
396 while i < chars.len() && chars[i] != '\n' {
398 i += 1;
399 }
400 continue;
401 }
402
403 if ch == '\'' {
404 in_single = true;
405 has_word = true;
406 i += 1;
407 continue;
408 }
409
410 if ch == '"' {
411 in_double = true;
412 has_word = true;
413 i += 1;
414 continue;
415 }
416
417 if ch == '`' {
418 env_or_eval_injection = true;
421 let escaped = next?;
422 if escaped != '\n' && escaped != '\r' {
423 current_word.push(escaped);
424 has_word = true;
425 }
426 i += 2;
427 continue;
428 }
429
430 if ch == '$' && next == Some('(') {
431 has_command_substitution = true;
432 current_word.push(ch);
433 has_word = true;
434 i += 1;
435 continue;
436 }
437
438 if matches!(ch, ';' | '\n' | '\r') {
440 flush_word(&mut current_word, &mut has_word, &mut current_cmd);
441 flush_cmd(&mut current_cmd, &mut commands);
442 i += 1;
443 continue;
444 }
445
446 if ch == '|' {
447 flush_word(&mut current_word, &mut has_word, &mut current_cmd);
448 flush_cmd(&mut current_cmd, &mut commands);
449 i += if next == Some('|') { 2 } else { 1 };
450 continue;
451 }
452
453 if ch == '&' && next == Some('&') {
454 flush_word(&mut current_word, &mut has_word, &mut current_cmd);
455 flush_cmd(&mut current_cmd, &mut commands);
456 i += 2;
457 continue;
458 }
459
460 if ch.is_whitespace() {
461 flush_word(&mut current_word, &mut has_word, &mut current_cmd);
462 i += 1;
463 continue;
464 }
465
466 current_word.push(ch);
467 has_word = true;
468 i += 1;
469 }
470
471 if in_single || in_double {
472 return None;
473 }
474
475 flush_word(&mut current_word, &mut has_word, &mut current_cmd);
476 flush_cmd(&mut current_cmd, &mut commands);
477
478 let mut has_destructive_delete = false;
479 for cmd in &commands {
480 if powershell_command_has_env_or_eval_injection(cmd) {
481 env_or_eval_injection = true;
482 }
483 if powershell_command_is_destructive_delete(cmd) {
484 has_destructive_delete = true;
485 }
486 }
487
488 Some(PowerShellSecurityAnalysis {
489 commands,
490 env_or_eval_injection,
491 has_command_substitution,
492 has_destructive_delete,
493 })
494}
495
496#[cfg(any(windows, test))]
497fn powershell_command_has_env_or_eval_injection(words: &[String]) -> bool {
498 let Some(head_raw) = words.first() else {
499 return false;
500 };
501 let head = head_raw.to_ascii_lowercase();
502 let normalized = super::shell::executable_name(head_raw);
503
504 if matches!(head.as_str(), "&" | ".") {
506 return true;
507 }
508
509 if let Some(rest) = head.strip_prefix("$env:") {
511 let key = rest.split('=').next().unwrap_or(rest);
512 let assigns =
513 rest.contains('=') || words.get(1).is_some_and(|w| w == "=" || w.starts_with('='));
514 if assigns && is_windows_injection_env_key(key) {
515 return true;
516 }
517 }
518
519 if matches!(
521 normalized.as_str(),
522 "invoke-expression"
523 | "iex"
524 | "invoke-command"
525 | "icm"
526 | "start-process"
527 | "saps"
528 | "start"
529 | "wsl"
530 | "runas"
531 ) {
532 return true;
533 }
534
535 if matches!(head.as_str(), "set-item" | "si" | "new-item" | "ni")
537 && words.iter().skip(1).any(|arg| {
538 let lower = arg.to_ascii_lowercase();
539 lower
540 .strip_prefix("env:\\")
541 .or_else(|| lower.strip_prefix("env:"))
542 .is_some_and(is_windows_injection_env_key)
543 })
544 {
545 return true;
546 }
547
548 if words.iter().skip(1).any(|arg| {
550 let lower = arg.to_ascii_lowercase();
551 matches!(
552 lower.as_str(),
553 "-enc" | "-ec" | "-e" | "-encodedcommand" | "/enc"
554 ) || lower.starts_with("-encoded")
555 }) {
556 return true;
557 }
558
559 false
560}
561
562#[cfg(any(windows, test))]
563fn is_windows_injection_env_key(key: &str) -> bool {
564 let upper = key.to_ascii_uppercase();
565 matches!(
566 upper.as_str(),
567 "PATH"
568 | "PATHEXT"
569 | "COMSPEC"
570 | "PSMODULEPATH"
571 | "LD_PRELOAD"
572 | "LD_AUDIT"
573 | "BASH_ENV"
574 | "ENV"
575 | "IFS"
576 | "GIT_EXTERNAL_DIFF"
577 | "GIT_PROXY_COMMAND"
578 | "PROMPT_COMMAND"
579 ) || upper.starts_with("DYLD_")
580 || upper.starts_with("GIT_CONFIG")
581}
582
583#[cfg(any(windows, test))]
584fn powershell_command_is_destructive_delete(words: &[String]) -> bool {
585 let Some(head) = words.first() else {
586 return false;
587 };
588 let normalized = super::shell::executable_name(head);
589 if !matches!(
590 normalized.as_str(),
591 "remove-item" | "ri" | "del" | "erase" | "rd" | "rmdir"
592 ) {
593 return false;
594 }
595 let mut operands = Vec::new();
596 for arg in words.iter().skip(1) {
597 let lower = arg.to_ascii_lowercase();
598 if lower.starts_with('-') || lower.starts_with('/') {
599 if matches!(
600 lower.as_str(),
601 "-recurse" | "-r" | "-rec" | "-rf" | "/s" | "/q"
602 ) || (lower.starts_with("-rec") && "-recurse".starts_with(&lower))
603 {
604 return true;
605 }
606 continue;
607 }
608 operands.push(arg.as_str());
609 }
610 operands.is_empty()
611 || operands.iter().any(|op| {
612 op.is_empty()
613 || matches!(*op, "." | ".." | "/" | "\\" | "*" | "~")
614 || op.ends_with("/*")
615 || op.ends_with("\\*")
616 || op
617 .chars()
618 .any(|ch| matches!(ch, '*' | '?' | '[' | '{' | '$' | '`'))
619 })
620}
621
622#[cfg(test)]
623mod tests {
624 use super::*;
625 use std::{env, ffi::OsString};
626
627 #[test]
628 fn windows_shell_cascade_prefers_pwsh_then_powershell_then_git_bash() {
629 let tools_dir = Path::new("/tools");
630 let pwsh_exe = tools_dir.join("pwsh.exe");
631 let path_env = env::join_paths([tools_dir]).expect("join paths");
632 let pathext = OsString::from(".EXE;.CMD");
633 let git_bash = vec![PathBuf::from(r"C:\Program Files\Git\bin\bash.exe")];
634
635 assert_eq!(
636 detect_windows_shell_with(None, Some(&path_env), Some(&pathext), &git_bash, |p| p
637 == pwsh_exe
638 || p == git_bash[0],),
639 WindowsShell::Pwsh
640 );
641
642 assert_eq!(
643 detect_windows_shell_with(None, Some(&path_env), Some(&pathext), &git_bash, |p| p
644 == Path::new(r"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe")
645 || p == git_bash[0],),
646 WindowsShell::PowerShell
647 );
648
649 assert_eq!(
650 detect_windows_shell_with(None, Some(&path_env), Some(&pathext), &git_bash, |p| p
651 == git_bash[0],),
652 WindowsShell::GitBash(git_bash[0].clone())
653 );
654
655 assert_eq!(
656 detect_windows_shell_with(
657 Some("bash"),
658 Some(&path_env),
659 Some(&pathext),
660 &git_bash,
661 |p| p == pwsh_exe || p == git_bash[0],
662 ),
663 WindowsShell::GitBash(git_bash[0].clone())
664 );
665
666 assert_eq!(
667 WindowsShell::Pwsh.command_argv("cargo test"),
668 vec![
669 "pwsh",
670 "-NoProfile",
671 "-NonInteractive",
672 "-Command",
673 "cargo test"
674 ]
675 );
676 assert_eq!(
677 WindowsShell::PowerShell.command_argv("cargo test"),
678 vec![
679 "powershell.exe",
680 "-NoProfile",
681 "-NonInteractive",
682 "-Command",
683 "cargo test"
684 ]
685 );
686 assert_eq!(
687 WindowsShell::Cmd.command_argv("dir"),
688 vec!["cmd.exe", "/C", "dir"]
689 );
690 }
691
692 #[test]
693 fn powershell_analysis_accepts_plain_commands_and_flags_dangerous_ones() {
694 let safe = analyze_powershell_script(r"rg foo src\main.rs | Select-String bar")
695 .expect("safe script parses");
696 assert!(!safe.env_or_eval_injection);
697 assert!(!safe.has_command_substitution);
698 assert!(!safe.has_destructive_delete);
699 assert_eq!(safe.commands.len(), 2);
700 assert!(safe.commands.iter().flatten().any(|t| t == r"src\main.rs"));
701
702 let iex = analyze_powershell_script("Invoke-Expression $payload").expect("parses");
703 assert!(iex.env_or_eval_injection);
704
705 let env_hijack =
706 analyze_powershell_script(r"$env:PATH = 'C:\evil;' + $env:PATH; cargo test")
707 .expect("parses");
708 assert!(env_hijack.env_or_eval_injection);
709
710 let delete_tree =
711 analyze_powershell_script(r"Remove-Item -Recurse -Force target").expect("parses");
712 assert!(delete_tree.has_destructive_delete);
713
714 let subexpr =
715 analyze_powershell_script("echo \"$(Get-Content C:\\secret.txt)\"").expect("parses");
716 assert!(subexpr.has_command_substitution);
717
718 assert!(analyze_powershell_script("echo 'unclosed").is_none());
719 let plain =
720 parse_plain_powershell_command_sequence(r"Get-Content src\lib.rs | Select-String foo")
721 .expect("plain sequence");
722 assert_eq!(plain.len(), 2);
723 }
724}